Pagini recente » Cod sursa (job #2141786) | Cod sursa (job #537139) | Cod sursa (job #795977) | Cod sursa (job #68725) | Cod sursa (job #710120)
Cod sursa(job #710120)
#include<stdio.h>
#define N 200005
FILE *f=fopen("heapuri.in","r"), *g=fopen("heapuri.out","w");
int h[N], poz[N], n, t, poz2[N];
void swap(int a,int b)
{
h[a]=h[a]^h[b];
h[b]=h[a]^h[b];
h[a]=h[a]^h[b];
}
int father(int k)
{
return k/2;
}
int left_son(int k)
{
return 2*k;
}
int right_son(int k)
{
return 2*k+1;
}
void sift(int n, int k)
{
int son, pozi=k;
do
{
son = left_son(k);
if( right_son(k) <= n && h[right_son(k)]> h[left_son(k)])
son=right_son(k);
if(h[son]>=h[k])
son=0;
if(son)
{
swap(k, son);
int aux= poz[son];
poz[son]= poz[k];
poz[pozi]= aux;
poz[son]=k;
poz[k]=son;
k=son;
}
}while(son);
poz[pozi]=k;
}
void percolate (int n, int k)
{
int val=h[k], pozi=k;
while( val < h[father(k)] && k>1)
{
swap(k, father(k));
int aux=poz[father(k)];
poz[father(k)]=poz[pozi];
poz[pozi]= aux;
poz2[k]=father(k);
poz2[father(k)]=poz[k];
k=father(k);
}
h[k]=val;
}
void add(int val)
{
h[++n]=val;
poz[n]=n;
poz2[n]=n;
percolate(n, n);
}
void delet(int k)
{
//poz[k]=0;
k=poz[k];
h[k] = h[n];
poz[poz2[n]]=k;
poz2[k]=k;
n--;
if(h[k]<h[father(k)])
percolate(n, k);
else
sift(n, k);
}
int main()
{
int x,y;
fscanf(f,"%d", &t);
for(int i=1;i<=t;i++)
{
fscanf(f,"%d", &x);
if(x==1)
{
fscanf(f,"%d", &y);
add(y);
}
else
if(x==2)
{
fscanf(f,"%d", &y);
delet(y);
}
else
fprintf(g,"%d\n", h[1]);
}
return 0;
}