题目
给出方程式 A / B = k A / B = k A/B=k, 其中 A A A 和 B B B 均为用字符串表示的变量, k k k 是一个浮点型数字。根据已知方程式求解问题,并返回计算结果。如果结果不存在,则返回 − 1.0 -1.0 −1.0。
示例 :
给定 a / b = 2.0 , b / c = 3.0 a / b = 2.0, b / c = 3.0 a/b=2.0,b/c=3.0
问题: a / c = ? , b / a = ? , a / e = ? , a / a = ? , x / x = ? a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? a/c=?,b/a=?,a/e=?,a/a=?,x/x=?
返回 [ 6.0 , 0.5 , − 1.0 , 1.0 , − 1.0 ] [6.0, 0.5, -1.0, 1.0, -1.0 ] [6.0,0.5,−1.0,1.0,−1.0]
输入为: vector<pair<string, string>> equations, vector& values, vector<pair<string, string>> queries(方程式,方程式结果,问题方程式), 其中 equations.size() == values.size(),即方程式的长度与方程式结果长度相等(程式与结果一一对应),并且结果值均为正数。以上为方程式的描述。 返回vector<double>类型。
基于上述例子,输入如下:
e q u a t i o n s ( 方 程 式 ) = [ [ " a " , " b " ] , [ " b " , " c " ] ] , equations(方程式) = [ ["a", "b"], ["b", "c"] ], equations(方程式)=[["a","b"],["b","c"]],
v a l u e s ( 方 程 式 结 果 ) = [ 2.0 , 3.0 ] , values(方程式结果) = [2.0, 3.0], values(方程式结果)=[2.0,3.0],
q u e r i e s ( 问 题 方 程 式 ) = [ [ " a " , " c " ] , [ " b " , " a " ] , [ " a " , " e " ] , [ " a " , " a " ] , [ " x " , " x " ] ] . queries(问题方程式) = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. queries(问题方程式)=[["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]].
输入总是有效的。你可以假设除法运算中不会出现除数为0的情况,且不存在任何矛盾的结果。
解题思路
- 并查集的思路:需要将路径距离进行保存, a / b , b a/b,b a/b,b作为根节点, a a a作为子结点, a a a的权值为 a / b , b a/b,b a/b,b的权值为 1.0 1.0 1.0。
- 对每个输入的字符串映射一个节点序号,从 n u m = 1 num = 1 num=1开始,初始化建立的 f a t h e r 和 w e i g h t father和weight father和weight数组。
- 在全部插入结点之后,对所有结点都进行路径压缩,这样在求解结果,直接用 w e i g h t weight weight的值相除。
代码
class Solution {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
//初始化结点
for(int i = 0; i < 1010; ++i){
father[i] = i;
weight[i] = 1.0;
}
int num = 1; //给结点排列序号
unordered_map<string, int> strToId;
int u, v;
for(int i = 0; i < equations.size(); ++i){
if(!strToId.count(equations[i][0])){
strToId[equations[i][0]] = num++;
}
if(!strToId.count(equations[i][1])){
strToId[equations[i][1]] = num++;
}
u = strToId[equations[i][0]];
v = strToId[equations[i][1]];
//然后对两结点进行合并
Union(u, v, values[i]);
}
//在全部插入结点之后,对所有结点都进行路径压缩,这样在求解结果,直接用weight的值相除
for(int i = 1; i < num; ++i){
Find(i);
}
//计算式子的结果
vector<double> ans;
for(int i = 0; i < queries.size(); ++i){
if(!strToId.count(queries[i][0]) || !strToId.count(queries[i][1])){
ans.push_back(-1.0);
continue;
}
u = strToId[queries[i][0]];
v = strToId[queries[i][1]];
if(father[u] != father[v]){
ans.push_back(-1.0);
continue;
}
ans.push_back(weight[u] / weight[v]);
}
return ans;
}
private:
int father[1010];
double weight[1010];
int Find(int x){
double ans = 1.0;
int origin = x;
while(x != father[x]){
ans *= weight[x];
x = father[x];
}
father[origin] = x;
weight[origin] = ans;
return x;
}
void Union(int x, int y, double val){
int a = Find(x);
int b = Find(y);
father[a] = b;
weight[a] = val * weight[y] / weight[x];
return;
}
};