-
Notifications
You must be signed in to change notification settings - Fork 22
/
does array represent heap
60 lines (51 loc) · 1.32 KB
/
does array represent heap
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
54
55
56
57
58
59
60
/*
Given an array A of size N, the task is to check if the given array represents a Binary Max Heap.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two lines.
The first line of input contains an integer N denoting the size of the array. Then in the next line are N space separated array elements.
Output:
If array represents a Binary Max Heap, print "1", else print "0" (without quotes).
Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= Ai <= 1015
Example:
Input:
2
6
90 15 10 7 12 2
6
9 15 10 7 12 11
Output:
1
0
Explanation:
Testcase 1: Array of first elements represents Binary Max Heap, so output is 1.
*/
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
bool heapify(ll a[], ll n, ll i){
ll root=i;
ll left=2*i + 1;
ll right=2*i + 2;
if(left<n && a[left]>a[root]) return false;
if(right<n && a[right]>a[root]) return false;
return true;
}
int main() {
int t; cin>>t; while(t--){
ll n,flag=0; cin>>n;
ll a[n]; for(ll i=0; i<n; i++) cin>>a[i];
for(ll i=n/2 -1; i>=0; i--){
if(heapify(a,n,i)==false){// for(i=0; i<n; i++){ if(a[(i-1)/2]>
//a[i])
flag=1;
break;
}
}
if(flag==1) cout<<0<<'\n';
else cout<<1<<'\n';
}
return 0;
}