Cod sursa(job #1325223)

Utilizator blue_skyPetrica Stefan Cosmin blue_sky Data 23 ianuarie 2015 15:39:29
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <fstream>
#define DIM 20000

using namespace std;

int n,c,x,v[2][DIM],H[DIM],hp,cr;

inline int ls(int k) {
    return k*2;
}
inline int rs(int k) {
    return k*2+1;
}
inline int father(int k) {
    return k/2;
}

int poz(int k)
{
    for(int i=1;i<=cr;++i)
    if(v[0][i]==k) return i;
}

void percolate(int k)
{
    while(H[father(k)] > H[k] && k>1)
    {
        swap(H[father(k)], H[k]);
        int a=poz(H[father(k)]);
        int b=poz(H[k]);
        swap(v[1][a],v[1][b]);
        k=father(k);
    }
}

void sift(int k)
{
    int son;
    do {
        son=0;
        if(ls(k) <=hp)
        {
            son=ls(k);
            if(rs(k) <=hp && H[rs(k)] < H[ls(k)])
            son=rs(k);

            if(H[son] >H[k])
            son=0;
        }
        if(son)
        {
            swap(H[son],H[k]);
            int a=poz(H[son]);
            int b=poz(H[k]);
            swap(v[1][a],v[1][b]);
            k=son;
        }
    }while(son);
}

void addHeap(int k)
{
    H[++hp]=k;
    percolate(hp);
}
void delHeap(int k)
{
    H[k]=H[hp--];
    sift(k);
}

int main()
{
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
    f>>n;
    for(int i=1;i<=n;++i)
    {
        f>>c;
        if(c==1)
        {
            f>>x;
            v[0][++cr]=x;
            v[1][cr]=hp+1;
            addHeap(x);
        }
        else if(c==2)
        {
            f>>x;
            delHeap(v[1][x]);
        }
        else
        g<<H[1]<<'\n';
    }
    f.close();
    g.close();
    return 0;
}