Cod sursa(job #3340239)

Utilizator jumaracosminJumara Cosmin-Mihai jumaracosmin Data 13 februarie 2026 01:34:40
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <bits/stdc++.h>

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

const int MOD = 1e9 + 7;
const int INF = 1e9 + 5;
const int64_t LONG_INF = static_cast<int64_t>(1e18) + 5;

namespace Heap {
struct node_t {
    int val;
    int idx;

    node_t(int _val = 0, int _idx = 0) : val(_val), idx(_idx) {
    }

    // Min-heap
    bool operator<(const node_t &other) const {
        return val < other.val;
    }
};

const int MAX_HEAP_SIZE = 2e5 + 5;
node_t h[MAX_HEAP_SIZE];
int heap_size = 0, inserted_cnt = 0;
int h_pos[MAX_HEAP_SIZE];

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

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

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

void swap(int x, int y) {
    std::swap(h[x], h[y]);
    std::swap(h_pos[h[x].idx], h_pos[h[y].idx]);
}

void siftTop(int pos) {
    while (pos > 1 && h[pos] < h[father(pos)]) {
        swap(pos, father(pos));
        pos = father(pos);
    }
}

void siftBottom(int pos) {
    int son = -1;
    if (leftSon(pos) <= heap_size) {
        son = leftSon(pos);
        if (rightSon(pos) <= heap_size && h[rightSon(pos)] < h[leftSon(pos)]) {
            son = rightSon(pos);
        }
    }

    if (son != -1 && h[son] < h[pos]) {
        swap(son, pos);
        siftBottom(son);
    }
}

int getTop() {
    return h[1].val;
}

void insert(int val) {
    heap_size++;
    inserted_cnt++;
    h[heap_size] = node_t(val, inserted_cnt);
    h_pos[h[heap_size].idx] = heap_size;
    siftTop(heap_size);
}

void remove(int of_idx) {
    int curr_pos = h_pos[of_idx];
    swap(curr_pos, heap_size);
    heap_size--;

    siftTop(curr_pos);
    siftBottom(curr_pos);
}
}; // namespace Heap

int n;

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);

    fin >> n;

    while (n--) {
        int type, x;
        fin >> type;

        if (type == 1) {
            fin >> x;
            Heap::insert(x);
        } else if (type == 2) {
            fin >> x;
            Heap::remove(x);
        } else {
            fout << Heap::getTop() << "\n";
        }
    }

    return 0;
}