AcWing 839. 模拟堆
原题链接
简单
作者:
岩专郭启童
,
2024-01-28 12:54:45
,
所有人可见
,
阅读 32
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int h[N],ph[N],hp[N],cnt;
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 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)
{
if(u/2&&h[u/2]>h[u])
{
heap_swap(u/2,u);
up(u/2);
}
}
int main()
{
int n,m=0;
cin>>n;
while(n--)
{
string op;
int k,x;
cin>>op;
if(op=="I")
{
cin>>x;
cnt++,m++;
h[cnt]=x;
hp[cnt]=m;ph[m]=cnt;
up(cnt);
}
else if(op=="PM")printf("%d\n",h[1]);
else if(op=="DM")
{
heap_swap(1,cnt);
cnt--;
down(1);
}
else if(op=="D")
{
cin>>k;
k=ph[k];
heap_swap(k,cnt);
cnt--;
up(k),down(k);
}
else
{
cin>>k>>x;
k=ph[k];
h[k]=x;
up(k),down(k);
}
}
}