Constructing Roads(POJ-2421)

POJ - 2421 传送门

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


解题思路

prim算法的简单应用,特殊的是最开始存在已经互通的点,直接令已经互通的点为 0,然后直接上prim
prim:
每次选取离当前点最近的那个点,然后相连,记录更新最短距离


AC代码

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn = 1e4;
const int Inf  = 0x3f3f3f3f;
int map[maxn][maxn];
int len[maxn];
int vis[maxn];
int sum = 0;
int n;
int q;
void prim()
{
	for(int i = 1 ; i <= n ; i++)
	{
		len[i] = map[1][i];//初始化len记录顶点'1'到其他点的距离 
	}


	len[1] = 0;
	vis[1] = 1;//标记当前点 已经用过


	for(int i = 2 ; i <= n ; i++)
	{
		int min = Inf;//初始化最小值
		int pos;//记录 1 ~ pos中的最短的距离,pos记录下标到哪个点
		for(int j = 1 ;  j <= n ; j++)//找' pos -> 1 '的最短距离,并记录点
		{
			if(vis[j] == -1 && len[j] < min)
			{
				min = len[j];
				pos = j;
			}
		}
		
//begin -处理找到的与 1 相连的最短点

		vis[pos] = 1;
		sum += min;

//end - 处理完毕


		//遍历所有的点找与上面那个点相连的最短边的点
		for(int k = 1 ; k <= n ; k++)
		{
			if(vis[k] == -1 && map[pos][k] < len[k])//找到 - >  pos 到 k 的距离比 1 到 k 的的距离还短就更新一下len[k]  
			{
				len[k] = map[pos][k];
			}
		}
	}
}
int main()
{
	while(cin>>n && n)
	{
		memset(vis,-1,sizeof(vis));sum = 0;
		for(int i = 1 ; i <= n ; i++)
		{
			for(int j = 1 ; j <= n ; j++)
			{
				cin>>map[i][j];
			}
		}//存图
		cin>>q;
		while(q--)
		{
			int a, b;
			cin>>a>>b;// a b had build
			map[a][b] = map[b][a] = 0;
		}
		prim();
		cout<<sum<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46425926/article/details/107746337
今日推荐