Cod sursa(job #1824081)

Utilizator fluture.godlikeGafton Mihnea Alexandru fluture.godlike Data 7 decembrie 2016 11:38:06
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.5 kb
/// Problema "Heapuri" - InfoArena
#include <cstdio>
#include <algorithm>

#define in "heapuri.in"
#define out "heapuri.out"
#define NMAX (200000 + 7)

using namespace std;
int H[NMAX], loc[NMAX], Rloc[NMAX], ct, N, cod, nr, sze;

int upheap(int key)
{
    while(key > 1)
    {
        if(H[key] < H[(key>>1)])
        {
            swap(H[key], H[(key>>1)]);
            loc[Rloc[key]] = (key>>1);
            loc[Rloc[(key>>1)]] = key;
            swap(Rloc[key], Rloc[(key>>1)]);
            key >>= 1;
        }
        else break;
    }
    return key;
}
inline void downheap(int key)
{
    while(((key<<1)|1) <= sze)
    {
        if(H[key] > min(H[(key<<1)], H[((key<<1)|1)]))
        {
            if(H[(key<<1)] < H[((key<<1)|1)])
            {
                swap(H[key], H[(key<<1)]);
                loc[Rloc[key]] = (key<<1);
                loc[Rloc[(key<<1)]] = key;
                swap(Rloc[key], Rloc[(key<<1)]);
                key = (key<<1);
                continue;
            }
            if(H[((key<<1)|1)] < H[(key<<1)])
            {
                swap(H[key], H[((key<<1)|1)]);
                loc[Rloc[key]] = ((key<<1)|1);
                loc[Rloc[((key<<1)|1)]] = key;
                swap(Rloc[key], Rloc[((key<<1)|1)]);
                key = ((key<<1)|1);
                continue;
            }
        }
        else break;
    }
    if((key<<1) == sze)
    {
        if(H[(key<<1)] < H[key])
        {
            swap(H[key], H[(key<<1)]);
            loc[Rloc[key]] = (key<<1);
            loc[Rloc[(key<<1)]] = key;
            swap(Rloc[key], Rloc[(key<<1)]);
            key = (key<<1);
        }
    }
}

inline void insereaza(const int &value)
{
    sze++;
    ct++;
    H[sze] = value;
    loc[ct] = sze;
    Rloc[sze] = ct;
    upheap(sze);
}
inline void elimina(int key)
{
    swap(H[key], H[sze]);
    loc[Rloc[sze]] = key;
    loc[Rloc[key]] = 0;
    Rloc[key] = Rloc[sze];
    Rloc[sze] = 0;
    --sze;
    key = upheap(key);
    downheap(key);
}

int main()
{
    freopen(in, "r", stdin);
    freopen(out, "w", stdout);
    scanf("%d", &N);
    for(; N; --N)
    {
        scanf("%d", &cod);
        if(cod == 1)
        {
            scanf("%d", &nr);
            insereaza(nr);
        }
        if(cod == 2)
        {
            scanf("%d", &nr);
            elimina(loc[nr]);
        }
        if(cod == 3)
        {
            printf("%d\n", H[1]);
        }
    }
    return 0;
}