模拟堆算法

题目

代码

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]);
        }
    }
}
相关推荐
martian6651 小时前
支持向量机(SVM)深度解析:从数学根基到工程实践
算法·机器学习·支持向量机
孟大本事要学习1 小时前
算法19天|回溯算法:理论基础、组合、组合总和Ⅲ、电话号码的字母组合
算法
??tobenewyorker2 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
贾全2 小时前
第十章:HIL-SERL 真实机器人训练实战
人工智能·深度学习·算法·机器学习·机器人
GIS小天2 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年7月4日第128弹
人工智能·算法·机器学习·彩票
满分观察网友z3 小时前
开发者的“右”眼:一个树问题如何拯救我的UI设计(199. 二叉树的右视图)
算法
森焱森4 小时前
无人机三轴稳定化控制(1)____飞机的稳定控制逻辑
c语言·单片机·算法·无人机
循环过三天4 小时前
3-1 PID算法改进(积分部分)
笔记·stm32·单片机·学习·算法·pid
闪电麦坤954 小时前
数据结构:二维数组(2D Arrays)
数据结构·算法
凌肖战5 小时前
力扣网C语言编程题:快慢指针来解决 “寻找重复数”
c语言·算法·leetcode