Cod sursa(job #621968)

Utilizator cristianalex81Cristian Alexandru cristianalex81 Data 17 octombrie 2011 00:04:07
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <stdio.h>
#include <vector>
#define dim 200001
using namespace std;

int a[dim],h[dim],poz[dim],an=1,hn=1;

inline int father (int nod)
{
    return nod>>1;
}
inline int lson (int nod)
{
    return nod<<1;
}
inline int rson (int nod)
{
    return nod<<1|1;
}

void shift(int n,int nod)
{
    int left,right,min,t1,t2;
    min = nod; //minimum is the actual node;
    if (lson(nod)<=n)
    {
        left = lson(nod);
        if (a[h[left]]<a[h[min]])
            min = left;
    }
    if (rson(nod)<=n)
    {
        right = rson(nod);
        if (a[h[right]]<a[h[min]])
            min = right;
    }
    if (min!=nod)//min is one of the sons
    {
        t1 = h[nod];
        t2 = poz[h[nod]];
        poz[h[nod]] = poz[h[min]];
        h[nod] = h[min];
        poz[h[min]] = t2;
        h[min] = t1;
        shift(n,min);
    }
}

void percolate(int n, int nod)
{
    int fat,t1,t2;
    if (nod>1)
    {
        fat = father(nod);
        if (a[h[fat]]>a[h[nod]])
        {
            t1=h[fat];
            t2=poz[h[fat]];
            poz[h[fat]]=poz[h[nod]];
            h[fat]=h[nod];
            poz[h[nod]]=t2;
            h[nod]=t1;
            percolate(n,fat);
        }
    }
}

void del(int n, int nod)
{
    int fat;
    poz[h[n]] = poz[h[nod]];
    poz[h[nod]] = 0;
    h[nod]=h[n];//aduc ultimul nod pe poz curenta
    hn--; // scad dim heap
    if (nod > 1)
        fat = father (nod);
    else
        fat = nod;
    if (a[h[nod]]<a[h[fat]])
        percolate(hn,nod);
    else
        shift(hn,nod);
}

int main()
{
    int i,m,c,x;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&m);
    for (i=0;i<m;i++)
    {
        scanf("%d",&c);
        if (c==1) // insert x in heap
        {
            scanf("%d",&x);
            a[an]=x;
            h[hn]=an;
            poz[an]=hn;
            percolate(hn,hn);
            an++;
            hn++;
        }
        if (c==2) // delete the x'th element inserted in heap
        {
            scanf("%d",&x);
            del(hn-1,poz[x]);
        }
        if (c==3) // print heap min
        {
            printf("%d\n",a[h[1]]);
        }
    }
    return 0;
}