Cod sursa(job #1249907)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 27 octombrie 2014 17:21:21
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.45 kb
#include <fstream>

#define Nmax 200100

using namespace std;

class HEAP {

    #define Root 1
    #define Father (Node >> 1)
    #define leftSon (Node << 1)
    #define rightSon ((Node << 1) | 1)
    #define compare(a, b) (A[Heap[a]] < A[Heap[b]])

    private:
        int top, Heap[Nmax], A[Nmax], Position[Nmax];

    public:

        HEAP() {

            top = 0;

        }

        void insert(int X, int Value) {

            A[X] = Value;
            Heap[++top] = X;
            Position[X] = top;

            up(top);

        }

        void pop(int X) {

            //A[X] = -1;

            Position[Heap[top]] = Position[X];
            Heap[Position[X]] = Heap[top--];

            down(Position[X]);
            up(Position[X]);

            Position[X] = -1;

        }

        int front() {

            return A[Heap[1]];


        }

        int size() {

            return top;

        }

    private:

        void up(int Node) {

            while(Node != Root && compare(Node, Father)) {
                swap(Heap[Node], Heap[Father]);
                swap(Position[Heap[Node]], Position[Heap[Father]]);
                Node = Father;
                }

        }

        void down(int Node) {

            int Son;

            do {

                Son = 0;

                if(leftSon <= size()) {

                    Son = leftSon;
                    if(rightSon <= size() && compare(rightSon, leftSon))
                        Son = rightSon;

                    if(compare(Node, Son))
                        Son = 0;

                    }

                if(Son != 0) {
                    swap(Heap[Node], Heap[Son]);
                    swap(Position[Heap[Node]], Position[Heap[Son]]);
                    Node = Son;
                    }

            } while(Son != 0);

        }

};

HEAP H;

int main() {

    int type, x, N, T;
    ifstream in("heapuri.in");
    ofstream out("heapuri.out");

    in >> T;

    for(N = 0; T--; ) {

        in >> type;

        switch(type) {

            case 1:
                in >> x;
                H.insert(++N, x);
                break;

            case 2:
                in >> x;
                H.pop(x);
                break;

            case 3:
                out << H.front() << '\n';

            }

        }

    in.close();
    out.close();

    return 0;

}