补题(堆数组模拟)

839. 模拟堆 - AcWing题库

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1e5+10;
int a[N];
int idx;
int hp[N];//维护idx与ph之间的查找关系
int ph[N];
int heap[N];//数组的每个数值大小
int L;

void heap_swap(int a,int b){
    swap(ph[hp[a]], ph[hp[b]]);
    swap(hp[a], hp[b]);
    swap(heap[a],heap[b]);
}
void down(int u){
    int t = u;
    if(2*u <= L && heap[2*u] < heap[t]) t = 2*u;
    if(2*u + 1 <= L&& heap[2*u + 1] < heap[t])t = 2*u + 1;
    if(u != t){
        heap_swap(u,t);
        down(t);
    }
}

void up(int u){
    while(u/2 && heap[u/2] > heap[u])
    {
        heap_swap(u/2,u);
        u/=2;
    }
}

int main(){
    int n;
    cin>>n;

    while(n--){
        int k,x;
        char op[10];
        cin>>op;
        if(!strcmp(op, "I")){
            cin>>x;
            L++;
            idx++;
            ph[idx] = L,hp[L] = idx;
            heap[L] = x;
            up(L);
        }else if(!strcmp(op, "PM"))cout<<heap[1]<<endl;
        else if(!strcmp(op, "DM")){
            heap_swap(1,L);
            L--;
            down(1);
        }else if(!strcmp(op, "D")){
            cin>>k;
            k = ph[k];
            heap_swap(k,L);
            L--;
            down(k),up(k);
        }else{
            cin>>k>>x;
            k = ph[k];
            heap[k] = x;
            down(k),up(k);
        }
    }
    return 0;
}

改成vector

#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
int a[N];
int idx;
vector<int> hp,ph,heap;
int L;

void heap_swap(int a,int b){
    swap(ph[hp[a]], ph[hp[b]]);
    swap(hp[a], hp[b]);
    swap(heap[a],heap[b]);
}
void down(int u){
    int t = u;
    if(2*u <= L && heap[2*u] < heap[t]) t = 2*u;
    if(2*u + 1 <= L&& heap[2*u + 1] < heap[t])t = 2*u + 1;
    if(u != t){
        heap_swap(u,t);
        down(t);
    }
}

void up(int u){
    while(u/2 && heap[u/2] > heap[u])
    {
        heap_swap(u/2,u);
        u/=2;
    }
}

int main(){
    int n;
    cin>>n;
    hp.resize(n+1);
    ph.resize(n+1);
    heap.resize(n+1);
    while(n--){
        int k,x;
        char op[10];
        cin>>op;
        if(!strcmp(op, "I")){
            cin>>x;
            L++;
            idx++;
            ph[idx] = L,hp[L] = idx;
            heap[L] = x;
            up(L);
        }else if(!strcmp(op, "PM"))cout<<heap[1]<<endl;
        else if(!strcmp(op, "DM")){
            heap_swap(1,L);
            L--;
            down(1);
        }else if(!strcmp(op, "D")){
            cin>>k;
            k = ph[k];
            heap_swap(k,L);
            L--;
            down(k),up(k);
        }else{
            cin>>k>>x;
            k = ph[k];
            heap[k] = x;
            down(k),up(k);
        }
    }
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值