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
原创粉丝点击