// 递推 publicintfind(int x){ int a = x; while (x != father[x]) { x = father[x]; } while (a != father[a]) { int temp = a; a = father[a]; father[temp] = x; } return x; }
// 递归 publicintfind(int x){ if (x == father[x]) { return x; } else { int f = find(father[x]); father[x] = f; return f; } }
UnionFind unionFind = new UnionFind(2 * equationSize); // 第 1 步:预处理,将变量的值与 id 进行映射,使得并查集的底层使用数组实现,方便编码 Map<String, Integer> map = new HashMap<>(2 * equationSize); int id = 0; for (int i = 0; i < equationSize; i++) { List<String> equation = equations.get(i); String x = equation.get(0); String y = equation.get(1); if (!map.containsKey(x)) { map.put(x, id++); } if (!map.containsKey(y)) { map.put(y, id++); } unionFind.union(map.get(x), map.get(y), values[i]); }
int querySize = queries.size(); double[] ans = newdouble[querySize]; for (int i = 0; i < querySize; i++) { String x = queries.get(i).get(0); String y = queries.get(i).get(1);