Cod sursa(job #805622)

Utilizator andreinsAndrei Nae andreins Data 31 octombrie 2012 20:07:07
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include<cstdio>
using namespace std;
int nh,h[200001],n,v[200001],poz[200001];
void schimb(int &a, int &b)
{
    int pahar;
    pahar=a;
    a=b;
    b=pahar;
}

void urca(int p)
{
    if(p==1 || v[h[p/2]]<v[h[p]])
        return;
    schimb(h[p],h[p/2]);
    poz[h[p]]=p;
    poz[h[p/2]]=p/2;
    urca(p/2);
}

void coboara(int p)
{
    int fs=2*p,fd=2*p+1,t=p;
    if(fs<=nh && h[fs]<=h[t])
        t=fs;
    if(fd<=nh && h[fd]<=h[t])
        t=fd;
    if(t!=p){
        schimb(h[p],h[t]);
        coboara(t);
    }
}


int main()
{
    int x,indice,k=0;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&indice);
        if(indice==1)
        {
            scanf("%d",&x);
            v[++k]=x;
            h[++nh]=k;
            poz[k]=nh;
            urca(nh);
        }
        if(indice==2)
        {
            scanf("%d",&x);
            schimb(h[nh--],h[poz[x]]);
            urca(poz[x]);
            coboara(poz[x]);
        }
        if(indice==3)
            printf("%d\n",v[h[1]]);
    }
    return 0;
}