Cod sursa(job #587695)

Utilizator socheoSorodoc Ionut socheo Data 5 mai 2011 17:03:58
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <cstdio>

using namespace std;

int a[200002],h[200002],pos[200002],nr,q,nrop,op,l,n;
void swap(int x, int y)
{   int aux = h[x];
    h[x] = h[y];
    h[y] = aux;
    aux = pos[h[x]];
    pos[h[x]] = pos[h[y]];
    pos[h[y]] = aux;

}

void sink(int nod)
{ if(a[h[nod]]>a[h[2*nod]]&&a[h[2*nod]]<a[h[2*nod+1]]&&nod<=l/2)
    {
        swap(nod,2*nod);
        sink(2*nod);
    }
    if(a[h[nod]]>a[h[2*nod+1]]&&a[h[2*nod]]>=a[h[2*nod+1]]&&nod<=l/2)
    {
        swap(nod,2*nod+1);
        sink(2*nod+1);
    }
    return ;
}

void swim(int nod)
{
    if(nod/2>=1)
    {
        if(a[h[nod/2]]>a[h[nod]])
          {
              swap(nod,nod/2);
              swim(nod/2);
          }
    }
    return;

}

int main()
{   freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&nrop);
    for(q=1;q<=nrop;q++)
    {
        scanf("%d",&op);
        if(op==1)
            //adaug elementul x
            {scanf("%d",&nr);
             a[++n]=nr;
             h[++l]=n;
             pos[n]=l;
             swim(l);
            }
        if(op==2)
            //sterg elementul x
            {scanf("%d",&nr);
            a[nr]=-1;
            swim(pos[nr]);
            pos[h[1]]=0;
            h[1]=h[l--];
            pos[h[1]]=1;
            if(l>1) sink(1);
            }
        if(op==3)
            //minimul
            {
                printf("%d\n",a[h[1]]);
            }
    }

    return 0;
}