Pagini recente » Cod sursa (job #203384) | Cod sursa (job #1240424) | Cod sursa (job #1514264) | Cod sursa (job #2852247) | Cod sursa (job #1528206)
#include <stdio.h>
#include <stdlib.h>
#define MAXN 200001
#define father(x) (x/2)
#define leftson(x) (2*x)
#define rightson(x) (2*x+1)
int heap[MAXN], n;
struct chestie{
int val, posh;
} v[MAXN];
inline void swap(int i, int j){
int aux=v[heap[i]].posh; v[heap[i]].posh=v[heap[j]].posh; v[heap[j]].posh=aux;
aux=heap[i]; heap[i]=heap[j]; heap[j]=aux;
}
void up(int pos){
while(father(pos) && v[heap[pos]].val<v[heap[father(pos)]].val){
swap(pos, father(pos));
pos=father(pos);
}
}
void down(int pos){
int s;
do{
s=0;
if(leftson(pos)<=n)
s=leftson(pos);
if(rightson(pos)<=n && v[heap[rightson(pos)]].val<v[heap[leftson(pos)]].val)
s=rightson(pos);
if(s && v[heap[s]].val<v[heap[pos]].val){
swap(pos, s);
pos=s;
} else
s=0;
} while(s);
}
int main()
{
FILE *fin, *fout;
int m, op, x, i, tot;
fin=fopen("heapuri.in", "r");
fout=fopen("heapuri.out", "w");
fscanf(fin, "%d", &m);
tot=0;
for(i=0; i<m; i++){
fscanf(fin, "%d", &op);
if(op==1){
++tot; ++n;
fscanf(fin, "%d", &v[tot].val);
v[tot].posh=n;
heap[n]=tot;
up(n);
} else if(op==2){
fscanf(fin, "%d", &x);
v[x].val=-3;
up(v[x].posh);
heap[1]=heap[n--];
v[heap[1]].posh=1;
down(1);
} else{
fprintf(fout, "%d\n", v[heap[1]].val);
}
}
fclose(fin);
fclose(fout);
return 0;
}