您的位置:首页 > 其它

HDU 1233 还是畅通工程

2017-02-10 19:50 253 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1233

题意:

某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。

思路:

我用了Kruskal算法。

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

const int maxn = 5000 + 5;

int n, ans;
int p[maxn];

struct node
{
int u;
int v;
int w;
}edge[maxn];

int find(int x)
{
return p[x] == x ? x : find(p[x]);
}

bool cmp(node a, node b)
{
return a.w < b.w;
}

void Kruskal()
{
int cnt = n*(n - 1) / 2;
sort(edge, edge + cnt, cmp);
for (int i = 0; i < cnt; i++)
{
int x = find(edge[i].u);
int y = find(edge[i].v);
if (x != y)
{
p[x] = y;
ans += edge[i].w;
}
}
}

int main()
{
//freopen("D:\\txt.txt", "r", stdin);
while (scanf("%d",&n) && n)
{
for (int i = 1; i <= n; i++)
p[i] = i;
for (int i = 0; i < n*(n - 1) / 2; i++)
{
scanf("%d%d%d", &edge[i].u, &edge[i].v , &edge[i].w);
}
ans = 0;
Kruskal();
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: