Cod sursa(job #3237612)

Utilizator SilviuC25Silviu Chisalita SilviuC25 Data 10 iulie 2024 16:58:07
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAXN = 200005;

int n, heapSize, elemCount;
int values[MAXN], heap[MAXN], pos[MAXN];

void heapPush(int ind) {
    int temp;
    while (ind > 0 && values[heap[ind]] < values[heap[(ind - 1) / 2]]) {
        temp = heap[ind];
        heap[ind] = heap[(ind - 1) / 2];
        heap[(ind - 1) / 2] = temp;
        pos[heap[ind]] = ind;
        pos[heap[(ind - 1) / 2]] = (ind - 1) / 2;
        ind = (ind - 1) / 2;
    }
}

void heapPop(int ind) {
    int temp, smallest = -1;
    while (ind != smallest) {
        smallest = ind;
        if (2 * smallest + 1 < heapSize && values[heap[ind]] > values[heap[2 * smallest + 1]]) {
            ind = 2 * smallest + 1;
        }
        if (2 * smallest + 2 < heapSize && values[heap[ind]] > values[heap[2 * smallest + 2]]) {
            ind = 2 * smallest + 2;
        }
        temp = heap[ind];
        heap[ind] = heap[smallest];
        heap[smallest] = temp;
        pos[heap[ind]] = ind;
        pos[heap[smallest]] = smallest;
    }
}

int main() {
    fin >> n;
    for (int i = 0; i < n; ++i) {
        int c, x;
        fin >> c;
        if (c == 1) {
            fin >> x;
            ++heapSize, ++elemCount;
            values[elemCount] = x;
            heap[heapSize - 1] = elemCount;
            pos[elemCount] = heapSize - 1;
            heapPush(heapSize - 1);
        } else if (c == 2) {
            fin >> x;
            values[x] = -1;
            heapPush(pos[x]);
            pos[heap[0]] = -1;
            heap[0] = heap[--heapSize];
            pos[heap[0]] = 0;
            if (heapSize > 1)
                heapPop(0);
        } else {
            fout << values[heap[0]] << "\n";
        }
    }
    return 0;
}