-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path399-evaluate-division.cpp
67 lines (61 loc) · 2.15 KB
/
399-evaluate-division.cpp
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution {
public:
unordered_map<string, vector<pair<string, double>>> m;
unordered_map<string, bool> v;
double dfs(string start, string end) {
double result = -1.0;
for (auto it = v.begin(); it != v.end(); it++) it->second = false;
stack<pair<string, double>> s;
s.push(make_pair(start, 1.0));
while (!s.empty()) {
pair<string, double> curr = s.top();
s.pop();
v[curr.first] = true;
for (auto& p : m[curr.first]) {
if (p.first == end) {
return curr.second * p.second;
}
if (!v[p.first]) {
s.push(make_pair(p.first, curr.second * p.second));
}
}
}
return result;
}
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
// Building graph
for (vector<string>& e : equations) {
if (m.find(e[0]) == m.end()) {
m[e[0]] = {make_pair(e[0], 1.0)};
v[e[0]] = false;
}
if (m.find(e[1]) == m.end()) {
m[e[1]] = {make_pair(e[1], 1.0)};
v[e[1]] = false;
}
}
for (int i = 0; i < equations.size(); i++) {
vector<string>& e = equations[i];
m[e[0]].push_back(make_pair(e[1], values[i]));
m[e[1]].push_back(make_pair(e[0], 1.0 / values[i]));
}
for (auto it = m.begin(); it != m.end(); it++) {
cout << it->first << ": ";
for (auto p : it->second) {
cout << p.first << ", " << p.second << "; ";
}
cout << endl;
}
vector<double> result;
// Iterate over queries
for (vector<string>& q : queries) {
if (m.find(q[0]) != m.end() && m.find(q[1]) != m.end()) {
double factor = dfs(q[0], q[1]);
result.push_back(factor);
} else {
result.push_back(-1.0);
}
}
return result;
}
};