Cod sursa(job #1239266)

Utilizator Alexa2001Alexa Tudose Alexa2001 Data 8 octombrie 2014 17:16:26
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <cstdio>

using namespace std;

struct nod
{
    int v,p;
};
nod H[200002],aux;
int t, i, p, x, n, Op, poz[200001];

void swap (int x, int y)
{
    poz[H[x].p]=y;
    poz[H[y].p]=x;
    nod aux=H[x];
    H[x]=H[y];
    H[y]=aux;
}

void HeapUp(int x)
{

    if(x<=1)return;
    int t=x/2;
    if(H[x].v<H[t].v)
    {
        swap(x,t);
        HeapUp(t);
    }
}

void HeapDown(int x, int nr)
{

    if (2*x>nr)return;
    int y, St=H[x].v;
    int Dr=St;
    if(2*x+1<=nr) Dr=H[2*x+1].v;
    if(St<=Dr) y=2*x;
    else y=2*x+1;
    if(H[x].v>H[y].v)
    {
        swap(x, y);
        HeapDown(x,y);
    }
}

int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&t);
    for (i=1; i<=t; i++)

    {
        scanf("%d",&Op);
        if (Op==1)
        {
            scanf("%d",&x);
            H[++n].v=x;
            H[n].p=n;
            poz[n]=n;
            HeapUp(n);

        }
        else if (Op==2)
        {
            scanf("%d",&x);
            int y=poz[x];
            swap(poz[x],n);
            n--;
            HeapDown(y,n);

        }
        else if (Op==3)
        {
            printf("%d\n",H[1].v);

        }

    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}