Cod sursa(job #1490883)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 24 septembrie 2015 12:50:40
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
#include <vector>
#include <stack>
#include <bitset>
#define INF 0x3f3f3f3f
using namespace std;

class Heap{
public:
    Heap() : n(0), el(0)
    {
        h.push_back(0);
        p.push_back(0);
        nr.push_back(0);
    }
    int top()
    {
        return nr[h[1]];
    }
    void push(int x)
    {
        h.push_back(++el);
        p.push_back(++n);
        nr.push_back(x);
        up(n);
    }
    void up(int down)
    {
        int up = down / 2;
        while ( up && nr[h[up]] > nr[h[down]] )
        {
            Swap(up, down);
            down = up;
            up /= 2;
        }
    }
    void pop(int x)
    {
        if ( p[x] == n )
        {
            --n;
            h.pop_back();
            return;
        }
        h[p[x]] = h[n--];
        p[h[p[x]]] = p[x];
        h.pop_back();
        down(p[x]);
    }
    void down(int up)
    {
        int down = 2 * up;
        while ( ( down <= n && nr[h[up]] > nr[h[down]] ) || ( down < n && nr[h[up]] > nr[h[down + 1]] ) )
        {
            if ( down < n && nr[h[down]] > nr[h[down + 1]] )
                ++down;
            Swap(up, down);
            up = down;
            down *= 2;
        }
    }
    void Swap(int x, int y)
    {
        swap(h[x], h[y]);
        swap(p[h[x]], p[h[y]]);
    }
private:
    int n, el;
    vector<int> h, p, nr;
} h;

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

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