1098 Insertion or Heap Sort (25分)

纯模拟,没有注意性质,插入排序的性质:排过序的部分A和为排过序的部分B,A升序,B和原序列一样。
所以可以先简单判断是不是插入排序,然后再求一个下一步就可以了

#include<iostream>
using namespace std;

const int N = 110;

int a[N], b[N];
int n;
int isHeap;
int ss;

void down(int x){
    int t = x;
    if(x * 2 <= ss && a[x * 2] > a[t]) t = x * 2;
    if(x * 2 + 1 <= ss && a[x * 2 + 1] > a[t]) t = x * 2 + 1;
    
    if(x != t){
        swap(a[x], a[t]);
        down(t);
    }
}

int max_heap(int ss){
    for(int i = ss / 2; i >= 1; i --) down(i);
}

int check(){
    for(int i = 1; i <= n; i ++)
        if(a[i] != b[i]) return 0;
        
    return 1;
}

int main(){
    cin >> n;
    
    for(int i = 1; i <= n; i ++) cin >> a[i];
    for(int i = 1; i <= n; i ++) cin >> b[i];
    
    ss = n;
    
    max_heap(ss);
    
    while(ss > 1){
        if(check()){
            isHeap = 1;
            break;
        }
        swap(a[1], a[ss --]);
        max_heap(ss);
    }
    
    if(!isHeap){
        puts("Insertion Sort");
        for(int i = 2; i <= n; i ++){
            if(b[i] < b[i - 1]){
                int j = i - 1, t = b[i];
                while(j >= 1 && t < b[j]){
                    b[j + 1] = b[j];
                    j --;
                }
                b[j + 1] = t;
                break;
            }
        }
        cout << b[1];
        for(int i = 2; i <= n; i ++) cout << ' ' << b[i];
    }else{
        puts("Heap Sort");
        swap(a[1], a[ss --]);
        max_heap(ss);
        cout << a[1];
        for(int i = 2; i <= n; i ++) cout << ' ' << a[i]; 
    }
    
    return 0;
}
#include<iostream>
#include<algorithm>

using namespace std;

const int N = 110;

int a[N], b[N];
int n;
int isHeap;

void down(int a[], int x, int ss){
    int t = x;
    if(x * 2 <= ss && a[x * 2] > a[t]) t = x * 2;
    if(x * 2 + 1 <= ss && a[x * 2 + 1] > a[t]) t = x * 2 + 1;
    
    if(x != t){
        swap(a[x], a[t]);
        down(a, t, ss);
    }
}

int max_heap(int a[], int ss){
    for(int i = ss / 2; i >= 1; i --) down(a, i, ss);
}

int main(){
    cin >> n;
    
    for(int i = 1; i <= n; i ++) cin >> a[i];
    for(int i = 1; i <= n; i ++) cin >> b[i];
    
    int idx = 2;
    while(idx <= n && b[idx] >= b[idx - 1]) idx ++;
    
    for(int i = idx; i <= n; i ++)
        if(a[idx] != b[idx]){
            isHeap = 1;
            break;
        }
    
    if(isHeap){
        puts("Heap Sort");
        int ss = n;
        while(b[1] <= b[ss]) ss --;
        swap(b[1], b[ss --]);
        max_heap(b, ss);
    }else{
        puts("Insertion Sort");
        sort(b + 1, b + idx + 1);
    }
    cout << b[1];
    for(int i = 2; i <= n; i ++) cout << ' ' << b[i];  
    
    return 0;
}
posted @ 2020-09-30 13:27  yys_c  阅读(129)  评论(0)    收藏  举报