Union Find 并查集
什么样的题目使用并查集
- 关于集合合并
- 判断在不在同一个集合中12345678910111213141516171819202122232425262728class UnionFind {HashMap<Integer, Integer> fathers = new HashMap<>();public UnionFind(Set<Integer> set) {for (int n : set) {fathers.put(n, n);}}public void union(int x, int y) {int fa_x = find(x);int fa_y = find(y);fathers.put(fa_x, fa_y);}public int find(int x) {int father = fathers.get(x);while (father != fathers.get(father)) {father = fathers.get(father);}while (fathers.get(x) != father) {int tmp = fathers.get(x);fathers.put(x, father);x = tmp;}return father;}}