AcWing 839.模拟堆

题目


思路

在这里插入图片描述

三个函数

  • 一个是数和节点的对应,交换节点,那么对应的数据结构所存储的数就要改变 并且涉及到交换了的节点其指针指向也要改变
  • 一个是上移节点对应的函数
  • 还有一个下移节点对应的函数

代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

const int N = 1e5 + 10;
int hp[N], ph[N];
int h[N];
int size;

// “I x”,插入一个数x;
// “PM”,输出当前集合中的最小值;
// “DM”,删除当前集合中的最小值(当最小值不唯一时,删除最早插入的最小值);
// “D k”,删除第k个插入的数;
// “C k x”,修改第k个插入的数,将其变为x;

void heap_swap(int u, int v)
{
    swap(ph[hp[u]], ph[hp[v]]);
    swap(hp[u], hp[v]);
    swap(h[u], h[v]);
}

void down(int u)
{
    int t = u;
    if (2*u <= size && h[2*u] < h[t]) t = 2*u;
    if (2*u+1 <= size && h[2*u+1] < h[t]) t = 2*u+1;
    if (t != u)
    {
        heap_swap(t, u);
        down(t);
    }
}

void up(int u)
{
    while (u/2 && h[u] < h[u/2])
    {
        heap_swap(u, u/2);
        u >>= 1;
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    char op[3];
    int a, b;
    int m = 0;
    while (n--)
    {
        scanf("%s", op);
        if (!strcmp(op, "I")) 
        {
            scanf("%d", &a);
            m++;
            h[++size] = a, ph[m] = size, hp[size] = m;
            up(size);
        }
        else if (!strcmp(op, "PM")) printf("%d\n", h[1]);
        else if (!strcmp(op, "DM")) 
        {
            heap_swap(1, size);
            size--;
            down(1);
        }
        else if (!strcmp(op, "D")) 
        {
            scanf("%d", &a);
            int u = ph[a];
            heap_swap(u, size);
            size--;
            up(u), down(u);
        }
        else
        {
            scanf("%d%d", &a, &b);
            int u = ph[a];
            h[u] = b;
            up(u), down(u);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值