Created
October 24, 2018 05:52
-
-
Save linfongi/22d2d0fea1e27ce461d3e6f1d9ee5278 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function calcEquation(equations, values, queries) { | |
| const parent = {}; | |
| const children = {}; | |
| const weight = {}; | |
| for (let i = 0; i < values.length; i++) { | |
| union(equations[i][0], equations[i][1], values[i]); | |
| } | |
| const res = []; | |
| for (let [c1, c2] of queries) { | |
| if (parent[c1] === undefined || parent[c2] === undefined || parent[c1] !== parent[c2]) { | |
| res.push(-1); | |
| } else { | |
| res.push(weight[c1] / weight[c2]); | |
| } | |
| } | |
| return res; | |
| function union(v1, v2, w) { | |
| let r1 = find(v1); | |
| let r2 = find(v2); | |
| if (r1 === r2) return; | |
| if (children[r1].length > children[r2].length) { | |
| [r1, r2, v1, v2, w] = [r2, r1, v2, v1, 1/w]; | |
| } | |
| w *= weight[v2] / weight[v1]; | |
| for (let c of children[r1]) { | |
| children[r2].push(c); | |
| parent[c] = r2; | |
| weight[c] *= w; | |
| } | |
| delete children[r1]; | |
| } | |
| function find(v) { | |
| if (parent[v] === undefined) { | |
| parent[v] = v; | |
| children[v] = [v]; | |
| weight[v] = 1; | |
| } | |
| while (v !== parent[v]) { | |
| parent[v] = parent[parent[v]]; | |
| v = parent[v]; | |
| } | |
| return v; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment