PAT 甲题 1155 Heap Paths

PAT 甲题 1155 Heap Paths


最近写程序有点迷,很简单的逻辑都写不清楚;
柳婼学姐推荐PAT从后往前刷,fine,先写最后一题,虽然30分,但是很简单,很短就AC了;
虽说程序短,逻辑简单,但是我还是调试了一段时间才AC,挫败感萌生。。。

思路:

深度优先搜索

代码:

#include<iostream>
#include<algorithm>
using namespace std;
int n, nodes[1000], no[10], sign;
void dfs(int begin, int level)
{
	 no[level] = nodes[begin];
	 if (level && ((sign == 1 && no[level] > no[level - 1]) || (sign == -1 && no[level] < no[level - 1])))
	 	 sign = 0;
	 if (2 * begin + 2 < n)
	 	 dfs(2 * begin + 2, level + 1);
	 if (2 * begin + 1 < n)
		 dfs(2 * begin + 1, level + 1);
	 else
	 {
	 	 printf("%d", no[0]);
	 	 for (int i = 1; i <= level; i++)
	  		printf(" %d", no[i]);
		 printf("\n");
	 }
	}
int main()
{
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
		scanf("%d", &nodes[i]);
	nodes[0] > nodes[1] ? sign = 1 : sign = -1;
	dfs(0, 0);
	switch (sign)
	{
		case  1 : printf("Max Heap"); break;
		case -1 : printf("Min Heap"); break;
		case  0 : printf("Not Heap");
	}
	return 0;
}
posted @ 2019-07-31 13:57  YuhanのBlog  阅读(94)  评论(0编辑  收藏  举报