Cod sursa(job #1027390)

Utilizator vasandANDREI POP vasand Data 12 noiembrie 2013 19:04:35
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
# include <iostream>
# include <fstream>
# define nmax 200000

using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

int v[nmax], h[nmax], p[nmax];

inline int left_son(int k)
{
    return k*2;
}

inline int right_son(int k)
{
    return k*2+1;
}

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

void schimba(int a, int b)
{
    int aux;
    aux=h[a];
    h[a]=h[b];
    h[b]=aux;
}

void sift(int n, int k)
{
    int poz_tmp=1,m,pm;
    while(poz_tmp)
    {
        poz_tmp=0;
        if(left_son(k) <= n)
        {
            poz_tmp = left_son(k);
            if(right_son(k) <=n && v[h[right_son(k)]] < v[h[left_son(k)]])
                poz_tmp = right_son(k);
        }

        if(v[h[k]] > v[h[poz_tmp]] && poz_tmp)
        {
            schimba(k, poz_tmp);
            p[h[k]]=k;
            p[h[poz_tmp]]=poz_tmp;
            k=poz_tmp;
        }
        else
            poz_tmp=0;
    }
}

void percolate(int n, int k)
{
    bool ok=1;
    while(ok)
    {
        ok=0;
        if(k!=1 && v[h[k]]<v[h[father(k)]])
        {
            schimba(k, father(k));
            p[h[k]]=k;
            p[h[father(k)]]=father(k);
            k=father(k);
            ok=1;
        }
    }
}

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

void add(int &n, int val)
{
    v[++n]=val;
    h[n]=n;
    p[n]=n;
    percolate(n, n);
}

int main()
{
    int n=0,i,nr,caz,aux;

    f>>nr;
    for(i=1; i<=nr; i++)
    {
        f>>caz;
        switch(caz)
        {
            case 1:
            {
                f>>aux;
                add(n,aux);
                break;
            }
            case 2:
            {
                f>>aux;
                ext(n,p[aux]);
                break;
            }
            case 3:
            {
                g<<v[h[1]]<<'\n';
                break;
            }
        }

    }
    return 0;
}