模拟堆算法

题目

代码

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]);
        }
    }
}
相关推荐
朱剑君7 小时前
第四天——贪心算法——种花
算法·贪心算法
TextIn智能文档云平台7 小时前
PDF文档解析新突破:图表识别、公式还原、手写字体处理,让AI真正读懂复杂文档!
图像处理·人工智能·算法·自然语言处理·pdf·ocr
Panesle7 小时前
HunyuanCustom:文生视频框架论文速读
人工智能·算法·音视频·文生视频
hie988947 小时前
matlab稳定求解高精度二维对流扩散方程
算法·机器学习·matlab
买了一束花8 小时前
MATLAB导出和导入Excel文件表格数据并处理
人工智能·算法·matlab
纪元A梦8 小时前
贪心算法应用:顶点覆盖问题详解
java·算法·贪心算法
爱补鱼的猫猫9 小时前
22、近端策略优化算法(PPO)论文笔记
论文阅读·算法
开心星人9 小时前
【论文阅读】Reconstructive Neuron Pruning for Backdoor Defense
论文阅读·算法·剪枝
_Itachi__10 小时前
LeetCode 热题 100 543. 二叉树的直径
java·算法·leetcode
是代码侠呀11 小时前
飞蛾扑火算法matlab实现
开发语言·算法·matlab·github·github star·github 加星