pta L2-012 关于堆的判断(创建堆)

题目链接

最小堆,在创建的过程中有序,每次通过与父亲节点比较来把节点放到合适的位置,创建好了直接模拟就好了

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
#define fir first
#define sec second

int a[1010];

void solve(int n){//创建小顶堆
    int i = n;
    int x = a[n];
    int s = i>>1;//父亲节点
    while(i>1 && a[s]>x){//通过不停与父亲节点比较并交换,找到此节点的正确位置
        a[i]=a[s];
        i = s;
        s = i>>1;
    }
    a[i]=x;
}

int main()
{
    int n,m;
    cin>>n>>m;
    a[0]=0;
    for(int i = 1;i <= n;i++){
        cin>>a[i];
        solve(i);
    }
    map<int,int>mp;
    for(int i = 1;i<=n;i++){
        mp[a[i]]=i;
    }
    for(int i = 0;i < m;i++){
        int x,y;
        cin>>x;
        string s1,s2,s3,s4;
        cin>>s1;
        if(s1[0]=='a'){
            cin>>y>>s2>>s3;
            if(mp[x]>>1==mp[y]>>1) cout<<"T"<<endl;
            else cout<<"F"<<endl;
        }
        else{
            cin>>s2;
            if(s2[0]=='a'){
                cin>>s3>>s4>>y;
                if(mp[x]>>1==mp[y]) cout<<"T"<<endl;
                else cout<<"F"<<endl;
            }
            else{
                cin>>s3;
                if(s3[0]=='r'){
                    if(mp[x]==1) cout<<"T"<<endl;
                    else cout<<"F"<<endl;
                }
                else{
                    cin>>s4>>y;
                    if(mp[y]>>1==mp[x]) cout<<"T"<<endl;
                    else cout<<"F"<<endl;
                }
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42754600/article/details/88081653