Cod sursa(job #981138)

Utilizator classiusCobuz Andrei classius Data 6 august 2013 14:32:59
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <fstream>
#include <algorithm>
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

const int MX_HP_SZ=1<<18;
typedef int Heap[MX_HP_SZ];
int v[200001],nd[200001];

inline int l_son(int nod){return nod*2;}
inline int r_son(int nod){return nod*2+1;}
inline int father(int nod){return nod/2;}
inline int mnx(Heap h){return h[1];}

void sift(Heap h,int n,int k)
{
    int son;

    do{
        son=0;

        if(l_son(k)<=n){
            son=l_son(k);
            if(r_son(k)<=n&&h[r_son(k)]<h[l_son(k)])
                son=r_son(k);
            if(h[son]>h[k])
                son=0;
        }

        if(son){
            swap(v[son],v[k]);
            swap(nd[v[k]],nd[v[son]]);
            swap(h[k],h[son]);
            k=son;
        }
    }while(son);

    return;
}

void percolate(Heap h,int n,int k)
{
    int key=h[k];

    while(k>1&&key<h[father(k)]){
        swap(v[k],v[father(k)]);
        swap(nd[v[k]],nd[v[father(k)]]);
        h[k]=h[father(k)];
        k=father(k);
    }
    h[k]=key;


    return;
}

void insert(Heap h,int& n,int key,int pz)
{
    h[++n]=key;
    v[pz]=n;
    nd[pz]=n;
    percolate(h,n,n);

    return;
}

void cut(Heap h,int& n,int k)
{
    h[k]=h[n];
    swap(v[k],v[n]);
    swap(nd[v[k]],nd[v[n]]);
    --n;
    if(k>1&&h[k]<h[father(k)])
        percolate(h,n,k);
    else
        sift(h,n,k);

    return;
}


int main()
{
    int n=0,m,k=0;
    Heap h;

    f>>m;

    for(int i=1;i<=m;i++){
        int op,x;
        f>>op;
        switch(op){
            case 1:
                f>>x;
                ++k;
                insert(h,n,x,k);
                break;
            case 2:
                f>>x;
                cut(h,n,nd[x]);
                break;
            case 3:
                g<<mnx(h)<<'\n';
                break;
        }
    }

    return 0;
}