CCCC团体程序设计天梯赛 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
手写小顶堆,有关数据结构的模拟题。小顶堆就是一棵特殊完全二叉树,满足所有非叶子节点的权值不大于其子节点权值。手写小顶堆后,判断两个数在二叉树上的关系,详细看代码。calc函数是获取关系字符串的数值。
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const ll inf = 1e18;
const int INF = 0x3f3f3f3f;
const int N = 1e6 + 10;
int n, m, c;
int h[N], cnt;
unordered_map<int, int> ump;
int calc(int sta, string s)
{
int num = 0;
int nm = 1;
if (s[sta] == '-') sta ++, nm = -1;
for (int i = sta; i < s.size(); i ++)
if (s[i] == ' ') break;
else num = num * 10 + s[i] - '0', c = i;
return num * nm;
}
void up(int u)
{
while (u / 2 && h[u / 2] > h[u]) {
swap(h[u], h[u / 2]);
u >>= 1;
}
}
void solve()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++) {
cin >> h[i];
up(i);
}
for (int i = 1; i <= n; i ++) ump[h[i]] = i;
getchar();
while (m --) {
string s;
getline(cin, s);
int num = calc(0, s);
if (s.back() == 't') {
if (h[1] == num) cout << 'T' << '\n';
else cout << 'F' << '\n';
}
else if (s.back() == 's') {
int num2 = calc(c + 6, s);
int x = ump[num], y = ump[num2];
if (x / 2 == y / 2) cout << 'T' << '\n';
else cout << 'F' << '\n';
}
else {
if (s[c + 5] == 't') {
int num2 = calc(c + 19, s);
if (ump[num2] / 2 == ump[num]) cout << 'T' << '\n';
else cout << 'F' << '\n';
}
else {
int num2 = calc(c + 16, s);
if (ump[num2] == ump[num] / 2) cout << 'T' << '\n';
else cout << 'F' << '\n';
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int T = 1;
while (T --) solve();
return 0;
}

浙公网安备 33010602011771号