Cod sursa(job #1320390)

Utilizator claudiu.gatinaFMI Claudiu Gatina claudiu.gatina Data 17 ianuarie 2015 22:35:44
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <cstdio>
#include <algorithm>
#define maxn 200001
#define numberlimit 1000000001

using namespace std;
long long int v[maxn],poz[maxn];
int nv,nh,a,n,i,x,h[maxn];

void percolate(int n)
{
    while (n/2 && v[h[n]]<v[h[n/2]])
    {
        swap(poz[h[n]], poz[h[n/2]]);
        swap(h[n], h[n/2]);
        n/=2;
    }
}

void sift(int n)
{
    while(n<=nh/2)
    {
        if(v[h[n]]>v[h[2*n]] || v[h[n]]>v[h[2*n+1]])
        {
            if(v[h[2*n]]<v[h[2*n+1]])
            {
                swap(poz[h[n]], poz[h[2*n]]);
                swap(h[n],h[2*n]);
                n*=2;
            }
            else
            {
                swap(poz[h[n]], poz[h[2*n+1]]);
                swap(h[n],h[2*n+1]);
                n=2*n + 1;
            }
        }
        else return;
    }
}

void deletee(int n)
{
    h[n]=h[nh];
    h[nh]=0;
    nh--;
    if (n>1 && v[h[n]]<v[h[n/2]])
        percolate(n);
    else sift(n);
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    v[0]=numberlimit;
    scanf("%d", &n);
    for (i=1;i<=n;i++)
    {
        scanf("%d ", &a);
        if (a==3)
            printf("%d\n", v[h[1]]);
        else
        {
            scanf("%d ", &x);
            if (a==1)
            {
                nh++;
                nv++;
                v[nv]=x;
                h[nh]=nv;
                poz[nv]=nh;
                percolate(nh);
            }
            if (a==2)
                deletee(poz[x]);
        }
    }
}