将一系列给定数字顺序插入一个初始为空的小顶堆H[]。随后判断一系列相关命题是否为真。命题分下列几种:

  • x is the rootx是根结点;
  • x and y are siblingsxy是兄弟结点;
  • x is the parent of yxy的父结点;
  • x is a child of yxy的一个子结点。

输入格式:

每组测试第1行包含2个正整数N(≤ 1000)和M(≤ 20),分别是插入元素的个数、以及需要判断的命题数。下一行给出区间[−10000,10000]内的N个要被插入一个初始为空的小顶堆的整数。之后M行,每行给出一个命题。题目保证命题中的结点键值都是存在的。

输出格式:

对输入的每个命题,如果其为真,则在一行中输出T,否则输出F

输入样例:

1
2
3
4
5
6
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

输出样例:

1
2
3
4
F
T
F
T

解题思路

题目描述的很清楚了,给出一个入队顺序来维护一个小顶堆。
复习一下:小顶堆就是一个完全二叉树,它满足任何一个节点的子节点都小于该节点。
那么小顶堆具有什么性质呢?完全二叉树——可以直接用一维数组来存,我设根节点下标为1,那么所有子节点的下标除以2都是父节点的下标。
小顶堆的维护是从底向上的,先将新的数插入当前堆的最后一个位置,然后不断与父节点比较,若小于父节点,则交换。
这样我们可以得到这个小顶堆。
但是询问里问的是,2个元素之间的关系,所以要先存下每个元素对应的小顶堆下标,遍历一遍小顶堆,用map存就好了
然后根据小顶堆的性质来处理每次询问。由于询问的字符串不复杂,有严格的格式,所以这题不涉及到字符串的处理,也不需要处理换行符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>

using namespace std;

const int N=1010;

int tree[N];//从1开始的完全二叉树
int n,m;
map<int,int>s;

int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
tree[i]=x;
int t=i;
while(t>1&&tree[t]<tree[t>>1])
{
swap(tree[t],tree[t>>1]);
t>>=1;
}
tree[t]=x;
}

for(int i=1;i<=n;i++)s[tree[i]]=i;

while(m--)
{
int x,y;
char str[50];
scanf("%d%s",&x,&str);
if(str[0]=='a')//x and y are siblings
{
scanf("%d%s%s",&y,&str,&str);
if(s[x]>>1==s[y]>>1)printf("T\n");else printf("F\n");
}
else
{
scanf("%s",&str);
if(str[0]=='a')//x is a child of y
{
scanf("%s%s%d",&str,&str,&y);
if(s[x]>>1==s[y])printf("T\n");else printf("F\n");
}
else
{
scanf("%s",&str);
if(str[0]=='r')//x is the root
{
if(s[x]==1)printf("T\n");else printf("F\n");
}
else//x is the parent of y
{
scanf("%s%d",&str,&y);
if(s[y]>>1==s[x])printf("T\n");else printf("F\n");
}
}
}
}
return 0;
}