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.
题解:有意思的题目。转化为图,再深度优先遍历!!!
class Solution {
public: //转化为图
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
int len=equations.size();
int len_q=queries.size();
vector<double> res(len_q);
for(int i=0;i<len;i++) {
pair<string,string> tmp=equations[i];
edge[tmp.first].push_back(tmp.second);
edge_w[tmp]=values[i];
if(values[i]!=0) {
pair<string,string> tmp2;
tmp2.first=tmp.second;tmp2.second=tmp.first;
edge[tmp2.first].push_back(tmp2.second);
edge_w[tmp2]=1.0/values[i];
}
}
for(int i=0;i<len_q;i++) {
pair<string,string> t=queries[i];
string a,b;
a=t.first,b=t.second;
res[i]=-1.0;
if(edge.find(a)!=edge.end()&&edge.find(b)!=edge.end()) {
bool f=false;
dfs(t.first,"",1.0,t.second,res[i],f);
}
}
return res;
}
void dfs(string cur,string f,double dis,string e,double& t,bool& flag) {
if(flag) return;
if(cur==e) {
t=dis;
flag=true;
return ;
}
for(int i=0;i<edge[cur].size();i++) {
string nex=edge[cur][i];
if(nex==f) continue;
double w=edge_w[pair<string,string>(cur,nex)];
dfs(nex,cur,dis*w,e,t,flag);
}
}
private:
map<pair<string,string>,double> edge_w;
map<string,vector<string>> edge;
};