Cod sursa(job #313158)

Utilizator nicolaetitus12Nicolae Titus nicolaetitus12 Data 8 mai 2009 01:17:50
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <stdio.h>
#define N 200001
int iheap[N],box[N],vf;//heapul contine indici box[iheap[i]]
int          where[N]; //unde se afla elementul i din cutie
void percolate(int i)//sa nu verifice la inceput
{int aux;
 aux=iheap[i];
 iheap[i]=iheap[i/2];
 iheap[i/2]=aux;

 aux=where[iheap[i]];
 where[iheap[i]]=where[iheap[i/2]];
 where[iheap[i/2]]=aux;

 if(vf>=4&&box[iheap[i/2]]<box[iheap[i/4]])
 {percolate(vf/2);
 }
}

void sift(int k)//trebuie sa verifice la inceput
{int aux,min=k;//presupune ca nodul curent este minim
 if((2*k<=vf)&&(box[iheap[2*k]]<box[iheap[min]]))
 {min=2*k;
 }
 if((2*k+1<=vf)&&(box[iheap[2*k+1]]<box[iheap[min]]))
 {min=2*k+1;
 }
 if(min!=k)
 {aux=iheap[min];iheap[min]=iheap[k];iheap[k]=aux;
  aux=where[iheap[k]];
  where[iheap[k]]=where[iheap[min]];
  where[iheap[min]]=aux;
  sift(2*k);
 }
}

void push(int k)
{box[++vf]=k;
 iheap[vf]=vf;
 where[vf]=vf;
 if((vf>1)&&k<box[iheap[vf/2]])
 {percolate(vf);
 }
}
void pop(int i)//where[i]
{int k=where[i];
 iheap[where[i]]=iheap[vf];
 where[iheap[vf]]=where[i];
 where[i]=0;
 vf--;
 if(k>1&&box[iheap[k]]<box[iheap[k/2]])
 {percolate(k);
 }
 else
 {sift(k);
 }
}
int main ()
{int i,n,a;
 freopen("heapuri.in","r",stdin);
 freopen("heapuri.out","w",stdout);
 scanf("%d",&n);
 for (i=1,vf=0;i<=n;i++)
 {scanf("%d",&a);
  if(a==1)//insereaza a in multime
  {scanf("%d",&a);
   push(a);
  }
  else if(a==2)      //sterge elementul al a-lea adaugat in heap
  {scanf("%d",&a);
   pop(a);
  }
  else                       //afiseaza elementul minim
  {printf("%d\n",box[iheap[1]]);
  }
 }
 return 0;
}