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.
思路就是 a/c = a/b * b/c 所以其实是一个搜索路径的问题。
a是start,c是end。看能不能从start搜到end。
所以用标准BFS来做。
class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equ, vector<double>& values, vector<pair<string, string>> que)
{
vector<double> ret; //返回的结果
map<string, set<pair<string, double>>> mp; //BFS使用
for (int i = 0; i < equ.size(); i++) //正反 和 本身 都存进去
{
mp[equ[i].first].insert(make_pair(equ[i].first, 1.0));
mp[equ[i].second].insert(make_pair(equ[i].second, 1.0));
mp[equ[i].first].insert(make_pair(equ[i].second, values[i]));
mp[equ[i].second].insert(make_pair(equ[i].first, 1 / values[i]));
}
for (int i = 0; i < que.size(); i++)
{
string start = que[i].first;
string end = que[i].second;
//排除 [x , x] 等从未出现过的情况
if (mp.find(start) == mp.end() || mp.find(end) == mp.end())
{
ret.push_back(-1.0);
continue;
}
int flag = 0;//用来判断是否有答案,没有的话是 -1
queue<pair<string, double>> route; //BFS
set<string> hash; //BFS搜索过的存下来 防止再次搜索
hash.insert(start);
route.push(make_pair(start, 1.0));
while (!route.empty())
{
string now_str = route.front().first;
double now_v = route.front().second;
route.pop();
//结束条件
if (now_str == end)
{
ret.push_back(now_v);
flag = 1;
break;
}
for (auto it : mp[now_str]) //BFS
{
if (hash.find(it.first) == hash.end() ) //本身就不再进入 BFS 搜索队列了
{
route.push(make_pair(it.first, it.second * now_v));
hash.insert(it.first);
}
}
}
if (flag == 0)
ret.push_back(-1.0);
}
return ret;
}
};
本文介绍了一个基于图的搜索算法来解决EvaluateDivision问题的方法。通过构建一个图,利用BFS算法来寻找两个变量之间的关系路径,并计算其乘积值。若路径不存在,则返回-1.0。适用于给定方程组求解未知比值问题。
508

被折叠的 条评论
为什么被折叠?



