Cod sursa(job #1701749)

Utilizator mariakKapros Maria mariak Data 13 mai 2016 23:32:16
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <bits/stdc++.h>
#define Nmax 200002
FILE *fin  = freopen("heapuri.in", "r", stdin);
FILE *fout = freopen("heapuri.out", "w", stdout);

using namespace std;
int n, N, nr_insert, H[Nmax], P[Nmax], IP[Nmax];
inline int parent(int x)
{
    return x >> 1;
}
inline int Lson(int x)
{
    return x << 1;
}
inline int Rson(int x)
{
    return x << 1 + 1;
}
void descend(int k)
{
    int son, lson, rson;
    do
    {
        son = 0;
        lson = Lson(k), rson = Rson(k);
        if(lson <= N)
        {
            son = lson;
            if(rson <= N && H[son] > H[rson])
                son = rson;
            if(H[k] <= H[son])
                son = 0;
        }
        if(son)
        {
            swap(H[son], H[k]);
            swap(P[IP[k]], P[IP[son]]);
            swap(IP[k], IP[son]);
            k = son;
        }
    }while(son);
}
void climb(int k, int pos)
{
    int key = H[k];
    while(k > 1 && key < H[parent(k)])
    {
        H[k] = H[parent(k)];
        P[IP[parent(k)]] = k;
        IP[k] = IP[parent(k)];
        k = parent(k);
    }
    H[k] = key;
    P[pos] = k;
    IP[k] = pos;
}
void h_insert(int &N, int key, int pos)
{
    H[++ N] = key;
    climb(N, pos);
}
void h_erase(int &N, int pos)
{
    int k = P[pos];
    H[k] = H[N];
    P[IP[N]] = k, IP[k] = IP[N];
    -- N;
    if(k > 1 && H[k] < H[parent(k)])
        climb(k, IP[k]);
    else descend(k);
    P[pos] = -1;
}
int main()
{
    int t, v;
    scanf("%d", &n);
    while(n --)
    {
        scanf("%d", &t);
        if(t == 3) printf("%d\n", H[1]);
        else
        {
            scanf("%d", &v);
            if(t == 1)
            {
                ++ nr_insert;
                h_insert(N, v, nr_insert);
            }
            else h_erase(N, v);
        }
    }
    return 0;
}