Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created May 13, 2018 06:30
Show Gist options
  • Save s4553711/346a3688d0c68f834958c900b6e86ac7 to your computer and use it in GitHub Desktop.
Save s4553711/346a3688d0c68f834958c900b6e86ac7 to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
unordered_map<string, unordered_map<string, double>> g;
for(int i = 0; i < equations.size(); i++) {
const string& A = equations[i].first;
const string& B = equations[i].second;
const double k = values[i];
g[A][B] = k;
g[B][A] = 1.0 / k;
}
vector<double> ans;
for(const auto& pair: queries) {
const string& X = pair.first;
const string& Y = pair.second;
if (!g.count(X) || !g.count(Y)) {
ans.push_back(-1.0);
continue;
}
unordered_set<string> visited;
ans.push_back(divide(X, Y, g, visited));
}
return ans;
}
double divide(const string& A, const string& B, unordered_map<string, unordered_map<string, double>>& g,
unordered_set<string>& visited) {
if (A == B) return 1.0;
visited.insert(A);
for(const auto& pair: g[A]) {
const string& C = pair.first;
if (visited.count(C)) continue;
double d = divide(C, B, g, visited);
if (d > 0) return d * g[A][C];
}
return -1.0;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment