hdoj Constructing Roads(最小生成树)

来源:互联网 发布:删除数组中指定元素 c# 编辑:程序博客网 时间:2024/04/27 15:56

Constructing Roads

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 17309    Accepted Submission(s): 6578


Problem 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
30 990 692990 0 179692 179 011 2
 

Sample Output
179
 


本题是一道水题只是英语比较难理解,题目大意说的是有n个村子知道每个村子之间的距离,有的村子之间路以修过求剩下的路的距离最小值,比如题目中的这个数据 3意为有三个村子,0 990 692分别是第一个村子到第一个村子,到第二个村子,到第三个村子,各自的距离。第二行同理第二个村子分别到1 2 3的距离,第四行1说明有一条路已经修,第五行给出这两个村子的编号。以下是我的代码。

#include<stdio.h>#include<algorithm>using namespace std;int n,i,j,q,x,y,a[110],b[110][110];//二维数组存放各村之间距离,两角标表示两个村子编号struct node//定义结构体存放两村子编号和两村之间距离{int xi,ki,d;}z[5000];void f()//村子编号数组初始化{for(int i=1;i<=n;i++)a[i]=i;}int fine(int x)//查{int r=x;while(r!=a[r])r=a[r];return r;}int join(int x,int y)//并{intx1=fine(x),x2=fine(y);if(x1!=x2){a[x2]=x1;return 1;}elsereturn 0;}int cmp(node a,node b){return a.d<b.d;}int main(){while(scanf("%d",&n)!=EOF){for(i=1;i<=n;i++)//输入这个二维数组for(j=1;j<=n;j++)scanf("%d",&b[i][j]);scanf("%d",&q);//输入已修几条路for(i=1;i<=q;i++){scanf("%d%d",&x,&y);//输入已修的路村子编号b[x][y]=0;//已修的路距离标为0}int t=0;for(i=1;i<=n;i++)//将二维数组的数据存入结构体,一方面避免重复的,另一方面方便排序for(j=i+1;j<=n;j++){z[t].xi=i;z[t].ki=j;z[t].d=b[i][j];t++;}f();sort(z,z+t,cmp);int sum=0;for(i=0;i<t;i++)if(join(z[i].xi,z[i].ki))//判断是否成环sum=sum+z[i].d;printf("%d\n",sum);}return 0;}


 

0 0