package com.heu.wsq.leetcode.bingchaji;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CalcEquation {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries){
int equationSize = equations.size();
UnionFind unionFind = new UnionFind(2 * equationSize);
Map<String, Integer> hashMap = new HashMap<>(2 * equationSize);
int id = 0;
for (int i = 0; i < equationSize; i++){
List<String> equation = equations.get(i);
String var1 = equation.get(0);
String var2 = equation.get(1);
if (!hashMap.containsKey(var1)){
hashMap.put(var1, id);
id++;
}
if (!hashMap.containsKey(var2)){
hashMap.put(var2, id);
id++;
}
unionFind.union(hashMap.get(var1), hashMap.get(var2), values[i]);
}
int queriesSize = queries.size();
double[] ans = new double[queriesSize];
for (int i = 0; i < queriesSize; i++){
List<String> query = queries.get(i);
String var1 = query.get(0);
String var2 = query.get(1);
Integer id1 = hashMap.get(var1);
Integer id2 = hashMap.get(var2);
if (id1 == null || id2 == null){
ans[i] = -1.0d;
}else{
ans[i] = unionFind.isConnected(id1, id2);
}
}
return ans;
}
private class UnionFind{
private int[] parent;
private double[] weight;
public UnionFind(int n){
this.parent = new int[n];
this.weight = new double[n];
for (int i = 0; i < n; i++){
this.parent[i] = i;
this.weight[i] = 1.0d;
}
}
public void union(Integer x, Integer y, double value) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY){
return;
}
parent[rootX] = rootY;
weight[rootX] = weight[y] * value / weight[x];
}
private int find(int x){
if (x != parent[x]){
int origin = parent[x];
parent[x] = find(origin);
weight[x] *= weight[origin];
}
return parent[x];
}
public double isConnected(Integer x, Integer y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY){
return weight[x] / weight[y];
}else{
return -1.0d;
}
}
}
}