In computer science, a max-heap is a specialized tree-based data structure that satisfies the heap property: if P is a parent node of C, then the key (the value) of P is greater than or equal to the key of C. A common implementation of a heap is the binary heap, in which the tree is a complete binary tree.
Your job is to first insert a given sequence of integers into an initially empty max-heap, then to judge if a given description of the resulting heap structure is correct or not. There are 5 different kinds of description statements:
x is the root
x and y are siblings
x is the parent of y
x is the left child of y
x is the right child of y
Input Specification:
Each input file contains one test case. For each case, the first line gives 2 positive integers: N (≤1,000), the number of keys to be inserted, and M (≤20), the number of statements to be judged. Then the next line contains N distinct integer keys in [−104,104] which are supposed to be inserted into an initially empty max-heap. Finally there are M lines of statements, each occupies a line.
Output Specification:
For each statement, print 1
if it is true, or 0
if not. All the answers must be print in one line, without any space.
Sample Input:
5 6
23 46 26 35 88
35 is the root
46 and 26 are siblings
88 is the parent of 46
35 is the left child of 26
35 is the right child of 46
-1 is the root
Sample Output:
011010
#include<iostream>
#include<unordered_map>
#include<algorithm>
using namespace std;
const int N = 1010;
int n,m,v[N];
unordered_map<int,int> r,l,depth,p;
void dfs(int root,int k,int d){
depth[root] = d;
if(2*k<=n) l[root] = v[2*k],p[l[root]] = root,dfs(l[root],2*k,d+1);
if(2*k+1<=n) r[root] = v[2*k+1],p[r[root]] = root,dfs(r[root],2*k+1,d+1);
}
void up(int u){
if(u/2&&v[u/2]<v[u]){
swap(v[u],v[u/2]);
up(u/2);
}
}
int main(){
scanf("%d %d",&n,&m);
for(int i = 1;i<=n;i++){
cin>>v[i];
up(i);
}
int root = v[1];
dfs(root,1,0);
getchar();
while(m--){
int suc = 0;
string s;getline(cin,s);
if(s.find("root")!=-1){
int a;
sscanf(s.c_str(),"%d is the root",&a);
if(a==root)suc = 1;
else suc = 0;
}
if(s.find("siblings")!=-1){
int a,b;
sscanf(s.c_str(),"%d and %d are siblings",&a,&b);
if(a!=b&&p[a]==p[b])suc = 1;
else suc = 0;
}
if(s.find("parent")!=-1){
int a,b;
sscanf(s.c_str(),"%d is the parent of %d",&a,&b);
if(p[b]==a)suc = 1;
else suc = 0;
}
if(s.find("left")!=-1){
int a,b;
sscanf(s.c_str(),"%d is the left child of %d",&a,&b);
if(l[b]==a)suc = 1;
else suc = 0;
}
if(s.find("right")!=-1){
int a,b;
sscanf(s.c_str(),"%d is the right child of %d",&a,&b);
if(r[b]==a)suc = 1;
else suc = 0;
}
cout<<suc;
}
}