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.
3
0 990 692
990 0 179
692 179 0
1
1 2
sample output
179
这题是一个最小生成树的模板题,详情直接见AC代码吧。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
using namespace std;
int map[105][105];
int s[105],l[105],c[105];
int main()
{
int n,i,j;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&map[i][j]);
int t;
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
int a,b;
scanf("%d%d",&a,&b);
map[a][b]=map[b][a]=0;
}
memset(s,0,sizeof(s));
s[1]=1;
for(int i=1;i<=n;i++)
{
l[i]=map[i][1];
c[i]=1;
}
int sum=0;
for(int i=1;i<n;i++)
{
int min=100001;
int u;
for(int j=1;j<=n;j++)
if(!s[j]&&l[j]<min)
{
min=l[j];
u=j;
}
s[u]=1;
sum=sum+l[u];
for(int j=1;j<=n;j++)
if(!s[j]&&l[j]>map[u][j])
{
l[j]=map[j][u];
c[j]=u;
}
}
printf("%d\n",sum);
}
}
本文介绍了一个经典的最小生成树问题,给出了详细的输入输出样例及AC代码实现。问题旨在通过已有村庄间的道路信息,找到使得所有村庄连通所需的最短总路径长度。
252

被折叠的 条评论
为什么被折叠?



