There are N villages, which are numbered from 1 to N, and you should build some roads such that ever

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

179

题意:
给出总共的村庄的编号,然后在下面的n行n列中,列举出来从i节点,到j节点的所有的权值 ,都为最后输入的那个数,之后在输入q表示有q组数据,表示接下来的q组数据表示已经联通,求出最后的最小生成树的最小权值

思路:
直接Prim算法。

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

const int N=110;
const int INF=0x3f3f3f3f;  //定义一个无穷大数值

int n,ans;   //n 为结点数量  ans为最小生成树的长度
int map[N][N],dis[N],vis[N];


// dist 数组保存各个点到连通部分的最短距离 dist[i] 表示 i 节点到连通部分的最短距离。初始时,dist 数组的各个元素为无穷大
// vis 数组保存节点的是和谁连通的。pre[i] = k 表示节点 i 和节点 k 之间需要有一条边。初始时,vis 的各个元素置为 0。
void Prim(){
    
    
	int i;
	for(int i=1;i<=n;i++){
    
      //注意: 节点1对应 序号1,而非0,没有节点0
		dis[i]=map[1][i];   //选择节点1为初始扩展节点,到联通图的距离便是与节点一的距离
		vis[i]=0;           //初始都为联通,默认置为0值
	}
	dis[1]=0;    
	vis[1]=1;
	int j,k,tmp;
	for(i=1;i<=n;i++){
    
    
		tmp=INF;
		for(j=1;j<=n;j++){
    
    
			if(!vis[j]&&tmp>dis[j]){
    
      //如果节点j未加入连通图 &&  tmp>dis[j] (找到未访问的节点中 与连通图相连的边 中最短的点)
				k=j;
				tmp=dis[j];
			}	
		}
		if(tmp==INF)   //如果最短边
			break;
		vis[k]=1;  //代表此次将节点k加入连通图, vis[k]==1 代表k已经访问过 
		ans+=dis[k]; //将k与连通图相连的边加入最小生成树
		for(j=1;j<=n;j++){
    
    
			if( !vis[j] && dis[j] >map[k][j])  // 如果vis[j]未访问过 && dis[j] > map[k][j] 结点k与连通图的路径大于 map[k][j]
				dis[j]=map[k][j];      //更新dis[j]的值
		}


	}


}

int main()
{
    
    
	while(cin>>n){
    
    
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++)
				cin>>map[i][j];
		int q,a,b;
		cin>>q;
		while(q--){
    
    
		scanf("%d%d",&a,&b);
		map[a][b]=map[b][a]=0;
		}
		ans=0;
		Prim();
		cout<<ans<<endl;
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/X131644/article/details/126366584
N!
n
N*
今日推荐