1147 Heaps 解析

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

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

#include <iostream>
#include <string>
#include <string.h>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <algorithm>

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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值