zoukankan      html  css  js  c++  java
  • 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
    ");
            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("
    ");
            }
            for(int i=p+1; i<=n; i++)
            {
                printf("%d",a[i]);
                if(i<n) printf(" ");
                else printf("
    ");
            }
        }
        else
        {
            printf("Heap Sort
    ");
            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("
    ");
            }
        }
    
        return 0;
    }
  • 相关阅读:
    学习canvas过程中的小菜鸟
    小菜鸟谈html语义化
    mui常用方法
    mui的侧滑菜单如何禁用手势侧滑
    ajax 传递数组参数
    LNMP状态管理命令
    LNMP相关软件目录及文件位置
    ubuntu常用命令
    Ubuntu设置允许root用户登录
    linux一键安装web环境(sh-1.3.0)
  • 原文地址:https://www.cnblogs.com/zufezzt/p/5642259.html
Copyright © 2011-2022 走看看