hdu1102(最小生成树)

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

分析:
这题只要把已经建好的路生成树,并且生成树的费用均为0;接下来的做法就跟城市规划那题的原理一样:将每条按费用高低从低到高排列起来 ,再用Kruskal算法选择最小总费用,实际就是利用并查集集成一棵树,因为费用已经从小排到大了,选全部最小的路做为一颗树,再选第二高的,若可以与第一棵树连则连起来,不能则另起一颗(即并查集),因为都是从最小的选起来,则生成的第一棵完整的树即是最小总费用的树。

ac代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;
int pa[105],ans,m;
struct mmp
{
	int x, y, z;

}p[10005];
bool cmp(mmp a, mmp b )
{
	return a.z < b.z;
}
int find(int x)
{
	while (x != pa[x])
		x = pa[x];
	return x;
}
void bcj()
{
	sort(p, p + m*m, cmp);
	for (int j = 0; j < m*m; j++)
	{
		int x = find(p[j].x), y = find(p[j].y);
		if (x != y)
		{
			ans += p[j].z;
			pa[x] = y;
		}
	}
}
int main()
{
	int c=0,n,a,b;
	while (cin >> m)
	{
		ans = 0;
		for (int i = 0; i < m; i++)
		{
			for (int j = 0; j < m; j++)
			{
				p[c].x = i + 1; p[c].y = j + 1; cin >> p[c].z; c++;
			}
		}
		for (int i = 0; i < m; i++)
			pa[i] = i;
		cin >> n;
		for (int i = 0; i < n; i++)
		{
			cin >> a >> b;
			p[(a-1)*m+b-1].z = 0;
			p[(b-1)*m + a-1].z = 0;
		}bcj();
		cout << ans << endl;
	}

	
}

猜你喜欢

转载自blog.csdn.net/weixin_43965698/article/details/86682800