Constructing Roads
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 17199 Accepted Submission(s): 6529
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
3
0 990 692
990 0 179
692 179 0
1
1 2
Sample Output
179
/* 题意:: 给一个值N,表示有几个村庄,接下来有N行,每行有N个数字。 每个数字分别表示它到其他村庄的距离。 例如:: 3 0 990 692 //表示1号村庄到一号村庄距离为0,,1到2的距离为990,,1到3的距离为692 990 0 179 //表示2到1的距离为990,2到2的距离为0,2到3的距离为179 692 179 0 //3到1的距离为692,3到2的距离为179,3到3的距离为0; 然后给一个数m (0=<m<=n*(n+1)/2).表示已经有几个村庄有路了,接下来 是m行,每行有两个数,表示有路的两个村庄。 要使所有村庄连通,求最短要修的路。 */
/*最小生成树---模板*/
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int a[110],sum;
struct zz
{
int f1,f2,l;
}q[10100];
int cmp(zz x,zz y)
{
return x.l<y.l;
}
int find(int x)
{
while(x!=a[x])
x=a[x];
return x;
}
int marge(int x,int y)
{
int fx,fy;
fx=find(x);fy=find(y);
if(fx!=fy)
{
a[fx]=fy;
return 1;
}
return 0;
}
int main()
{
int n,i,j,c1,c2,k,m;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
a[i]=i;
k=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&q[k].l);
q[k].f1=i;q[k].f2=j;
k++;
}
scanf("%d",&m);
while(m--)
{
scanf("%d%d",&c1,&c2);
marge(c1,c2);
}
sort(q,q+k,cmp);
sum=0;
for(i=0;i<n*n;i++)
{
if(marge(q[i].f1,q[i].f2))
{
sum+=q[i].l;
}
}
printf("%d\n",sum);
}
return 0;
}