Pagini recente » Cod sursa (job #2958418) | Cod sursa (job #1055651) | Cod sursa (job #317778) | Monitorul de evaluare | Cod sursa (job #3297501)
#include <bits/stdc++.h>
#define NMAX 200000
#define MMAX 400000
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie {
int a, b, cost;
}mch[MMAX + 2];
int n, m;
int cnt, cost_min;
int rad[NMAX + 2], rang[NMAX + 2];
vector<pair<int, int>> mch_apm;
bool cmp(muchie a, muchie b) {
return a.cost < b.cost;
}
int Find(int x) {
if (x == rad[x]) {
return x;
}
return rad[x] = Find(rad[x]);
}
void Union(int x, int y) {
if (rang[x] < rang[y]) {
rad[x] = y;
}
else {
if (rang[x] == rang[y]) {
rang[x]++;
}
rad[y] = x;
}
}
int main() {
ios_base::sync_with_stdio(false);
fin.tie(NULL);
fout.tie(NULL);
fin >> n >> m;
for (int i = 1; i <= n; i++) {
rad[i] = i;
rang[i] = 1;
}
for (int i = 1; i <= m; i++) {
fin >> mch[i].a >> mch[i].b >> mch[i].cost;
}
sort(mch + 1, mch + m + 1, cmp);
for (int i = 1; i <= m; i++) {
int rad_a = Find(mch[i].a);
int rad_b = Find(mch[i].b);
if (rad_a != rad_b) {
cost_min += mch[i].cost;
mch_apm.push_back({mch[i].a, mch[i].b});
Union(rad_a, rad_b);
cnt++;
if (cnt == n - 1) {
break;
}
}
}
fout << cost_min << '\n';
fout << cnt << '\n';
for (int i = 0; i < cnt; i++) {
fout << mch_apm[i].first << ' ' << mch_apm[i].second << '\n';
}
return 0;
}