HDU-1233【最小生成树+kruskal算法】
【模板水题】
#include <iostream>
#include <algorithm>
using namespace std;
static const int maxn = 100;
int p[maxn];
struct Edge
{
int u, v, cost;
} roads[5000];
int find(int x)
{
return p[x] == x ? x : p[x] = find(p[x]);
}
int cmp(Edge x, Edge y)
{
return x.cost < y.cost;
}
int main(int argc, const char **argv)
{
std::ios::sync_with_stdio(false);
std::cin.tie(0),cout.tie(0);
int n;
int k;
while (cin >> n && n)
{
k = n * (n - 1) / 2;
for (int i = 0; i < k; i++)
{
cin >> roads[i].u >> roads[i].v >> roads[i].cost;
}
sort(roads, roads + k, cmp);
for (int i = 0; i <= n; i++)
p[i] = i;
int ans = 0, cnt = 0;
for (int i = 0; i < k; i++)
{
int t1 = find(roads[i].u);
int t2 = find(roads[i].v);
if (t1 != t2)
{
ans += roads[i].cost;
p[t1] = t2;
cnt++;
}
if (cnt == n - 1)
break;
}
cout << ans << endl;
}
return 0;
}