Cod sursa(job #850189)

Utilizator blechereyalBlecher Eyal blechereyal Data 8 ianuarie 2013 00:50:08
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
using namespace std;
#include <fstream>
#define father(nod) (nod/2)
#define left_son(nod) (nod*2)
#define right_son(nod) (nod*2+1)

ifstream f("heapuri.in");
ofstream g("heapuri.out");


int heap[1000001],timp[1000001],t=0;

void swap(int H[],int a,int b)
{int aux;
aux=H[a];
H[a]=H[b];
H[b]=aux;
aux=timp[a];
timp[a]=timp[b];
timp[b]=aux;     
     
}

void sift(int H[],int N,int K)
{
int son;
do
  {
  son=0;
  
  if (left_son(K) <= N)
     {
     son=left_son(K);
     if (( right_son(K)<=N ) && (H[right_son(K)] < H[left_son(K)]))
      son=right_son(K);
     }
     
  if (H[son]>=H[K]) son=0;    
  
  if (son) 
     {
     swap(H,son,K);
     K=son;
     }
  } while (son);
}

void percolate(int H[],int N,int K)
{
while ( ( H[K]<H[father(K)] ) && (father(K)>=1) )
 {swap(H,K,father(K));
 K=father(K);
 }

}



void del(int H[],int &N,int K)
{int i=1;

while (timp[i]!=K)
 i++;
H[i]=H[N];N--;
if ( (K>1) && (H[K]<H[father(K)]) )
     percolate(H,N,K);
else 
     sift(H,N,K);
}

void add(int H[],int &N,int val)
{
N++;
H[N]=val;
t+=1;
timp[N]=t;
percolate(H,N,N);  


}


int main()
{int lines,N=0,cod,x;
f>>lines;
for (int i=1;i<=lines;i++)
{
f>>cod;
switch (cod)
       {case 1:
       f>>x;
       add(heap,N,x);
       break;
       case 2:
       f>>x;
       del(heap,N,x);
       break;
       case 3:
       g<<heap[1]<<"\n";
       break;
       }
}


return 0;
}