Pagini recente » Cod sursa (job #536753) | Cod sursa (job #3244635) | Cod sursa (job #1766172) | Cod sursa (job #1277581) | Cod sursa (job #1983041)
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
const int N = 200000;
const int M = 400000;
struct muchie {
int x, y, c;
};
ifstream in;
ofstream out;
int n, m, t[1+N], h[1+N], cost;
muchie e[M];
bool sel[M];
bool cmp(muchie const &e1, muchie const &e2) {
return e1.c < e2.c;
}
void citire() {
in.open("apm.in");
in >> n >> m;
for (int i = 0; i < m; i++) {
in >> e[i].x >> e[i].y >> e[i].c;
}
in.close();
}
int radacina(int x) {
if (t[x] == 0) {//am ajuns in radacina
return x;
}
t[x] = radacina(t[x]);//compactarea drumurilor
return t[x];
}
void kruskal() {
for (int i = 0; i < m; i++) {
int rx = radacina(e[i].x);
int ry = radacina(e[i].y);
if (rx != ry) {
cost += e[i].c;
sel[i] = true;
if (h[rx] < h[ry]) {
t[rx] = ry;
} else if (h[rx] > h[ry]) {
t[ry] = rx;
} else {
t[rx] = ry;
h[ry]++;
}
}
}
}
void afisare() {
out.open("apm.out");
out << cost << "\n" << n - 1 << "\n";
for (int i = 0; i < m; i++) {
if (sel[i]) {
out << e[i].x << " " << e[i].y << "\n";
}
}
out.close();
}
int main() {
citire();
sort(e, e + m, cmp);
kruskal();
afisare();
return 0;
}