#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>
using namespace std;
int n,m;
int q;
int x,y;
int father[10005];
//寻找代表元
int find(int k){
while(father[k]!=k){
k=father[k];
}
return k;
}
int hb(int u,int v){
father[v]=u;
}
int main(){
freopen("并查集.in","r",stdin);
freopen("并查集.out","w",stdout);
scanf("%d%d",&n,&m);
//初始化
for(int i=1;i<=n;i++){
father[i]=i;
}
//读入,处理
for(int i=1;i<=m;i++){
scanf("%d%d",&x,&y);
int r1,r2;
r1=find(x);
r2=find(y);
if(r1!=r2){
hb(r1,r2);
}
}
scanf("%d",&q);
for(int i=1;i<=q;i++){
scanf("%d%d",&x,&y);
if(find(x)==find(y)){
printf("Yes\n");
}
else printf("No\n");
}
return 0;
}
并查集
最新推荐文章于 2024-07-29 20:58:50 发布