Pagini recente » Cod sursa (job #3308607) | Cod sursa (job #3353594) | Cod sursa (job #1701337) | Cod sursa (job #641698) | Cod sursa (job #3334976)
#include <algorithm>
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
struct Muchie {
int x, y, c;
bool operator<(const Muchie &m) const {
return c < m.c;
}
};
const int MAX = 400000;
vector<Muchie> M;
vector<pair<int, int> > APCM;
int tata[MAX + 1], h[MAX + 1];
void Initialize(int u) {
tata[u] = 0;
h[u] = 0;
}
int Find(int u) {
if (tata[u] == 0) {
return u;
}
return tata[u] = Find(tata[u]);
}
void Union(int u, int v) {
int ru = Find(u);
int rv = Find(v);
if (h[ru] > h[rv]) {
tata[rv] = ru;
} else {
tata[ru] = rv;
if (h[ru] == h[rv]) {
h[rv]++;
}
}
}
int main() {
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m, cost = 0;
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y, c;
fin >> x >> y >> c;
M.push_back({x, y, c});
}
sort(M.begin(), M.end());
for (int i = 1; i <= n; i++) {
Initialize(i);
}
for (const auto &muchie: M) {
if (Find(muchie.x) != Find(muchie.y)) {
cost += muchie.c;
Union(muchie.x, muchie.y);
APCM.push_back({muchie.x, muchie.y});
if (APCM.size() == n - 1) {
break;
}
}
}
fout << cost << "\n";
for (const auto &muchie: APCM) {
fout << muchie.first << " " << muchie.second << "\n";
}
return 0;
}