PAT-2021年春季考试-甲级

**

PAT-2021年春季考试-甲级 7-3 structure of max-heap

**

在这里插入图片描述
对我个人来说,这道题的难点在于没能利用sscanf 以及 cin.get() 函数进行提问内容的读取 ,以至于虽然数据处理好了但是却没能针对提问进行回答。还有一些小细节需要注意!
本题思路参考https://blog.csdn.net/Exupery_/article/details/114754481

#include<iostream>
#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
int node[1002];
int cnt = 1;
//建立堆的过程
void insert(int x){
	int i = cnt;
	node[cnt] = x;
	while(i/2>=1){
		if(node[i] > node[i/2]){
			swap(node[i], node[i/2]);
		}
		i /= 2;//第一次写的时候忘记对i进行/2,结果一直无限循环
	}
	cnt++;
}
int find_x(int x){//查找x的位置(从1~n)
	for(int i = 0; i < 1002; i++ ){
		if(node[i] == x) return i;
	}
	return -1;//如果不存在,返回-1
}
int main(){
	int n,m;
	cin>>n>>m;
	for(int i =0;i <n; i++){
		int temp;
		cin>>temp;
		insert(temp);
	}
	cin.get();//这个地方是为了将回车字符吸收 
	for(int i = 0; i < m; i++){
		string str;
		bool result  = false;
		//!!!!!!!!!!!!!!!!!!!!!!!!! 
		getline(cin,str);//getline是以“/n”为结束符
		if(str.back() == 't'){
			int y;
			sscanf(str.c_str(), "%d is the root", &y);//!!sscanf是很重要的一个函数  头文件是#include<cstdio>
			int pos = find_x(y); 
			if(pos == node[1]&& pos!= -1) result = true;
		} 
		else if(str.back() == 's'){
			int x, y;
			sscanf(str.c_str(), "%d and %d are siblings", &x,&y);
			int posx = find_x(x);
			int posy = find_x(y);
			if(posx != -1 && posy != -1 && posx /2 == posy /2) result = true;//!!!!!!!!!!!!!!!!!!!!!!!!! 
		}
		else if(str.find("parent") != string::npos){//!!!!!!!!!!!!!!!!!!!!!!!!! 
			int x,y;
			sscanf(str.c_str(), "%d is the parent of %d", &x,&y);
			int posx = find_x(x);
			int posy = find_x(y);
			if(posx != -1 && posy != -1 && posy / 2 == posx) result = true;
		}else if(str.find("left") != string::npos){
			int x,y;
			sscanf(str.c_str(), "%d is the left child of %d", &x,&y);
			int posx = find_x(x);
			int posy = find_x(y);
			if(posx != -1 && posy != -1 && posx == posy*2) result = true;
		}
		else{
			int x,y;
			sscanf(str.c_str(), "%d is the right child of %d", &x,&y);
			int posx = find_x(x);
			int posy = find_x(y);
			if(posx != -1 && posy != -1 && posx == posy*2+1) result = true;
		}
		
		if(result) cout<<1;
		else cout<<0;
	}
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值