Cod sursa(job #3131116)

Utilizator iordyIordache Andrei Tudor iordy Data 19 mai 2023 11:48:47
Problema Heapuri cu reuniune Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int MAX_N = 100005; // Numărul maxim de mulțimi

vector<int> heap[MAX_N]; // Vector de mulțimi implementat ca un heap
int heapSize[MAX_N]; // Dimensiunea fiecărei mulțimi în heap

void insert(int m, int x) {
    heap[m].push_back(x); // Adăugăm elementul la sfârșitul mulțimii m
    heapSize[m]++;
    int i = heapSize[m] - 1;
    int parent = (i - 1) / 2;
    while (i > 0 && heap[m][parent] < heap[m][i]) {
        swap(heap[m][parent], heap[m][i]);
        i = parent;
        parent = (i - 1) / 2;
    }
}



void heapify(int m, int i) {
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;

    if (left < heapSize[m] && heap[m][left] > heap[m][largest]) {
        largest = left;
    }

    if (right < heapSize[m] && heap[m][right] > heap[m][largest]) {
        largest = right;
    }

    if (largest != i) {
        swap(heap[m][i], heap[m][largest]);
        heapify(m, largest);
    }
}


int extractMax(int m) {
    int maxElement = heap[m][0];
    heap[m][0] = heap[m][heapSize[m] - 1]; // Înlocuim elementul maxim cu ultimul element din mulțime
    heap[m].pop_back(); // Eliminăm ultimul element
    heapSize[m]--;
    heapify(m, 0); // Refacem heap-ul
    return maxElement;
}

void mergeSets(int a, int b) {
    heap[a].insert(heap[a].end(), heap[b].begin(), heap[b].end()); // Adăugăm elementele mulțimii b la sfârșitul mulțimii a
    heapSize[a] += heapSize[b];
    heap[b].clear(); // Mulțimea b devine vidă
    heapify(a, 0); // Refacem heap-ul în mulțimea rezultată
}




int main() {
    int N, Q;
    fin >> N >> Q;

    for (int i = 0; i < Q; i++) {
        int op;
        fin >> op;
        if (op == 1) {
            int m, x;
            fin >> m >> x;
            insert(m, x);
        } else if (op == 2) {
            int m;
            fin >> m;
            int maxElement = extractMax(m);
            fout << maxElement << '\n';
        } else if (op == 3) {
            int a, b;
            fin >> a >> b;
            mergeSets(a, b);
        }
    }

    fin.close();
    fout.close();
    return 0;
}