SDAU 练习四1001 acm村庄建设最小长度问题
2016-06-26 11:33
309 查看
Problem A
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)[align=left]Input[/align]
The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within
[1, 1000]) between village i and village j.<br><br>Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.<br>
[align=left]Output[/align]
You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum. <br>
[align=left]Sample Input[/align]
3
0 990 692
990 0 179
692 179 0
1
1 2
[align=left]Sample Output[/align]
179
简单题意:
有N个村庄,从1到N编号,你应该建立一些道路,这样每一个两个村庄可以连接到对方。我们说两个村庄A和B是连接,当且仅当有A和B之间的道路,或存在C这样的一个村庄之间有一条路和C,C和B连接。我们知道已经有一些道路之间的一些村庄,你的工作是构建道路,所有的村庄都连接和道路建设是最小的长度。
简单思路:
采用邻接表的方式将数据保存下来。在用邻接表优化的prim算法即可。。典型的例题哈
4000
ACID:00776486
代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 101;
struct Edge
{
int begin;
int end;
int weight;//边的权值
}edges[maxn*maxn];
int father[maxn];
int map[maxn][maxn];
int find(int a)
{
if(a == father[a])
return a;
return father[a] = find(father[a]);
}
int kruscal(int count)
{
int i;
for(i = 1 ; i < maxn ; ++i)
{
father[i] = i;
}
int sum = 0;
for(i = 1 ; i <= count ; ++i)
{
int fx = find(edges[i].begin);
int fy = find(edges[i].end);
if(fx != fy)
{
father[fx] = fy;
sum += edges[i].weight;
}
}
return sum;
}
bool cmp(const Edge& a, const Edge& b)
{
return a.weight < b.weight;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i;
int j;
for(i = 1 ; i <= n ; ++i)
{
for(j = 1 ; j <= n ; ++j)
{
cin>>map[i][j];
}
}
int m;
cin>>m;
while(m--)
{
int a,b;
cin>>a>>b;;
map[a][b] = map[b][a] = 0;
}
int cnt = 1;
for(i = 1 ; i <= n ; ++i)
{
for(j = 1 ; j <= i ; ++j)
{
edges[cnt].begin = i;
edges[cnt].end = j;
edges[cnt++].weight = map[i][j];
}
}
cnt = cnt-1;
sort(edges+1,edges+1+cnt,cmp);
cout<<kruscal(cnt)<<endl;
}
return 0;
}
相关文章推荐
- BigDecimal的简单使用
- 复印curl学习记录
- ipython常用方法说明
- 你可能不了解java接口
- PAT 1007. Maximum Subsequence Sum (25)
- OpenCV代码提取:merge/split函数的实现
- OpenCV代码提取:merge/split函数的实现
- 利用正则表达查找文件
- 关于acm专题的相关资料下载
- FileStream\StreamReader\StreamWriter
- pySerial -- Python的串口通讯模块
- PHP实现简单的万年历(实例)
- JPA关系映射之many-to-many
- 函数指针的使用
- Java安全通信:HTTPS与SSL
- java安全框架-Shiro学习笔记(一)-入门小案例
- 纯Javascript炫酷时钟、滚动文字广告--网站实用实例
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis+Git)
- Linux学习之软件包管理--yum在线管理
- Struts2—非UI标签—数据标签