Cod sursa(job #3203282)

Utilizator VVasiuVasiu Vasile VVasiu Data 13 februarie 2024 13:53:15
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
#define N 200000
ifstream fin("apm.in");
ofstream fout("apm.out");

int n, m, l[N+1], k, cst, nr, a, b;
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 main()
{
    fin >> n >> m;
    for(int i=1; i<=m; i++)
        fin >> v[i].x >> v[i].y >> v[i].cost;

    sort(v+1, v+m+1, cmp);
    for(int i=1; i<=n; i++)
        l[i] = i;

    k = 0;
    int i = 1;
    while(k < n-1)
    {
        if(l[v[i].x] != l[v[i].y])
        {
            k++;
            cst += v[i].cost;
            sol[k].x = v[i].x;
            sol[k].y = v[i].y;
            a = l[v[i].x];
            b = l[v[i].y];
            for(int j=1; j<=n; j++)
                if(l[j] == b)
                    l[j] = a;
        }
        i++;
    }
    fout << cst << "\n";
    fout << k << "\n";
    for(int i=1; i<=k; i++)
        fout << sol[i].x << " " << sol[i].y << "\n";
    return 0;
}