Cod sursa(job #1675624)

Utilizator hegedusPaul Hegedus hegedus Data 5 aprilie 2016 14:08:37
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <cstdio>
using namespace std;

const int nmax=200000;
int v[nmax],w[nmax],n,x,test,op,opx,k,k1,poz;

int minim(int i, int j)
{
    if (v[j] && v[i]>v[j]) return v[j];
    else return i;
}

void urcare(int x)
{
    int tata,aux;
    tata=x/2;
    while(v[x]<v[tata])
    {
        aux=v[x];
        v[x]=v[tata];
        v[tata]=aux;
        x/=2;
        tata/=2;
    }
}

void coborare(int x)
{
    int fiu,fius,fiud,aux;
    fius=2*x; fiud=2*x+1;

    if (v[fius] && (v[fius]<v[fiud] || !v[fiud])) fiu=fius;
    else if (v[fiud]) fiu=fiud;
    else fiu=0;

    while(fiu && v[x]>v[fiu])
    {
        aux=v[x],
        v[x]=v[fiu],
        v[fiu]=aux,
        x=fiu;
        fius=2*x; fiud=2*x+1;

        if (v[fius] && (v[fius]<v[fiud] || !v[fiud])) fiu=fius;
        else if (v[fiud]) fiu=fiud;
        else fiu=0;
    }
}

int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&op);
    for(opx=1;opx<=op;opx++)
    {
        scanf("%d",&test);
        if (test==1)
        {
            scanf("%d",&v[++n]);
            w[++k]=v[n];
            urcare(n);
        }
        else if (test==2)
        {
            scanf("%d",&k1);
            x=w[k1];
            for(poz=1;poz<=n;poz++)
                if (x==v[poz])
                    break;
            v[poz]=v[n];
            v[n--]=0;

            if (v[poz]<v[poz/2]) urcare(poz);
            else coborare(poz);
        }
        else printf("%d\n",v[1]);
    }
    return 0;
}