Evaluate Division

Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.

Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].

The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.

According to the example above:

equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. 

分析:
这是一道典型的graph题,因为从一个变量可以到另一个变量,并得到它们的关系。
 1 public class Solution {
 2     public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
 3         Map<String, Map<String, Double>> graph = buildGraph(equations, values);
 4         double[] result = new double[queries.length];
 5 
 6         for (int i = 0; i < queries.length; i++) {
 7             result[i] = getPathWeight(queries[i][0], queries[i][1], new HashSet<>(), graph);
 8         }
 9         return result;
10     }
11 
12     private double getPathWeight(String start, String end, Set<String> visited,
13             Map<String, Map<String, Double>> graph) {
14         if (!graph.containsKey(start)) {
15             return -1.0;
16         }
17 
18         if (graph.get(start).containsKey(end)) {
19             return graph.get(start).get(end);
20         }
21 
22         visited.add(start);
23         for (Map.Entry<String, Double> neighbour : graph.get(start).entrySet()) {
24             if (!visited.contains(neighbour.getKey())) {
25                 double productWeight = getPathWeight(neighbour.getKey(), end, visited, graph);
26                 if (productWeight != -1.0) {
27                     return neighbour.getValue() * productWeight;
28                 }
29             }
30         }
31         return -1.0;
32     }
33 
34     private Map<String, Map<String, Double>> buildGraph(String[][] equations, double[] values) {
35         Map<String, Map<String, Double>> graph = new HashMap<>();
36         String u, v;
37 
38         for (int i = 0; i < equations.length; i++) {
39             u = equations[i][0];
40             v = equations[i][1];
41             graph.putIfAbsent(u, new HashMap<>());
42             graph.get(u).put(v, values[i]);
43             graph.putIfAbsent(v, new HashMap<>());
44             graph.get(v).put(u, 1 / values[i]);
45         }
46         return graph;
47     }
48 }

猜你喜欢

转载自www.cnblogs.com/beiyeqingteng/p/11287706.html
今日推荐