Problem4-1004
2016-07-03 22:08
232 查看
简单题意:给你一些镇子,和镇子之间的距离,现在要修一条路,把所有镇子连起来,求路的最短距离。
解题思路:最小生成树问题,我采用的还是KRUSKAL是第一题的简化版,详情请看第一题。
代码如下:
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
const int N = 105;
int father
;
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()
{
//ifstream cin("aaa.txt");
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;
}
解题思路:最小生成树问题,我采用的还是KRUSKAL是第一题的简化版,详情请看第一题。
代码如下:
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
const int N = 105;
int father
;
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()
{
//ifstream cin("aaa.txt");
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;
}
相关文章推荐
- 达夫设备详解
- Spring 事务的处理
- poj3040
- UIStepper
- kernel - 硬中断的内核线程。
- 图算法2之1003
- 基础补充
- iOS Foundation 基础框架
- Android如何使用API
- LeetCode(2)——Intersection of Two Arrays
- 怎么将excel中的小数变成整数(不只是隐藏小数部分哦)?
- grunt 记录
- 7.4 私有变量
- C语言 求两个数的最大公约数
- laravel框架学习(一)
- easyui radio 无法选中的原因
- 'XCTest/XCTest.h' file not found
- 新手应该如何入门前端
- 算法_归并排序
- 【Java进阶四】抽象类和接口