将一系列给定数字顺序插入一个初始为空的小顶堆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的一个子结点。
输入格式:
每组测试第1行包含2个正整数N(≤ 1000)和M(≤ 20),分别是插入元素的个数、以及需要判断的命题数。下一行给出区间[−10000,10000]内的N个要被插入一个初始为空的小顶堆的整数。之后M行,每行给出一个命题。题目保证命题中的结点键值都是存在的。
输出格式:
对输入的每个命题,如果其为真,则在一行中输出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
- 从空堆开始建,明显是一个完全二叉树
- 小顶堆(大顶堆)根节点<= (>=)子节点
#include <bits/stdc++.h>
#define lll __int128_t
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int N=1e4+5;
int n,m,a[N],cnt;
void creat(int x)
{
a[++cnt]=x;//inx从一开始
int t=cnt;
while(t>1&&a[t/2]>a[t])
{
a[t]=a[t/2];
a[t/2]=x;
t/=2;
}
}
int main()
{
// freopen("D:\\LYJ.txt","r",stdin);
cin>>n>>m;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
creat(x);
}
map<int,int> p;
string s;
for(int i=1;i<=n;i++) p[a[i]]=i;
while(m--)
{
int x=0,y=0;
cin>>x>>s;
if(s[0]=='a')//x and y are siblings
{
cin>>y;
getline(cin,s);
if(p[x]/2==p[y]/2) puts("T");
else puts("F");
}else{
// x is the root
// x is the parent of y
// x is a child of y
cin>>s;
if(s[0]=='t'){
cin>>s;
if(s[0]=='r'){// x is the root
if(p[x]==1) puts("T");
else puts("F");
}else{// x is the parent of y
cin>>s>>y;
if(p[x]==p[y]/2) puts("T");
else puts("F");
}
}else if(s[0]=='a'){// x is a child of y
cin>>s;
cin>>s>>y;
if(p[x]/2==p[y]) puts("T");
else puts("F");
}
}
}
return 0;
}
版权声明:本文为qq_44461900原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。