Pagini recente » Borderou de evaluare (job #2017189) | Cod sursa (job #2501071) | Borderou de evaluare (job #2005718) | Borderou de evaluare (job #2016345) | Cod sursa (job #1967850)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct Edge {
int x, y, w;
bool operator < (const Edge & E) const {
return w < E.w;
}
};
int n, m, k, s;
vector<Edge> E;
vector<Edge> Ans;
vector<int> t, h;
void Read();
void Kruskal();
void Union(int x, int y);
int Find(int x);
void Write();
int main() {
Read();
Kruskal();
Write();
fin.close();
fout.close();
return 0;
}
void Kruskal() {
t = h = vector<int>(n + 1);
for (int i = 1; i <= n; i++)
t[i] = i, h[i] = 1;
sort(E.begin(), E.end());
int c1, c2;
for (const auto & e : E) {
c1 = Find(e.x);
c2 = Find(e.y);
if (c1 == c2) continue;
k++; s += e.w;
Ans.push_back(e);
Union(c1, c2);
if (k == n - 1) break;
}
}
int Find(int x) {
if (t[x] == x) return x;
return t[x] = Find(t[x]);
}
void Union(int x, int y) {
if (h[x] < h[y]) t[x] = y;
else {
t[y] = x;
if (h[x] == h[y]) h[x]++;
}
}
void Write() {
fout << s << '\n' << k << '\n';
for (const auto & e : Ans)
fout << e.x << ' ' << e.y << '\n';
}
void Read() {
fin >> n >> m;
int x, y, w;
for (int i = 1; i <= m; i++) {
fin >> x >> y >> w;
E.push_back({x, y, w});
}
}