Cod sursa(job #1300967)

Utilizator EpictetStamatin Cristian Epictet Data 25 decembrie 2014 12:36:44
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>
using namespace std;
ifstream fin ("heapuri.in");
ofstream fout ("heapuri.out");
int N, t, val, nr, cr, num, Poz[200010], Heap[200010], V[200010];

void Insert_Heap(int x)
{
    while (x / 2 && V[Heap[x]] < V[Heap[x / 2]])
    {
        swap (Heap[x], Heap[x / 2]);
        //swap (Poz[Heap[x]], Poz[Heap[x / 2]]);
        Poz[Heap[x]] = x;
        Poz[Heap[x / 2]] = x / 2;
        x /= 2;
    }
}

void Erase_Heap(int x)
{
    swap(Heap[x], Heap[nr]);
    nr--;

    while (x * 2 <= nr)
    {
        if (x * 2 < nr && V[Heap[x*2]] > V[Heap[x*2+1]] && V[Heap[x]] > V[Heap[x*2+1]])
        {
            swap (Heap[x], Heap[x*2+1]);
            Poz[Heap[x]] = x;
            Poz[Heap[x*2+1]] = x*2+1;
            x = x * 2 + 1;
        }
        else if (V[Heap[x]] > V[Heap[x*2]])
        {
            swap (Heap[x], Heap[x*2]);
            Poz[Heap[x]] = x;
            Poz[Heap[x*2]] = x*2;
            x = x * 2;
        }
        else
        {
            x = nr + 1;
        }
    }
}

int Extract_Min()
{
    return V[Heap[1]];
}

int main()
{
    fin >> N;
    for (int i = 1; i <= N; i++)
    {
        fin >> t;
        switch (t)
        {
            case 1 :
            {
                fin >> val;
                V[++num] = val;
                Heap[++nr] = num;
                Poz[num] = nr;
                Insert_Heap(nr);
                break;
            }
            case 2 :
            {
                fin >> val;
                Erase_Heap(Poz[val]);
                break;
            }
            case 3 :
            {
                fout << Extract_Min() << '\n';
                break;
            }
        }
    }

    fout.close();
    return 0;
}