Cod sursa(job #754479)

Utilizator gluonIancu Codarascu gluon Data 2 iunie 2012 10:44:06
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <stdio.h>

int v[20000], poz[20000], h[20000], N, nh=0, n=0;

void schimb(int x, int y)
{
    int aux = h[x];
    h[x] = h[y];
    h[y] = aux;
    poz[h[x]] = x;
    poz[h[y]] = y;
}

void down(int p)
{
    int fs = p << 1, fd = (p << 1) + 1, pmin = p;

    if(fs <= nh && v[h[fs]] < v[h[pmin]])
        pmin = fs;

    if(fd <= nh && v[h[fd]] < v[h[pmin]])
        pmin = fd;

    if(pmin != p)
    {
        schimb(p, pmin);
        down(pmin);
    }
}

void up(int p)
{
    while(p > 1 && v[h[p]] < v[h[p>>1]])
    {
        schimb(p, p>>1);
        p >>= 1;
    }
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    int qw, p, x;
    scanf("%d", &N);
    nh = 0;

    for(int i = 0; i < N; i++)
    {
        scanf("%d",&qw);

        switch(qw)
        {
            case 1:
                scanf("%d", &v[++n]);
                h[++nh] = n;
                poz[n] = nh;
                up(nh);
                break;
            case 2:
                scanf("%d", &x);
                p = poz[x];
                h[p] = h[nh--];
                poz[h[p]] = p;
                up(p);
                down(p);
                break;
            case 3:
                printf("%d\n", v[h[1]]);
                break;
        }
    }

    return 0;
}