Cod sursa(job #963431)

Utilizator mvcl3Marian Iacob mvcl3 Data 17 iunie 2013 14:42:56
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>
#define max_size 200009
using namespace std;

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

int N, in, t, tip, x, fr1[max_size], fr2[max_size], Heap[max_size];

inline void Swap(int poz1, int poz2)
{
    swap(Heap[poz1], Heap[poz2]);
    swap(fr1[poz1], fr1[poz2]);
    fr2[fr1[poz1]] = poz1,  fr2[fr1[poz2]] = poz2;
}

void percolate(int son)
{
    int father = son >> 1;
    if(Heap[son] < Heap[father] && father > 0)
    {
        Swap(son, father);
        percolate(father);
    }
}

inline int give_left_son(int father)
{
    return father * 2;
}

void sift(int father, int n)
{
    int left_son = give_left_son(father),
        right_son = left_son + 1, min_son = left_son;

    if(left_son > n)    return;
    if(left_son < n)
        if(Heap[left_son] > Heap[right_son])
            min_son = right_son;

    if(Heap[father] > Heap[min_son])
    {
        Swap(father, min_son);
        sift(min_son, n);
    }
}

int main()
{
    f >> t;

    while(t --)
    {
        f >> tip;
        switch(tip)
        {
            case 1 :
            {
                f >> x;
                Heap[++N] = x;
                fr1[N] = ++in;
                fr2[in] = N;
                percolate(N);
                break;
            }
            case 2:
            {
                f >> x;
                int poz = fr2[x];
                Swap(poz, N);
                --N;
                percolate(poz);
                sift(poz, N);
                break;
            }
            case 3:
            {
                g << Heap[1] << '\n';
                break;
            }
        }
    }

    g.close();
    return 0;
}