题目链接:
https://www.luogu.org/problem/P1551
并查集模板:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Main {
static int father[];
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
StreamTokenizer in=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
while(in.nextToken()!=StreamTokenizer.TT_EOF) {
int n=(int)in.nval;
father=new int[n+1];
for(int i=1;i<=n;i++) {
father[i]=i;
}
in.nextToken();
int m=(int)in.nval;
in.nextToken();
int p=(int)in.nval;
for(int i=0;i<m;i++) {
in.nextToken();
int a=(int)in.nval;
in.nextToken();
int b=(int)in.nval;
union(a,b);
}
for(int i=0;i<p;i++) {
in.nextToken();
int a=(int)in.nval;
in.nextToken();
int b=(int)in.nval;
a=findParent(a);
b=findParent(b);
System.out.println(a==b?"Yes":"No");
}
}
}
private static void union(int f, int t) {
// TODO Auto-generated method stub
int a=findParent(f);
int b=findParent(t);
if(a==b)return;
if(a>b) {
father[a]=b;
}else
father[b]=a;
}
private static int findParent(int f) {
// TODO Auto-generated method stub
while(father[f]!=f) {
f=father[f];
}
return f;
}
}