PTA天梯赛 关于堆的判断| 小根堆

思路

1.偷个懒,用库函数建小根堆 push_heap(heap+1,heap+sizes+1,greater());
2.用得到的小根堆数组建树,并在建树的过程中,用map标记维护father、siblings结点。因为会出现负数结点值,所以这里选择用map标记
3.解析查询语句,用getline(cin,string)读入一整行,根据不同查询语句来实现各功能,自己编写了一个get(num)函数,取得字符串第num个整数;

代码

#include<bits/stdc++.h>
using namespace std;

const int maxn = 11100;
int n,d,m;
int heap[maxn],sizes;
map<int,int> father;
map<int,int> sibling;

//1.偷个懒,用库函数建小根堆 push_heap(heap+1,heap+sizes+1,greater<int>()); 
void put(int d){
	heap[++sizes]=d;
	push_heap(heap+1,heap+sizes+1,greater<int>());
}

struct node{
	int v;
	node *l,*r;
};

//2.用得到的小根堆数组建树,并在建树的过程中,用map标记维护father、siblings结点 
node * build(int pos){
	if(pos > sizes) return NULL;
	node *root = new node();
	root->v = heap[pos];
	root->l = NULL,root->r = NULL;
	root->l = build(pos*2);
	root->r = build(pos*2+1);
	if(root->l != NULL){
		father[root->l->v] = root->v; 
	}
	if(root->r != NULL){
		father[root->r->v] = root->v;
	}
	if(root->l != NULL && root->r != NULL){
		sibling[root->l->v] = root->r->v;
		sibling[root->r->v] = root->l->v;
	}
	return root;
}

//自己编写了一个get(num)函数,取得字符串第num个整数; 
int get(string sql,int num){
	int len = sql.length();
	int u = 0,v = 0,pos = 0;
	bool flag1 = false, flag2 = false;
	while(pos < len && sql[pos] <'0' || sql[pos] > '9') {
		if(sql[pos] == '-') flag1 = true;
		pos++;
	}
	while(pos < len && sql[pos] >= '0' && sql[pos] <= '9'){
		u = u * 10 + (sql[pos++] - '0');
	}
	if(num == 1) return flag1 ? -u : u;
	while(pos < len && sql[pos] <'0' || sql[pos] > '9') {
		if(sql[pos] == '-') flag2 = true;
		pos++;
	}
	while(pos < len && sql[pos] >= '0' && sql[pos] <= '9'){
		v = v * 10 + (sql[pos++] - '0');
	}
	return flag2 ? -v: v;
}
 
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		cin>>d;
		put(d);
	}
	node *Root = new node();
	Root = build(1);
	father[Root->v] = -2;
	string s;
	getline(cin,s);
        //3.解析查询语句,根据不同查询语句来实现各功能 
	for(int i=1;i<=m;i++){
		string sql;
		getline(cin,sql);
		if(sql.find("root") != string::npos){
			int root = 0,pos = 0;
			root = get(sql,1);
			if(Root->v == root) puts("T");
			else puts("F");
		}else if(sql.find("siblings") != string::npos){
			int u = get(sql,1);
			int v = get(sql,2);
			if(sibling[u] != 0 && sibling[v] != 0 && sibling[u] == v && sibling[v] == u){
				puts("T");
			}else puts("F");
		}else if(sql.find("parent") != string::npos){
			int u = get(sql,1);
			int v = get(sql,2);
			if(father[v] == u) puts("T");
			else puts("F");
		}else{
			int u = get(sql,1);
			int v = get(sql,2);
			if(father[u] == v) puts("T");
			else puts("F");
		}
	}
	return 0;
}

/*
5 4
46 23 26 24 10
46 is the root
26 and 23 are siblings
46 is the parent of 23
23 is a child of 10
*/
posted @ 2020-04-02 22:54  fishers  阅读(301)  评论(0编辑  收藏  举报