Cod sursa(job #235700)

Utilizator DastasIonescu Vlad Dastas Data 25 decembrie 2008 13:39:39
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 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;

    t = ph[x];
    ph[x] = ph[y];
    ph[y] = t;

    a[ ph[x] ] = x;
    a[ ph[y] ] = y;
}

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

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

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

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

        if ( swapper > k )
            break;

        if ( swapper + 1 <= k )
            if ( h[swapper + 1] < h[swapper] )
                ++swapper;

        if ( h[t] > h[swapper] )
        {
            swap(t, 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);

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

    return 0;
}