与1155 Heap Paths异曲同工
#include<cstdio>
#include<vector>
using namespace std;
#define maxn 1010
bool testmaxheap(int heap[], int n, int now) {
int right = now * 2 + 2, left = right - 1;
bool testright = true, testleft = true;
if (right < n) {
if (heap[right] > heap[now]) return false;
testright = testmaxheap(heap, n, right);
}
if (left < n) {
if (heap[left] > heap[now]) return false;
testleft = testmaxheap(heap, n, left);
}
return testleft && testright;
}
bool testminheap(int heap[], int n, int now) {
int right = now * 2 + 2, left = right - 1;
bool testright = true, testleft = true;
if (right < n) {
if (heap[right] < heap[now]) return false;
testright = testminheap(heap, n, right);
}
if (left < n) {
if (heap[left] < heap[now]) return false;
testleft = testminheap(heap, n, left);
}
return testleft && testright;
}
void postorder(int heap[], int n, int now) {
int right = now * 2 + 2, left = right - 1;
if (left < n) postorder(heap, n, left);
if (right < n) postorder(heap, n, right);
printf("%d", heap[now]);
if (now != 0) printf(" ");
else printf("\n");
}
int main() {
int M, N;
int heap[maxn];
scanf("%d %d", &M, &N);
while (M--) {
for (int i = 0; i < N; i++) {
scanf("%d", &heap[i]);
}
if (testmaxheap(heap, N, 0)) printf("Max Heap\n");
else if (testminheap(heap, N, 0)) printf("Min Heap\n");
else printf("Not Heap\n");
postorder(heap, N, 0);
}
return 0;
}