Cod sursa(job #1131483)

Utilizator obidanDan Ganea obidan Data 28 februarie 2014 20:28:01
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <cstdio>
#include <algorithm>
using namespace std;
inline int left(int i) { return (i<<1); }
inline int right(int i) {return (i<<1)+1; }
inline int dad(int i) {return (i>>1);}
int a[200010],timp[200010],poz[200010];
int heapsize;
int t=1;
void heapify(int x)
{
   int l=left(x),r=right(x),minim;
    if((l<=heapsize)&&(timp[a[l]]<timp[a[x]]))
    {
        minim=l;
    }
    else
        minim=x;
    if((r<=heapsize) &&(timp[a[r]]<timp[a[minim]]))
    {
        minim=r;
    }
    if(minim!=x)
    {
        swap(poz[a[x]],poz[a[minim]]); // <- To look at
        swap(a[x],a[minim]);
        heapify(minim);
    }
}
void percolate(int x)
{
    int cheie;
    cheie=a[x];
    while((x>1)&&(timp[cheie]<timp[a[dad(x)]]))
    {
        poz[a[dad(x)]]= x;
        a[x]=a[dad(x)];
        x=dad(x);
    }
    poz[cheie]=x;
    a[x]=cheie;
}
void Insert(int x)
{
    heapsize++;
    a[heapsize]=x;
    poz[x]=heapsize;
   percolate(heapsize);

}
void extractMin()
{
    printf("%d\n",timp[a[1]]);
}
void Delete(int x)
{
    int parinte;
    a[poz[x]]=a[heapsize];
    poz[a[heapsize]]=poz[x];
    heapsize--;
    if(heapsize>1)
    {
        parinte=dad(poz[x]);
        if(timp[a[parinte]]>timp[a[poz[x]]])
        {
            percolate(poz[x]);
        }
        else
        {
            heapify(poz[x]);
        }

    }

}
int main()
{
    int i,x,n,c;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&c);
        if((c==1)||(c==2))
        {
            scanf("%d",&x);
            if(c==1)
            {
                timp[t]=x;
                Insert(t);
                t++;
            }
            else
            {
                Delete(x);
            }
        }
        else
        {
            extractMin();
        }
    }

}