【模板】并查集 - 洛谷
#include <bits/stdc++.h>
using namespace std;
const int N=2e5+9;
int a[N];
int Find(int x)
{if(x==a[x]){return x;}else{a[x]=Find(a[x]);return a[x];}
}
void push(int x,int y)
{a[Find(x)]=Find(y);return ;
}
int main()
{int n,m; cin>>n>>m;for(int i=1;i<=n;i++){a[i]=i;}for(int i=1;i<=m;i++){int op,x,y; cin>>op>>x>>y;if(op==1) //连接{push(x,y);}else{if(Find(x)==Find(y)){cout<<"Y"<<endl;}else cout<<"N"<<endl;}}return 0;
}
0城市群的数量 - 蓝桥云课 (lanqiao.cn)
#include <bits/stdc++.h>
using namespace std;
int a[100000];
int n, m;int Find(int x)
{if(a[x]!=x) a[x]=Find(a[x]);return a[x];
}void Union(int x,int y)
{x=Find(x),y=Find(y);if(x!=y) a[x]=y;
}int main()
{cin >> n >> m;int sum=0;for (int i=1; i <= n; i++) a[i] = i;for (int i = 1; i <= m; i++){int u, v; cin >> u >> v;Union(u, v);}for(int i=1;i<=n;i++){if(a[i]==i) sum++;}cout<<sum;return 0;
}