PAT

PAT

**

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

**


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

#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;
} 

发布者:admin,转转请注明出处:http://www.yc00.com/news/1687655502a28661.html

相关推荐

  • PAT

    2023-6-25
    140
  • PAT中段错误的原因及解决方法

    PAT中段错误的原因及解决方法 文章目录PAT中段错误的原因及解决方法一.查找方法二.可能原因1.越界访问2.大数组一定要开全局&#xff0c;而不是写在main函数里面。3.sort函数使用错误一.查找方法 段错误⼀般是由数组越

    1月前
    150

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信