Cod sursa(job #1789288)

Utilizator delta_wolfAndrei Stoica delta_wolf Data 26 octombrie 2016 20:53:27
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <cstdio>
#include<algorithm>
using namespace std;
int t,n,m,op,x,ax;
int hp[200005],b[200005],a[200005];
void UP(int p)
{
    if(p/2<1) return ;
    if(hp[p]<hp[p/2])
    {
        swap(hp[p], hp[p/2]);
        a[m]=p/2;
        a[b[p/2]]=p;
        b[p]=b[p/2];
        b[p/2]=m;
        UP(p/2);
    }
}
void DOWN(int p)
{
    if(p*2>n) return ;

    if(hp[p]>hp[p*2]&&hp[p]>hp[p*2+1])
    {
        if(hp[p*2]<hp[p*2+1])
        {
            swap(hp[p], hp[p*2]);
            int bp=b[p];
            a[b[p*2]]=p;
            b[p]=b[p*2];
            a[bp]=p*2;
            b[p*2]=bp;
            DOWN(p*2);
        }
        else
        {
            swap(hp[p], hp[p*2+1]);
            int bp=b[p];
            a[b[p*2+1]]=p;
            b[p]=b[p*2+1];
            a[bp]=p*2+1;
            b[p*2+1]=bp;
            DOWN(p*2+1);
        }
        return;
    }
    if(hp[p]>hp[p*2])
    {
         swap(hp[p], hp[p*2]);
        int bp=b[p];
        a[b[p*2]]=p;
        b[p]=b[p*2];
        a[bp]=p*2;
        b[p*2]=bp;
        DOWN(p*2);
    }
    if(hp[p]>hp[p*2+1])
    {
        swap(hp[p], hp[p*2+1]);
        int bp=b[p];
        a[b[p*2+1]]=p;
        b[p]=b[p*2+1];
        a[bp]=p*2+1;
        b[p*2+1]=bp;
        DOWN(p*2+1);
    }
}

int main()
{

    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    scanf("%d", &t);
    while(t)
    {
        t--;
        scanf("%d", &op);
        if(op==3)
        {
            printf("%d\n", hp[1]);
            continue;
        }
        if(op==1)
        {
            scanf("%d", &x);
            n++;
            m++;
            hp[n]=x;
            b[n]=m;
            a[m]=n;
            UP(n);
            continue;
        }
        if(op==2)
        {
            scanf("%d", &x);
            hp[a[x]]=hp[n];
            ax=a[x];
            a[b[n]]=a[x];
            b[a[x]]=b[n];
            n--;
            DOWN(a[x]);
        }
    }
    return 0;
}