Cod sursa(job #1099058)

Utilizator dragos-giidragos ghinoiu dragos-gii Data 5 februarie 2014 15:23:37
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#define maxzise 200006

using namespace std;

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

int N, L, NR;
int H[maxzise];
int A[maxzise];
int ORDER[maxzise];

void sift(int pos)
{
    int son = 0;

    while (pos != son)
    {
        son = pos;

        if (son * 2 <= L && A[H[pos]] > A[H[son * 2]])
            pos = son * 2;
        if (son * 2 + 1 <= L && A[H[pos]] > A[H[son * 2 + 1]])
            pos = son * 2 + 1;

        swap (H[pos], H[son]);

        ORDER[H[pos]] = pos;
        ORDER[H[son]] = son;
    }
}
void percolate(int pos)
{
    int key = A[H[pos]];

    while (pos > 1 && key < A[H[pos / 2]])
    {
        swap (H[pos], H[pos / 2]);

        ORDER[H[pos]] = pos;
        ORDER[H[pos / 2]] = pos / 2;
        pos /= 2;
    }
}

int main()
{
    int x, y, i;

    fin >> N;

    for (int i = 1; i <= N; ++i)
    {
        fin >> x;

        if (x == 1)
        {
            fin >> y;

            ++L;
            ++NR;
            A[NR] = y;
            H[L] = NR;
            ORDER[NR] = L;

            percolate (L);
        }

        if (x == 2)
        {
            fin >> y;

            A[y] = -1;
            percolate (ORDER[y]);

            //aducem ultima pozitie pe locul 1 in heap
            ORDER[H[1]] = 0;
            H[1] = H[L];
            --L;
            ORDER[H[1]] = 1;

            if (L > 1)
                sift (1);
        }

        if (x == 3)
        {
            fout << A[H[1]] << "\n";
        }
    }

}