Cod sursa(job #1630661)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 5 martie 2016 10:40:25
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <iostream>
#include <vector>
#define INF 0x3f3f3f3f
using namespace std;

ifstream is("heapuri.in");
ofstream os("heapuri.out");

using VI = vector<int>;

class Heap{
public:
    Heap() : n(0), cnt(0)
    {
        h = v = p = VI(1);
    }
    int top()
    {
        return v[h[1]];
    }
    void insert(int x)
    {
        h.push_back(++cnt);
        v.push_back(x);
        p.push_back(++n);
        up(n);
    }
    void erase(int x)
    {
        p[h[n]] = p[x];
        h[p[x]] = h[n--];
        h.pop_back();
        down(p[x]);
    }
    void up(int poz)
    {
        while ( poz >> 1 && v[h[poz]] < v[h[poz >> 1]] )
        {
            swap(h[poz], h[poz >> 1]);
            swap(p[h[poz]], p[h[poz >> 1]]);
            poz >>= 1;
        }
    }
    void down(int poz)
    {
        while ( ( poz << 1 <= n && v[h[poz]] > v[h[poz << 1]] ) || ( poz << 1 < n && v[h[poz]] > v[h[(poz << 1) + 1]] ) )
        {
            poz <<= 1;
            if ( poz < n && v[h[poz + 1]] < v[h[poz]] )
                ++poz;
            swap(h[poz], h[poz >> 1]);
            swap(p[h[poz]], p[h[poz >> 1]]);
        }
    }
private:
    int n, cnt;
    VI v, h, p;
} h;

int m;

int main()
{
    is >> m;
    int tip, x;
    while ( m-- )
    {
        is >> tip;
        if ( tip == 3 )
            os << h.top() << "\n";
        else
        {
            is >> x;
            if ( tip == 1 )
                h.insert(x);
            else
                h.erase(x);
        }
    }
    is.close();
    os.close();
    return 0;
}