L2-012 关于堆的判断 (25 分)
将一系列给定数字顺序插入一个初始为空的小顶堆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;
const static int INF=10005;
struct Heap
{
int size;
vector<int> Elem;
Heap()
{
size = 0;
Elem.push_back(-INF); //哨兵
}
void insert(int val)
{
Elem.push_back(val);
size++;
int child = size;
int parent = child/2;
while(Elem[child] < Elem[parent])
{
swap(Elem[child], Elem[parent]);
child = parent;
parent = parent/2;
}
}
int top()
{
if(size > 0)
return Elem[1];
return Elem[0];
}
int getIndex(int val)
{
for(int i=1;i<=size;i++)
{
if(val == Elem[i])
return i;
}
return 0;
}
int getFather(int val)
{
int p = getIndex(val) / 2;
if(p >= 1 && p <= size)
return Elem[p];
return Elem[0];
}
};
vector<string> split(const string &str, const char &c) //分割字符串
{
string buff;
vector<string> vec;
for(auto n:str)
{
if(n == c && buff != "")
{
vec.push_back(buff);
buff = "";
}
else
buff += n;
}
if(buff != "")
vec.push_back(buff);
return vec;
}
int main()
{
int n, m;
cin >> n >> m;
Heap H;
int v;
for(int i=0;i<n;i++)
{
cin >> v;
H.insert(v);
}
string cmd;
int len, p1, p2;
for(int i=0;i<m;i++)
{
getline(cin, cmd);
while(cmd == "")
getline(cin, cmd);
vector<string> vstr = split(cmd, ' ');
len = vstr.size();
if(vstr[len-1] == "root")
{
p1 = atoi(vstr[0].c_str());
if(H.top() == p1 && H.top() != -INF)
cout << "T" << endl;
else
cout << "F" << endl;
}
else if(vstr[len-1] == "siblings")
{
p1 = atoi(vstr[0].c_str());
p2 = atoi(vstr[2].c_str());
if(H.getFather(p1) == H.getFather(p2) && H.getFather(p1) != -INF)
cout << "T" << endl;
else
cout << "F" << endl;
}
else if(vstr[3] == "parent")
{
p1 = atoi(vstr[0].c_str());
p2 = atoi(vstr[len-1].c_str());
if(H.getFather(p2) == p1 && p1 != -INF)
cout << "T" << endl;
else
cout << "F" << endl;
}
else
{
p1 = atoi(vstr[0].c_str());
p2 = atoi(vstr[len-1].c_str());
if(H.getFather(p1) == p2 && p2 != -INF)
cout << "T" << endl;
else
cout << "F" << endl;
}
}
return 0;
}