LN : leetcode 399 Evaluate Division
lc 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.
DFS Accepted##
这个星期老师讲了图的分解以及DFS算法,所以我就在leetcode上找了一道相关的题目。问题的关键在于创建一个有向图,对于每一个字符串结点来说,应用map<string, map<string,double>> node
这样的数据结构来存储每个有向边是很适应该问题的。根据equations和values中的值来创建有向边,正向为values[i],反向为1/values[i]。
创建完有向图后,利用DFS对每个query从起点出发进行搜索,每次都乘以该条路径上的值,若两点间不能连通或点不在node范围之内,则返回0,最终输出-1.0。
class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
vector<double> ans;
map<string, map<string,double>> node;
for (int i = 0; i < values.size(); i++) {
node[equations[i].first].insert(make_pair(equations[i].second, values[i]));
node[equations[i].second].insert(make_pair(equations[i].first, 1/values[i]));
}
for (auto i : queries) {
set<string> s;
double num = myfind(i.first, i.second, node, s);
if (num) ans.push_back(num);
else ans.push_back(-1.0);
}
return ans;
}
double myfind(string first, string second, map<string, map<string,double>> &node, set<string> &s) {
if (node[first].find(second) != node[first].end()) return node[first][second];
for (auto i : node[first]) {
if (s.find(i.first) == s.end()) {
s.insert(i.first);
double num = myfind(i.first, second, node, s);
if (num) return i.second*num;
}
}
return 0;
}
};