传送门:Constructing Roads
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.
InputThe 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.
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.
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.
OutputYou 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 2Sample Output
179
呃 。。。 英文蒟蒻 第一次尝试没用翻译。。。果然错误不断啊;
题目大意: 给定一个 n * n 的矩阵,第 i 行 j 列的数 表示 从 i 到 j 的花费,从i 到 j 当然和 从 j 到 i 花费一样了。。。
从图像上可以看出,处理的时候只处理下三角就可以了(当然 处理矩阵也完全可以。。
本题是一道最小生成树的题,可以用 克鲁斯卡尔 来做 : 如果已经有了路,则赋值为0,然后按边的权值由小到大排序,再依次判断是否同处一个集合,若不在一个集合中,则加入相同集合,把花费相加。全部处理完后的得到的花费即为最小花费!
蛤?为么有多组输入???鬼知道!!!
克鲁斯卡尔 :
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int n,Q,x,y;
int a[120][120],fa[120];
struct Node{
int a;
int b;
int len;
}node[10009];
int find(int x)
{
if(x!=fa[x])
fa[x] = find(fa[x]);
return fa[x];
}
bool cmp(Node x,Node y)
{
return x.len < y.len;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>a[i][j];
}
fa[i] = i;
}
cin>>Q;
for(int i=1;i<=Q;i++)
{
cin>>x>>y;
fa[find(x)] = find(y);
a[x][y] = a[y][x] = 0;
}
int p = 0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i][j]!=0)
{
p++;
node[p].a = i;
node[p].b = j;
node[p].len = a[i][j];
}
}
}
sort(node+1,node+p+1,cmp);
int sum = 0;
for(int i=1;i<=p;i++)
{
int r1 = find(node[i].a);
int r2 = find(node[i].b);
if(r1!=r2)
{
fa[r1] = r2;
sum += node[i].len;
}
}
cout<<sum<<endl;
}
return 0;
}