Cod sursa(job #1884957)

Utilizator cristicretancristi cretan cristicretan Data 19 februarie 2017 15:16:34
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
#define NMax 200001
#define INF 0x3f3f3f3f
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

int n, heap[NMax], cod, x, L, nr, a[NMax], poz[NMax];

void push(int x)
{
    while (x/2 && a[heap[x]] < a[heap[x/2]])
    {
        swap(heap[x], heap[x / 2]);
        poz[heap[x]] = x;
        poz[heap[x/2]] = x/2;
        x /= 2;
    }
}

void pop(int x)
{
    int y = 0;

    while (x != y)
    {
        y = x;

        if (y*2 <= L && a[heap[x]] > a[heap[y*2]]) x = y*2;
        if (y*2 + 1 <= L && a[heap[x]] > a[heap[y*2+1]]) x = y*2+1;

        swap(heap[x], heap[y]);

        poz[heap[x]] = x;
        poz[heap[y]] = y;
    }
}

int main()
{
    f >> n;
    for(int i = 1; i <= n; ++i)
    {
        f >> cod;
        if(cod < 3) f >> x;
        if(cod == 1)
        {
            a[++nr] = x;
            heap[++L] = nr;
            poz[nr] = L;

            push(L);
        }
        else if(cod == 2)
        {
            a[x] = -1;
            push(poz[x]);

            poz[heap[1]] = 0;
            heap[1] = heap[--L];
            poz[heap[1]] = 1;
            if(L > 1) pop(1);
        }
        else if(cod == 3) g << heap[1] << '\n';
    }
    return 0;
}