题目描述
blablabla
样例
blablabla
算法1
Java 代码
import java.io.*;
import java.util.*;
public class Main {
static class UFind {
int[] father;
UFind(int n){
father = new int[n+1];
for(int i = 1; i <= n; i++){
father[i] = i;
}
}
public int find(int x) {
if(father[x] != x){
father[x] = find(father[x]);
}
return father[x];
}
public void union(int p, int q) {
int fp = find(p);
int fq = find(q);
if(fp != fq){
father[fp] = fq;
}
}
}
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception {
String[] s = read.readLine().split(" ");
int n = Integer.valueOf(s[0]);
int m = Integer.valueOf(s[1]);
UFind uf = new UFind(n);
for(int i = 0; i < m; i++){
s = read.readLine().split(" ");
int p = Integer.valueOf(s[1]);
int q = Integer.valueOf(s[2]);
if("M".equals(s[0])){
uf.union(p, q);
}else if ("Q".equals(s[0])){
String out = uf.find(p)
== uf.find(q) ? "Yes" : "No";
log.write(out + "\n");
}
}
log.flush();
}
}