模拟堆算法

题目

代码

cpp 复制代码
#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]);
        }
    }
}
相关推荐
kk”9 分钟前
C语言快速排序
数据结构·算法·排序算法
纪元A梦13 分钟前
贪心算法应用:基因编辑靶点选择问题详解
算法·贪心算法
3壹18 分钟前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
skytier1 小时前
Construct内报错和定位解决
算法
skytier1 小时前
Ascend print数据落盘使用
算法
etcix1 小时前
dmenux.c: integrate dmenu project as one file
c语言·前端·算法
papership1 小时前
【入门级-算法-6、排序算法:选择排序】
数据结构·算法·排序算法
汉克老师2 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(4、最大空白区)
c++·算法·蓝桥杯·蓝桥杯c++·c++蓝桥杯
共享家95272 小时前
优先搜索(DFS)实战
算法·leetcode·深度优先
一只懒洋洋2 小时前
中值滤波、方框滤波、高斯滤波、均值滤波、膨胀、腐蚀、开运算、闭运算
算法·均值算法