# PAT_甲级_1147 Heaps

#### 算法思路：

##### isMaxHeap
``````// 判断是否是大根堆
bool isMaxHeap(){
for (int i = 1; i <= N; ++i) {
if((2*i<=N&&heap[2*i]>heap[i])||(2*i+1<=N&&heap[2*i+1]>heap[i])){
return false;
}
}
return true;
}``````
##### isMinHeap
``````// 判断是否是小根堆
bool isMinHeap(){
for (int i = 1; i <= N; ++i) {
if((2*i<=N&&heap[2*i]<heap[i])||(2*i+1<=N&&heap[2*i+1]<heap[i])){
return false;
}
}
return true;
}``````

#### AC代码：

``````#include<cstdio>

using namespace std;

int heap[1005];
int M,N;

// 判断是否是大根堆
bool isMaxHeap(){
for (int i = 1; i <= N; ++i) {
if((2*i<=N&&heap[2*i]>heap[i])||(2*i+1<=N&&heap[2*i+1]>heap[i])){
return false;
}
}
return true;
}

// 判断是否是小根堆
bool isMinHeap(){
for (int i = 1; i <= N; ++i) {
if((2*i<=N&&heap[2*i]<heap[i])||(2*i+1<=N&&heap[2*i+1]<heap[i])){
return false;
}
}
return true;
}

int num;// 控制空格输出
void postTraverse(int root){
if(root>N) return;
postTraverse(2*root);
postTraverse(2*root+1);
printf("%d",heap[root]);
if(num<N-1) printf(" ");
++num;
}

int main(){
scanf("%d %d",&M,&N);
for (int i = 0; i < M; ++i) {
// M次查询
num = 0;// 每次都得赋值为0
for (int j = 1; j <= N; ++j) {
scanf("%d",&heap[j]);
}
if(isMinHeap()){
printf("Min Heap\n");
} else if(isMaxHeap()){
printf("Max Heap\n");
} else {
printf("Not Heap\n");
}
postTraverse(1);
printf("\n");// 记得换行
}
return 0;
}

``````

566 声望
13 粉丝
0 条评论