还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 56089 Accepted Submission(s): 25448
当N为0时,输入结束,该用例不被处理。
思路:明显的最小生成树,这里采用kruskal算法
代码:
#include<cstdio>
#include<algorithm>
using namespace std;
int f[105];
struct road
{
int l,r,cost;
}num[5000];
bool cmp(road x,road y)
{
return x.cost < y.cost;
}
int find(int x)
{
if (x != f[x])
f[x] = find(f[x]);
return f[x];
}
void join(int x,int y)
{
int fx = find(x),fy = find(y);
if (fx != fy)
f[fx] = fy;
}
int main()
{
int n,i;
while (~scanf("%d",&n) && n)
{
for (i = 1;i <= n;i ++)
f[i] = i;
int ty = n * (n - 1) / 2,ans = 0,cnt = 0;
for (i = 0;i < ty;i ++)
scanf("%d %d %d",&num[i].l,&num[i].r,&num[i].cost);
sort(num,num + ty,cmp);
for (i = 0;i <= ty;i ++)
{
if (find(num[i].l) != find(num[i].r))
ans += num[i].cost,join(num[i].l,num[i].r),cnt ++;
if (cnt == n - 1) break;
}
printf("%d\n",ans);
}
return 0;
}