将一系列给定数字顺序插入一个初始为空的小顶堆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>
using namespace std;
//查找父节点位置
int parent(int n){
return (n-1)/2;
}
//创建小顶堆
void buildHeap(int n , int data[]){
for(int i= 1; i < n ; i++){
int t = i;
while( t != 0 && data[parent(t)] > data[t]){
int temp = data[t];
data[t] = data[parent(t)];
data[parent(t)] = temp;
t = parent(t);
}
}
}
//查找元素在数组中的位置
int search(int k,int a[],int n){
int i;
for(i=0;i<n;i++){
if(k == a[i]) break;
}
return i;
}
//定义判断语句中的数字元素
int num1,num2,num3,num4,num5,num6,num7;
int main()
{
// 输入
int n,m;
cin >> n >> m;
int a[10000] = {0};
for(int i=0;i<n;i++){
cin >> a[i];
}
// 创建
buildHeap(n,a);
string s[m];
cin.ignore();
for(int j=0;j<m;j++){
getline(cin,s[j]);
string str=s[j];
istringstream ss(str); //istringstream流来获取每一个单词
string s;
if(str.find("root")!=-1){
while(ss>>s){
num1 = atoi(s.c_str());//将数字字符串转为整型
break;
}
if(num1 == a[0]) cout << "T\n";//判断与0号元素是否相同
else cout << "F\n";
}
if(str.find("siblings")!=-1){
int x = 0;
while(ss>>s){
if(x==0) num2 = atoi(s.c_str());
if(x==2) num3 = atoi(s.c_str());
x++;
}
int id2 = search(num2,a,n);//查找位置
int id3 = search(num3,a,n);
if((a[id2-1]==num3||a[id2+1]==num3)&&(id2-1)/2==(id3-1)/2) cout << "T\n";//判断是否相邻且同父
else cout << "F\n";
}
if(str.find("parent")!=-1){
int x = 0;
while(ss>>s){
if(x==0) num4 = atoi(s.c_str());
if(x==5) num5 = atoi(s.c_str());
x++;
}
int id4 = search(num4,a,n);
if(a[2*(id4)+1]==num5||a[2*(id4)+2]==num5) cout << "T\n";//判断父子
else cout << "F\n";
}
if(str.find("child")!=-1){
int x = 0;
while(ss>>s){
if(x==0) num6 = atoi(s.c_str());
if(x==5) num7 = atoi(s.c_str());
x++;
}
int id7 = search(num7,a,n);
if(a[2*(id7)+1]==num6||a[2*(id7)+2]==num6) cout << "T\n";//判断父子
else cout << "F\n";
}
}
return 0;
}