題目重述
將一系列給定數字順序插入一個初始爲空的小頂堆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
題解
構造最小堆,然後判斷即可,因爲我是從下標1開始輸出的 所以i的父親下標就是i/2。
C++ AC
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int heap[1005];
int n,m,x,y;
int find_loc(int value)
{
for(int i=1;i<=n;i++)
{
if(value==heap[i])
{
return i;
}
}
return -1;
}
int main()
{
string tmp="";
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>heap[i];
int t=i;
while(t>1&&heap[t]<heap[t/2])
{
swap(heap[t],heap[t/2]);
t/=2;
}
}
for(int i=0;i<m;i++)
{
cin>>x;
cin>>tmp;
if(tmp=="is")
{
cin>>tmp;
if(tmp=="the")
{
cin>>tmp;
if(tmp=="root")
{
cout<<((x==heap[1])? "T":"F")<<endl;
}
else
{
cin>>tmp;
cin>>y;
cout<<((find_loc(x)==find_loc(y)/2)? "T":"F")<<endl;
}
}
else
{
cin>>tmp;
cin>>tmp;
cin>>y;
//cout<<x<<":"<<y<<endl;
cout<<((find_loc(y)==find_loc(x)/2)? "T":"F")<<endl;
}
}
else
{
cin>>y;
cin.ignore();
getline(cin,tmp);
int lox=(find_loc(x))/2;
int loy=(find_loc(y))/2;
cout<<(lox==loy? "T":"F")<<endl;
}
}
return 0;
}