Cod sursa(job #1332025)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 1 februarie 2015 15:55:19
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.54 kb
#include <fstream>

#define Nmax 200100

using namespace std;

class priorityQueue {

    #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 size, Heap[Nmax], Location[Nmax], A[Nmax];

    public:
        priorityQueue() {
            size = 0;
        }

        void insert(int index, int value) {
            A[index] = value;
            Heap[++size] = index;
            Location[index] = size;

            up(size);
        }

        void update(int index, int value) {
            A[index] = value;
            up(Location[index]);
        }

        void pop() {
            Heap[1] = Heap[size--];
            Location[Heap[1]] = 1;
            down(1);
        }

        inline int operator[](int index) {
            return A[index];
        }

        int front() {
            return Heap[1];
        }

        bool empty() {
            return (size == 0);
        }

    private:
        void up(int node) {

            while(node != root && compare(node, father)) {
                swap(Heap[node], Heap[father]);
                swap(Location[Heap[node]], Location[Heap[father]]);
                node = father;
            }
        }

        void down(int node) {

            int son;
            do {
                son = 0;

                if(leftSon <= size) {
                    son = leftSon;

                    if(rightSon <= size && compare(rightSon, son))
                        son = rightSon;

                    if(compare(node, son))
                        son = 0;
                }

                if(son != 0) {
                    swap(Heap[node], Heap[son]);
                    swap(Location[Heap[node]], Location[Heap[son]]);
                    node = son;
                }
            } while(son);
        }
} pq;

int main() {

    int type, x, queries, N = 0;
    ifstream in("heapuri.in");
    ofstream out("heapuri.out");

    in >> queries;

    while(queries--) {

        in >> type;
        switch(type) {
            case 1:
                in >> x;
                pq.insert(++N, x);
                break;

            case 2:
                in >> x;
                pq.update(x, -1);
                pq.pop();
                break;

            case 3:
                out << pq[pq.front()] << '\n';
        }
    }

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

    return 0;
}