L2-012 关于堆的判断
题目
L2-012 关于堆的判断 (25 分)
将一系列给定数字顺序插入一个初始为空的小顶堆H[]。随后判断一系列相关命题是否为真。命题分下列几种:
x is the root:x是根结点;
x and y are siblings:x和y是兄弟结点;
x is the parent of y:x是y的父结点;
x is a child of y:x是y的一个子结点。
输入格式:
给出插入元素的个数、以及需要判断的命题数。
输出格式:
每个命题输出T或F。
输入样例:
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
#### 代码
```cpp
#include <bits/stdc++.h>
using namespace std;
int cnt;
int a[1005];
void build(int x) //建堆操作
{
int t=cnt;//cnt是全局变量,所以t并不是每次都是0
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;
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和y是兄弟结点
{
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是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是根结点
{
if(mp[x]==1) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
else //x是y的父结点
{
cin>>s>>y;
if(mp[x]==mp[y]/2) cout<<"T"<<endl;
else cout<<"F"<<endl;
}
}
}
}
}
return 0;
}