并查集:
思路:把所有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;
}
原创文章,作者:端木书台,如若转载,请注明出处:https://blog.ytso.com/268334.html