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>
.
思路,用深度优先算法来求解。先用一个映射mp来存放已知的式子中的分子分母和结果(mp中既要包含已知的式子,也要包含已知式子的倒数,否则用dfs会出现错误),然后看要求的分子和分母是否在mp,若分子分母中有一个不在mp中,则结果是-0.1;否则,通过dfs来得出结果(mp中和结果分子相同的开始)。
class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
vector<double> result(queries.size());
if(!queries.size())
return result;
unordered_map<string, unordered_map<string,double>> mp;
unordered_set<string> temp;
mp.clear();
bool canReach = true;
double res = 1.0, tmpres;
for(int i = 0; i < equations.size(); ++ i){
mp[equations[i].first][equations[i].second] = values[i];
mp[equations[i].second][equations[i].first] = 1.0/values[i];
}
for(int i = 0; i < queries.size(); ++ i){
if(mp.find(queries[i].first) == mp.end() || mp.find(queries[i].second) == mp.end())
result[i] = -1.0;
else{
canReach = false;
tmpres = 1.0;
res = -1.0;
temp.clear();
temp.insert(queries[i].first);
dfs(queries[i].first, queries[i].second, res, tmpres, canReach, mp, temp);
result[i] = res;
}
}
return result;
}
private:
void dfs(string &sta, string &ends, double &res, double &tmpres, bool &canReach, unordered_map<string, unordered_map<string,double>> &mp, unordered_set<string> &vis){
if(sta == ends){
res = tmpres;
canReach = true;
return ;
}
unordered_map<string,double>::iterator it = mp[sta].begin();
double vres = 1.0;
string u = "";
for(; it != mp[sta].end(); ++ it){
if(vis.find(it->first) != vis.end())
continue;
vres = tmpres*it->second;
u = it->first;
vis.insert(it->first);
dfs(u, ends, res, vres, canReach, mp, vis);
}
}
};