首页 > 其他 > 详细

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

时间:2020-05-16 12:13:24      阅读:167      评论:0      收藏:0      [点我收藏+]

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

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

输入格式:

每组测试第1行包含2个正整数N≤ 1000)和M≤ 20),分别是插入元素的个数、以及需要判断的命题数。下一行给出区间[内的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

大顶堆:每个结点的值都大于或等于其左右孩子结点的值

小顶堆:每个结点的值都小于或等于其左右孩子结点的值

堆的四个主要用法:

1.make_heap(first,last,compare_function)范围--[first,last)

 若构建数组0-n的小顶堆,则make_heap(a,a+n,greater<int>());

2.pop_heap(first,last,compare_function) 

 不是真的把最大(最小)的元素从堆中弹出来。而是重新排序堆。它
把first和last交换,然后将[first,last-1)的数据再做成一个堆。

3.push_heap(first,last,compare_function) 

 push_heap()假设由[first,last-1)是一个有效的堆,然后,再把堆中的新元素加
进来,做成一个堆。-----对于此题来讲用push_heap和make_heap没什么区别,因为此题要求按序插入

默认的和用less<int>()一样的,建立的是大顶堆
建小顶堆则是greater<int>()
其实我们可以发现,所有的算法默认用的都是less<T>.sort函数也是的,默认是less<int>,得到的结果是升序。
重点就是:按序插入make_heap(a,a+i+1,greater<int>());
技术分享图片
#include<bits/stdc++.h>
using namespace std;
int a[1005],n,m;
int findd(int x){
    int i;
    for(i=0;i<n;i++){
        if(a[i]==x)return i;
    }
}
int main(){
    int i;
    cin>>n>>m;
    for(i=0;i<n;i++)cin>>a[i],make_heap(a,a+i+1,greater<int>());
    while(m--){
        char s[10];
        int t;
        scanf("%d %s",&t,s);
        string ss;
        if(s[0]==a&&s[1]==n&&s[2]==d){
            int tt;cin>>tt;
            getline(cin,ss);
            int k1=findd(t),k2=findd(tt);
            if(k2-k1==1&&k2%2==0||k1-k2==1&&k1%2==0)cout<<"T\n";
            else cout<<"F\n";
        }
        else{
            getline(cin,ss);
            if(ss.find("root")!=string::npos){
                if(t==a[0])cout<<"T\n";
                else cout<<"F\n";
            }
            else{
                for(i=0;i<ss.size();i++){
                    if(ss[i]==f)break;
                }
                string ab="";
                for(int j=i+2;j<ss.size();j++){
                    ab+=ss[j];
                }
                stringstream iii;
                iii<<ab;
                int a;iii>>a;
                if(ss.find("parent")!=string::npos){
                    int k1=findd(t),k2=findd(a);
                    if(k2==k1*2+1||k2==k1*2+2)cout<<"T\n";
                    else cout<<"F\n";
                }
                else{
                    int k1=findd(t),k2=findd(a);
                    if(k1==k2*2+1||k1==k2*2+2)cout<<"T\n";
                    else cout<<"F\n";
                }
            }
        }
    }
    return 0;
}
View Code

 

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

原文:https://www.cnblogs.com/ydw--/p/12582498.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!