#include<bits/stdc++.h>
using namespace std;
const int M=2e5+10,N=1e4+10;
int n,m,x,y,z;
int pre[N];
int rk[N];
int find(int x){
if(pre[x]==x) return x;
return pre[x]=find(pre[x]);
}
bool isSame(int x,int y){
return find(x)==find(y);
}
void join(int x,int y){
x=find(x);
y=find(y);
if(x==y) return;
if(rk[x]>rk[y]) pre[y]=x;
else{
if(rk[x]==rk[y]) rk[y]++;
pre[x]=y;
}
}
int main(){
ios::sync_with_stdio(false);
cin>>n>>m;
for(int i=1;i<=n;i++){
pre[i]=i;
rk[i]=1;
}
while(m--){
cin>>z>>x>>y;
if(z==1){
join(x,y);
}else if(z==2){
if(isSame(x,y)) cout<<"Y"<<endl;
else cout<<"N"<<endl;
}
}
return 0;
}
还是并查集
#include<bits/stdc++.h>
using namespace std;
const int N=5e3+100;
int n,m,p;
int pre[N];
int rk[N];
int find(int x){
if(pre[x]==x) return x;
return pre[x]=find(pre[x]);
}
bool isSame(int x,int y){
return find(x)==find(y);
}
void join(int x,int y){
x=find(x);
y=find(y);
if(x==y) return;
if(rk[x]>rk[y]) pre[y]=x;
else{
if(rk[x]==rk[y]) rk[y]++;
pre[x]=y;
}
}
int main(){
ios::sync_with_stdio(0);
cin>>n>>m>>p;
for(int i=1;i<=n;i++){
pre[i]=i;
rk[i]=1;
}
while(m--){
int x,y;
cin>>x>>y;
join(x,y);
}
while(p--){
int a,b;
cin>>a>>b;
if(isSame(a,b)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}
还是并查集
#include<bits/stdc++.h>
using namespace std;
const int N=2e4+100;
int n,m,p,q,x,y;
int pre[N];
int rk[N];
int find(int x){
if(pre[x]==x) return x;
return pre[x]=find(pre[x]);
}
bool isSame(int x,int y){
return find(x)==find(y);
}
void join(int x,int y){
x=find(x);
y=find(y);
if(rk[x]>rk[y]) pre[y]=x;
else{
if(rk[x]==rk[y]) rk[y]++;
pre[x]=y;
}
}
int main(){
ios::sync_with_stdio(false);
cin>>n>>m>>p>>q;
for(int i=1;i<=n;i++){
pre[i]=i;
rk[i]=1;
}
for(int i=n+1;i<=n+m;i++){
pre[i]=i;
rk[i]=1;
}
rk[1]=N;rk[n+1]=N;
while(p--){
cin>>x>>y;
join(x,y);
}
while(q--){
cin>>x>>y;
x*=-1;y*=-1;
join(x+n,y+n);
}
int ans1=0,ans2=0;
for(int i=1;i<=n;i++){
if(find(i)==1) ans1++;
}
for(int i=n+1;i<=n+m;i++){
if(find(i)==n+1) ans2++;
}
cout<<min(ans1,ans2)<<endl;
return 0;
}