并查集

合根植物

#include <bits/stdc++.h>
using namespace std;

const int N=11000010;
int p[N];
int ans=0;
int find(int x){
	if(p[x]!=x)p[x]=find(p[x]);
	return p[x];
}
int main(){
	
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int n,m,k;
	cin>>n>>m>>k;
	for(int i=1;i<=n*m;i++){
		p[i]=i;
	}
	for(int i=1;i<=k;i++){
		int a,b;
		cin>>a>>b;
		int pa=find(a);
		int pb=find(b);
		if(pa!=pb)p[pa]=pb;
	}
	for(int i=1;i<=n*m;i++){if(p[i]==i)ans++;}
	cout<<ans;
	return 0;
}
posted @ 2025-03-24 17:25  冬天的睡袋  阅读(5)  评论(0)    收藏  举报