GPLT L2-012 关于堆的判断(二叉堆)
题目链接: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 的一个子结点。
思路
模拟。
代码
#include <bits/stdc++.h> #define lc(i) H[idx[i] * 2] #define rc(i) H[idx[i] * 2 + 1] #define par(i) H[idx[i] / 2] #define Print(i) cout << (i ? 'T' : 'F') << "\n" using namespace std; int H[1010]; map<int, int> idx; void upAdjust(int i) { while (i != 1 && H[i] < H[i / 2]) { swap(H[i], H[i / 2]); i /= 2; } } int main() { int n, k; cin >> n >> k; for (int i = 1; i <= n; i++) { cin >> H[i]; upAdjust(i); } for (int i = 1; i <= n; i++) { idx[H[i]] = i; } for (int i = 0; i < k; i++) { int x, y; string str; cin >> x >> str; if (str == "and") {//2 cin >> y >> str >> str; Print(par(x) == par(y)); } else { cin >> str; if (str == "a") {//4 cin >> str >> str >> y; Print(par(x) == y); } else { cin >> str; if (str == "root") {//1 Print(H[1] == x); } else {//3 cin >> str >> y; Print(lc(x) == y || rc(x) == y); } } } } }
参考了: 柳婼 的博客。

浙公网安备 33010602011771号