PAT甲级-1098 Insertion or Heap Sort (25 分)

题目:1098 Insertion or Heap Sort (25 分)
分析:插入排序和堆排序,其中堆排的关键:建堆和向下调整。
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
#define MAX 999999999
typedef long long ll;
int n,m,k;
int jdg(int a[],int b[])
{
    
    
    for(int i = 1;i<=n;i++)
        if(a[i] != b[i])
            return 0;
    return 1;
}
void downAdjust(int a[],int k)
{
    
    
    int i = k;
    int j = i * 2;
    while(i <= n && j <= n)
    {
    
    
        if(j + 1 <= n && a[j + 1] > a[j])
            j++;
        if(a[j] > a[i]){
    
    
            swap(a[i], a[j]);
            i = j;
            j = i*2;
        }
        else break;
    }
}
void createHeap(int a[])
{
    
    
    for(int i = n/2; i >= 1; i--)
        downAdjust(a,i);
}
int main()
{
    
    
    cin>>n;
    int ori_a[n + 1],a[n + 1],b[n + 1];
    for(int i = 1;i<=n;i++){
    
    
        cin>>ori_a[i];
        a[i] = ori_a[i];
    }
    for(int i = 1;i<=n;i++)
        cin>>b[i];
    int f = 0;
    for(int i = 2;i<=n;i++)
    {
    
    
        int t = a[i];
        int j = i - 1;
        for(;j>=1 && t < a[j];j--)
            a[j + 1] = a[j];
        a[j + 1] = t;
        if(jdg(a,b)){
    
    
            cout<<"Insertion Sort\n";
            t = a[i + 1];
            j = i;
            for(;j>=1 && t < a[j];j--)
                a[j + 1] = a[j];
            a[j + 1] = t;
            cout<<a[1];
            for(int j = 2;j<=n;j++)
                cout<<" "<<a[j];
            return 0;
        }
    }
    for(int i = 1;i<=n;i++)
        a[i] = ori_a[i];
    createHeap(a);
    int cpy_n = n;
    for(int i = 1;i<=n;i++)
    {
    
    
        swap(a[1],a[n]);
        n--;
        downAdjust(a,1);
        if(jdg(a,b))
        {
    
    
            cout<<"Heap Sort\n";
            swap(a[1],a[n]);
            n--;
            downAdjust(a,1);
            cout<<a[1];
            for(int j = 2;j<=cpy_n;j++)
                cout<<" "<<a[j];
            break;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43567222/article/details/113822367