Cod sursa(job #1261336)

Utilizator binicBinica Nicolae binic Data 12 noiembrie 2014 11:39:16
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
// Heap de tip minim
#include<cstdio>
#include<algorithm>
using namespace std;
int n,i,cod,l,nr,x,p1,a[200004],p[200004];
typedef int heap[200004];
heap h;
void sift(heap h,int n,int k)// Elementul k coboara in arbore
{
    //h[k*2] este fiul stang al nodului k
    //h[k*2+1] este fiul drept al nodului k
    while(h[k]>h[k*2]||h[k]>h[k]*2+1)
    {
        if(h[k*2]>h[k*2+1]&&k*2+1<=n)
        {
            swap(h[k],h[k*2+1]);   //Functie care intershimba h[k]cu h[k*2+1]
            p[h[k]]=k;
            p[h[k*2+1]]=k*2+1;
            k=k*2+1;
        }
        else if(k*2<=n)
        {
            swap(h[k],h[k*2]);
            p[h[k]]=k;
            p[h[k*2]]=k*2;
            k=k*2;
        }
        else break;
    }
}
void percolate(heap h,int n,int k) // Elementul k urca in arbore
{
    while(h[k]<h[k/2]&&k/2>0)
    {
        swap(h[k],h[k/2]);
        p[h[k]]=k;
        p[h[k/2]]=k/2;
        k=k/2;
    }
}
void cut(heap h, int n,int k)
{
    h[k]=h[n];
    n--;
    if(k>1&&h[k]<h[k/2])percolate(h,n,k);
    else sift(h,n,k);
}
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&cod);
        if(cod==1)
        {
            scanf("%d",&x);
            l++;
            nr++;
            a[nr]=x;
            h[l]=x;
            percolate(h,l,l);
        }
        if(cod==2)
        {
            scanf("%d",&x);
            p1=p[a[x]];
            cut(h,l,p1);
        }
        if(cod==3)printf("%d\n",h[1]);
    }
    return 0;
}