Cod sursa(job #1366639)

Utilizator sorynsooSorin Soo sorynsoo Data 1 martie 2015 12:24:59
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <cstdio>
#include <algorithm>
using namespace std;
int heap[200001],poz[200001],dim_heap,i,n,nr,x,tip;
int father(int nod)
{
    return nod/2;
}
int left_son(int nod)
{
    return nod*2;
}
int right_son(int nod)
{
    return nod*2+1;
}
void coboara(int N, int K)//heap-ul are n valori, vreau sa coboaraez noul k
{
    int son;
    do
    {
        son = 0;
        // Alege un fiu mai mic ca tatal.
        if (left_son(K) <= N)
        {
            son = left_son(K);
            if (right_son(K) <= N && heap[right_son(K)] < heap[left_son(K)])
                son = right_son(K);

            if (heap[son] >= heap[K])
                son = 0;
        }

        if (son)
        {
            swap(poz[heap[K]],poz[heap[son]]);
            swap(heap[K], heap[son]);
            K = son;
        }
    } while (son);
}
void urca(int N, int K) {
    int key = heap[K];

    while ((K > 1) && (key < heap[father(K)]))
    {
        heap[K] = heap[father(K)];
        K = father(K);
    }

    swap(poz[heap[K]],poz[key]);
    heap[K] = key;
}
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    for(i=1; i<=n; i++)
    {
        scanf("%d",&tip);
        if(tip==1)
        {
            scanf("%d",&x);
            heap[++dim_heap]=x;
            nr++;   poz[x]=nr;
            urca(dim_heap, dim_heap);
        }
        if(tip==2)
        {
            scanf("%d",&x);
            heap[x]=heap[dim_heap--];
            x=poz[x];
            if ((x > 1) && (heap[x] < heap[father(x)]))
                urca(dim_heap, x);
            else
                coboara(dim_heap, x);
        }
        if(tip==3)
            printf("%d\n",heap[1]);
    }

}