Pagini recente » Cod sursa (job #371583) | Cod sursa (job #481407) | Cod sursa (job #2245111) | Cod sursa (job #3333885) | Cod sursa (job #3321773)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m, x, y, c;
struct muchie{
int first, second, cost;
};
vector<muchie> l;
vector<int> p, h;
int Find(int x) {
while(x != p[x]) {
x = p[x];
}
return x;
}
void Union(int x, int y) {
x = Find(x);
y = Find(y);
if(x != y) {
if (h[x] < h[y]) {
p[x] = y;
}
else {
if (h[y] < h[x]) {
p[y] = x;
} else {
p[x] = y;
h[y] ++;
}
}
}
}
int main() {
fin >> n >> m;
for(int i = 1; i <= m; i ++){
fin >> x >> y >> c;
l.push_back({x, y, c});
}
sort(l.begin(), l.end(), [](muchie a, muchie b){
return a.cost < b.cost;
});
p.resize(m + 1);
h.resize(m + 1);
for(int i = 1; i <= n; i ++) {
p[i] = i;
h[i] = 1;
}
int sol = 0;
vector< pair<int, int> > K;
for(auto e : l) {
x = e.first, y = e.second, c = e.cost;
if(Find(x) != Find(y)) {
sol += c;
K.push_back({x, y});
Union(x, y);
}
}
fout << sol << '\n' << K.size() << '\n';
for(auto e : K) {
fout << e.first << ' ' << e.second << '\n';
}
return 0;
}