-
Notifications
You must be signed in to change notification settings - Fork 28
/
Evaluate_Division.cpp
50 lines (48 loc) · 1.72 KB
/
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
class Solution {
#define X first
#define Y second
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
int n = (int)equations.size();
vector<double> result;
if(n == 0) return result;
unordered_map<string, vector<pair<string, double>>> adj;
for(int i = 0; i < n; i++) {
string u = equations[i].X;
string v = equations[i].Y;
double cost = values[i];
adj[u].push_back({v, cost});
adj[v].push_back({u, 1.0 / cost});
}
for(int i = 0; i < queries.size(); i++) {
string src = queries[i].X;
string dest = queries[i].Y;
double value = -1.0;
if(adj.count(src) > 0 and adj.count(dest) > 0) {
queue<pair<string, double>> Q;
unordered_set<string> visited;
Q.push({src, 1.0});
visited.insert(src);
while(!Q.empty()) {
string u = Q.front().X;
double d = Q.front().Y;
Q.pop();
if(dest == u) {
value = d;
break;
}
for(int i = 0; i < adj[u].size(); i++) {
string v = adj[u][i].X;
double factor = adj[u][i].Y;
if(!visited.count(v)) {
Q.push({v, d * factor});
visited.insert(v);
}
}
}
}
result.push_back(value);
}
return result;
}
};