自学内容网 自学内容网

模拟堆算法

题目

代码

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int heap[N], sz, cnt;
int th[N], ht[N];
void hswap(int a, int b)
{
    swap(heap[a], heap[b]);
    swap(ht[a], ht[b]);
    swap(th[ht[a]], th[ht[b]]);
}
void down(int h)
{
    int t = h;
    if(2*h <= sz && heap[2*h] < heap[t]) t = 2*h;
    if(2*h+1 <= sz && heap[2*h+1] < heap[t]) t = 2*h+1;
    if(t != h)
    {
        hswap(h, t);
        down(t);
    }
}
void up(int h)
{
    int t = h/2;
    if(t > 0 && heap[h] < heap[t])
    {
        hswap(h, t);
        up(t);
    }
}
int main()
{
    int n;
    cin >> n;
    
    for(int i = 1; i <= n; i++)
    {
        string op;
        cin >> op;
        
        if(op == "I")
        {
            int x;
            cin >> x;
            heap[++sz] = x;
            ht[sz] = ++cnt;
            th[cnt] = sz;
            up(sz);
        }
        else if(op == "PM")
        {
            cout << heap[1] << '\n';
        }
        else if(op == "DM")
        {
            hswap(1, sz--);
            down(1);
        }
        else if(op == "D")
        {
            int k;
            cin >> k;
            int u = th[k]; //这一步要注意,交换之后有up,down操作,用参数就要存参数
            hswap(th[k], sz--);
            up(u);
            down(u);
        }
        else if(op == "C")
        {
            int k, x;
            cin >> k >> x;
            heap[th[k]] = x;
            up(th[k]);
            down(th[k]);
        }
    }
}


原文地址:https://blog.csdn.net/m0_73669127/article/details/142828419

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!