Cod sursa(job #3371398)

Utilizator dragosdragonnIosub Dragos Casian dragosdragonn Data 30 octombrie 2026 08:44:24
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream> 
#include <fstream>
#include <algorithm>
using namespace std;

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

int parinti[100001];
int sz[100001];

int Find(int x)
{
    while(x != parinti[x])
    {
        x = parinti[x];
    }
    return x;
}

void Union(int x, int y)
{
    x = Find(x);
    y = Find(y);

    if(sz[x] < sz[y])
    {
        parinti[x] = y;
        sz[y] += sz[x];
    }
    else
    {
        parinti[y] = x;
        sz[x] += sz[y];
    }
}

struct muchie
{
    int x, y, c;
};

muchie v[400001], sol[200001];

bool cmp(muchie a, muchie b)
{
    return a.c < b.c;
}

int main()
{
    int n, m;
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        parinti[i] = i;
        sz[i] = 1;
    }
    for(int i = 1; i <= m; i++)
    {
        fin >> v[i].x >> v[i].y >> v[i].c;
    }
    sort(v + 1, v + m + 1, cmp);

    int apm = 0;
    int nr = 0;
    for(int i = 1; i <= m; i++)
    {
        if(Find(v[i].x) != Find(v[i].y))
        {
            apm += v[i].c;
            Union(v[i].x, v[i].y);
            sol[++nr] = v[i];
        }
    }
    fout << apm << '\n';
    fout << nr << '\n';
    for(int i = 1; i <= nr; i++)
    {
        fout << sol[i].x << " " << sol[i].y << '\n';
    }
    return 0;
}