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"] ].
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.
题目理解:给定一些除法等式,再给定一些除法问题,写出这些问题的答案,不可能算出答案就写-1
解题思路:
一步一步思考,首先,我们要将给的所有条件存储起来,可以使用一个二维数组record[i][j]表示i / j = record[i][j],由于除数和被除数不一定是数字,因此考虑使用一个字典将字符串表示的除数和被除数映射为整型数字。
存储了所有的条件等式之后,需要判断某一个除法问题是否有答案,答案是什么,考虑到可能需要使用多个条件等式才能得到答案,例如a/b=1,b/c=2,c/d=3,d/e=4问a/e的答案,可以发现这是一个类似于求有向图节点之间最短距离的问题,在这里需要类比求任意两个节点之间的最短距离,因此考虑使用普利姆算法,这个算法的代码比较简单,经过这个算法的处理之后,所有能得到答案的除法式子的答案就都求出来了,不能得到答案的式子则为初始值,然后遍历问题就可得解。
class Solution {
public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
Map<String, Integer> map = new HashMap<String, Integer>();
int lenOfQueries = queries.length;
double[] res = new double[lenOfQueries];
Arrays.fill(res, -1);
double def = 0.56239;
int ct = 0, len = equations.length;
for(String[] it : equations){
for(String str : it){
if(!map.containsKey(str))
map.put(str, ct++);
}
}
double[][] record = new double[ct][ct];
for(double[] it : record)
Arrays.fill(it, def);
for(int i = 0; i < len; i++){
int a = map.get(equations[i][0]), b = map.get(equations[i][1]);
record[a][b] = values[i];
}
for(int k = 0; k < ct; k++){
for(int i = 0; i < ct; i++){
for(int j = 0; j < ct; j++){
if(record[i][j] != def)
continue;
if(i == j){
record[i][j] = 1;
continue;
}
if(record[j][i] != def){
record[i][j] = 1 / record[j][i];
continue;
}
if(record[i][k] != def && record[j][k] != def){
record[i][j] = record[i][k] / record[j][k];
continue;
}
if(record[i][k] != def && record[k][j] != def){
record[i][j] = record[i][k] * record[k][j];
continue;
}
}
}
}
for(int i = 0; i < lenOfQueries; i++){
String[] it = queries[i];
int a, b;
if(map.containsKey(it[0]))
a = map.get(it[0]);
else
continue;
if(map.containsKey(it[1]))
b = map.get(it[1]);
else
continue;
if(record[a][b] != def)
res[i] = record[a][b];
}
return res;
}
}