Cod sursa(job #514622)

Utilizator Magnuscont cu nume gresit sau fals Magnus Data 19 decembrie 2010 11:56:14
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <stdio.h>
#include <algorithm>

using namespace std;

int h[200001],p[200001],v[200001],n,op,i;

inline int father(int nod)
{
    return nod/2;
}

inline int lson(int nod)
{
    return 2*nod;
}

inline int rson(int nod)
{
    return 2*nod+1;
}

void sift(int k)
{
    int ok=1;
    while (ok)
    {
        if ((lson(k)<=n)&&(h[lson(k)]<h[k])&&(h[lson(k)]<h[rson(k)]))
            {
                swap(h[k],h[lson(k)]);
                swap(p[v[k]],p[v[lson(k)]]);
                swap(v[k],v[lson(k)]);
                k=lson(k);
            }
        else if ((rson(k)<=n)&&(h[rson(k)]<h[k]))
            {
                swap(h[k],h[rson(k)]);
                swap(p[v[k]],p[v[rson(k)]]);
                swap(v[k],v[rson(k)]);
                k=rson(k);
            }
        else ok=0;
    }
}

void percolate(int k)
{
    int ok=1;
    while ((ok)&&(k>1))
    {
        if (h[father(k)]>h[k])
        {
            swap(h[k],h[father(k)]);
            swap(p[v[k]],p[v[father(k)]]);
            swap(v[k],v[father(k)]);
            k=father(k);
        }
        else ok=0;
    }
}

void cut(int k)
{
    h[k]=h[n];
    p[v[k]]=p[v[n]];
    v[k]=v[n];
    --n;
    if ((k>1)&&(h[k]<h[father(k)])) percolate(k);
    else sift(k);
}

int main()
{
    int x,a=0;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&op);
    for (i=1;i<=op;++i)
    {
        scanf("%d",&x);
        if (x==1)
        {
            ++n;++a;
            scanf("%d",&h[n]);
            v[n]=a;
            p[a]=n;
            percolate(n);
        }
        else if (x==2)
        {
            scanf("%d",&x);
            cut(p[x]);
        }
        else printf("%d\n",h[1]);
    }
    return 0;
}