PAT研究生入学考试2015.03第三题Insertion or Heap Sort (25) 题解
2015-09-21 16:16
323 查看
题目:http://www.patest.cn/contests/pat-a-practise/1098
题目大意是判断给出的序列是原序列经过插入排序还是堆排序的一次或多次迭代后产生的序列。注意:某次迭代中某刻的序列不算,堆排序建堆时的序列不算,题目没说清楚。其实不过就是考堆排序和插入排序,麻烦了点,但是并不难。
题目大意是判断给出的序列是原序列经过插入排序还是堆排序的一次或多次迭代后产生的序列。注意:某次迭代中某刻的序列不算,堆排序建堆时的序列不算,题目没说清楚。其实不过就是考堆排序和插入排序,麻烦了点,但是并不难。
#include <iostream> #include <stdio.h> //1ms 288kb const int MAX=110; int a[MAX]; int b[MAX]; int c[MAX]; int n; bool finished=false; bool check(const int(&a)[MAX]) { bool same=true; for (int i=0;i<n;i++) if (a[i]!=b[i]) { same=false; break; } return same; } void adjust_down(int a[MAX],int i,int last) { int child=2*i+1; int temp=a[i]; while (child<=last) { if (child<last && a[child]<a[child+1]) child++; if (temp>=a[child]) break; a[(child-1)/2]=a[child]; child=child*2+1; } a[(child-1)/2]=temp; } void Swap(int& a,int& b) { int temp=a; a=b; b=temp; } void heap_sort(int (&a)[MAX]) { finished=false; for (int i=(n-2)/2;i>=0;i--) adjust_down(a,i,n-1); //this step isn't included in the 'iteration' of the question for (int i=n-1;i>0;i--) { Swap(a[i],a[0]); adjust_down(a,0,i-1); if (finished) return; finished=check(a); } } void insertion_sort(int (&a)[MAX]) { finished=false; for (int i=1;i<n;i++) { int temp=a[i]; int j; for (j=i;j>0;j--) if (a[i]>=a[j-1]) break; for (int k=i;k>j;k--) a[k]=a[k-1]; a[j]=temp; if (finished) return; finished=check(a); } } int main() { scanf("%d",&n); for (int i=0;i<n;i++) { scanf("%d",&a[i]); c[i]=a[i]; } for (int i=0;i<n;i++) scanf("%d",&b[i]); heap_sort(a); if (finished) { printf("Heap Sort\n"); for (int i=0;i<n-1;i++) printf("%d ",a[i]); printf("%d",a[n-1]); } else { insertion_sort(c); printf("Insertion Sort\n"); for (int i=0;i<n-1;i++) printf("%d ",c[i]); printf("%d",c[n-1]); } return 0; }