Cod sursa(job #1430414)

Utilizator PlatonVPlaton Vlad PlatonV Data 8 mai 2015 13:29:29
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#include <algorithm>
#include <iostream>

#define maxn 200003

using namespace std;

int N, h[maxn], p[maxn], s, a[maxn], nr; 
void insereaza(int x)
{
    ++s;   
    h[s] = x;
    int pos = s;
    p[x] = s;
    while (h[pos / 2] > h[pos] && pos / 2)
    {
        p[h[pos / 2]] = pos;
        p[h[pos]] = pos / 2;

        swap(h[pos / 2], h[pos]);

        pos /= 2;
    }
}

void sterge(int x)
{
    int at = p[a[x]];
    swap (h[at], h[s]);
    h[s] = 0;
    s--; 

    bool da = true;
    while (da)
    {
        da = false;
        if (h[at * 2] < h[at] && at * 2 <= s)
        {
            p[h[at]] = at * 2;
            p[h[at * 2]] = at;

            swap (h[at], h[at * 2]);
            at *= 2;

            da = true;
        }
        else if (h[at * 2 + 1] < h[at] && at * 2 + 1 <= s) 
        {
            p[h[at]] = at * 2 + 1;
            p[h[at * 2 + 1]] = at;

            swap (h[at], h[at * 2 + 1]);
            at *= 2; at++;

            da = true;
        }
    }
}

void afiseaza()
{
    cout << h[1] << endl;
}

int main()
{
    ifstream f("heapuri.in");
    freopen("heapuri.out", "w", stdout);

    f >> N;
    for (int p = 0; p < N; ++p)
    {
        int cod, val;
        f >> cod;
        if (cod == 1)
        {
            f >> val;
            a[++nr] = val;
            insereaza(val);
        }
        else if (cod == 2)
        {
            f >> val;
            sterge(val);
        }
        else
            afiseaza();
    }

    return 0;
}