399. 除法求值
题目
描述:
给你一个变量对数组 equations 和一个实数值数组 values 作为已知条件,其中 equations[i] = [Ai, Bi] 和 values[i] 共同表示等式 Ai / Bi = values[i]。每个 Ai 或 Bi 是一个表示单个变量的字符串。
另有一些以数组 queries 表示的问题,其中 queries[j] = [Cj, Dj] 表示第 j 个问题,请你根据已知条件找出 Cj / Dj = ? 的结果作为答案。
返回 所有问题的答案。如果存在某个无法确定的答案,则用 -1.0 替代这个答案。如果问题中出现了给定的已知条件中没有出现的字符串,也需要用 -1.0 替代这个答案。
注意: 输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。
注意: 未在等式列表中出现的变量是未定义的,因此无法确定它们的答案。
示例 1:
- 输入:
equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]] - 输出:
[6.00000,0.50000,-1.00000,1.00000,-1.00000]
示例 2:
- 输入:
equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]] - 输出:
[3.75000,0.40000,5.00000,0.20000]
提示:
1 <= equations.length <= 201 <= queries.length <= 20- 变量由小写英文字母与数字组成
题解
用边权表示两个变量的比值
把变量名作为图的节点。已知 x / y = v,就加入从 x 到 y、权重为 v 的边,同时加入从 y 到 x、权重为 1.0 / v 的边。反向边让同一条等式也能用于反向查询。
沿路径相乘会消去中间变量。例如已知 a/b = 2、b/c = 3,沿 a → b → c 得到 (a/b) × (b/c) = a/c = 6;反向查询则得到 c/a = 1/6。题目保证等式不矛盾,所以找到任意一条连接路径即可。
DFS 传递从起点到当前点的乘积
dfs(curr, target, accValue, ...) 中,accValue 表示起点变量与当前变量的比值,初始为 1。沿权重为 weight 的边移动时,传入 accValue * weight;到达目标就返回累计值。
每个查询新建一个 visited 集合,避免因反向边或其他环反复访问节点。某条分支失败后继续尝试其他邻居,所有分支都无法到达目标才返回 -1.0。同一次查询无须在回溯时移除访问标记:这里只判断可达性,已探索的节点不必从另一条路径重复搜索。
先检查变量是否存在
查询中的任一变量未出现在等式中,结果就是 -1.0。即使查询为 x/x,也必须先确认 x 已知;已知变量除以自身才返回 1.0。两个变量都已知但处于不同连通分量时,也会搜索失败。
设图有 $V$ 个变量、$E$ 条等式,查询数为 $Q$。构图时间为 $O(V+E)$,每个查询最坏为 $O(V+E)$,总时间为 $O(V+E+Q(V+E))$。不计答案数组,邻接表、访问集合和递归栈合计为 $O(V+E)$ 空间。
完整示例
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import java.util.*;
public class Main {
public static double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
Map<String, Map<String, Double>> graph = new HashMap<>();
for (int i = 0; i < equations.size(); i++) {
String u = equations.get(i).get(0);
String v = equations.get(i).get(1);
double val = values[i];
graph.putIfAbsent(u, new HashMap<>());
graph.putIfAbsent(v, new HashMap<>());
graph.get(u).put(v, val);
graph.get(v).put(u, 1.0 / val);
}
double[] result = new double[queries.size()];
for (int i = 0; i < queries.size(); i++) {
String start = queries.get(i).get(0);
String end = queries.get(i).get(1);
if (!graph.containsKey(start) || !graph.containsKey(end)) {
result[i] = -1.0;
} else if (start.equals(end)) {
result[i] = 1.0;
} else {
Set<String> visited = new HashSet<>();
result[i] = dfs(start, end, 1.0, visited, graph);
}
}
return result;
}
private static double dfs(String curr, String target, double accValue,
Set<String> visited,
Map<String, Map<String, Double>> graph) {
if (curr.equals(target)) {
return accValue;
}
visited.add(curr);
for (Map.Entry<String, Double> entry : graph.get(curr).entrySet()) {
String next = entry.getKey();
double weight = entry.getValue();
if (!visited.contains(next)) {
double result = dfs(next, target, accValue * weight, visited, graph);
if (result != -1.0) {
return result;
}
}
}
return -1.0;
}
// 按题面格式输出:保留 5 位小数,逗号后不加空格
private static String format(double[] arr) {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < arr.length; i++) {
if (i > 0) sb.append(',');
sb.append(String.format("%.5f", arr[i]));
}
return sb.append(']').toString();
}
public static void main(String[] args) {
List<List<String>> equations1 = new ArrayList<>();
equations1.add(Arrays.asList("a", "b"));
equations1.add(Arrays.asList("b", "c"));
double[] values1 = {2.0, 3.0};
List<List<String>> queries1 = new ArrayList<>();
queries1.add(Arrays.asList("a", "c"));
queries1.add(Arrays.asList("b", "a"));
queries1.add(Arrays.asList("a", "e"));
queries1.add(Arrays.asList("a", "a"));
queries1.add(Arrays.asList("x", "x"));
System.out.println("示例 1 输入:");
System.out.println("equations = " + equations1);
System.out.println("values = " + Arrays.toString(values1));
System.out.println("queries = " + queries1);
double[] res1 = calcEquation(equations1, values1, queries1);
System.out.println("示例 1 输出: " + format(res1));
System.out.println("-----------------------------");
List<List<String>> equations2 = new ArrayList<>();
equations2.add(Arrays.asList("a", "b"));
equations2.add(Arrays.asList("b", "c"));
equations2.add(Arrays.asList("bc", "cd"));
double[] values2 = {1.5, 2.5, 5.0};
List<List<String>> queries2 = new ArrayList<>();
queries2.add(Arrays.asList("a", "c"));
queries2.add(Arrays.asList("c", "b"));
queries2.add(Arrays.asList("bc", "cd"));
queries2.add(Arrays.asList("cd", "bc"));
System.out.println("示例 2 输入:");
System.out.println("equations = " + equations2);
System.out.println("values = " + Arrays.toString(values2));
System.out.println("queries = " + queries2);
double[] res2 = calcEquation(equations2, values2, queries2);
System.out.println("示例 2 输出: " + format(res2));
}
}
运行结果(OpenJDK 21.0.12):
1
2
3
4
5
6
7
8
9
10
11
示例 1 输入:
equations = [[a, b], [b, c]]
values = [2.0, 3.0]
queries = [[a, c], [b, a], [a, e], [a, a], [x, x]]
示例 1 输出: [6.00000,0.50000,-1.00000,1.00000,-1.00000]
-----------------------------
示例 2 输入:
equations = [[a, b], [b, c], [bc, cd]]
values = [1.5, 2.5, 5.0]
queries = [[a, c], [c, b], [bc, cd], [cd, bc]]
示例 2 输出: [3.75000,0.40000,5.00000,0.20000]
