Cod sursa(job #2288781)

Utilizator livliviLivia Magureanu livlivi Data 23 noiembrie 2018 21:16:14
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include<fstream>
#include<vector>
using namespace std;

ifstream cin("heapuri.in");
ofstream cout("heapuri.out");

vector<bool> erased;
vector<pair<int,int> > heap;

void insertHeap(int x){
    erased.push_back(false);
    heap.push_back({x, erased.size() - 1});

    int p = heap.size() - 1;
    while(p > 1){
        if (heap[p] < heap[p / 2]){
            swap(heap[p], heap[p / 2]);
            p /= 2;
        }
        else p = 1;
    }
}

void popHeap(){
    swap(heap[1], heap.back());
    heap.pop_back();

    int p = 1;
    while(p * 2 < heap.size()){
        if (p * 2 + 1 == heap.size() && heap[p] > heap[p * 2]){
            swap(heap[p], heap[p * 2]);
            p *= 2;
        }
        else
        if (heap[p] > heap[p * 2] && heap[p * 2] < heap[p * 2 + 1]){
            swap(heap[p], heap[p * 2]);
            p *= 2;
        }
        else
        if (heap[p] > heap[p * 2 + 1] && heap[p * 2] > heap[p * 2 + 1]){
            swap(heap[p], heap[p * 2 + 1]);
            p = p * 2 + 1;
        }
        else p = heap.size();
    }
}

void eraseHeap(int x){
    erased[x] = true;

    while(heap.size() > 1 && erased[heap[1].second] == true){
        popHeap();
    }
}

int queryHeap(){
    while(heap.size() > 1 && erased[heap[1].second] == true){
        popHeap();
    }

    return heap[1].first;
}

int main(){
    int n;
    cin >> n;

    insertHeap(0);
    for(int i = 0; i < n; i++){
        int op;
        cin >> op;

        if (op == 1){
            int x;
            cin >> x;
            insertHeap(x);
        }
        else
        if (op == 2){
            int x;
            cin >> x;
            eraseHeap(x);
        }
        else cout << queryHeap() << '\n';
    }

    return 0;
}