Cod sursa(job #1675609)

Utilizator hegedusPaul Hegedus hegedus Data 5 aprilie 2016 13:55:21
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 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 fius,fiud,aux;
    fius=2*x; fiud=2*x+1;

    while(v[fius] && v[x]>minim(fius,fiud))
    {
        if (!v[fiud] || v[fius]<v[fiud])
            aux=v[x],
            v[x]=v[fius],
            v[fius]=aux,
            x=fius;
        else
            aux=v[x],
            v[x]=v[fiud],
            v[fiud]=aux,
            x=fiud;

        fius=2*x; fiud=2*x+1;
    }
}

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;
}