training11.14

7-10 关于堆的判断 (25分)
 

题目:将一系列给定数字顺序插入一个初始为空的小顶堆H[]。随后判断一系列相关命题是否为真。命题分下列几种:

  • x is the rootx是根结点;
  • x and y are siblingsxy是兄弟结点;
  • x is the parent of yxy的父结点;
  • x is a child of yxy的一个子结点。

 

代码:

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cmath>
 5 #include<cstring>
 6 using namespace std;
 7 const int maxx=1e5+2;
 8 //角标之间的关系已经是知道的了 现在需要数根据已知角标和位置的关系进行补充
 9 //数之间的位置关系,找的时候也根据角标进行查找就行
10 int n;
11 int a[1500];
12 int find(int x){
13     for(int i=1;i<=n;i++){
14         if(a[i]==x){
15             return i;
16         }
17     }
18     return -1;
19 }
20 int main(){
21     int m;
22     scanf("%d %d",&n,&m);
23     for(int i=1;i<=n;i++){
24         scanf("%d",&a[i]);
25         int k=i;
26         while(k>1&&a[k/2]>a[k]){
27             swap(a[k/2],a[k]);
28             k/=2;
29         }
30     }
31     while(m--){
32         int num1;
33         scanf("%d",&num1);
34         string f1;
35         cin>>f1;
36         if(f1=="and"){
37             int num2;
38             scanf("%d",&num2);
39             string f2;
40             getline(cin,f2);
41             if(find(num1)/2==find(num2)/2){
42                 printf("T\n");
43             }else{
44                 printf("F\n");
45             }
46         }else{
47             string f2;
48             cin>>f2;
49             if(f2=="a"){
50                 string f3;
51                 string f4;
52                 int num2;
53                 cin>>f3;
54                 cin>>f4;
55                 cin>>num2;
56                 if(find(num1)/2==find(num2)){
57                     printf("T\n");
58                 }else{
59                     printf("F\n");
60                 }
61             }else{
62                 string f3;
63                 cin>>f3;
64                 if(f3=="root"){
65                     if(find(num1)==1){
66                         printf("T\n");
67                     }else{
68                         printf("F\n");
69                     }
70                 }else{
71                     string f4;
72                     cin>>f4;
73                     int num2;
74                     cin>>num2;
75                     if(find(num1)==find(num2)/2){
76                         printf("T\n");
77                     }else{
78                         printf("F\n");
79                     }
80                 }
81             }
82         }
83     }
84 }
View Code

 

思路:角标之间的关系已经是知道的了 现在需要数根据已知角标和位置的关系进行补充数之间的位置关系,找的时候也根据角标进行查找就行。每个数读入以后跟其所在位置根的数之间进行比较。保证根节点的数字是最小的,小于左右节点的数。

 

posted @ 2020-11-22 19:46  bonel  阅读(88)  评论(0)    收藏  举报