Cod sursa(job #1263197)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 14 noiembrie 2014 02:04:56
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.2 kb
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

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

class Heap{
public:
    Heap(int n = 0) :
        nH(0), cnt(0), D(n + 1), H(vector<int>(n + 1)), P(vector<int>(n + 1))
    {
    }
    int top() const
    {
        return D[H[1]];
    }
    void pop(int nod = 1) // stergerea nodului
    {
        nod = P[nod];
        H[nod] = H[nH--];
        P[H[nod]] = nod;
        down(nod);
    }
    void push(int nod)
    {
        D[++cnt] = nod;
        nod = cnt;
        H[++nH] = nod;
        P[nod] = nH;
        up(nH);
    }
    void up(int down)
    {
        int up = down / 2;
        while ( up > 0 && D[H[down]] < D[H[up]] )
        {
            Swap(down, up);
            down = up;
            up /= 2;
        }
    }
    void down(int up)
    {
        int down = up * 2;
        while ( down <= nH )
        {
            if ( down + 1 <= nH && D[H[down + 1]] < D[H[down]] )
                ++down;
            if ( D[H[up]] > D[H[down]] )
            {
                Swap(down, up);
                up = down;
                down *= 2;
            }
            else
                return;
        }
    }
    void Swap(int nod1, int nod2)
    {
        swap(H[nod1], H[nod2]);
        P[H[nod1]] = nod1;
        P[H[nod2]] = nod2;
    }
    void show()
    {
        for ( int i = 1; i <= nH; ++i )
            os << H[i] << " ";
        os << "\n";
        for ( int i = 1; i <= nH; ++i )
            os << D[H[i]] << " ";
        os << "\n";
        for ( int i = 1; i <= nH; ++i )
            os << P[i] << " ";
        os << "\n";
        os << "\n";
    }
private:
    int nH, cnt;
    vector<int> H, P, D;
};

int main()
{
    int t, op, nod;
    is >> t;
    Heap heap(t);
    while ( t-- )
    {
        is >> op;
        if ( op < 3 )
        {
            is >> nod;
            if ( op == 1 )
                heap.push(nod);
            else
                heap.pop(nod);
        }
        else
            os << heap.top() << "\n";
        //heap.show();
        //cin.get();
    }
    is.close();
    os.close();
    return 0;
}