Cod sursa(job #2453132)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 2 septembrie 2019 16:03:30
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <vector>
#include <fstream>

using std::swap;
using std::vector;

std::ifstream fin("heapuri.in");
std::ofstream fout("heapuri.out");

class Heap {
  private:
    int n;
    vector<int> a;
    vector<int> b;
    vector<int> p;

    void heapify(int i) {
        int min = i;
        if (2 * i <= n && a[2 * i] < a[i])
            min = 2 * i;
        if (2 * i + 1 <= n && a[2 * i + 1] < a[min])
            min = 2 * i + 1;
        if (min != i) {
            swap(a[i], a[min]);
            swap(b[i], b[min]);
            swap(p[b[i]], p[b[min]]);
            heapify(min);
        }
    }

    void decreaseKey(int i, int key) {
        a[i] = key;
        while (i > 1 && a[i] < a[i / 2]) {
            swap(a[i], a[i / 2]);
            swap(b[i], b[i / 2]);
            swap(p[b[i]], p[b[i / 2]]);
            i /= 2;
        }
    }

  public:
    Heap()
        : n(0), a(1), b(1), p(1) { }

    int top() {
        return a[1];
    }

    void pop(int x) {
        a[p[x]] = a[n];
        b[p[x]] = b[n];
        p[b[n]] = p[x];
        n--;
        a.pop_back();
        b.pop_back();
        heapify(p[x]);
    }

    void push(int key) {
        a.push_back(2e9);
        b.push_back(p.size());
        p.push_back(++n);
        decreaseKey(n, key);
    }
};

int main() {
    Heap heap;
    vector<int> past;

    int q; fin >> q;
    for (int i = 0; i < q; i++) {
        int type; fin >> type;
        if (type == 1) {
            int x; fin >> x;
            past.push_back(x);
            heap.push(x);
        }
        else if (type == 2) {
            int x; fin >> x;
            heap.pop(x);
        }
        else
            fout << heap.top() << '\n';
    }

    fout.close();
    return 0;
}