题目:
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可以看成从a到b的一条edge。因为a/b != b/a, 则a/b的值就是从a到b这条edge的权,b/a的值就是从b到a这条edge的权。
但只要知道a/b和b/a中的任意一个值,就能知道另一个的值,这样就形成了一个有向图。判断b/c是否有解,只要判断该图中是否能从b到达c,且b/c的值等于b,c间的最短路径的各
条edge的权值累乘的值。
具体的code如下:
class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
map<string, double> EdgeWeight;
set<string> Vertex;
//形成graph,并在图的每条edge赋上权值。
for(int i = 0; i < equations.size(); i++) {
string a = equations[i].first;
string b = equations[i].second;
double val = values[i];
EdgeWeight[a+"->"+a] = 1.0;
EdgeWeight[b+"->"+b] = 1.0;
EdgeWeight[a+"->"+b] = val;
EdgeWeight[b+"->"+a] = 1/val;
Vertex.insert(a);
Vertex.insert(b);
}
//方便于变量间的赋值,将变量的定义为auto类型。
//计算图中所有edge的权值之间所能形成的所有情况的值。
string i,j,k;
for(auto a = Vertex.begin(); a != Vertex.end(); ++a) {
for(auto b = Vertex.begin(); b != Vertex.end(); ++b) {
for(auto c = Vertex.begin(); c !=Vertex.end(); c++) {
i = *a;
j = *b;
k = *c;
if(EdgeWeight.find(i+"->"+k) == EdgeWeight.end() || EdgeWeight.find(k+"->"+j) == EdgeWeight.end())
continue;
EdgeWeight[i+"->"+j] = EdgeWeight[i+"->"+k] * EdgeWeight[k+"->"+j];
}
}
}
//查找是否有queries所对应的路径,并返回改路径所有edge的权累乘的值。
vector<double> results;
for(auto q: queries) {
string keyword = q.first+"->"+q.second;
if(EdgeWeight.find(keyword) != EdgeWeight.end())
results.push_back(EdgeWeight[keyword]);
else
results.push_back(-1);
}
return results;
}
};
end!