PAT研究生入学考试2015.03第三题Insertion or Heap Sort (25) 题解
来源:互联网 发布:sql中的distinct 编辑:程序博客网 时间:2024/06/03 23:04
题目:http://www.patest.cn/contests/pat-a-practise/1098
题目大意是判断给出的序列是原序列经过插入排序还是堆排序的一次或多次迭代后产生的序列。注意:某次迭代中某刻的序列不算,堆排序建堆时的序列不算,题目没说清楚。其实不过就是考堆排序和插入排序,麻烦了点,但是并不难。
#include <iostream>#include <stdio.h>//1ms 288kbconst 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;}
0 0
- PAT研究生入学考试2015.03第三题Insertion or Heap Sort (25) 题解
- PAT 1098. Insertion or Heap Sort (25)
- [PAT]1098. Insertion or Heap Sort (25)
- 【PAT】1098. Insertion or Heap Sort (25)
- PAT 1098. Insertion or Heap Sort (25)
- PAT A1098. Insertion or Heap Sort (25)
- PAT 1098-Insertion or Heap Sort (25)
- PAT A1098 insertion or heap sort (25)
- PAT-Insertion or Heap Sort
- PAT研究生入学考试2015.03第一题Consecutive Factors (20) 题解
- PAT A 1098. Insertion or Heap Sort (25)
- PAT(Advance) 1098. Insertion or Heap Sort (25)
- PAT (Advanced Level) Practise 1098 Insertion or Heap Sort (25)
- PAT 1098 Insertion or Heap Sort (25)(待修改)
- 1098. Insertion or Heap Sort (25) PAT甲级
- [转]PAT甲级练习1098. Insertion or Heap Sort (25)
- PAT甲级1098. Insertion or Heap Sort (25)
- PAT-A-1098. Insertion or Heap Sort (25)
- Android 代码混淆
- Quartz.net Could not initialize scheduler Scheduler already exists.
- 数据加密介绍<1>
- kNN算法python代码学习2-手写识别系统
- android.断开SVN连接 清理.svn文件夹
- PAT研究生入学考试2015.03第三题Insertion or Heap Sort (25) 题解
- iOS开发技术分享】协议与代理
- Errors & Logging
- js 数组sort()
- 计划看一本英文版的Python基础教程
- 第四周-项目4-建立双链表算法库
- 第三周项目二 建设“顺序表”的算法库
- Javascript高性能动画与页面渲染
- URAL 1210 Kind Spirits (DP动态规划)