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
分析:根据输入依次在堆中插入元素建立小顶堆,因为判断元素间关系需要用位置做判断,因此通过 unordered_map
记录每个元素的数组中的序号,在接收到命题之后直接取出元素对应的位置 pos
就行了。
#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;
}
分类:
刷题笔记: PTA
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
2020-04-22 OJ中的语言选项里G++ 与 C++的区别
2020-04-22 如何在CSDN上如何快速转载博客
2020-04-22 #2035:人见人爱A^B
2020-04-22 #2030:汉字统计--统计给定文本文件中汉字的个数
2020-04-22 #2028:Lowest Common Multiple Plus(n个数的最小公倍数)