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
结尾无空行
题目分析:前两天刚刚复习y总的堆,就做到了,构建大根堆(主要使用up来调整),并用map存储一个数字对应的下标,后面的string真的头疼,调试调了半个多小时…string真的难度不大,侮辱性极高…
代码实现:
//1. 建树(调整up),并且给每个数一个下标index,可以使用map存储
//2. 根据信息填1/0
#include<iostream>
#include<vector>
#include<map>
#include<iostream>
using namespace std;
int n, m;
vector<int> v, res;
map<int, int> mapp;
void up(int i){
while(i / 2 && v[i / 2] < v[i]){//父亲比孩子小,调整
swap(mapp[v[i]], mapp[v[i / 2]]);
swap(v[i], v[i / 2]);
i /= 2;
}
}
int main(){
scanf("%d%d", &n, &m);
v.resize(n + 1);
res.resize(m);
for(int i = 1; i <= n; i ++){
scanf("%d", &v[i]);
mapp[v[i]] = i;
up(i);
}
getchar();
string temp;
for(int i = 0; i < m; i ++){
int x, y = 0;
cin >> x;
getline(cin, temp);
if(temp.find("root") < temp.size()){
if(mapp[x] == 1) res[i] = 1;
}else if(temp.find("and") < temp.size()){
int y = stoi(temp.substr(temp.find("and") + 4, temp.find(" are silings")));
if(mapp[y] / 2 == mapp[x] / 2){
res[i] = 1;
}
}else{
int y = stoi(temp.substr(temp.find("of") + 3));
int xindex = mapp[x], yindex = mapp[y];
if(temp.find("parent") < temp.size()){
if(yindex / 2 == xindex){
res[i] = 1;
}
}else if(temp.find("left") < temp.size()){
if(xindex == yindex * 2){
res[i] = 1;
}
}else{
if(xindex == yindex * 2 + 1){
res[i] = 1;
}
}
}
}
for(int i = 0; i < res.size(); i ++){
cout << res[i];
}
return 0;
}