其他分享
首页 > 其他分享> > 217A - Ice Skating

217A - Ice Skating

作者:互联网

并查集:

思路:把所有x或y相同的点合并成一个集合,所需要加的点数就是连通块数量-1。

#include <iostream>
using namespace std;
const int N = 110;
int n;
int x[N],y[N],p[N];
int find (int x) {
	if (p[x] != x) p[x] = find (p[x]);
	return p[x];
}
int main () {
	cin >> n;
	for (int i = 1;i <= n;i++) {
		cin >> x[i] >> y[i];
		p[i] = i;
	}
	for (int i = 1;i <= n;i++) {
		for (int j = i+1;j <= n;j++) {
			if (x[i] == x[j] || y[i] == y[j]) p[find (i)] = find (j);
		}
	}
	int ans = 0;
	for (int i = 1;i <= n;i++) {
		if (p[i] == i) ans++;
	}
	cout << ans-1 << endl;
	return 0;
}

标签:Skating,217A,const,int,查集,Ice,110,find
来源: https://www.cnblogs.com/incra/p/16389853.html