首页 > 代码库 > POJ 2421 Constructing Roads
POJ 2421 Constructing Roads
来源:http://poj.org/problem?id=2421
Constructing Roads
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 19645 | Accepted: 8193 |
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.
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.
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
Source
PKU Monthly,kicc
题意: 略。
题解: 图论、最小生成树、Prim。 这题和POJ 1258 基本上是没区别,只是在初始阶段就给它加上了几条边,这些边只要将他们的权值赋值为零就可以了~~
AC代码:
#include<iostream> #include<cstring> const int INF=0x3fffffff; using namespace std; int map[105][105],t,n,x,y,wage=0,pb; bool p[105]; void Prim(){ int tempx,tempy; while(pb--){ int min=INF; for(int i=1;i<=n;i++) if(p[i]){ for(int j=1;j<=n;j++){ if(!p[j]&&map[i][j]<min){ tempx=i;tempy=j; min=map[i][j]; } } } p[tempy]=true; wage+=min; } } int main(){ memset(p,0,sizeof(p)); p[1]=true; cin>>n; pb=n-1; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) cin>>map[i][j]; cin>>t; while(t--){ cin>>x>>y; map[x][y]=0; map[y][x]=0; } Prim(); cout<<wage<<endl; return 0; }
POJ 2421 Constructing Roads
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。