题目:
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
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define MAX 105
struct Node{int x,y,dis;}node[MAX * MAX];
int f[MAX];
int find_father(int x)
{
int r = x,temp;
while(r != f[r]) r = f[r];
while(x != f[x]){
temp = f[x];
f[x] = r;
x = temp;
}
return x;
}
void combine(int a,int b)
{
int c = find_father(a);
int d = find_father(b);
if(c == d) return;
f[d] = c;
}
int kruskal(int m)
{
int ans = 0;
for(int i = 0;i < m;i++){
if(find_father(node[i].x) != find_father(node[i].y)){
combine(node[i].x,node[i].y);
ans += node[i].dis;
}
}
return ans;
}
bool cmp(Node a,Node b) {return a.dis < b.dis;}
void init(int n) {for(int i = 0;i <= n;i++) f[i] = i;}
int main()
{
int N,Q,num,a,b,k = 0;
scanf("%d",&N);
for(int i = 1;i <= N;i++){
for(int j = 1;j <= N;j++){
cin >> num;
if(i < j){
node[k].x = i;
node[k].y = j;
node[k++].dis = num;
}
}
}
cin >> Q;
for(int i = 0;i < Q;i++){
cin >> a >> b;
for(int j = 0;j < k;j++){
if((node[j].x == a) && (node[j].y == b)) node[j].dis = 0;
}
}
sort(node,node + k,cmp);
init(N);
int ans = kruskal(k);
cout << ans << endl;
return 0;
}
这道题考察的是最小生成树,先将所有边的信息保存下来,然后将已经建造的路,全部赋值为0,最后使用kruskal就可以了,总体来说是一道十分简单的水题,当然也可以用prime算法来完成。