Leetcode 399 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"] ].
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.0.对于分子分母相等的目标计算式,如果运算元素在已知条件等式中,则返回结果1,不然结果仍为-1.0.分子分母都是由string表示的一个数。
解法分析
当目标计算式就在已知条件中时可以直接得到结果,如果不在其中,需要判断经过多次相乘,能否得到最终结果,由于a/b=2.0,同时可得b/a=0.5,加入目标为a/c,则该问题可以看做a和c之间的寻路问题,a->b的权重为2.0,b->a的权重为0.5.因此可以利用已知等式构造一个图,从起点a开始寻路到c,利用深度优先搜索,遍历a的相邻点,并延某一点一直往下走,注意走过的点要用attended进行记录。
由本题可以看到,BFS和DFS的运用最主要是将问题转化为一个图问题,树的遍历只是一个特例。C++代码如下:
class Solution {
private:
double value;
string b;
unordered_map<string, vector<pair<string,double>>> myGraph;
unordered_set<string> attended;
public:
double findWay(string a){
double res;
if(attended.count(a))
return -1.0;
attended.insert(a);
for(auto p:myGraph[a]){
value*=p.second;
if(p.first==b)
return value;
res=findWay(p.first);
if(res==-1.0)
value/=p.second;
else
return res;
}
return -1.0;
}
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries){
for(int i=0;i<values.size();i++){
myGraph[equations[i].first].push_back(make_pair(equations[i].second,values[i]));
myGraph[equations[i].second].push_back(make_pair(equations[i].first,1.0/values[i]));//make the graph
}
vector<double> res;
for(auto q:queries){
b=q.second;
value=1;
attended.clear();
if(myGraph.count(q.first)==0||myGraph.count(q.second)==0)
res.push_back(-1.0);
else{
if(q.first==q.second)
res.push_back(1.0);
else
res.push_back(findWay(q.first));
}
}
return res;
}
};
代码中用unordered_map<string,vector<pair<string,double>>>作为表示本图的数据结构,string作为关键字,对应一个vector,vector元素为pair,存储与关键字相邻(已知条件中分母)的string,以及他们的商。用unordered_set<string>来标记到过的节点,关联容器STL s.count(x)返回关键字x出现的次数,对于本题用到的关联容器,关键字不能重复出现,因此返回值为0、1。