Cod sursa(job #1811778)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 21 noiembrie 2016 16:27:27
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.57 kb
#include <bits/stdc++.h>
#define SZ(x) ((int) (x).size())
using namespace std;

vector<int> v;

template<class T>
struct Heap {
    vector<T> heap;
    vector<int> posInHeap;

    static bool Compare(const T& a, const T& b) {
        return v[a] < v[b];
    }

    Heap() {
    }

    Heap(const vector<T>& el) : heap(el) {
        posInHeap.resize(SZ(el));
        for (int i = 0; i < SZ(heap); i++) {
            posInHeap[heap[i]] = i;
        }
        for (int i = SZ(heap) / 2 - 1; i >= 0; i--) {
            DownHeap(i);
        }
    }

    void DownHeap(int node) {
        int bestNode; bool changed;
        do {
            changed = false;
            bestNode = node;
            if (2 * node + 1 < SZ(heap) and Compare(heap[2 * node + 1], heap[bestNode])) {
                bestNode = 2 * node + 1;
            }
            if (2 * node + 2 < SZ(heap) and Compare(heap[2 * node + 2], heap[bestNode])) {
                bestNode = 2 * node + 2;
            }
            if (bestNode != node) {
                posInHeap[heap[node]] = bestNode;
                posInHeap[heap[bestNode]] = node;
                swap(heap[node], heap[bestNode]);
                changed = true;
                node = bestNode;
            }
        } while (changed);
    }

    void UpHeap(int node) {
        int ancestor = (node - 1) / 2;
        while (node > 0 and Compare(heap[node], heap[ancestor])) {
            posInHeap[heap[node]] = ancestor;
            posInHeap[heap[ancestor]] = node;
            swap(heap[node], heap[ancestor]);
            node = ancestor;
            ancestor = (node - 1) / 2;
        }
    }

    void Insert(const T& x) {
        heap.emplace_back(x);
        posInHeap.emplace_back(SZ(heap) - 1);
        UpHeap(posInHeap[x]);
    }

    void Erase(const T& x) {
        const int pos = posInHeap[x];
        heap[pos] = heap.back();
        posInHeap[heap[pos]] = pos;
        heap.pop_back();
        DownHeap(pos);
    }

    T Top() const {
        return heap.front();
    }
};

int main() {
    #ifdef INFOARENA
    ifstream cin("heapuri.in");
    ofstream cout("heapuri.out");
    #endif
    cin.tie(0);
    ios_base::sync_with_stdio(false);

    int numOp; cin >> numOp;
    Heap<int> m_heap;
    for (int iter = 0; iter < numOp; iter++) {
        int opType; cin >> opType;
        if (opType == 1) {
            int x; cin >> x;
            v.emplace_back(x);
            m_heap.Insert(SZ(v) - 1);
        } else if (opType == 2) {
            int idx; cin >> idx;
            m_heap.Erase(idx - 1);
        } else {
            cout << v[m_heap.Top()] << '\n';
        }
    }
}