问题来源
问题描述
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.
问题分析
实际看完题目我们就能意识到这道题目其实就是给出起点终点求路径的问题。显然,这是一个有向图,如有 a/b = 4
的两个顶点,则在图中建立a到b权值为4以及b到a权值为 1/4 的边,接着只需要按照提供的query查找相应的边并将边上的权值相乘即可。注意到题目中最后一句,there is no contradiction,也就是说,就算有多条路径到达统一顶点,他们的权值相乘结果是一样的。这便意味着我们可以很方便的用深搜来解决这个问题了。
解决代码
class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
unordered_map<string, unordered_map<string, double> > graph;
vector<double> res;
if (equations.empty()) return res;
int tmp_s = equations.size();
for (auto i = 0; i < tmp_s; ++i) {
graph[equations[i].first].insert(make_pair(equations[i].second,values[i]));
graph[equations[i].second].insert(make_pair(equations[i].first,1/values[i]));
}
for (auto i : queries) {
visited.clear();
int tmp = res.size();
dfs(i.first, i.second, res, graph, 1);
if (tmp == res.size()) res.push_back(-1.0);
}
return res;
}
set<string> visited;
void dfs(string start, string end, vector<double> & res,unordered_map<string, unordered_map<string, double> > & graph, double product) {
visited.insert(start);
if (start == end && graph.count(start)) {
res.push_back(product);
return;
}
for (auto i : graph[start]) {
if (visited.find(i.first) == visited.end())
dfs(i.first, end, res, graph, product * i.second);
}
}
};