L2-012. 关于堆的判断
2017-03-15 14:24
375 查看
本题要求:
将一系列给定数字顺序插入一个初始为空的小顶堆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
解题思路 :
建造小根堆时要注意,边插入边建堆,不能读完后统一建堆。
代码 :
#include<iostream> #include<queue> #include<string> #include<cstring> #include<algorithm> using namespace std; int r[1002]; int n, m; void creatHeep(int m, int n) { int i, j, flag; i = m; j = 2 * i; r[0] = r[i]; flag = 0; while (j <= n && flag != 1) { if (j < n && r[j] > r[j + 1]) { j++; } if (r[0] < r[j]) { flag = 1; } else { r[i] = r[j]; i = j; j = 2 * i; r[i] = r[0]; } } } void heepSort(int n) { int i; for (i = n / 2; i >= 1; i--) { creatHeep(i, n); } } int getN(int k) { for (int i = 1; i <= n; i++) { if (r[i] == k) { return i; } } return 0; } int main() { cin >> n >> m; for(int i = 1; i <= n; i++) { cin >> r[i]; heepSort(i); } for (int i = 0; i < m; i++) { int num; cin >> num; string str; cin >> str; if (str == "and") { int num2; cin >> num2; if (getN(num) /2 == getN(num2) / 2) { cout << "T" << endl; } else { cout << "F" << endl; } getline(cin, str); } else { cin >> str; cin >> str; if (str == "root") { if (getN(num) == 1) { cout << "T" << endl; } else { cout << "F" << endl; } } else if (str == "parent") { int num2; cin >> str; cin >> num2; if (getN(num2) / 2 == getN(num)) { cout << "T" << endl; } else { cout << "F" << endl; } } else { int num2; cin >> str; cin >> num2; if (getN(num) / 2 == getN(num2)) { cout << "T" << endl; } else { cout << "F" << endl; } } } } return 0; }
相关文章推荐
- PAT L2-012. 关于堆的判断【数据结构】
- 团体程序设计天梯赛-练习集 L2-012. 关于堆的判断
- L2-012. 关于堆的判断
- L2-012. 关于堆的判断
- L2-012. 关于堆的判断
- L2-012. 关于堆的判断
- L2-012. 关于堆的判断
- L2-012 关于堆的判断
- PAT L2-012. 关于堆的判断
- 团体程序设计天梯赛-练习集 -- L2-012. 关于堆的判断(最小堆)
- PAT L2-012. 关于堆的判断(堆)
- 团体程序设计天梯赛L2-012 关于堆的判断
- L2-012. 关于堆的判断-PAT团体程序设计天梯赛GPLT
- L2-012. 关于堆的判断
- L2-012. 关于堆的判断
- PAT L2-012. 关于堆的判断(最小堆调整)
- L2-012. 关于堆的判断-PAT甲级真题(堆的建立,向上调整)
- L2-012. 关于堆的判断 (堆操作)
- L2-012. 关于堆的判断
- L2-012. 关于堆的判断 (小顶堆)