天梯赛&&HBU训练营——关于堆的判断 (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

理解完全二叉树(堆)中父结点和子结点编号之间的关系,无论是左孩子还是右孩子,编号/2就是父结点,所以可以根据结点编号进行判断,根据小顶堆的特性,边判断边插入边调整,堆中采用下标(编号)从1开始,这样符合父结点和子结点编号之间的/2关系,便于判断。关于判断是哪一个命题,需要分批次输入子串,通过命题之间的不同子串或字符,从而确定命题
#include <iostream>
#include <string> 
#include <map> 
using namespace std;

int h[1005];
int n,m;

void swap(int x,int y){
	int temp = h[x];
	h[x] = h[y];
	h[y] = temp;
}

//建立小顶堆 
void heap(){
	for(int i = 1;i<=n;i++){
		cin >> h[i];
		int k = i;
		while(k/2>0&&h[k]<h[k/2]){
			swap(k,k/2);
			k /= 2;
		}
	}
}

int main(){	
	int a,b;
	cin >> n >> m;
	map<int,int> mm;
	string s1,s2,s;
	heap();
	for(int i = 1;i<=n;i++){
		mm[h[i]] = i;//值与下标相对应 
	}
	for(int i = 0;i<m;i++){
		cin >> a >> s1;
		if(s1=="and"){
			cin >> b;
			getline(cin,s);
			if(mm[a]/2==mm[b]/2)//是否是兄弟结点
				cout << "T" << endl;
			else
				cout << "F" << endl;
		}else{
			cin >> s2 >> s;
			if(s=="root"){//是否是根结点
				if(mm[a]==1)
					cout << "T" << endl;
				else
					cout << "F" << endl; 
			}else if(s=="parent"){
				cin >> s >> b;
				if(mm[a]!=mm[b]/2)//是否是父结点
					cout << "F" << endl;
				else
					cout << "T" << endl;
			}else{
				cin >> s >> b;
				if(mm[a]/2==mm[b])//是否是子结点
					cout << "T" << endl;
				else
					cout << "F" << endl;
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45845039/article/details/107901307