Cod sursa(job #351587)

Utilizator mihaionlyMihai Jiplea mihaionly Data 28 septembrie 2009 18:27:37
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <stdio.h>
#define nmax 200001
#define f(x) x/2
#define rs(x) 2*x+1
#define ls(x) 2*x

long H[nmax],P[nmax],Px[nmax],n,m,nr;
void swap(long &xx,long &yy)
 {
 int ax=xx;
 xx=yy;
 yy=ax;
 }
void up_up(long x)
 {
 while(f(x)>=1&&H[x]<H[f(x)])
  {
  swap(H[f(x)],H[x]);
  swap(P[f(x)],P[x]);
  Px[P[f(x)]]=f(x);
  Px[P[x]]=x;
  x=f(x);
  }
 }
void down(long x)
 {
 int y=0;
 while(x!=y)
  {
  y=x;
  if(ls(x)<=m&&H[x]>H[ls(x)]) y=ls(x);
  if(rs(x)<=m&&H[x]>H[rs(x)]) y=rs(x);
  swap(H[x],H[y]);
  swap(P[x],P[y]);
  Px[P[x]]=x;
  Px[P[y]]=y;
  
  }
 }
int main()
 {
 long cod,x,z;
 FILE *f=fopen("heapuri.in","r");
 FILE *g=fopen("heapuri.out","w");
 fscanf(f,"%ld",&n);
 for(int i=0;i<n;i++)
  {
  fscanf(f,"%ld",&cod);
  if(cod==1)
   {
   fscanf(f,"%ld",&H[++m]);
   P[m]=(++nr);
   Px[P[m]]=m;
   if(f(m)>=1&&H[m]<H[f(m)])
    up_up(m);
   }
  else if(cod==2)
   {
   fscanf(f,"%ld",&x);
   z=Px[x];
   swap(H[Px[x]],H[m]);
   swap(P[Px[x]],P[m]);
   m--;
   Px[P[z]]=z;
   if(f(z)>=1&&H[z]<H[f(z)])
    {
    up_up(z);
    }
   else //if( (ls(P[z])<=m&&H[ls(P[z])]<H[P[z]]) || (rs(P[z])<=m&&H[rs(P[z])]<H[P[z]]) )
    {
    down(z);
    }
   }
  else if(m>=1)
   fprintf(g,"%ld\n",H[1]);
  }
 return 0;
 }