Cod sursa(job #1789250)

Utilizator ionutpop118Pop Ioan Cristian ionutpop118 Data 26 octombrie 2016 20:12:50
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <cstdio>
#include <algorithm>

using namespace std;
const int NMAX = 200000;

int N, p, best;
int heap[4 * NMAX + 5];
int timp[NMAX + 5];
int poz[NMAX + 5];

void MySwap(int a, int b)
{
    poz[timp[a]] = b;
    poz[timp[b]] = a;
    swap(timp[a], timp[b]);
    swap(heap[a], heap[b]);
}
void adaug(int x)
{
    heap[++N] = x; p = N;
    while (p != 1 && heap[p] < heap[p / 2])
    {
        MySwap(p, p / 2);
        p /= 2;
    }
}
void elimin(int x)
{
    p = poz[x];
    MySwap(p, N); --N;
    while (p * 2 <= N)
    {
        best = 2 * p;
        if(2 * p + 1 <= N && heap[best] > heap[2 * p + 1])
            best = 2 * p + 1;

        if(heap[p] > heap[best])
        {
            MySwap(p, best);
            p = best;
        }
        else
            break;
    }
}
int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    int k, test, x;
    scanf("%d", &k);
    for (register int op = 1; op <= k; ++op)
    {
        scanf("%d", &test);
        if (test == 1)
        {
            scanf("%d", &x);
            adaug(x);
        }
        else if (test == 2)
        {
            scanf("%d", &x);
            elimin(x);
        }
        else
            printf("%d\n", heap[1]);
    }
    return 0;
}