HOJ 1233 还是畅通工程(并查集、最小生成树)

使用Prime,直接暴力过。

#include
#include
using namespace std;
const int NN = 100 + 5, INF = 99999999;
int a[NN][NN], f[NN];//a[i][j]为i到j的距离,f[i]为i的根节点,也可以理解为所在集合的标记

int find(int x)
{//寻找根节点
	if (x == f[x]) return x;
	f[x] = find(f[x]);
	return f[x];
}

int mer(int x, int y)
{
	x = find(x);
	y = find(y);
	if (x != y)
		f[x] = y;
	return 1;
}

int main()
{
	int n, x, y, z, sum;
	while (scanf("%d", &n) != EOF, n)
	{
		sum = 0;
		for (int i = 1; i <= n; i++)
			f[i] = i;//每个顶点的根节点记录为自己
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
				a[i][j] = INF;//初始化所有的距离均为无穷大
		for (int i = 0; i < n * (n - 1) / 2; i++)
		{
			scanf("%d %d %d", &x, &y, &z);
			if (z == 0) z = INF;//不知道测试数据有没有0,但如果有0就是自身到自身,记录为无穷大
			a[x][y] = z;
			a[y][x] = z;
		}
		while (1)
		{
			int min0 = INF, flag = 1;
			for (int i = 1; i <= n; i++)
				for (int j = 1; j <= i; j++)
					if (find(i) != find(j) && a[i][j] < min0)
					{
						min0 = a[i][j];
						x = i;
						y = j;
						flag = 0;//如果找不到这样的边了,则flag是1,跳出while
					}
			if (flag) break;
			mer(x, y);
			sum += a[x][y];
		}//while
		cout << sum << endl;
	}
	return 0;
}

你可能感兴趣的:(HOJ 1233 还是畅通工程(并查集、最小生成树))