399. Evaluate Division

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class Solution {
private static class UnionFind {
private final int[] parent;
private final double[] divisionValues; // 至 parent[x] 的除法值

public UnionFind(int n) {
this.parent = new int[n];
this.divisionValues = new double[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
divisionValues[i] = 1.0;
}
}

public void union(int x, int y, double divisionValue) {
int xRoot = getRoot(x);
int yRoot = getRoot(y);
if (xRoot == yRoot) {
return;
}

// before:
// x -> xRoot
// y -> yRoot

// after:
// x -> xRoot
// | |
// \/ \/
// y -> yRoot

parent[xRoot] = yRoot;
// x -> xRoot -> yRoot / x -> y -> yRoot 这两条路径都能到达 yRoot
// 因为改变了 xRoot 的指向,所以此处更新 divisionValues[xRoot] 的值,即更新的 xRoot -> yRoot 这条路径的权重
divisionValues[xRoot] = divisionValue * divisionValues[y] / divisionValues[x];
}

public int getRoot(int x) {
if (x != parent[x]) {
int p = parent[x];
int root = getRoot(p);
divisionValues[x] *= divisionValues[p];
parent[x] = root; // path compression
}

return parent[x];
}

public double getDivisionValue(int x, int y) {
return divisionValues[x] / divisionValues[y];
}

public boolean isUnion(int x, int y) {
return getRoot(x) == getRoot(y); // 注意此处是比较 root 是否相等,而不是比较 parent 的指向
}
}

public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
Map<String, Integer> varToIndexMap = new HashMap<>();
for (List<String> equation : equations) {
for (String var : equation) {
if (!varToIndexMap.containsKey(var)) {
varToIndexMap.put(var, varToIndexMap.size());
}
}
}

UnionFind unionFind = new UnionFind(varToIndexMap.size());

// 构建至并查集
for (int i = 0; i < equations.size(); i++) {
List<String> equation = equations.get(i);
int index1 = varToIndexMap.get(equation.get(0)), index2 = varToIndexMap.get(equation.get(1));
unionFind.union(index1, index2, values[i]);
}

// 计算结果
double[] results = new double[queries.size()];
for (int i = 0; i < queries.size(); i++) {
List<String> query = queries.get(i);
Integer index1 = varToIndexMap.get(query.get(0)), index2 = varToIndexMap.get(query.get(1));
if (index1 == null || index2 == null || !unionFind.isUnion(index1, index2)) {
results[i] = -1.0;
} else {
results[i] = unionFind.getDivisionValue(index1, index2);
}
}

return results;
}
}

References

399. Evaluate Division
剑指 Offer II 111. 计算除法