Cod sursa(job #1468400)

Utilizator pepsiM4A1Ozturk Arif pepsiM4A1 Data 5 august 2015 23:09:44
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.45 kb
#include <cstdio>
#include <algorithm>
using namespace std;
int heap1[200006],heap2[200023],nod[200023],n,tot;
int left(int nr)
{
    return 2*nr;
}
int right(int nr)
{
    return 2*nr+1;
}
int tata(int nr)
{
    return nr/2;
}
void checkup(int pos)
{
    int t=tata(pos);
    while(t>0&&heap1[t]>heap1[pos])
    {
        swap(heap1[t],heap1[pos]);
        swap(heap2[t],heap2[pos]);
        swap(nod[heap2[t]],nod[heap2[pos]]);
        pos=t;
        t=tata(t);
    }
}
void checkdown(int pos)
{
    while(1)
    {
        int best=heap1[pos],caz=1,l=left(pos),r=right(pos);
        if(l<=n&&heap1[l]<best)
        {
            caz=2;
            best=heap1[l];
        }
        if(r<=n&&heap1[r]<best)
        {
            caz=3;
            best=heap1[r];
        }
        if(caz==1) break;
        else
        {
            if(caz==2)
            {
                swap(heap1[pos],heap1[l]);
                swap(heap2[pos],heap2[l]);
                swap(nod[heap2[pos]],nod[heap2[l]]);
                pos=l;
            }
            else if(caz==3)
            {
                swap(heap1[pos],heap1[r]);
                swap(heap2[pos],heap2[r]);
                swap(nod[heap2[pos]],nod[heap2[r]]);
                pos=r;
            }
        }
    }
}
int main()
{
    freopen ("heapuri.in","r",stdin);
    freopen ("heapuri.out","w",stdout);
    int op;
    scanf("%d",&op);
    for(;op>0;op--)
    {
        int tip,nr;
        scanf("%d",&tip);
        if(tip==1)
        {
            scanf("%d",&nr);
            n++;
            tot++;
            heap2[n]=n;
            heap1[n]=nr;
            nod[tot]=n;
            checkup(n);
        }
        else if(tip==2)
        {
            scanf("%d",&nr);
            nr=nod[nr];
            swap(heap1[nr],heap1[n]);
            swap(heap2[nr],heap2[n]);
            swap(nod[heap2[nr]],nod[heap2[n]]);
            n--;
            checkdown(nr);
        }
        else
        {
            printf("%d\n",heap1[1]);
            /*
            for(int i=1;i<=n;i++) printf("%d ",nod[i]);
            printf("\n");
            for(int i=1;i<=n;i++) printf("%d ",heap2[i]);
            printf("\n");
            printf("\n");*/
        }
     /*   for(int i=1;i<=n;i++) printf("%d ",heap1[i]);
        printf("\n");
        for(int i=1;i<=n;i++) printf("%d ",heap2[i]);
        printf("\n");
        printf("\n");*/
    }
}