-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0399-evaluate-division.cpp
More file actions
38 lines (37 loc) · 1.33 KB
/
0399-evaluate-division.cpp
File metadata and controls
38 lines (37 loc) · 1.33 KB
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
36
37
38
class Solution {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
unordered_map<string, vector<pair<string, double>>> g;
for (int i = 0; i < equations.size(); i++) {
g[equations[i][0]].emplace_back(equations[i][1], values[i]);
g[equations[i][1]].emplace_back(equations[i][0], 1.0/values[i]);
}
set<string> seen;
function<double(string&, string&)> dfs = [&](string& current, string& target) {
if (current == target) {
return 1.0;
}
for (auto [neib, val]: g[current]) {
if (seen.find(neib) != seen.end()) {
continue;
}
seen.insert(neib);
double res = val * dfs(neib, target);
if (res > 0) return res;
}
return -1.0;
};
vector<double> ans(queries.size());
for (int i = 0; i < queries.size(); i++) {
string a = queries[i][0], b = queries[i][1];
if (g.find(a) == g.end() || g.find(b) == g.end()) {
ans[i] = -1.0;
continue;
}
seen.clear();
seen.insert(a);
ans[i] = dfs(a, b);
}
return ans;
}
};