Cod sursa(job #911816)

Utilizator TeodoraTanaseTeodora Tanase TeodoraTanase Data 11 martie 2013 21:19:07
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.24 kb
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

vector < pair < int, int > > H;
vector < int > ord;

int n;

void Up(int poz)
{
    if(poz == 0)
        return;

    int father = poz / 2;

    if(H[poz].first < H[father].first)
    {
        swap(H[poz], H[father]);
        ord[H[poz].second] = poz;
        ord[H[father].second] = father;

        Up(father);
        return;
    }
}

void Down(int poz)
{
    int left = (poz << 1);
    int right = left + 1;

    if(left < n && right >= n && H[poz].first > H[left].first)
    {
        swap(H[poz], H[left]);
        ord[H[poz].second] = poz;
        ord[H[left].second] = left;

        Down(left);
        return;
    }

    if(right < n && left >= n && H[poz].first > H[right].first)
    {
        swap(H[poz], H[right]);
        ord[H[poz].second] = poz;
        ord[H[right].second] = right;

        Down(right);
        return;
    }

    if(left < n && right < n)
    {
        if(H[poz].first > H[left].first)
        {
            swap(H[poz], H[left]);
            ord[H[poz].second] = poz;
            ord[H[left].second] = left;

            Down(left);
            return;
        }

        if(H[poz].first > H[right].first)
        {
            swap(H[poz], H[right]);
            ord[H[poz].second] = poz;
            ord[H[right].second] = right;

            Down(right);
            return;
        }
    }
}

int main()
{
    int m;
    int c;
    int x;

    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    scanf("%d\n", &m);

    while(m --)
    {
        scanf("%d ", &c);

        if(c == 3)
            printf("%d\n", H[0].first);
        else
        {
            scanf("%d ", &x);

            if(c == 1)
            {
                H.push_back(make_pair(x, n));
                ord.push_back(n);
                ++ n;

                Up(n - 1);
            }
            else
            {
                -- x;
                H[ord[x]] = H[n - 1];
                H.pop_back();

                Down(ord[x]);

                ord[x] = ord[n];
                -- n;
            }
        }
    }

    return 0;
}