Constructing Roads
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 14028 Accepted Submission(s): 5337
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.
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/* 心得:不读题的后果很严重,n次RE+WA无语………………………………………… 题意:输入n接着有n行n列i行j列表示第i个村庄和第j个村庄相连并且输入的值为权值;其实只有一半数据有用 2014-08-12 19:47 */ #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define MAX 110 struct Node{ int s,e; int w; }road[MAX*MAX]; int father[MAX*MAX]; int N,Q; int findRoot(int x){ return father[x]==x?father[x]:father[x]=findRoot(father[x]); } void merge(int a,int b){ a=findRoot(a); b=findRoot(b); if(a!=b) father[b]=a; } bool cmp(Node a,Node b){ return a.w<b.w; } int main(){ while(scanf("%d",&N)!=EOF){ int num=0; for(int i=1;i<=N;i++){ for(int j=1;j<=N;j++){ int w; scanf("%d",&w); if(i>=j)continue; road[num].s=i; road[num].e=j; road[num].w=w; num++; } } /* for(int i=1;i<=N;i++){ printf("%d %d %d\n",road[i].s,road[i].e,road[i].w); } */ sort(road,road+num,cmp); for(int i=1;i<=N;i++) father[i]=i; int M; scanf("%d",&M); while(M--){ int a,b; scanf("%d%d",&a,&b); merge(a,b); } int Cost=0; for(int i=0;i<num;i++){ int s=findRoot(road[i].s); int e=findRoot(road[i].e); if(s!=e){ merge(s,e); Cost+=road[i].w; } } printf("%d\n",Cost); } return 0; }