Home PAT 1147 Heaps
Post
Cancel

PAT 1147 Heaps

Link

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
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
int m,n;
int a[1010];
bool isFirst;
bool isMaxHeap(int x){
    if(x>n) return true;
    if((x<<1)<=n){
        if(a[x<<1]>a[x]) return false;
        else if(((x<<1)+1)<=n&&a[(x<<1)+1]>a[x]) return false;
    }
    return isMaxHeap(x<<1)&&isMaxHeap((x<<1)+1);
}
bool isMinHeap(int x){
    if(x>n) return true;
    if((x<<1)<=n){
        if(a[x<<1]<a[x]) return false;
        else if(((x<<1)+1)<=n&&a[(x<<1)+1]<a[x]) return false;
    }
    return isMinHeap(x<<1)&&isMinHeap((x<<1)+1);
}
void PostOrder(int x){
    if(x>n) return;
    PostOrder(x<<1);
    PostOrder((x<<1)+1);
    if(!isFirst) printf(" ");
    else isFirst=false;
    printf("%d",a[x]);
}
int main() {
    scanf("%d%d",&m,&n);
    while(m--){
        for(int i=1;i<=n;++i)
            scanf("%d",&a[i]);
        if(a[2]<=a[1]){
            if(isMaxHeap(1)) printf("Max Heap\n");
            else printf("Not Heap\n");
        }else{
            if(isMinHeap(1)) printf("Min Heap\n");
            else printf("Not Heap\n");
        }
        isFirst=true;
        PostOrder(1);
        printf("\n");
    }
    return 0;
}
This post is licensed under CC BY 4.0 by the author.