PAT (Advanced Level) 1098. Insertion or Heap Sort (25)

Posted Fighting Heart

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT (Advanced Level) 1098. Insertion or Heap Sort (25)相关的知识,希望对你有一定的参考价值。

简单题。判断一下是插排还是堆排。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;

const int maxn=200;
int a[maxn],b[maxn],n;

int main()
{
    memset(b,-1,sizeof b);
    scanf("%d",&n);
    for(int i=1; i<=n; i++) scanf("%d",&a[i]);
    for(int i=1; i<=n; i++) scanf("%d",&b[i]);

    int flag=1;

    int p=n+1;
    for(int i=2; i<=n; i++)
        if(b[i]<b[i-1])
        {
            p=i;
            break;
        }

    for(int i=p; i<=n; i++)
    {
        if(a[i]==b[i]) continue;
        else flag=0;
    }

    if(flag==1)
    {
        printf("Insertion Sort\n");
        if(p==n+1) p=n;
        sort(a+1,a+p+1);
        for(int i=1; i<=p; i++)
        {
            printf("%d",a[i]);
            if(i<n) printf(" ");
            else printf("\n");
        }
        for(int i=p+1; i<=n; i++)
        {
            printf("%d",a[i]);
            if(i<n) printf(" ");
            else printf("\n");
        }
    }
    else
    {
        printf("Heap Sort\n");
        sort(a+1,a+1+n);
        for(int i=n; i>=1; i--)
        {
            if(a[i]==b[i]) p=i;
            else break;
        }

        swap(b[1],b[p-1]);

        int i=1;;
        while(1)
        {
            if(2*i<p-1&&2*i+1<p-1)
            {
                if(b[i]<max(b[2*i],b[2*i+1]))
                {

                    if(b[2*i]>b[2*i+1])
                    {
                        swap(b[2*i],b[i]);
                        i=2*i;
                    }
                    else
                    {
                        swap(b[2*i+1],b[i]);
                        i=2*i+1;
                    }
                }
                else break;
            }
            else if(2*i<p-1)
            {
                if(b[i]<b[2*i])
                {
                    swap(b[2*i],b[i]);
                    i=2*i;
                }
            }
            else break;

        }
        for(int i=1; i<=n; i++)
        {
            printf("%d",b[i]);
            if(i<n) printf(" ");
            else printf("\n");
        }
    }

    return 0;
}

 

以上是关于PAT (Advanced Level) 1098. Insertion or Heap Sort (25)的主要内容,如果未能解决你的问题,请参考以下文章

PAT (Advanced Level) 1098. Insertion or Heap Sort (25)

PAT (Advanced Level) 1025. PAT Ranking (25)

PAT Advanced Level 1044

PAT Advanced Level 1043

PAT Advanced Level 1079

PAT Advanced Level 1095