Cod sursa(job #2890711)

Utilizator ViAlexVisan Alexandru ViAlex Data 16 aprilie 2022 13:11:41
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include<iostream>
#include<fstream>
#include<vector>

using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");

const int mx = 2e5 + 10;

int heap[mx], heap_size = 0, current_time = 0, index_to_time[mx], time_to_index[mx];

int father(int x) {
    return x / 2;
}

int left(int x) {
    return x * 2;
}

int right(int x) {
    return x * 2 + 1;
}

void swap_nodes(int a, int b) {
    swap(heap[a], heap[b]);
    swap(time_to_index[index_to_time[a]], time_to_index[index_to_time[b]]);
    swap(index_to_time[a], index_to_time[b]);
}


void lift(int x) {
    int f = father(x);
    while (f != 0 && heap[x] < heap[f]) {
        swap_nodes(x, f);
        x = f;
        f = father(x);
    }
}

void shift(int x) {
    int best;
    do {
        best = 0;
        int l = left(x), r = right(x);

        if (l <= heap_size) {
            best = l;
            if (r <= heap_size) {
                best = heap[l] < heap[r] ? l : r;
            }
        }
        if (best != 0 && heap[x] > heap[best]) {
            swap_nodes(x, best);
            x = best;
        }
    } while (best);
}

void insert(int x) {
    heap[++heap_size] = x;
    index_to_time[heap_size] = ++current_time;
    time_to_index[current_time] = heap_size;
    lift(heap_size);
}

void erase(int time_index) {
    int node = time_to_index[time_index];
    swap_nodes(node, heap_size);
    heap_size--;
    shift(node);
}

int minimum() {
    return heap[1];
}


void solve() {
    int n, a, b;
    in >> n;
    while (n--) {
        in >> a;
        if (a == 1) {
            in >> b;
            insert(b);
        } else if (a == 2) {
            in >> b;
            erase(b);
        } else {
            out << minimum() << '\n';
        }
    }
}

int main() {
    solve();
    return 0;
}