博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POJ - 2421 Constructing Roads (最小生成树)
阅读量:5334 次
发布时间:2019-06-15

本文共 1836 字,大约阅读时间需要 6 分钟。

There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.
We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.

Input

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.
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.

Output

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.

Sample Input

30 990 692990 0 179692 179 011 2

Sample Output

179 解题思路:

要修公路,输入一个n,表示n个村庄。接着输入n*n的矩阵,然后输入一个q 接下来的q行

每行包含两个数a,b,表示a、b这条边联通,就是已经有公路不用修了,要让所有村庄联通在一起问:修路最小代价?

最小生成树的变形,有的村庄已经连接了,就直接把他们的权值赋为0,一样的做最小生成树,Prim算法。

代码如下:

1 #include
2 #include
3 #include
4 using namespace std; 5 6 int N; 7 int dis[1001][1001]; 8 bool vis[1001][1001]; 9 struct edge{10 int u;11 int v;12 int w;13 }e[10005];14 int pre[1001];15 int find(int x)16 {17 return (x==pre[x])?x:pre[x] = find(pre[x]);18 }19 bool cmp(edge a , edge b)20 {21 return a.w

 

转载于:https://www.cnblogs.com/yewanting/p/10798461.html

你可能感兴趣的文章
用DOS命令配置服务开机自启动
查看>>
cookie解析
查看>>
阿里 RPC 框架 DUBBO 初体验
查看>>
node中 path.join 和 path.resovle 区别
查看>>
Linux cp强制覆盖解决办法
查看>>
2013腾讯马拉松编程初赛3月21日1002
查看>>
isee图片专家批量处理图片大小教程
查看>>
java enmu 使用说明
查看>>
java连接Oracle数据库练习题
查看>>
java反射机制的实现原理
查看>>
js页面传值,c#接收中文出现乱码问题
查看>>
成都UBER优步司机第六组奖励政策
查看>>
软件项目管理的成功原则
查看>>
Java for LeetCode 068 Text Justification
查看>>
bzoj1015: [JSOI2008]星球大战starwar
查看>>
Docker安装MySQL
查看>>
zookeeper 服务端上下线,客户端感知
查看>>
Python-读文件
查看>>
Javascript:猜猜弹出的是啥?为啥?
查看>>
浮点型表示方法
查看>>