Constructing Roads
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
Source
kicc
给定N个村庄以及村庄之间的距离,还有Q两两连通的村庄,问要是所有村庄相连需要修最短多长的路。看代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
//最小生成树kruskal算法变形
using namespace std;
struct ss//保存节点a,b之间的距离l
{
int a, b, l;
};
bool cmp(ss a, ss b)
{
if(a.l < b.l) return true;
else return false;
}
int g[105];
int fin(int x)
{
int y = x;
while(g[x] != x)//路径合并
{
x = g[x];
g[y] = g[x];
}
return x;
}
int main()
{
int N, Q, xlen, k, aa, bb, ans;
while(scanf("%d", &N) != EOF)
{
k = ans = 0;
for(int i = 0;i < 105; ++i) g[i] = i;//并查集初始化
ss f[10000];
for(int i = 1;i <= N; ++i)
{
for(int j = 1;j <= N; ++j)
{
scanf("%d", &xlen);
if(i >= j) continue;//只需保存一半数据,另一半数据重复了
f[k].a = i;
f[k].b = j;
f[k++].l = xlen;
}
}
sort(f, f+k, cmp);//排序,从最小的边开始
scanf("%d", &Q);
for(int i = 0;i < Q; ++i)
{
scanf("%d %d", &aa, &bb);
int x = fin(aa);
int y = fin(bb);
g[x] = y;//道路存在,不用另外修,直接连通
}
for(int i = 0;i < k; ++i)
{
int x = fin(f[i].a);
int y = fin(f[i].b);
if(x != y)//加入这条边不产生环,则加入,并加入总长度ans里
{
g[x] = g[y];
ans += f[i].l;
}
}
cout << ans << endl;
}
return 0;
}