Pagini recente » Cod sursa (job #2099073) | Cod sursa (job #508832) | Cod sursa (job #2055549) | Cod sursa (job #3156549) | Cod sursa (job #1050569)
#include <stdio.h>
#include <cstring>
#include <algorithm>
#define heapLEN 200001
#define ROOT(x) (x>>1)
#define LEFT(x) (x<<1)
#define RIGHT(x) ((x<<1)+1)
#define SIZE(v) v[0]
#define MINHEAP heap[1]
using namespace std;
int heap[heapLEN]; //min heap, keeps value
int at[heapLEN]; //position vector, keeps position in heap given insert idx
int idx[heapLEN]; //position vector, keeps insert idx given postion in heap
void percolate(int x)
{
while(x>1&&heap[ROOT(x)]>heap[x])
{
swap(heap[ROOT(x)],heap[x]);
swap(at[idx[ROOT(x)]],at[idx[x]]);
swap(idx[ROOT(x)],idx[x]);
x=ROOT(x);
}
}
void sift(int x)
{
while(x<=SIZE(heap))
{
int next;
if(RIGHT(x)<=SIZE(heap))
heap[LEFT(x)]<heap[RIGHT(x)] ? next=LEFT(x) : next=RIGHT(x);
else
if(LEFT(x)<=SIZE(heap)) next=LEFT(x);
else return;
swap(heap[x],heap[next]);
swap(at[idx[x]],at[idx[next]]);
swap(idx[x],idx[next]);
x=next;
}
}
void insert(int val)
{
++SIZE(heap);
heap[SIZE(heap)]=val;
++SIZE(at);
at[SIZE(at)]=SIZE(heap);
idx[SIZE(at)]=SIZE(heap);
percolate(SIZE(heap));
}
void cut(int pos)
{
swap(heap[at[pos]],heap[SIZE(heap)]);
swap(at[pos],at[idx[SIZE(at)]]);
swap(pos,idx[SIZE(at)]);
//heap[SIZE(heap)]=0;
//at[idx[SIZE(at)]]=0;
//idx[SIZE(at)]=0;
--SIZE(heap);
if(at[pos]>1&&heap[ROOT(at[pos])]>heap[at[pos]]) percolate(at[pos]);
else sift(at[pos]);
}
int main()
{
freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w",stdout);
memset(heap,0,sizeof(heap));
memset(at,0,sizeof(at));
memset(idx,0,sizeof(idx));
int N;
scanf("%d",&N);
while(N--)
{
int cod;
scanf("%d",&cod);
switch(cod)
{
case 1:
int val;
scanf("%d",&val);
insert(val);
break;
case 2:
int pos;
scanf("%d",&pos);
cut(pos);
break;
case 3:
printf("%d\n",MINHEAP);
break;
}
/*
printf("Size (heap) : %d\n",SIZE(heap));
printf("Size (at) : %d\n",SIZE(at));
printf("Heap : ");
for(int i=1;i<=SIZE(heap);++i)
printf("%d ",heap[i]);
printf("\n");
printf("At (heap) : ");
for(int i=1;i<=SIZE(at);++i)
printf("%d ",at[i]);
printf("\n");
printf("Idx (at) : ");
for(int i=1;i<=SIZE(at);++i)
printf("%d ",idx[i]);
printf("\n\n");
*/
}
return 0;
}