-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0399.cpp
More file actions
executable file
·70 lines (55 loc) · 1.32 KB
/
LC0399.cpp
File metadata and controls
executable file
·70 lines (55 loc) · 1.32 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
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
68
69
70
/*
Problem Statement: https://leetcode.com/problems/evaluate-division/
Time: O((n + q) • m)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class UnionFind {
private:
unordered_map<string, pair<string, double>> link;
public:
pair<string, double> find(string x) {
string y, z;
double a, b;
if (!link.count(x))
link[x] = {x, 1.0};
tie(y, a) = link[x];
if (x == y)
return {y, a};
tie(z, b) = find(y);
return link[x] = {z, a * b};
}
void unify(string a, string b, double v) {
string pa, pb;
double va, vb;
tie(pa, va) = find(a);
tie(pb, vb) = find(b);
if (pa != pb)
link[pa] = {pb, vb / va * v};
}
double query(string a, string b) {
string pa, pb;
double va, vb;
if (!link.count(a) || !link.count(b))
return -1.0;
tie(pa, va) = find(a);
tie(pb, vb) = find(b);
if (pa == pb)
return va / vb;
else
return -1.0;
}
};
class Solution {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
UnionFind dsu;
vector<double> res;
int m = equations.size(), q = queries.size();
for (int i = 0; i < m; i++)
dsu.unify(equations[i][0], equations[i][1], values[i]);
for (vector<string>& eq: queries)
res.push_back(dsu.query(eq[0], eq[1]));
return res;
}
};