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
.java
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 ].
lua
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>
.spa
According to the example above:code
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.orm
題目大意:blog
給一系列表達式的值,查詢某一表達式是否能以給定表達式的值求出。rem
解法:get
根據表達式的值能夠組成圖,好比a/b=2,那麼就是a到b存在邊,且邊上的權重爲2,b到a也是存在邊的,且權重爲1/2.input
java:string
class Solution { private double dfs(String start,String end,Map<String,ArrayList<String>> pairs, Map<String, ArrayList<Double>> values, HashSet<String> set, double value){ if (set.contains(start)) return 0.0; if (!pairs.containsKey(start)) return 0.0; if (start.equals(end)) return value; set.add(start); ArrayList<String> strList=pairs.get(start); ArrayList<Double> valueList=values.get(start); double tmp=0.0; for (int i=0;i<strList.size();i++){ tmp=dfs(strList.get(i),end,pairs,values,set,value*valueList.get(i)); if (tmp!=0){ break; } } set.remove(start); return tmp; } public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { Map<String,ArrayList<String>> pairs=new HashMap<>(); Map<String,ArrayList<Double>> valuesPair=new HashMap<>(); for (int i=0;i<equations.size();i++){ pairs.computeIfAbsent(equations.get(i).get(0),k->new ArrayList<>()).add(equations.get(i).get(1)); valuesPair.computeIfAbsent(equations.get(i).get(0),k->new ArrayList<>()).add(values[i]); pairs.computeIfAbsent(equations.get(i).get(1),k->new ArrayList<>()).add(equations.get(i).get(0)); valuesPair.computeIfAbsent(equations.get(i).get(1),k->new ArrayList<>()).add(1/values[i]); } double[] res=new double[queries.size()]; for (int i=0;i<queries.size();i++){ res[i]=dfs(queries.get(i).get(0),queries.get(i).get(1),pairs,valuesPair,new HashSet<>(),1.0); if (res[i]==0.0) res[i]=-1.0; } return res; } }