-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20 May | 399. Evaluate Division.cpp
57 lines (48 loc) · 1.61 KB
/
20 May | 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
class Solution {
public:
unordered_map<string, vector<pair<string, double>>> adjList;
vector<double> ans;
bool dfs(string dividend, string divisor, unordered_set<string> vis, double currProd){
if(vis.find(dividend) != vis.end()){
return false;
}
vis.insert(dividend);
if(dividend == divisor){
ans.push_back(currProd);
return true;
}
bool found = false;
for(auto ne: adjList[dividend]){
found = dfs(ne.first, divisor,vis, currProd * ne.second);
if(found){
return true;
}
}
return false;
}
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
int n = equations.size(), m = queries.size();
adjList.clear();
ans.clear();
for(int i = 0; i < n; i++){
string dividend = equations[i][0];
string divisor = equations[i][1];
adjList[dividend].push_back({divisor, values[i]});
adjList[divisor].push_back({dividend, 1.0 / values[i]});
}
for(auto &q : queries){
string dividend = q[0];
string divisor = q[1];
if(adjList.find(dividend) == adjList.end() || adjList.find(divisor) == adjList.end()){
ans.push_back(-1.0);
}
else{
unordered_set<string> vis;
if(!dfs(dividend, divisor, vis, 1.0)){
ans.push_back(-1);
}
}
}
return ans;
}
};