模拟堆算法

题目

代码

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]);
        }
    }
}
相关推荐
瓦特what?14 分钟前
关于C++的#include的超超超详细讲解
java·开发语言·数据结构·c++·算法·信息可视化·数据挖掘
楽码1 小时前
自动修复GoVet:语言实现对比
后端·算法·编程语言
杰克尼1 小时前
415. 字符串相加
算法
lifallen1 小时前
JCTools 无锁并发队列基础:ConcurrentCircularArrayQueue
java·开发语言·数据结构·算法
来自天蝎座的孙孙2 小时前
洛谷P1595讲解(加强版)+错排讲解
python·算法
GawynKing3 小时前
图论(5)最小生成树算法
算法·图论·最小生成树
试剂界的爱马仕3 小时前
胶质母细胞瘤对化疗的敏感性由磷脂酰肌醇3-激酶β选择性调控
人工智能·科技·算法·机器学习·ai写作
打不了嗝 ᥬ᭄3 小时前
Linux 信号
linux·开发语言·c++·算法
张子夜 iiii3 小时前
机器学习算法系列专栏:主成分分析(PCA)降维算法(初学者)
人工智能·python·算法·机器学习
一匹电信狗4 小时前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio