Cod sursa(job #2027926)

Utilizator osiaccrCristian Osiac osiaccr Data 26 septembrie 2017 21:22:59
Problema Arbore partial de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

struct elem {
    int x, y, cost;
} v[400001], sol[400001];

int n, m, Min, pozMin, cost, T[100001], k, rx, ry;

bool cmp (const elem a, const elem b) {
    return a.cost <= b.cost;
}

int rad (int nod) {
    while (T[nod] > 0) {
        nod = T[nod];
    }
    return nod;
}

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++) {
        T[i] = -1;
    }

    for (int i = 1; i <= m; i++) {
        rx = rad (v[i].x);
        ry = rad (v[i].y);
        if (rx == ry)
            continue;
        if (rx != ry) {
            if (T[rx] < T[ry]) {
                T[rx] += T[ry];
                T[ry] = rx;
            }
            else {
                T[ry] += T[rx];
                T[rx] = ry;
            }
        }
        sol[++k].x = v[i].x;
        sol[k].y = v[i].y;
        cost += v[i].cost;
    }

    fout << cost << "\n" << k << "\n";
    for (int i = 1; i <= k; i++) {
        fout << sol[i].x << " " << sol[i].y << "\n";
    }

    return 0;
}