L2-012 关于堆的判断 (25 分)

L2-012 关于堆的判断 (25 分)

题目链接

题意

在这里插入图片描述

思路

1.读入的数组转变为符合小顶堆规则的顺序,根据小顶堆数组下标规则判断是否正确

代码

#include<iostream>
#include<map>
using namespace std;
const int N=1e5+10;
int h[N],n,m,sz;
// 题目中没说所有的值都是唯一的
void down(int u){
    int t = u;
    if(u*2<=sz&&h[u*2]<h[t])t = u*2;
    if((u*2+1)<=sz&&h[u*2+1]<h[t])t = u*2+1;
    if(t!=u){
        swap(h[u],h[t]);
        down(t);
    }
}

void up(int u){
    while(u>1&&(h[u]<h[u/2])){
        swap(h[u],h[u/2]);
        u/=2;
    }
}

map<int,int>pos;

int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        int x;cin>>x;
        h[++sz]=x;
        up(sz);
    }
    
    for(int i=1;i<=n;i++){
        pos[h[i]]=i;
    }
    while(m--){
        int x;
        string s;cin>>x>>s;
        int posx=pos[x];
        if(s=="is"){
            cin>>s;
            int y;
            if(s=="a"){
                cin>>s>>s;
                cin>>y;
                int posy=pos[y];
                if(posx/2==posy){// x是y的子节点
                    cout<<"T"<<endl;
                }
                else{
                    cout<<"F"<<endl;
                }
            }
            else{
                cin>>s;
                if(s=="root"){
                    if(pos[x]==1){
                        cout<<"T"<<endl;
                    }
                    else{
                        cout<<"F"<<endl;
                    }
                }
                else if(s=="parent"){
                    cin>>s;
                    cin>>y;
                    int posy=pos[y];
                    if(pos[y]/2==pos[x]){
                        cout<<"T"<<endl;
                    }
                    else{
                        cout<<"F"<<endl;
                    }
                }
            }
        }
        else{//and 兄弟节点
            int y;cin>>y;
            getline(cin,s);
            int posy=pos[y];
            if(posx/2 == posy/2){
                cout<<"T"<<endl;
            }
            else{
                cout<<"F"<<endl;
            }
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值