Pagini recente » Cod sursa (job #2160045) | Cod sursa (job #403873) | Cod sursa (job #1473941) | Cod sursa (job #1776657) | Cod sursa (job #1701417)
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
typedef pair<int,int> paer;
int graf[200001];
struct muchie {
int x, y, c;
};
int top(int x) {
int t = x;
while (graf[t]) {
int p = graf[graf[t]];
if (p) {
graf[t] = p;
}
t = graf[t];
}
if (t != x) {
graf[x] = t;
}
return t;
}
bool comp(muchie x, muchie y) {
return x.c < y.c;
}
int main()
{
ifstream in("apm.in");
ofstream out("apm.out");
int n, m;
in>>n>>m;
muchie lm[m];
int i, j;
for (i=0; i<m; i++) {
in>>lm[i].x>>lm[i].y>>lm[i].c;
}
sort(lm, lm+m, comp);
int h[n+1];
std::fill(h, h+n+1, 0);
paer apm[n-1];
j = 0;
int suma = 0;
for (i = 0; i < m; i++) {
int t1 = top(lm[i].x), t2 = top(lm[i].y);
if (t1 != t2) {
suma += lm[i].c;
if (h[t1] > h[t2]) {
graf[t2] = t1;
}
else {
graf[t1] = t2;
if (h[t1] == h[t2]) {
h[t2]++;
}
}
apm[j] = paer(lm[i].x, lm[i].y);
j++;
}
}
out<<suma<<endl;
out<<n-1<<endl;
for (i=0; i<n-1; i++) {
out<<apm[i].first<<" "<<apm[i].second<<endl;
}
in.close();
out.close();
return 0;
}