将一系列给定数字顺序插入一个初始为空的小顶堆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
这道题很简单,关键点在于如何确定输入中具体让干的是什么,由于采用cin输入是,每次只读一个单词,所以可以很方便处理该问题,scanf("%s")其实也可以,但是如果是采用这种方式输入到字符数组中的话,比较时需要用到strcmp()函数,较为麻烦,不如直接采用cin读入到字符串中,比较时可以直接采用=,极为方便。事实上sscanf也可以,具体做法这里不再赘述。
#include<iostream>
using namespace std;
int H[1005],size;
int find(int x);
int main()
{
int n,m;
cin>>n>>m;
H[0]=-999999;
for(int i=1;i<=n;i++)
{
int t,j=++size;
cin>>t;
for(;H[j/2]>t;j/=2)
{
H[j]=H[j/2];
}
H[j]=t;
}
for(int i=0;i<m;i++)
{
int x,y;
cin>>x;
string str;
cin>>str;
if(str=="and")
{
cin>>y>>str>>str;
if(find(x)!=0&&find(x)/2==find(y)/2)
cout<<"T\n";
else
cout<<"F\n";
}
else
{
cin>>str;
if(str=="a")
{
cin>>str>>str>>y;
if(find(x)!=0&&find(x)/2==find(y))
{
cout<<"T\n";
}
else
cout<<"F\n";
}
else
{
cin>>str;
if(str=="root")
{
if(find(x)==1)
cout<<"T\n";
else
cout<<"F\n";
}
else
{
cin>>str>>y;
if(find(y)&&find(y)/2==find(x))
cout<<"T\n";
else
cout<<"F\n";
}
}
}
}
}
int find(int x)
{
for(int i=1;i<=size;i++)
{
if(x==H[i])return i;
}
return 0;
}