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-1)条路把n个村庄连接起来,同时,但是这n-1条路已经修了m条路,问剩下的路最小需要修多长,还是一个最小生成树,用prime算法,不能用kru算法,要超时
<span style="font-size:18px;">#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define inf 999999999
int pic[105][105],dis[105],vis[105];//dis【i】表示i点到树的距离
int m,n,i,j,a,b;
void prime()
{
int sign,sum=0;
for(i=1;i<=n;i++)
{
vis[i]=0;
dis[i]=inf;
}
dis[1]=0;//源点赋为0
for(i=1;i<=n;i++)
{
int mm=inf;
for(j=1;j<=n;j++)
{
if(vis[j]==0&&dis[j]<=mm)
{
mm=dis[j];
sign=j;
}
}
vis[sign]=1;
sum+=dis[sign];//最小和的叠加
for(j=1;j<=n;j++)
{
if(vis[j]==0&&dis[j]>pic[sign][j])//更新【j】到树的最小距离
dis[j]=pic[sign][j];
}
}
printf("%d\n",sum);
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&pic[i][j]);
scanf("%d",&m);
while(m--)
{
scanf("%d%d",&a,&b);
pic[a][b]=pic[b][a]=0;//这里把题目给的已经修好的路长度变为0;算和的时候加起来自然就是剩下公路最小和
}
prime();
}
return 0;
}
</span>