AcWing 1640. 堆--- 树的遍历(DFS)
原题链接
简单
作者:
巨鹿噜噜噜路
,
2020-06-02 22:16:48
,
所有人可见
,
阅读 1217
C++ 代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX_N = 1010;
int lOrder[MAX_N];
bool isMaxH, isMinH;
void DFS(int i, int n, vector<int>& pOrder) {
if (i != 1) {
//如果不是根节点,比较父节点与当前节点大小
if (lOrder[i / 2] > lOrder[i]) {
isMaxH = true;
}
else if (lOrder[i / 2] < lOrder[i]) {
isMinH = true;
}
}
if (i * 2 <= n) DFS(i * 2, n, pOrder);
if (i * 2 + 1 <= n) DFS(i * 2 + 1, n, pOrder);
//后续遍历
pOrder.push_back(lOrder[i]);
}
int main() {
int n, m;
scanf("%d%d", &m, &n);
while (m--) {
isMaxH = false;
isMinH = false;
for (int i = 1; i <= n; i++) scanf("%d", &lOrder[i]);
vector<int> pOrder;
DFS(1, n, pOrder);
//如果互相矛盾,则不是堆
if (isMaxH && isMinH) puts("Not Heap");
else if (isMaxH) puts("Max Heap");
else puts("Min Heap");
for (int i = 0; i < pOrder.size(); i++) {
if (i) printf(" ");
printf("%d", pOrder[i]);
}
printf("\n");
}
return 0;
}