题目描述
将一系列给定数字顺序插入一个初始为空的小顶堆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,对于任意节点编号为 x 的节点,(此时为左右子节点均有的状态)。
现在我们有一棵小根堆,若要向堆中添加节点 x,首先我们先在层序遍历的最后一个节点后开辟一个新的节点,然后使用 up 操作:
void up(int u)
{
while (u / 2 && h[u] < h[u / 2])
{
h_swap(u, u / 2);
u /= 2;
}
}
即由当前节点向上依次与值更大的节点交换。
注意新开一个数组将值与下标对应起来,由于数值区间存在负数,需要添加偏移量。
Accept代码
#include <bits/stdc++.h>
using namespace std;
const int N = 20010, eps = 10010;
int n, m;
int h[N], ph[N];
void h_swap(int x, int y)
{
swap(h[x], h[y]);
swap(ph[h[x]], ph[h[y]]);
}
void up(int u)
{
while (u / 2 && h[u] < h[u / 2])
{
h_swap(u, u / 2);
u /= 2;
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++)
{
cin >> h[i];
h[i] += eps;
ph[h[i]] = i;
up(i);
}
string s1, s2, s3, s4;
int x, y;
while (m --)
{
cin >> x >> s1;
x += eps;
if (s1[0] == 'a')
{
cin >> y >> s2 >> s3;
y += eps;
if (ph[x] / 2 == ph[y] / 2) cout << "T" << "\n";
else cout << "F" << "\n";
}
else
{
cin >> s2;
if (s2[0] == 'a')
{
cin >> s3 >> s4 >> y;
y += eps;
if (ph[x] / 2 == ph[y]) cout << "T" << "\n";
else cout << "F" << "\n";
}
else
{
cin >> s3;
if (s3[0] == 'r')
{
if (ph[x] == 1) cout << "T" << "\n";
else cout << "F" << "\n";
}
else
{
cin >> s4 >> y;
y += eps;
if (ph[x] == ph[y] / 2) cout << "T" << "\n";
else cout << "F" << "\n";
}
}
}
}
return 0;
}