Cod sursa(job #3155953)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 10 octombrie 2023 12:12:02
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
#define MAXN 200000

using namespace std;

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

int n = 0, heap[MAXN], q, current = 0, arr[MAXN], pos[MAXN];

int swim(int k) {
    while (k / 2 && arr[heap[k]] < arr[heap[k / 2]]) {
        swap(heap[k], heap[k / 2]);
        pos[heap[k]] = k;
        pos[heap[k / 2]] = k / 2;
        k /= 2;
    }
    return k;
}

int sink(int k) {
    int j = 0;
    while (k != j) {
        j = k;
        if (j * 2 <= n && arr[heap[k]] > arr[heap[j * 2]])
            k = j * 2;
        if (j * 2 + 1 <= n && arr[heap[k]] > arr[heap[j * 2 + 1]])
            k = j * 2 + 1;
        swap(heap[k], heap[j]);
        pos[heap[k]] = k;
        pos[heap[j]] = j;
    }
    return k;
}

int main() {
    fin >> q;
    for (; q; q--) {
        int op, x;
        fin >> op;
        switch (op) {
        case 1:
            fin >> arr[current];
            heap[++n] = current;
            pos[current] = swim(n);
            current++;
            break;
        case 2:
            fin >> x;
            x--;
            arr[x] = -1;
            pos[x] = swim(pos[x]);

            pos[heap[1]] = 0;
            heap[1] = heap[n--];
            pos[heap[1]] = 1;
            if (n > 1)
                sink(1);
            break;
        case 3:
            fout << arr[heap[1]] << '\n';
            break;
        }
    }
    return 0;
}