P2097 资料分发1 求连通块数量 并查集板
作者:
多米尼克領主的致意
,
2024-05-26 15:08:39
,
所有人可见
,
阅读 6
code:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int f[N];
int find(int x){
if(x != f[x])f[x] = find(f[x]);
return f[x];
}
void merge(int a, int b){
a = find(a), b = find(b);
f[a] = b;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for(int i = 1;i <= n;i++)f[i] = i;
for(int i = 1;i <= m;i++){
int a, b;
cin >> a >> b;
merge(a, b);
}
int ans = 0;
for(int i = 1;i <= n;i++)if(f[i] == i)ans++;
cout << ans;
return 0;
}