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
| import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;
class Solution { public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { int nvars = 0; Map<String, Integer> variables = new HashMap<>();
int n = equations.size(); for (List<String> equation : equations) { if (!variables.containsKey(equation.get(0))) { variables.put(equation.get(0), nvars++); } if (!variables.containsKey(equation.get(1))) { variables.put(equation.get(1), nvars++); } }
int[] f = new int[nvars]; double[] w = new double[nvars]; Arrays.fill(w, 1.0); for (int i = 0; i < nvars; i++) { f[i] = i; } for (int i = 0; i < n; i++) { int va = variables.get(equations.get(i).get(0)), vb = variables.get(equations.get(i).get(1)); merge(f, w, va, vb, values[i]); } int queriesCount = queries.size(); double[] ret = new double[queriesCount]; for (int i = 0; i < queriesCount; i++) { List<String> query = queries.get(i); double result = -1.0; if (variables.containsKey(query.get(0)) && variables.containsKey(query.get(1))) { int ia = variables.get(query.get(0)), ib = variables.get(query.get(1)); int fa = find(f, w, ia), fb = find(f, w, ib); if (fa == fb) { result = w[ia] / w[ib]; } } ret[i] = result; } return ret; }
public void merge(int[] f, double[] w, int x, int y, double val) { int fx = find(f, w, x); int fy = find(f, w, y); f[fx] = fy; w[fx] = val * w[y] / w[x]; }
public int find(int[] f, double[] w, int x) { if (f[x] != x) { int father = find(f, w, f[x]); w[x] = w[x] * w[f[x]]; f[x] = father; } return f[x]; } }
|