题目链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805064676261888
最小堆,是一种经过排序的完全二叉树,其中任一非终端节点的数据值均不大于其左孩子和右孩子节点的值。
#include <bits/stdc++.h>
using namespace std;
int cnt;
int a[1005];
void build(int x) //建堆操作
{
int t=cnt;
a[cnt]=x; //将值加入堆的底部
cnt++;
while(t>1&&(a[t/2]>a[t])) //不超过堆顶并且存在要换值的情况
{
a[t]=a[t/2]; //底部和顶部的值交换
a[t/2]=x; //底部和顶部的值交换
t=t/2; //继续向着顶部迭代
}
a[t]=x; //最后将x填入顶部
}
int main()
{
int n,m,x,y;
string s;
while(cin>>n>>m)
{
cnt=1;
for(int i=0;i<n;i++)
{
cin>>x;
build(x); //加入小顶堆
}
map<int,int>mp;
mp.clear();
for(int i=1;i<=n;i++) mp[a[i]]=i; //通过map将数值和它在堆中的位置对应起来
for(int i=0;i<m;i++)
{
cin>>x>>s;
if(s[0]=='a') //x and y are siblings
{
cin>>y; cin>>s; cin>>s;
if(mp[x]/2==mp[y]/2) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
else
{
cin>>s;
if(s[0]=='a') //x is a child of y
{
cin>>s; cin>>s; cin>>y;
if(mp[x]/2==mp[y]) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
else
{
cin>>s;
if(s[0]=='r') //x is the root
{
if(mp[x]==1) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
else //x is the parent of y
{
cin>>s>>y;
if(mp[x]==mp[y]/2) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
}
}
}
}
return 0;
}