Pagini recente » Cod sursa (job #41554) | Cod sursa (job #2267431) | Cod sursa (job #561307) | Cod sursa (job #2838914) | Cod sursa (job #843314)
Cod sursa(job #843314)
#include <stdio.h>
#define MAXN 200001
int values[MAXN]; // valorile adaugate
int heap[MAXN]; // heap de indici
int pos[MAXN]; // pozitia in heap a celui de-al n-lea element
int count=0;
int n=0;
// x,y indecsi de heap
void swap(int x, int y)
{
int aux;
aux = heap[x];
heap[x] = heap[y];
heap[y] = aux;
aux = pos[heap[x]];
pos[heap[x]] = pos[heap[y]];
pos[heap[y]] = aux;
}
void heap_add(int value)
{
values[++count]=value;
heap[++n] = count;
pos[count] = n;
upp(n);
}
void heap_del(int el)
{
int node = pos[el];
pos[heap[n]] = node;
heap[node] = heap[n];
n--;
if( node != 1 && values[heap[node]] < values[heap[node/2]] )
upp(node);
else{
downn(node);
}
downn(pos[el]);
}
int upp(int node)
{
while( node != 1 && values[heap[node]] < values[heap[node/2]] ){
swap(node, node/2);
node = node/2;
}
}
int downn(int node)
{
int min = node;
if( 2*node <= n && values[heap[2*node]] < values[heap[node]] )
min = 2*node;
if( (2*node+1) <= n && values[heap[2*node+1]] < values[heap[min]] )
min = 2*node+1;
if( node != min ){
swap(node, min);
downn(min);
}
}
void printHeap()
{
int i;
for(i=1;i<=n;i++)
printf("%d ",values[heap[i]]);
printf("\n");
}
int main(int argc, char * argv[])
{
freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w",stdout);
int i,M,op,el;
scanf("%d",&M);
for(i=0;i<M;i++){
scanf("%d",&op);
switch(op){
case 1:
scanf("%d",&el);
heap_add(el);
break;
case 2:
scanf("%d",&el);
heap_del(el);
break;
case 3:
printf("%d\n",values[heap[1]]);
break;
}
}
return 0;
}