题解 | #畅通工程#

畅通工程

https://www.nowcoder.com/practice/4878e6c6a24e443aac5211d194cf3913

#include<iostream>
using namespace std;

// 畅通工程 
const int MAX = 1000;
int father[MAX];
int height[MAX];

void Initial(int n) {
	for (int i = 0; i <= n; i++) {
		father[i] = i;
		height[i] = 0;
	}
}

int Find(int x) {
	if (x != father[x]) {
		father[x] = Find(father[x]);
	}
	return father[x];
}

void Union(int x, int y) {
	x = Find(x);
	y = Find(y);
	if (x != y) {
		if (height[x] < height[y]) {
			father[x] = y;
		}
		else if (height[x] > height[y]) {
			father[y] = x;
		}
		else {
			father[y] = x;
			height[x]++;
		}
	}
}

int main()
{
	int n, m;
	while (cin >> n) {
		if (n == 0) {
			break;
		}
		cin >> m;
		Initial(n);
		for (int i = 0; i < m; i++) {
			int x, y;
			cin >> x >> y;
			Union(x, y);
		}
		int ans = -1;
		for (int i = 1; i <= n; i++) {
			if (i == father[i]) {
				ans++;
			}
		}
		cout << ans << endl;
	}

	return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务