1147 Heaps 解析

感觉最近两次30分的题,不像以前那么麻烦了...

检查最大最小堆.然后做一个后续遍历...序号从1开始就好了..多注意下端点的值,别搞错就好了。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int M, N;
int * list;

bool isMinHeap(int node) {
	bool tag = true;

	int left = 2 * node;
	int right = 2 * node + 1;

	if (left <= N) {
		if (list[node] >= list[left]) {
			tag = false;
		}
		if (tag) {
			tag = isMinHeap(left);
		}
	}

	if (right <= N) {
		if (list[node] >= list[right]) {
			tag = false;
		}
		if (tag) {
			tag = isMinHeap(right);
		}
	}

	return tag;
}


bool isMaxHeap(int node) {
	bool tag = true;

	int left = 2 * node;
	int right = 2 * node + 1;

	if (left <= N) {
		if (list[node] <= list[left]) {
			tag = false;
		}
		if (tag) {
			tag = isMaxHeap(left);
		}
	}

	if (right <= N) {
		if (list[node] <= list[right]) {
			tag = false;
		}
		if (tag) {
			tag = isMaxHeap(right);
		}
	}

	return tag;
}

int * post;
int p = 0;

void PostOrder(int root) {
	if (root <= N) {
		PostOrder(root * 2);
		PostOrder(root * 2 + 1);
		post[p++] = list[root];
	}
}

int main() {
	scanf("%d %d", &M, &N);

	list = new int[N + 1];
	post = new int[N + 1];

	for (int i = 0; i < M; i++) {
		for (int j = 1; j <= N; j++) {
			scanf("%d", &list[j]);
		}
		bool minheap = isMinHeap(1);
		bool maxheap = isMaxHeap(1);
		if (minheap && !maxheap) {
			printf("Min Heap\n");
		}
		else if (maxheap && !minheap) {
			printf("Max Heap\n");
		}
		else {
			printf("Not Heap\n");
		}
		p = 0;
		PostOrder(1);
		for (int x = 0; x < N; x++) {
			if (x == 0) {
				printf("%d", post[x]);
			}
			else {
				printf(" %d", post[x]);
			}
		}
		printf("\n");
	}

	return 0;
}


 

你可能感兴趣的:(1147 Heaps 解析)