团体程序设计天梯赛-练习集: 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
。
输入样例:
1 2 3 4 5 6
| 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
|
输出样例:
分析:根据输入依次在堆中插入元素建立小顶堆,因为判断元素间关系需要用位置做判断,因此通过 unordered_map
记录每个元素的数组中的序号,在接收到命题之后直接取出元素对应的位置 pos
就行了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include <bits/stdc++.h> using namespace std; vector<int> heap; int len = 0; void insert(int x) { int hole = ++len; for (; hole > 1 && heap[hole / 2] > x; hole /= 2) heap[hole] = move(heap[hole / 2]); heap[hole] = move(x); } int main() { int n, m, a, b; scanf("%d%d", &n, &m); heap.resize(n + 1); for (int i = 0; i < n; i++) { scanf("%d", &a); insert(a); } unordered_map<int, int> pos; for (int i = 1; i <= n; i++) pos[heap[i]] = i; char temp[10]; for (int i = 0; i < m; i++) { scanf("%d %s", &a, temp); if (strcmp(temp, "and") == 0) { scanf("%d %*s %*s", &b); printf("%c\n", pos[a] / 2 == pos[b] / 2 ? 'T' : 'F'); } else { scanf("%*s %s", temp); if (strcmp(temp, "root") == 0) printf("%c\n", a == heap[1] ? 'T' : 'F'); else { scanf("%*s %d", &b); if (strcmp(temp, "parent") == 0) printf("%c\n", pos[a] == pos[b] / 2 ? 'T' : 'F'); else printf("%c\n", pos[b] == pos[a] / 2 ? 'T' : 'F'); } } } return 0; }
|