1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public: vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) { for (int i = 0; i < equations.size(); ++i) { g[equations[i][0]][equations[i][1]] = values[i]; g[equations[i][1]][equations[i][0]] = 1 / values[i]; } vector<double> ret; for (auto&& query : queries) { ret.emplace_back(helper(query[0], query[1])); } return ret; }
double helper(const string &begin, const string &end) { if (g.count(begin) == 0 || g.count(end) == 0) return -1.0; if (g.count(begin) && g[begin].count(end)) return g[begin][end]; unordered_set<string> s; queue<pair<string, double>> q{{{begin, 1.0}}}; while (!q.empty()) { auto [u, product] = q.front(); q.pop(); if (s.count(u)) continue; if (g[u].count(end)) return product * g[u][end]; s.emplace(u); g[begin][u] = product; g[u][begin] = 1 / product; for (auto [v, quotient] : g[u]) { q.emplace(v, product * quotient); } } return -1.0; }
unordered_map<string, unordered_map<string, double>> g; };
|