题意:把一些镇子连起来,求连起来的最短距离
思路:显然是最下生成树问题,kruskal算法解决就可以
感想:无
源代码:
#include <iostream>
#include <fstream>#include <algorithm>
using namespace std;
const int N = 105;
int father[N];
int find(int x)
{
if (x != father[x])
father[x] = find(father[x]);
return father[x];
}
struct edge
{
int x, y, v;
}e[N*(N - 1) / 2];
int cmp(edge e1, edge e2)
{
return e1.v<e2.v;
}
int main()
{
int n;
while (cin >> n&&n)
{
for (int i = 0; i <= n; ++i)
father[i] = i;
n = n*(n - 1) / 2;
for (int i = 0; i<n; i++)
cin>>e[i].x>>e[i].y>>e[i].v;
sort(e, e + n, cmp);
int ans = 0;
for (int i = 0; i < n; ++i)
{
int x = find(e[i].x);
int y = find(e[i].y);
if (x != y)
{
ans += e[i].v;
father[x] = y;
}
}
cout << ans << endl;
}
return 0;
}