堆 AcWing 839. 模拟堆
原题链接
算法标签
堆
思路
由于题目需要支持随机修改删除, 因此需要存储每个节点映射
摘自该题解
交换过程
对应代码
void heap_swap(int a, int b)
{
// 如图中蓝色虚线
swap(ph[hp[a]],ph[hp[b]]);
// 如图中绿色虚线
swap(hp[a], hp[b]);
// 堆中a, b两点
swap(h[a], h[b]);
}
代码
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
const int N = 100010;
// ph[k] = i来指明,第k插入的数字在h[]中对应的i是多少
// hp{k] = i来指明,存储每个堆数组的k下标对应i
int h[N], ph[N], hp[N], cnt;
void heap_swap(int a, int b)
{
// 如图中蓝色虚线
swap(ph[hp[a]],ph[hp[b]]);
// 如图中绿色虚线
swap(hp[a], hp[b]);
// 堆中a, b两点
swap(h[a], h[b]);
}
void down(int u)
{
int t = u;
if (u * 2 <= cnt && h[u * 2] < h[t]) t = u * 2;
if (u * 2 + 1 <= cnt && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
if (u != t)
{
heap_swap(u, t);
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, m = 0;
scanf("%d", &n);
while (n -- )
{
char op[5];
int k, x;
scanf("%s", op);
if (!strcmp(op, "I"))
{
scanf("%d", &x);
cnt ++ ;
m ++ ;
// 增加映射关系
ph[m] = cnt, hp[cnt] = m;
// 插入数字x
h[cnt] = x;
up(cnt);
}
else if (!strcmp(op, "PM")) printf("%d\n", h[1]);
else if (!strcmp(op, "DM"))
{
heap_swap(1, cnt);
cnt -- ;
down(1);
}
else if (!strcmp(op, "D"))
{
scanf("%d", &k);
k = ph[k];
heap_swap(k, cnt);
cnt -- ;
up(k);
down(k);
}
else
{
scanf("%d%d", &k, &x);
k = ph[k];
h[k] = x;
up(k);
down(k);
}
}
return 0;
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈