Cod sursa(job #2039200)

Utilizator razvan99hHorhat Razvan razvan99h Data 14 octombrie 2017 12:43:46
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <algorithm>
#include <fstream>
#define DM 200005
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");

struct muchie { int x, y, cost;};
muchie v[DM], arb[DM];
int n, m, cost_total, dad[DM], a, b, c, dim;

bool cmp(muchie A, muchie B){
    return A.cost < B.cost;
}
int root(int nod){
    if(dad[nod] == nod)
        return nod;
    return dad[nod] = root(dad[nod]);
}
void unite(int x, int y){
    dad[root(x)] = root(y);
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++){
        fin >> a >> b >> c;
        v[i] = {a, b, c};
    }

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

    for(int i = 1; i <= m; i++){
        int x = v[i].x;
        int y = v[i].y;
        int c = v[i].cost;
        if(root(x) != root(y)){
            unite(x, y);
            arb[++dim] = {x, y, c}; // nu ne pasa de cost
            cost_total += c;
        }
    }

    fout << cost_total << '\n';
    for(int i = 1; i <= dim; i++)
        fout << arb[i].x << ' ' << arb[i].y << '\n';
    return 0;
}