Cod sursa(job #630021)

Utilizator theocmtAxenie Theodor theocmt Data 4 noiembrie 2011 15:47:49
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <cstdio>

using namespace std;

int v[200001],h[200001],poz[200001],nr,nh;

inline void swap(int &a,int &b)
{
    int c;
    c=a;
    a=b;
    b=c;
}

void scrie_h()
{
    for(int i=1 ; i<=nh ; i++)
        printf("h[%d]=%d,v[%d]=%d\t",i,h[i],h[i],v[h[i]]);
    printf("\n");
}

void urca(int p)
{
    while ((p != 1) && (v[h[p]] < v[h[p/2]]))
    {
        swap(h[p],h[p/2]);
        //swap(poz[h[p]],poz[h[p/2]]);
        poz[h[p]] = p;
        poz[h[p/2]] = p/2;
        p=p/2;
    }
}

void coboara(int p)
{
    int ps=p;
    if ((p*2 <= nh) && (v[h[2*p]] < v[h[ps]]))
        ps = 2*p;
    if ((p*2+1 <= nh) && (v[h[2*p+1]] < v[h[ps]]))
        ps = 2*p+1;
    if (ps != p)
    {
        swap(h[p],h[ps]);
        //swap(poz[h[p]],poz[h[ps]]);
        poz[h[p]] = p;
        poz[h[ps]] = ps;
        coboara(ps);
    }
}

int main()
{
    int i,n,op,x;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    for (i=1; i<=n; i++)
    {
        scanf("%d",&op);
        //printf("nh = %d\t",nh);
        if (op == 1)
        {
            scanf("%d",&x);
            v[++nr]=x;
            h[++nh]=nr;
            poz[nr]=nh;
            urca(nh);
           // printf("am adaugat %d:\n",x);
            //scrie_h();
        }
        if (op == 2)
        {
            scanf("%d",&x);
            h[poz[x]] = h[nh];
            poz[h[poz[x]]] = x;
            nh--;
            //urca(poz[x]);
            coboara(poz[x]);
           // printf("am scos al %d - lea elem = %d, aflat in h pe poz %d:\n",x,v[x],poz[x]);
            //scrie_h();
        }
        if (op == 3)
        {
            printf("%d\n",v[h[1]]);
        }
    }
    return 0;
}