Cod sursa(job #296293)

Utilizator drag0shSandulescu Dragos drag0sh Data 4 aprilie 2009 16:09:29
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <stdio.h>
#define max 200001
FILE *f=fopen("heapuri.in","r"),*g=fopen("heapuri.out","w");
int v[max],n,h[max],poz[max],nr,m;

void heap_down(int);
void heap_up(int);

void adauga(){
  int a;
  fscanf(f,"%d",&a);
  nr++;
  n++;
  v[nr]=a;// valoarea indicelui din ordine normala
  poz[nr]=n;//pt ordine normala ->ordine din heap
  h[n]=nr;//elementele din heap ->ordine normala
  heap_up(n);
}


void heap_up(int k){

  while(k>1&&(v[h[k]]<v[h[k/2]])){
    int aux=h[k/2];
    h[k/2]=h[k];
    h[k]=aux;
    poz[h[k]]=k;
    poz[h[k/2]]=k/2;
    k=k/2;
    }
}

void sterge(){
  int a,k;
  fscanf(f,"%d",&a);
  k=poz[a];
  h[k]=h[n];
  //  poz[h[k]]=k;
  n--;
  if(k>1&&h[k]<h[k/2]) heap_up(k);
  else
    heap_down(k);
}


void heap_down(int k){
  int son; 
  do {
    son=0;
    if(2*k<=n){
      son=2*k;
      if(2*k+1<=n&&v[h[son+1]]<v[h[son]])son++;
      if(v[h[son]]>=v[h[k]])son=0;
    }
    if(son){
      int aux=h[k];
      h[k]=h[son];
      h[son]=aux;
      poz[h[k]]=k;
      poz[h[son]]=son;
      k=son;
      }
    
  }
  while(son);
}


int main(){
  fscanf(f,"%d",&m);
  int cod,i;
  for(i=1;i<=m;i++){
    fscanf(f,"%d",&cod);
    if(cod==1)adauga();
    if(cod==2)sterge();
    if(cod==3)fprintf(g,"%d\n",v[h[1]]);
  }
  
  fclose(f);
  fclose(g);
}