Pagini recente » Cod sursa (job #1864955) | Cod sursa (job #943038) | Cod sursa (job #61158) | Cod sursa (job #1420929) | Cod sursa (job #246021)
Cod sursa(job #246021)
#include<stdio.h>
#define N 100000
int heap[N],poz[N],ord[N],n=0,aux,ok,q=0;
// poz[i] pozitia in heap a celui de-al i-lea nod intrat in heap
// ord[i] al catelea intrat in heap e nodul i
inline int left_son(int x){
return 2*x;
}
inline int right_son(int x){
return 2*x+1;
}
inline int parent(int x){
return x/2;
}
void replace(int p, int q)
{
aux=heap[p];
heap[p]=heap[q];
heap[q]=aux;
aux=ord[p];
ord[p]=ord[q];
ord[q]=aux;
aux=poz[ord[p]];
poz[ord[p]]=poz[ord[q]];
poz[ord[q]]=aux;
}
void down(int x)
{
int son; //fiul care trebuie sa urce
while ((right_son(x)<=n) && ((heap[x] > heap[left_son(x)]) || (heap[x] > heap[right_son(x)])))
{
if ((heap[x] > heap[left_son(x)]) && (heap[x] > heap[right_son(x)]))
if (heap[left_son(x)] > heap[right_son(x)])
son=right_son(x);
else
son=left_son(x);
else
if (heap[x] > heap[left_son(x)])
son=left_son(x);
else
son=right_son(x);
if(heap[x]!=heap[son])
replace(x,son);
x=son;
}
if ((left_son(x) == n) && (heap[x] > heap[left_son(x)]))
replace(x, left_son(x));
}
void up(int x)
{
while(heap[x]<heap[parent(x)])
{
replace(x,parent(x));
x=parent(x); //urc la urmatorul nivel
}
}
void insert(int x)
{
heap[++n]=x;
poz[++q]=n;
ord[n]=q;
up(n);
}
void remove(int x)
{
//inlocuiesc nodul x cu ultimul nod si scad numarul nodurilor
heap[x]=heap[n];
poz[ord[n]]=x;
ord[x]=ord[n];
--n;
down(x); //doar il cobor; se obs ca nodul pe care il aducem in locul celui scos nu poate fi mai mic decat tatal nodului scos
}
int main()
{
freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w",stdout);
int nr,op,x;
scanf("%d",&nr);
for(;nr>0;--nr)
{
scanf("%d",&op);
if(op==3) printf("%d\n",heap[1]); //afisez minimul
else
{
scanf("%d",&x);
if(op==1) //inserez elementul x
insert(x);
else //sterg al x-lea nod intrat
remove(poz[x]);
}
}
return 0;
}