#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const ll N = 1e8 +10;
int pre[N];
int a[N];
int root(int x){
return pre[x] = (pre[x] == x ? x : root(pre[x]) );
}
void merge(int x,int y){
pre[root(x)] = root(y);
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int m,n;
int k;
cin >> m >> n >> k;
for(int i = 1; i <= m*n; i++) pre[i] = i;
for(int i = 1; i <= k; i++){
int x,y;
cin >> x >> y;
merge(x,y);
}
ll ans = 0;
for(int i = 1; i <= m*n; i++){
a[root(i)] = 1;
if(a[i] == 1) ans++;
}
cout << ans;
return 0;
}
注意底下的代码,刚开始将a数组中的所有数都变为0,合根后,让a[老大]变为1,再遍历,在a数组中找到每一个老大的名字代表的数,若该数为1,答案加1。