AcWing 836. 合并集合-JAVA刷题模板
原题链接
简单
作者:
acw_weian
,
2020-04-20 23:07:32
,
所有人可见
,
阅读 524
import java.util.*;
import java.io.*;
class Main{
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 t = Integer.valueOf(s[1]);
UFind uf = new UFind(n);
for(int i = 0; i < t; i++){
s = read.readLine().split(" ");
if("M".equals(s[0])){
uf.union(Integer.valueOf(s[1]), Integer.valueOf(s[2]));
}else{
String out = uf.find(Integer.valueOf(s[1]))
== uf.find(Integer.valueOf(s[2])) ? "Yes" : "No";
log.write(out + "\n");
}
}
log.flush();
}
static class UFind {
int[] father;
UFind(int n) {
father = new int[n + 1];
for(int i = 1; i <= n; i++){
father[i] = i;
}
}
public void union(int node1, int node2) {
int find1 = find(node1);
int find2 = find(node2);
if(find1 != find2) {
father[find1] = find2;
}
}
public int find(int node) {
if (father[node] == node) {
return node;
}
father[node] = find(father[node]);
return father[node];
}
}
}