Cod sursa(job #1090798)

Utilizator ScateWayScateWay ScateWay Data 23 ianuarie 2014 08:43:15
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include<stdio.h>
#include<algorithm>
#include<vector>
#define NMAX 200005
using namespace std;
typedef int heap[NMAX];
vector <int> a;
heap h;
int n,i,tip,x,poz[NMAX],nr,l;
int left_son(int nod)
{
    return nod*2;
}
int right_son(int nod)
{
    return nod*2+1;
}
int father(int nod)
{
    return nod/2;
}
void sift(int nod)
{
    int son;
    do
    {
        son=0;
        if(left_son(nod)<=l)
        {
            son=left_son(nod);
            if(right_son(nod) <= l && a[h[left_son(nod)]] <= a[h[right_son(nod)]])
                son=right_son(nod);
            if(a[h[son]] >= a[h[nod]])
                son=0;
        }
        if(son)
        {
            swap(h[son],h[nod]);
            poz[h[son]]=son;
            poz[h[nod]]=nod;
            nod=son;
        }
    }while(son);
}
void perlocate(int nod)
{
    int key=h[nod];
    while(nod>1 && a[h[father(nod)]] > a[key])
    {
        h[nod]=h[father(nod)];
        poz[h[nod]]=nod;
        nod=father(nod);
    }
    h[nod]=key;
    poz[h[nod]]=nod;
}
void cut(int nod)
{
    h[nod]=h[l];
    poz[h[nod]]=nod;
    l--;
    if(nod>1 && a[h[nod]] < a[h[father(nod)]])
        perlocate(nod);
    else
        sift(nod);
}
int main()
{
    a.push_back(0);
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&tip);
        if(tip==1)
        {
            scanf("%d",&x);
            nr++;
            l++;
            a.push_back(x);
            h[l]=nr;
            poz[nr]=l;
            perlocate(l);
        }
        if(tip==2)
        {
            scanf("%d",&x);
            cut(poz[x]);
        }
        if(tip==3)
            printf("%d\n",a[h[1]]);
    }
    return 0;
}