Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct Node {
- string variable;
- double value;
- };
- class UnionFind {
- map<string, int> rank;
- map<string, Node> parent;
- public:
- UnionFind(vector<vector<string>>& equations) {
- for(auto i : equations) {
- parent[i[0]] = {i[0], 1};
- parent[i[1]] = {i[1], 1};
- }
- }
- Node findParent(string x) {
- if(parent[x].variable.empty()) {
- return parent[x];
- }
- if(x != parent[x].variable) {
- Node p = findParent(parent[x].variable);
- parent[x].variable = p.variable;
- parent[x].value *= p.value;
- }
- return parent[x];
- }
- void unionSet(string u, string v, double value) {
- Node ulp_u = findParent(u);
- Node ulp_v = findParent(v);
- if(ulp_u.variable == ulp_v.variable) return;
- if(rank[ulp_u.variable] < rank[ulp_v.variable]) {
- parent[ulp_u.variable].variable = ulp_v.variable;
- parent[ulp_u.variable].value = ulp_v.value / ulp_u.value * value;
- } else if(rank[ulp_u.variable] > rank[ulp_v.variable]) {
- parent[ulp_v.variable].variable = ulp_u.variable;
- parent[ulp_v.variable].value = ulp_u.value / ulp_v.value / value;
- } else {
- parent[ulp_v.variable].variable = ulp_u.variable;
- parent[ulp_v.variable].value = ulp_u.value / ulp_v.value / value;
- rank[ulp_u.variable]++;
- }
- }
- };
- class Solution {
- public:
- vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
- int n = equations.size();
- UnionFind uf(equations);
- // union
- for(int i = 0; i < n; i++) {
- uf.unionSet(equations[i][0], equations[i][1], values[i]);
- }
- // evaluate
- vector<double> ans;
- int m = queries.size();
- for(int i = 0; i < m; i++) {
- string x = queries[i][0];
- string y = queries[i][1];
- auto par_x = uf.findParent(x);
- auto par_y = uf.findParent(y);
- if(par_x.variable.empty() || par_y.variable.empty() ||
- par_x.variable != par_y.variable) {
- ans.push_back(-1);
- } else {
- ans.push_back(par_x.value / par_y.value);
- }
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement