题目链接:PAT – Advanced Level – 1155
DFS。
吐槽:同样是30分的题差别怎么这么大啊?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| #include <bits/stdc++.h> using namespace std; typedef long long LL; const int MAX_N = 1000 + 5; int n, a[MAX_N]; vector < vector <int> > path; vector <int> stk; void dfs(int x) { stk.push_back(a[x]); if (x * 2 + 1 <= n) dfs(x * 2 + 1); if (x * 2 <= n) dfs(x * 2); else path.push_back(stk); stk.pop_back(); } bool minHeap = true, maxHeap = true; void check() { for (auto &v: path) { for (unsigned i = 1; i < v.size(); ++i) { if (v[i] > v[i - 1]) maxHeap = false; if (v[i] < v[i - 1]) minHeap = false; } for (int i = 0; i < v.size(); ++i) { printf("%d%c", v[i], i == v.size() - 1 ? '\n' : ' '); } } } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", a + i); dfs(1); check(); if (!minHeap && !maxHeap) { puts("Not Heap"); } else if (minHeap) { puts("Min Heap"); } else if (maxHeap) { puts("Max Heap"); } return 0; }
|