Pagini recente » Cod sursa (job #451742) | Cod sursa (job #1979654) | Cod sursa (job #1536919) | Cod sursa (job #2231769) | Cod sursa (job #2452502)
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
int n, m, t[200002], rang[200002], mArb, cost;
struct muchie{
int x, y, c;
} muchii[400004];
struct raspuns{
int x, y;
} ans[200002];
bool cmp(muchie a, muchie b) {
return a.c <= b.c;
}
int root(int k) {
if(t[k] == 0)
return k;
else {
int x = root(t[k]);
t[k] = x;
return x;
}
}
void reunion(int a, int b) {
if(a != b) {
if(rang[a] < rang[b])
t[b] = a;
else {
t[a] = b;
if(rang[a] == rang[b])
rang[b]++;
}
}
}
int main() {
f >> n >> m;
for(int i = 0; i < m; i++)
f >> muchii[i].x >> muchii[i].y >> muchii[i].c;
sort(muchii, muchii+m, cmp);
for(int i = 0; i < m && mArb < n-1; i++) {
int rx = root(muchii[i].x);
int ry = root(muchii[i].y);
if(rx != ry) {
reunion(rx, ry);
cost += muchii[i].c;
ans[mArb++] = {muchii[i].x, muchii[i].y};
}
}
g << cost << '\n' << mArb << '\n';
for(int i = 0; i < mArb; i++)
g << ans[i].x << ' '<< ans[i].y << '\n';
}