-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
43 lines (41 loc) · 1.2 KB
/
Solution.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
class Solution {
public:
unordered_map<string, string> p;
unordered_map<string, double> w;
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
int n = equations.size();
for (auto e : equations)
{
p[e[0]] = e[0];
p[e[1]] = e[1];
w[e[0]] = 1.0;
w[e[1]] = 1.0;
}
for (int i = 0; i < n; ++i)
{
vector<string> e = equations[i];
string a = e[0], b = e[1];
string pa = find(a), pb = find(b);
if (pa == pb) continue;
p[pa] = pb;
w[pa] = w[b] * values[i] / w[a];
}
int m = queries.size();
vector<double> res(m);
for (int i = 0; i < m; ++i)
{
string c = queries[i][0], d = queries[i][1];
res[i] = p.find(c) == p.end() || p.find(d) == p.end() || find(c) != find(d) ? -1.0 : w[c] / w[d];
}
return res;
}
string find(string x) {
if (p[x] != x)
{
string origin = p[x];
p[x] = find(p[x]);
w[x] *= w[origin];
}
return p[x];
}
};