Cod sursa(job #3309479)

Utilizator Victor5539Tanase Victor Victor5539 Data 5 septembrie 2025 11:27:19
Problema Heapuri cu reuniune Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <queue>

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

const int MAX=100;
int n,i,q,v[MAX+5],type,ind,x,ind2;
priority_queue <int> pq[MAX+5];

void unite(int x, int y)
{
    int idx_x=v[x],idx_y=v[y];

    if (pq[idx_x].size()>=pq[idx_y].size())
    {
        while (!pq[idx_y].empty())
        {
            pq[idx_x].push(pq[idx_y].top());
            pq[idx_y].pop();
        }
    }
    else
    {
        while (!pq[idx_x].empty())
        {
            pq[idx_y].push(pq[idx_x].top());
            pq[idx_x].pop();
        }

        swap(v[x],v[y]);
    }
}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(0); fout.tie(0);

    fin>>n>>q;

    for (i=1; i<=n; i++)
        v[i]=i;

    while (q--)
    {
        fin>>type;

        if (type==1)
        {
            fin>>ind>>x;
            ind=v[ind];
            pq[ind].push(x);
        }
        else
        if (type==2)
        {
            fin>>ind;
            ind=v[ind];
            fout<<pq[ind].top()<<'\n';
            pq[ind].pop();
        }
        else
        {
            fin>>ind>>ind2;
            unite(ind,ind2);
        }
    }



    return 0;
}