PAT甲级 1147 Heaps
PAT1147链接
题目大意 给定查询次数M和完全二叉树的结点个数N及每棵树的层序遍历,每次查询输出它的后序遍历,并判断是否为最大最小堆
# include<iostream>
# include<cstring>
# include<vector>
using namespace std;
const int maxn = 1010;
vector<int>post;
int layer[maxn];
//int CompleteBinaryTree[maxn];
int n, m;
int num = 0;
void PostTraversal(int index)
{
if (index > m) return;
PostTraversal(index * 2);
PostTraversal(index * 2+1);
post.push_back(layer[index]);
}
bool IsMaxHeap()
{
for (int i = 1;i <= m / 2;i++) //遍历根结点
{
if (2 * i + 1 <= m) //如果有右孩子
{
if (!(layer[i]>=layer[2*i]&&layer[i]>=layer[2*i+1]))
{
return false;
}
}
else //没有右孩子
{
if (layer[i] <= layer[2 * i]) return false;
}
}
return true;
}
bool IsMinHeap()
{
for (int i = 1;i <= m / 2;i ++) //遍历根结点
{
if (2 * i + 1 <= m) //如果有右孩子
{
if (!(layer[i]<=layer[2*i]&&layer[i]<=layer[2*i+1]))
{
return false;
}
}
else //没有右孩子
{
if (layer[i] >= layer[2 * i]) return false;
}
}
return true;
}
int main()
{
cin >> n >> m;
for (int i = 0;i < n;i++)
{
post.clear();
for (int j = 1;j <= m;j++)
{
cin >> layer[j];
}
PostTraversal(1);
bool flag1 = IsMaxHeap();
bool flag2 = IsMinHeap();
if (flag1) cout << "Max Heap" << endl;
else if (flag2) cout << "Min Heap"<<endl;
else if (!flag1 && !flag2) cout << "Not Heap"<<endl;
for (int i = 0;i < post.size();i++)
{
cout << post[i];
if (i != post.size() - 1) cout << " ";
}
cout << endl;
}
return 0;
}