Cod sursa(job #3126095)

Utilizator vatau.lorenaVatau Lorena vatau.lorena Data 5 mai 2023 23:29:33
Problema Heapuri cu reuniune Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 105;
const int MAXQ = 3e5 + 5;
const int INF = 2e9;

int N, Q, id[MAXN];
vector<int> H[MAXN];
struct TwoThreeHeap {
    vector<int> heap;

    TwoThreeHeap() {
        heap.push_back(-INF);
    }

    int size() const {
        return heap.size() - 1;
    }

    void insert(int x) {
        heap.push_back(x);
        int pos = size();
        while (pos > 1 && heap[pos] > heap[pos / 2]) {
            swap(heap[pos], heap[pos / 2]);
            pos /= 2;
        }
    }

    void remove() {
        int last = size();
        swap(heap[1], heap[last]);
        heap.pop_back();
        last--;
        int pos = 1;
        while (true) {
            int next_pos = pos;
            for (int i = 2 * pos; i <= last && i <= 2 * pos + 2; i++) {
                if (heap[i] > heap[next_pos]) {
                    next_pos = i;
                }
            }
            if (next_pos == pos) {
                break;
            }
            swap(heap[pos], heap[next_pos]);
            pos = next_pos;
        }
    }

    int top() const {
        return heap[1];
    }

    void merge(const TwoThreeHeap& other) {
        for (int x : other.heap) {
            insert(x);
        }
    }
};

TwoThreeHeap heap[MAXN];

int main() {
    ifstream cin("mergeheap.in");
    ofstream cout("mergeheap.out");

    cin >> N >> Q;
    for (int i = 1; i <= N; i++) {
        id[i] = i;
    }
    while (Q--) {
        int t, a, b;
        cin >> t >> a;
        if (t == 1) {
            cin >> b;
            heap[id[a]].insert(b);
        } else if (t == 2) {
            cout << heap[id[a]].top() << "\n";
            heap[id[a]].remove();
        } else {
            cin >> b;
            int old_id = id[b];
            id[b] = id[a];
            heap[id[a]].merge(heap[old_id]);
        }
    }

    return 0;
}