# 杭电OJ 1233 还是畅通工程

## 杭电OJ 1233 还是畅通工程

Problem Description

Input

Output

#include<bits/stdc++.h>
using namespace std;
vector<int> parent(110);
struct Edge
{
int a_{ -1 };
int b_{ -1 };
int distance_{ -1 };
};
bool cmp(const Edge &lhs, const Edge &rhs)
{
return lhs.distance_ < rhs.distance_;
}
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
void Union(int x, int y)
{
int a = find(x);
int b = find(y);
if (a != b) parent[a] = b;
}
int main()
{
#ifdef LOCAL
freopen("input.txt", "r", stdin);//freopen("output.txt", "w", stdout);
#endif
int n;
while (cin >> n, n) {
//边按权值排序.
int m = n * (n - 1) / 2;
vector<Edge> edge_set(m);
for (auto &i : edge_set) cin >> i.a_ >> i.b_ >> i.distance_;
sort(edge_set.begin(), edge_set.end(), cmp);
//初始化.
for (int i = 1; i <= n; ++i) {
parent[i] = i;
}
int distance = 0, ctr = 0;
//生成最小生成树
for (auto &i : edge_set) {
if (find(i.a_) != find(i.b_)) {
Union(i.a_, i.b_);
++ctr;
distance += i.distance_;
}
if (ctr == n - 1) break;
}
cout << distance << endl;
}
}


02-25 69

08-04 230
01-20 3279
08-03 220
08-15 715
01-05 336
01-28 90
01-03 355
02-25 90
07-17 60
01-21 61
01-18 458
01-23 88
01-23 116
08-14 373
08-04 247
03-27 435
03-15 90
04-06 271