博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
poj2412——Constructing Roads(最小生成树变形)
阅读量:2344 次
发布时间:2019-05-10

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

Description

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

3

0 990 692
990 0 179
692 179 0
1
1 2
Sample Output

179

给出1到n个村庄和互相之间的距离,其中有些村庄之间已经通了道路,求这种情况下最少要建多长的道路形成最小生成树。

注意到样例里,990并不是最小的生成树里的一部分,但这已经建好了,所以再建179的就行,不然692+179才是最小生成树。所以要把已经建好的道路长度变成0,这样就成为了最小生成树的一部分,才能用算法解决

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#define INF 0x3f3f3f3f#define MAXN 105#define Mod 10001using namespace std;int n,vis[MAXN],map[MAXN][MAXN],dis[MAXN];int prim(){ int i,j,pos,min,ans=0; memset(vis,0,sizeof(vis)); vis[1]=1,pos=1; for(i=1; i<=n; ++i) if(i!=pos) dis[i]=map[pos][i]; for(i=1; i
map[pos][j]) dis[j]=map[pos][j]; } return ans;}int main(){ while(~scanf("%d",&n)&&n) { for(int i=1; i<=n; ++i) for(int j=1; j<=n; ++j) scanf("%d",&map[i][j]); int q,a,b; scanf("%d",&q); while(q--) { scanf("%d%d",&a,&b); map[a][b]=map[b][a]=0; } printf("%d\n",prim()); } return 0;}

转载地址:http://wpcvb.baihongyu.com/

你可能感兴趣的文章
cmake 简介
查看>>
CMake学习笔记(1)——用CMake编译一个hello world程序
查看>>
cmake使用总结---工程主目录CMakeList文件编写
查看>>
CMake学习之路
查看>>
cmake学习笔记6-catkin的CmakeList.txt讲解
查看>>
cmake手册详解
查看>>
Maplab框架介绍(一)
查看>>
Maplab开源VI-SLAM框架介绍
查看>>
maplab(1):安装
查看>>
陀螺仪随机误差的Allan方差分析
查看>>
Ubuntu 64位安装Adobe Reader 9.5.5
查看>>
Ubuntu 下如何查看已安装的软件
查看>>
Linux 系统下可以注释标注的pdf阅读器安装、比较和推荐
查看>>
福昕阅读器foxit reader Linux版
查看>>
Ubuntu 安装百度云客户端
查看>>
每天一个linux命令:locate
查看>>
Linux 环境下载百度云资源,Firefox插件(百度网盘助手)
查看>>
ubuntu Firefox/chrome adobe flash 插件安装
查看>>
OpenCV图像变换(仿射变换与透视变换)
查看>>
仿射变换与透视变换
查看>>