PAT (Advanced Level) 1089. Insert or Merge (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()
{
    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("Merge Sort\n");

        int len=1;
        while(1)
        {
            int pp=1;
            while(1)
            {
                if(pp+len-1>n)
                {
                    sort(a+pp,a+n+1);
                    break;
                }
                else
                {
                    sort(a+pp,a+pp+len);
                    pp=pp+len;
                }
            }

            int fail=0;
            for(int i=1; i<=n; i++) if(a[i]!=b[i]) fail=1;

            if(fail==0)
            {
                len=len*2;
                int ppp=1;
                while(1)
                {
                    if(ppp+len-1>n)
                    {
                        sort(a+ppp,a+n+1);
                        break;
                    }
                    else
                    {
                        sort(a+ppp,a+ppp+len);
                        ppp=ppp+len;
                    }
                }
                for(int i=1;i<=n;i++)
                {
                    printf("%d",a[i]);
                    if(i<n) printf(" ");
                    else printf("\n");
                }
                break;
            }
            len=len*2;
        }
    }

    return 0;
}

 

posted @ 2016-07-03 22:53  Fighting_Heart  阅读(232)  评论(0编辑  收藏  举报