Pagini recente » Cod sursa (job #1748810) | Cod sursa (job #1028180) | Cod sursa (job #2139301) | Cod sursa (job #1499591) | Cod sursa (job #1650404)
#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, arb;
vector<int> t, h;
int cost, c1, c2;
void Read();
int Find(int x);
void Union(int x, int y);
void Write();
int main() {
Read();
sort(G.begin(), G.end());
int k = 0;
for (const auto e : G) {
c1 = Find(e.x); c2 = Find(e.y);
if (c1 != c2) {
k++; cost += e.w;
arb.push_back(e);
Union(c1, c2);
}
if (k == N - 1) break;
}
Write();
fin.close();
fout.close();
return 0;
}
void Write() {
fout << cost << '\n' << arb.size() << '\n';
for (const auto e : arb)
fout << e.x << ' ' << e.y << '\n';
}
void Union(int x, int y) {
if (h[x] > h[y]) t[y] = x;
else {
t[x] = y;
if (h[x] == h[y]) h[y]++;
}
}
int Find(int x) {
if (x == t[x]) return x;
else t[x] = Find(t[x]);
}
void Read() {
fin >> N >> M;
for (int i = 1, x, y, w; i <= M; i++) {
fin >> x >> y >> w;
G.push_back({x, y, w});
}
t = h = vector<int>(N + 1);
for (int i = 1; i <= N; i++) {
t[i] = i; h[i] = 1;
}
}