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
queries are:
return
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"] ].
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.
解法:
这个题a/b, b/c, so we know a/c 因此是一个graph问题
edge case:
a/b thus we also know b/a 因此是一个undirected graph
a/b, a/c 所以图结构为:
Map<String,Map<String,Double>>
Map<String,Map<String,Double>> dividendToDivisor = new HashMap<>();
public boolean notFound = true;
public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
for(int i = 0; i < equations.length; i++){
String[] eq = equations[i];
dividendToDivisor.putIfAbsent(eq[0],new HashMap<>());
dividendToDivisor.get(eq[0]).put(eq[1],values[i]);
dividendToDivisor.putIfAbsent(eq[1],new HashMap<>());
dividendToDivisor.get(eq[1]).put(eq[0],1/values[i]);
}
double[] ans = new double[queries.length];
for(int i = 0; i < queries.length; i++){
String[] q = queries[i];
notFound = true;
ans[i] = find(q[0],q[1],new HashSet<>());
}
return ans;
}
public double find(String x, String y,Set<String> visited){
// System.out.println(x+" "+y+(visited.contains(x)||!dividendToDivisor.containsKey(x)));
if(visited.contains(x) || !dividendToDivisor.containsKey(x)) return -1;
if(x.equals(y)) {notFound = false; return 1.0;}
visited.add(x);
for(Map.Entry<String, Double> entry: dividendToDivisor.get(x).entrySet()) {
String next = entry.getKey();
double ans = find(next,y,visited);
if(!notFound)
return dividendToDivisor.get(x).get(next)*ans;
}
visited.remove(x);
return -1;
}
没有评论:
发表评论