Pagini recente » Cod sursa (job #2955936) | Cod sursa (job #2572351) | Cod sursa (job #2285420) | Cod sursa (job #2941730) | Cod sursa (job #1921538)
#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;
vector<Edge> G;
vector<int> h, t;
vector<Edge> arb;
int cost_min;
void Read();
void Kruskal();
void Write();
int Find(int x);
void Union(int x, int y);
int main(){
Read();
Kruskal();
Write();
fin.close();
fout.close();
return 0;
}
void Kruskal() {
sort(G.begin(), G.end());
int k = 0;
int c1, c2;
for (const auto & e : G) {
c1 = Find(e.x); c2 = Find(e.y);
if (c1 != c2) {
k++;
cost_min += e.w;
arb.push_back(e);
Union(c1, c2);
}
if (k == n - 1) break;
}
}
int Find(int x) {
if (t[x] == x) return x;
else t[x] = Find(t[x]);
}
void Union(int x, int y) {
if (h[y] > h[x]) t[x] = y;
else {
t[y] = x;
if (h[y] == h[x]) h[x]++;
}
}
void Write() {
fout << cost_min << '\n' << n - 1 << '\n';
for (const auto & e : arb)
fout << e.x << ' ' << e.y << '\n';
}
void Read() {
fin >> n >> m;
h = t = vector<int>(n + 1);
for (int i = 1; i <= n; i++)
t[i] = i, h[i] = 0;
int x, y ,w;
for (int i = 1; i <= m; i++) {
fin >> x >> y >> w;
G.push_back({x, y, w});
}
}