PAT--1098 Insertion or Heap Sort--插入排序與堆排序

題目鏈接:https://pintia.cn/problem-sets/994805342720868352/problems/994805368847187968

題目大意

給你長度爲n的數組a和b,其中數組a是原數組,b是插入排序或堆排序過程中的某一步得到的數組,讓你判斷是哪種排序方法,以及下一步得到的數組是什麼。

分析

如果是插入排序,那麼b數組前半部分一定是有序的,後半部分與a數組相同,否則就是堆排序。如果是堆排序,那麼當前在序列中,也分爲兩部分,後半部分一定比b[1]大,前半部分b[1]是最大的元素,那麼我們就可以從後往前找第一個比b[1]小的,假設位置爲x,交換b[1]與b[x],然後再把1--x-1按照堆排序的方法操作一遍就可以了。

代碼

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n, a[110], b[110];
void solve(int l, int r) {
	int x = 1;
	while(x <= r) {
		int j = x << 1;
		if(j > r) break;
		if(j + 1 <= r && b[j + 1] > b[j])
			j++;
		if(b[j] <= b[x]) break;
		swap(b[x], b[j]);
		x = j;
	}
}
int main() {
	scanf("%d", &n);
	for(int i = 1; i <= n; i++)
		scanf("%d", &a[i]);
	for(int i = 1; i <= n; i++)
		scanf("%d", &b[i]);
	int x = 2;
	while(x <= n && b[x] >= b[x - 1])
		x++;
	int id = x;
	while(x <= n && a[x] == b[x])
		x++;
	if(x == n + 1) {
		printf("Insertion Sort\n");
		sort(b + 1, b + id + 1);
		for(int i = 1; i <= n; i++)
			printf("%d%s", b[i], i == n ? "\n" : " ");
	} else {
		printf("Heap Sort\n");
		x = n;
		while(x > 2 && b[x] >= b[1])
			x--;
		swap(b[1], b[x]);
		solve(1, x - 1);
		for(int k = 1; k <= n; k++)
			printf("%d%s", b[k], k == n ? "\n" : " ");
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章