Cod sursa(job #235583)

Utilizator DastasIonescu Vlad Dastas Data 24 decembrie 2008 15:54:06
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <cstdio>

const int maxn = 200001;

FILE *in = fopen("heapuri.in","r"), *out = fopen("heapuri.out","w");

int n;
int a[maxn], h[maxn], ph[maxn], k, nr;

void swap(int x, int y)
{
    int t = h[x];
    h[x] = h[y];
    h[y] = t;
}

void insert(int x)
{
    h[++k] = x;
    ph[ h[k] ] = k;

    int t = k;
    while ( t / 2 )
    {
        if ( a[ h[t] ] < a[ h[t / 2] ] )
        {
            swap(t, t / 2);

            ph[ h[t] ] = t ;
            ph[ h[t / 2] ] = t / 2;

            t /= 2;
        }
        else
            break;
    }
}

void del(int x)
{
    int t = ph[x];
    swap(ph[x], k);
    --k;

    while ( 2*t <= k )
    {
        int swapper = 2*t;

        if ( 2*t + 1 <= k )
            if ( a[ h[2*t + 1] ] < a[ h[swapper] ] )
                swapper = 2*t + 1;

        if ( a[ h[t] ] > a[ h[swapper] ] )
        {
            swap(t, swapper);

            ph[ h[t] ] = t;
            ph[ h[swapper] ] = swapper;

            t = swapper;
        }
        else
            break;
    }
}

int main()
{
    int op = 0, x = 0;

    fscanf(in, "%d", &n);

    for ( int i = 1; i <= n; ++i )
    {
        fscanf(in, "%d", &op);

        if ( op == 1 || op == 2 )
        {
            fscanf(in, "%d", &x);
            a[++nr] = x;

            switch (op)
            {
                case 1:
                    insert(nr);
                    break;
                case 2:
                    del(x);
                    break;
            }
        }
        else
            fprintf(out, "%d\n", a[ h[1] ]);
    }

    return 0;
}