原题:1098. Insertion or Heap Sort (25)
解题思路:
写好模拟一次堆排序或插入排序的函数即可,提高效率,判断是否为插入排序即可。
注:插入排序最后输出的排序序列必须与输入给的中间结果不同。
代码如下:
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 100 + 5;
int origin[maxn], temp[maxn];
int insertion[maxn], heap[maxn];
int n;
bool judge(int a[], int b[])
{
for(int i = 1; i <= n; i++)
if(a[i] != b[i]) return false;
return true;
}
void OneTimeInsertionSort(int pos)
{
sort(insertion+1, insertion+pos+1);
}
void OneTimeHeapSort(int pos)
{
swap(heap[1], heap[pos]);
int p = 1;
while(2*p < pos)
{
if(2*p+1 < pos)
{
if(heap[2*p] < heap[2*p+1] && heap[p] < heap[2*p+1])
{
swap(heap[p], heap[2*p+1]);
p = 2*p+1;
}
else if(heap[p] < heap[2*p])
{
swap(heap[p], heap[2*p]);
p = 2*p;
}
else
break;
}
else if(heap[p] < heap[2*p])
{
swap(heap[p], heap[2*p]);
p = 2*p;
}
else
break;
}
}
int main()
{
while(scanf("%d", &n) == 1)
{
for(int i = 1; i <= n; i++)
{
scanf("%d", &origin[i]);
insertion[i] = origin[i];
}
for(int i = 1; i <= n; i++)
{
scanf("%d", &temp[i]);
heap[i] = temp[i];
}
int flag = 0;
for(int i = 2; i <= n; i++)
{
OneTimeInsertionSort(i);
if(judge(temp, insertion))
{
flag = 1;
int cnt = 1;
while(judge(temp, insertion)) {OneTimeInsertionSort(i+cnt); cnt++;}
break;
}
}
if(flag)
{
printf("Insertion Sort\n");
for(int i = 1; i <= n; i++)
if(i == 1) printf("%d", insertion[i]);
else printf(" %d", insertion[i]);
printf("\n");
}
else
{
int pos = n;
while(heap[pos] > heap[1]) pos--;
OneTimeHeapSort(pos);
printf("Heap Sort\n");
for(int i = 1; i <= n; i++)
if(i == 1) printf("%d", heap[i]);
else printf(" %d", heap[i]);
printf("\n");
}
}
return 0;
}