Cod sursa(job #3203578)

Utilizator VVasiuVasiu Vasile VVasiu Data 13 februarie 2024 22:11:05
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
#define N 200000
ifstream fin("apm.in");
ofstream fout("apm.out");

int n, m, k, cst, nr, a, b, tatax, tatay;
int tati[N+1], rang[N+1];
struct muchie
{
    int x, y;
    int cost;
}v[2*N+1], sol[2*N+1];
bool cmp(muchie a, muchie b)
{
    return a.cost < b.cost;
}

int radacina(int nod)
{
    while(tati[nod] != nod)
        nod = tati[nod];

    return nod;
}

int main()
{
    fin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        fin >> v[i].x;
        fin >> v[i].y;
        fin >> v[i].cost;
    }

    sort(v+1, v+m+1, cmp);
    for(int i=1; i<=n; i++)
    {
        tati[i] = i;
        rang[i] = 1;
    }

    for(int i=1; i<=m; i++)
    {
        tatax = radacina(v[i].x);
        tatay = radacina(v[i].y);
        if(tatax != tatay)
        {
            cst += v[i].cost;
            sol[++k].x = v[i].x;
            sol[k].y = v[i].y;
            if(rang[tatax] > rang[tatay])
                tati[tatay] = tatax;
            else
            {
                tati[tatax] = tatay;
                if(rang[tatax] == rang[tatay])
                    rang[tatay]++;
            }

        }
    }

    fout << cst << "\n";
    fout << k << "\n";
    for(int i=1; i<=k; i++)
        fout << sol[i].x << " " << sol[i].y << "\n";
    return 0;
}