HDU 1233 还是畅通工程
2017-02-10 19:50
288 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1233
题意:
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
思路:
我用了Kruskal算法。
题意:
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
思路:
我用了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; }
相关文章推荐
- PAT A1072 Gas Station(30)
- 2月14日情人节即将来临,储君为大家找到了“程序员聊没女朋友的四大神坑”,辛苦奋斗的猿们不要再次入坑
- 1051. Pop Sequence (25)
- java多维数组
- mysql 日期加减简单的计算
- 关于矩阵乘法按照列乘行的方式来看
- poj 1185 炮兵阵地 【状态压缩dp】
- php及codeigniter使用session-cookie
- C实例---写入文件
- javascript面向对象实现方法(类的继承与多态)
- 拉格朗日乘数法
- NOIp2012疫情控制
- linux编程之pipe()函数
- PAT 1094 The Largest Generation
- PAT 1003 我要通过!
- 1.3 使用jmeter进行http接口测试
- iOS原生人脸识别CIDetector使用
- chattr命令锁定账户敏感文件
- spring 在web 容器启动时,执行FIFO队列初始化方法
- 文章标题