Cod sursa(job #1380090)

Utilizator pulseOvidiu Giorgi pulse Data 6 martie 2015 21:51:10
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 200010;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int n, m, x, h[MAXN];
int pos[MAXN], ord[MAXN], cnt;

int father(int x)
{
    return x / 2;
}

int lson(int x)
{
    return 2 * x;
}

int rson(int x)
{
    return 2 * x + 1;
}

void swaperino(int a, int b)
{
    swap(h[a], h[b]);
    swap(pos[ord[a]], pos[ord[b]]);
    swap(ord[a], ord[b]);
}

void percolate(int x)
{
    while (x > 1 && h[x] < h[father(x)])
    {
        swaperino(x, father(x));
        x = father(x);
    }
}

void sift(int x)
{
    int son;
    do
    {
        son = 0;
        if (lson(x) <= n)
        {
            son = lson(x);
            if (rson(x) <= n && h[rson(x)] < h[son])
                son = rson(x);
            if (h[son] > h[x])
                son = 0;
        }
        if (son)
        {
            swaperino(x, son);
            x = son;
        }
    } while (son);
}

void add(int x)
{
    ++cnt;
    ++n;
    ord[n] = cnt;
    pos[cnt] = n;
    h[n] = x;
    percolate(n);
}

void del(int x)
{
    int i = pos[x];
    swaperino(i, n);
    --n;
    if (i > 1 && h[i] < h[father(i)])
        percolate(i);
    else
        sift(i);
}

int main()
{
    fin >> m;
    for (int tip; m; --m)
    {
        fin >> tip;
        if (tip == 3)
            fout << h[1] << '\n';
        else
        {
            fin >> x;
            if (tip == 1) add(x);
            else del(x);
        }
    }
    return 0;
}