Cod sursa(job #3317792)

Utilizator MMEnisEnis Mutlu MMEnis Data 25 octombrie 2025 13:14:35
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

ifstream f("apm.in");
ofstream g("apm.out");

struct cel
{
    int cost, x1, x2;
}v[400001];

cel sol[200001];
int k, costk;

int sef[200001];

bool cmp ( cel a, cel b )
{
    return a.cost < b.cost;
}

int boss ( int x )
{
    if ( sef[x] == x )
        return x;
    else
    {
        sef[x] = boss ( sef[x] );
        return sef[x];
    }
}

void unire ( int x, int y )
{
    sef[ boss(y) ] = boss (x);
}

int main()
{
    int n, m;
    f >> n >> m;
    for ( int i = 1; i <= m; i ++ )
        f >> v[i].x1 >> v[i].x2 >> v[i].cost;
    sort ( v + 1, v + m + 1, cmp );
    for ( int i = 1; i <= n; i ++ )
        sef[i] = i;
    for ( int i = 1; i <= m && k < n - 1; i ++ )
    {
        cel c = v[i];
        if ( boss ( c.x1 ) == boss ( c.x2 ) )
            continue;
        else
        {
            unire ( c.x1, c.x2 );
            sol[++k] = c;
            costk += c.cost;
        }
    }
    g << costk << '\n' << k << '\n';
    for ( int i = 1; i <= k; i ++ )
        g << sol[i].x1 << " " << sol[i].x2 << '\n';
    return 0;
}