|
| 1 | +package class14; |
| 2 | + |
| 3 | +// 这个文件课上没有讲 |
| 4 | +// 原理和课上讲的完全一样 |
| 5 | +// 最大的区别就是这个文件实现的并查集是用数组结构,而不是map结构 |
| 6 | +// 请务必理解这个文件的实现,而且还提供了测试链接 |
| 7 | +// 提交如下的code,并把"Code06_UnionFind"这个类名改成"Main" |
| 8 | +// 在测试链接里可以直接通过 |
| 9 | +// 请同学们务必参考如下代码中关于输入、输出的处理 |
| 10 | +// 这是输入输出处理效率很高的写法 |
| 11 | +// 测试链接 : https://www.nowcoder.com/questionTerminal/e7ed657974934a30b2010046536a5372 |
| 12 | +import java.io.BufferedReader; |
| 13 | +import java.io.IOException; |
| 14 | +import java.io.InputStreamReader; |
| 15 | +import java.io.OutputStreamWriter; |
| 16 | +import java.io.PrintWriter; |
| 17 | +import java.io.StreamTokenizer; |
| 18 | + |
| 19 | +public class Code06_UnionFind { |
| 20 | + |
| 21 | +public static int MAXN = 1000001; |
| 22 | + |
| 23 | +public static int[] father = new int[MAXN]; |
| 24 | + |
| 25 | +public static int[] size = new int[MAXN]; |
| 26 | + |
| 27 | +public static int[] help = new int[MAXN]; |
| 28 | + |
| 29 | +// 初始化并查集 |
| 30 | +public static void init(int n) { |
| 31 | +for (int i = 0; i <= n; i++) { |
| 32 | +father[i] = i; |
| 33 | +size[i] = 1; |
| 34 | +} |
| 35 | +} |
| 36 | + |
| 37 | +// 从i开始寻找集合代表点 |
| 38 | +public static int find(int i) { |
| 39 | +int hi = 0; |
| 40 | +while (i != father[i]) { |
| 41 | +help[hi++] = i; |
| 42 | +i = father[i]; |
| 43 | +} |
| 44 | +for (hi--; hi >= 0; hi--) { |
| 45 | +father[help[hi]] = i; |
| 46 | +} |
| 47 | +return i; |
| 48 | +} |
| 49 | + |
| 50 | +// 查询x和y是不是一个集合 |
| 51 | +public static boolean isSameSet(int x, int y) { |
| 52 | +return find(x) == find(y); |
| 53 | +} |
| 54 | + |
| 55 | +// x所在的集合,和y所在的集合,合并成一个集合 |
| 56 | +public static void union(int x, int y) { |
| 57 | +int fx = find(x); |
| 58 | +int fy = find(y); |
| 59 | +if (fx != fy) { |
| 60 | +if (size[fx] >= size[fy]) { |
| 61 | +size[fx] += size[fy]; |
| 62 | +father[fy] = fx; |
| 63 | +} else { |
| 64 | +size[fy] += size[fx]; |
| 65 | +father[fx] = fy; |
| 66 | +} |
| 67 | +} |
| 68 | +} |
| 69 | + |
| 70 | +public static void main(String[] args) throws IOException { |
| 71 | +BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 72 | +StreamTokenizer in = new StreamTokenizer(br); |
| 73 | +PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); |
| 74 | +while (in.nextToken() != StreamTokenizer.TT_EOF) { |
| 75 | +int n = (int) in.nval; |
| 76 | +init(n); |
| 77 | +in.nextToken(); |
| 78 | +int m = (int) in.nval; |
| 79 | +for (int i = 0; i < m; i++) { |
| 80 | +in.nextToken(); |
| 81 | +int op = (int) in.nval; |
| 82 | +in.nextToken(); |
| 83 | +int x = (int) in.nval; |
| 84 | +in.nextToken(); |
| 85 | +int y = (int) in.nval; |
| 86 | +if (op == 1) { |
| 87 | +out.println(isSameSet(x, y) ? "Yes" : "No"); |
| 88 | +out.flush(); |
| 89 | +} else { |
| 90 | +union(x, y); |
| 91 | +} |
| 92 | +} |
| 93 | +} |
| 94 | +} |
| 95 | +} |
0 commit comments