Cod sursa(job #2507525)

Utilizator cristiifrimIfrim Cristian cristiifrim Data 10 decembrie 2019 13:46:15
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

int n, m, conex[200001], cnt;

long long costmax;


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

muchie v[400001], sol[200001];

void citire() {
    f >> n >> m;
    for(int i = 1; i <= n; ++i)
        conex[i] = i;
    for(int i = 1; i <= m; ++i)
        f >> v[i].x >> v[i].y >> v[i].cost;
}

bool test(muchie a, muchie b) {
    return a.cost < b.cost;
}

void afisare() {
    g << costmax << '\n' << n - 1 << '\n';
    for(int i = 1; i < n; ++i)
        g << sol[i].x << ' ' << sol[i].y << '\n';
}

int main()
{
    citire();
    sort(v + 1, v + m + 1, test);
    int k = 1;
    while(cnt < n - 1) {
        if(conex[v[k].x] != conex[v[k].y]) {
            sol[++cnt] = v[k];
            costmax += v[k].cost;
            int a = conex[v[k].x], b = conex[v[k].y];
            for(int j = 1; j <= n; ++j)
                if(conex[j] == b)
                    conex[j] = a;
        }
        k++;
    }
    afisare();
    g.close();
    f.close();
    return 0;
}