Add 堆排序

master
puy4bwhfe 4 years ago
parent 757629aa6f
commit 5c66b52a3b

@ -0,0 +1,73 @@
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e6+6;
int size1=0,h[N],n,m=0,hp[N],ph[N];
void heap_swap(int a, int b)
{
swap(ph[hp[a]],ph[hp[b]]);
swap(hp[a],hp[b]);
swap(h[a],h[b]);
}
void down(int u)
{
int t=u;
if(u*2<=size1&&h[u*2]<h[t]) t=u*2;
if(u*2+1<=size1&&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/2]>h[u])
{
heap_swap(u/2,u);
u/=2;
}
}
int main()
{
scanf("%d",&n);
while(n--)
{
char op[10];
int k,x;
scanf("%s",op);
if(!strcmp(op,"I"))
{
scanf("%d",&x);
size1++;
m++;
ph[m]=size1,hp[size1]=m;
h[size1]=x;
up(size1);
}
else if(!strcmp(op,"PM"))printf("%d\n",h[1]);
else if(!strcmp(op,"DM"))
{
heap_swap(1,size1);
size1--;
down(1);
}
else if(!strcmp(op,"D"))
{
scanf("%d",&k);
k=ph[k];
heap_swap(k,size1);
size1--;
down(k),up(k);
}
else
{
scanf("%d %d",&k,&x);
k=ph[k];
h[k]=x;
down(k),up(k);
}
}
return 0;
}
Loading…
Cancel
Save