首先从要求入手:因为要对第k个插入的数进行操作,所以需要添加一个ph(pointer heap)数组,即用来索引第k个插入的数在堆中的下标。这样当我们需要删除第k个插入的数时,通过ph[k]就能找到它在堆中的下标,然后和堆尾元素交换,再对堆中下标是k的数up、down一遍即可。
似乎一个ph数组足够了,为什么还要hp数组呢?
原因就在于,当我们交换两个元素时,输入的是堆中的下标,那么此时必须要有一个数组通过下标索引到插入次序,于是hp(heap pointer)数组就诞生了!
hp[u]=k , ph[k]=u,两者是一一映射关系。
1.h[u]数组:在堆中下标是u的数值
2.hp[u]:在堆中下标是u的数的插入次序(在heap_swap中相当于一个中介,通过下标为ph数组提供插入次序)
3.ph[k]:第k个插入的数在堆中的下标
4.cnt存储当前堆的规模
5.m存储当前插入的次序
注意:当未移除元素前cnt和m相等,但当移除元素后,两者不同(当初困扰了我半天。。。)
#include <iostream>
using namespace std;
const int N = 100010;
int h[N] , hp[N] , ph[N] , cnt , m;
int n;
void heap_swap(int a , int b)
{
swap(h[a] , h[b]);
swap(hp[a] , hp[b]);
swap(ph[hp[a]] , ph[hp[b]]);
}
void up(int k)
{
while(k >> 1 && h[k >> 1] > h[k]){
heap_swap(k , k >> 1);
k >>= 1;
}
}
void down(int k)
{
int t = k;
if(k*2 <= cnt && h[t] > h[k*2]) t = k*2;
if(k*2+1 <= cnt && h[t] > h[k*2+1]) t = k*2+1;
if(t != k) heap_swap(t , k) , down(t);
}
int main()
{
cin >> n;
while(n--)
{
string op;
int x , k;
cin >> op;
if(op == "I")
{
int x;
cin >> x;
m++ , cnt++;
hp[cnt] = m , ph[m] = cnt;
h[cnt] = x;
up(cnt);
}
else if(op == "PM") cout << h[1] << endl;
else if(op == "DM")
{
heap_swap(1 , cnt--);
down(1);
}
else if(op == "D")
{
cin >> k;
k = ph[k];
heap_swap(k , cnt--);
down(k);
up(k);
}
else
{
cin >> k >> x;
k = ph[k];
h[k] = x;
down(k);
up(k);
}
}
return 0;
}