Cod sursa(job #3039771)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 28 martie 2023 20:51:46
Problema Heapuri cu reuniune Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
/// Preset de infoarena
#include <fstream>
#include <queue>

using namespace std;

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

const int maxN = 105;
int n, q, root[maxN];
priority_queue <int> heap[maxN];

int findRoot(int x)
{
    if(x == root[x])
        return x;
    root[x] = findRoot(root[x]);
    return root[x];
}

int main()
{
    fin >> n >> q;
    for(int i = 1; i <= n; i++)
        root[i] = i;
    while(q--)
    {
        int op;
        fin >> op;
        if(op == 1)
        {
            int m, x;
            fin >> m >> x;
            m = findRoot(m);
            heap[m].push(x);
        }
        if(op == 2)
        {
            int m;
            fin >> m;
            m = findRoot(m);
            fout << heap[m].top() << '\n';
            heap[m].pop();
        }
        if(op == 3)
        {
            int m1, m2;
            fin >> m1 >> m2;
            m1 = findRoot(m1);
            m2 = findRoot(m2);
            if(heap[m1].size() > heap[m2].size())
            {
                root[m2] = m1;
                while(!heap[m2].empty())
                {
                    int x = heap[m2].top();
                    heap[m2].pop();
                    heap[m1].push(x);
                }
            }
            else
            {
                root[m1] = m2;
                while(!heap[m1].empty())
                {
                    int x = heap[m1].top();
                    heap[m1].pop();
                    heap[m2].push(x);
                }
            }
        }
    }
    return 0;
}