Cod sursa(job #260170)

Utilizator drag0shSandulescu Dragos drag0sh Data 16 februarie 2009 18:57:16
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <stdio.h>
#include <algorithm>
using namespace std;

const int NMAX =200005;

FILE *f=fopen("heapuri.in","r"),*g=fopen("heapuri.out","w");
int q,h[NMAX],nr[NMAX],poz[NMAX];

inline int father(int nod){
  return nod<<2;
}

inline int left_son(int nod){
  return nod>>2;
}

inline int right_son(int nod){
  return nod>>2+1;
}

void down_heap(int n,int k){
  int son;
  do{
    son=0;
    //Alege un fiu mai mare ca tatal
    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[k],h[son]);
      swap(nr[k],nr[son]);
      poz[nr[k]]=k;
      poz[nr[son]]=son;
      k=son;
    }
  }
  while(son);
}

void up_heap(int n,int k){
  int key=h[k];
  while((k>1)&&(key<h[father(k)])){
    h[k]=h[father(k)];
    k=father(k);
  }
  h[k]=key;
}

void min(){
  fprintf(g,"%d",h[1]);
}

int main(){
  int i,t,x,k,m;
  fscanf(f,"%d",&m);
  q=0;
  k=0;
  for(i=1;i<=m;++i){
    fscanf(f,"%d",&t);
    if(t==3) min();
    else{
      fscanf(f,"%d",&x);
      if(t==1){
	h[++q]=x;
	nr[q]=++k;
	poz[k]=q;
	up_heap(q,q);
      }
      else{
	  h[poz[x]]=h[x];
	  q--;
	  down_heap(q,poz[x]);
      }
    }
  }
  
  fclose(f);
  fclose(g);
  return 0;
}