输入:
5 4
46 23 26 24 10
24 is the root
26 and 23 are siblings
46 is the parent of 23
23 is a child of 10
输出:
F
T
F
T
小顶堆(任意一个节点,它的左子树与右子树上的节点都大于该节点)的建立:每输入一个数,把这个数与它的父节点比较,如果这个值比父节点小的话就交换,再将交换后的父节点与父节点的父节点比较,以此类推;如果某个节点的值大于父节点的值就结束查找。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <sstream>
#define ll long long
#define lowbit(x) ((~x+1)&x)
#define inf 0x3f3f3f3f
using namespace std;
int h[1005],cnt;
void creat(int val) {
h[++cnt] = val;
int r=cnt,l=cnt/2;
while(r>1) {
if(h[r]<h[l]) {
swap(h[l],h[r]);
r=l;
l=r/2;
}
else break;
}
}
int cal(string s) {
int h_top=0,base=1;
for(int i=s.size()-1; i>=0; i--) {
if(s[i]>='0'&&s[i]<='9') {
h_top+=(s[i]-'0')*base;
base*=10;
}
}
if(s[0]=='-') return -h_top;
else return h_top;
}
int main() {
int n,m;
cin>>n>>m;
for(int i=1; i<=n; i++) {
int k;
cin>>k;
creat(k);
}
cin.ignore();
while(m--) {
string str;
vector<string>p;
getline(cin,str);
stringstream ss;
ss<<str;
while(ss>>str) {
p.push_back(str);
}
if(p[3]=="root") {
int top = h[1];
int h_top=cal(p[0]);
int base=1;
if(h_top==top) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
else if(p[1]=="and") {
int one = cal(p[0]),two=cal(p[2]);
int pos_one,pos_two;
for(int i=1; i<=n; i++) {
if(h[i]==one) {
pos_one = i;
}
else if(h[i]==two) {
pos_two = i;
}
}
if(pos_two/2==pos_one/2) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
else if(p[3]=="parent") {
int parent=cal(p[0]),child=cal(p[5]);
int pos_parent,pos_child;
for(int i=1; i<=n; i++) {
if(h[i]==parent) {
pos_parent=i;
}
else if(h[i]==child) {
pos_child = i;
}
}
if(pos_child/2==pos_parent) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
else if(p[3]=="child") {
int child=cal(p[0]),parent=cal(p[5]);
int pos_child,pos_parent;
for(int i=1; i<=n; i++) {
if(h[i]==child) {
pos_child = i;
}
else if(h[i]==parent) {
pos_parent = i;
}
}
if(pos_child/2==pos_parent) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
}
return 0;
}