模拟堆算法

题目

代码

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]);
        }
    }
}
相关推荐
stolentime1 小时前
通信题:洛谷P15942 [JOI Final 2026] 赌场 / Casino题解
c++·算法·洛谷·joi·通信题
初生牛犊不怕苦1 小时前
与AI一起学习《C专家编程》:数组与指针
c语言·学习·算法
Kk.08022 小时前
数据结构|排序算法(二) 冒泡排序
数据结构·算法·排序算法
沛沛rh452 小时前
深入并发编程:从 C++ 到 Rust 的学习笔记
c++·笔记·学习·算法·rust
Kk.08022 小时前
数据结构|排序算法(二) 希尔排序
数据结构·算法·排序算法
AI医影跨模态组学2 小时前
NPJ Precis Oncol(IF=8)复旦大学肿瘤医院等团队:基于生境CT放射组学解析可切除非小细胞肺癌时空异质性预测新辅助化疗免疫治疗病理反应
大数据·人工智能·算法·医学·医学影像
Book思议-3 小时前
二叉树的递归遍历详解:前序、中序与后序
数据结构·算法·二叉树的递归遍历-前中后序
Demon--hx3 小时前
[LeetCode]100 链表-专题
算法·leetcode·链表
Omics Pro3 小时前
首款多模态生物推理大语言模型
人工智能·算法·语言模型·自然语言处理·数据挖掘·数据分析·aigc