题目要求
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.
解题思路
unordered_map<string, unordered_map<string, double>>::iterator
复杂度分析
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
typedef unordered_map<string, unordered_map<string, double>> Map;
Map m;
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
unsigned long n = equations.size();
for (int i = 0; i < n; ++i) {
m[equations[i].first][equations[i].second] = values[i];
m[equations[i].second][equations[i].first] = 1.0 / values[i];
}
for (auto& kv: m)
kv.second[kv.first] = 1.0;
for (auto k = m.begin(); k != m.end(); ++k)
for (auto i = m.begin(); i != m.end(); ++i)
for (auto j = m.begin(); j != m.end(); ++j)
i->second[j->first] = max(i->second[j->first], i->second[k->first] * k->second[j->first]);
vector<double> res;
for (const auto& q: queries) {
auto val = m[q.first][q.second];
res.push_back(val ? val: -1.0);
}
return res;
}
};
int main(){
vector<pair<string, string>>e;
e.push_back(make_pair("a", "b"));
e.push_back(make_pair("b", "c"));
vector<double>v;
//(2.0,3.0);
v.push_back(2.0);
v.push_back(3.0);
vector<pair<string, string>>q;
q.push_back(make_pair("a", "c"));
q.push_back(make_pair("b", "a"));
q.push_back(make_pair("a", "e"));
q.push_back(make_pair("a", "a"));
Solution me;
vector<double>r;
r=me.calcEquation(e, v, q);
for (int i =0 ; i<r.size(); i++) {
cout << r[i] << " ";
}
cout << endl;