Cod sursa(job #353239)

Utilizator MarquiseMarquise Marquise Data 4 octombrie 2009 15:04:07
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <stdio.h>

#define NMAX 200005

int N, NH, NV, h[NMAX], v[NMAX], poz[NMAX] ;


void swap(int i, int j)
{
     int aux;
     
     poz[h[i]] = j;
     poz[h[j]] = i;
     
     aux = h[i];
     h[i] = h[j];
     h[j] = aux;

}

void HeapUp(int f)
{
     int t;
     if (f <= 1) return;
     
     t = f >> 1;
     if ( v[h[t]] > v[h[f]])
     {
          swap(t, f);
          HeapUp(t);
     }
}

void HeapDw(int t)
{
     int f;
     
     f = t << 1;
     if ( f <= NH)
     {
          if (  (f | 1) <= NH  &&  v[h[f]] > v[h[(f | 1)]] )
             f++;
             
          if ( v[h[t]] > v[h[f]])
          {
               swap(t, f);
               HeapDw(f);
          }   
             
     }
}


int main()
{
    int i, o, val;
    
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    
    scanf("%d", &N);
    
    for ( i = 1; i <= N; i++)
    {
        scanf("%d", &o);
        
        if ( o == 1)
        {
             scanf("%d", &val);
             v[++NV] = val;
             h[++NH] = NV;
             poz[NV] = NH;

             HeapUp(NH);
        }
       else 
        if ( o == 2)
        {
             scanf("%d", &val);
             v[val] = -1;
             HeapUp(poz[val]);
             
             poz[h[1]] = 0;
             h[1] = h[NH--];
             poz[h[1]] = 1;
             
             HeapDw(1);
      
        }   
        else
            printf("%d\n", v[h[1]]);
            
            
    }
    
    return 0;
}