題目如下:
L2-012. 關於堆的判斷
將一系列給定數字順序插入一個初始爲空的小頂堆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
但是需要記錄每個節點的下標,剛開始我用的數組來記錄,提交只過了一個案例,後來發現節點還可以是負數,這時就不能用數組來記
錄,於是換成了map,鍵爲節點數值,值爲下標,就可以了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
using namespace std;
int n, a[1005];
//建樹的 “模板”
void up( int son )
{
int t = a[son];
int tson = son;
while( (tson > 1)&&( a[tson/2] > t))
{
a[tson] = a[tson/2];
tson = tson/2;
}
a[tson] = t;
}
void charu( int t)
{
a[ ++n ] = t;
up( n );
}
int main ()
{
int k, m, x, y;;
map <int, int> index; //記錄下標
string s;
cin >> k >> m;
n=0;
//建樹
for(int i=0; i<k; i++)
{
cin >> x;
charu(x);
}
//給map賦值
for(int i=1; i<=n; i++)
{
index[a[i]] = i;
}
for(int i=0; i<m; i++)
{
cin >> x;
cin >> s;
int index_x = index[x];
int index_y;
if(s[0] == 'a')
{
cin >> y;
getline(cin, s); //這個函數可以輸入一個帶空格的字符串
index_y = index[y];
if(index_x/2 == index_y/2)
puts("T");
else
puts("F");
}
else
{
cin >> s;
cin >> s;
if(s[0] == 'r')
{
if(index_x == 1)
puts("T");
else
puts("F");
}
else if(s[0] == 'p')
{
cin >> s;
cin >> y;
index_y = index[y];
if(index_y/2 == index_x)
puts("T");
else
puts("F");
}
else
{
cin >> s;
cin >> y;
index_y = index[y];
if(index_x/2 == index_y)
puts("T");
else
puts("F");
}
}
}
return 0;
}