# LeetCode

## 除法求值

给定 a / b = 2.0, b / c = 3.0



equations(方程式) = [ ["a", "b"], ["b", "c"] ],
values(方程式结果) = [2.0, 3.0],
queries(问题方程式) = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].


## 解法：并查集

a/b=2 , b/c=3

c  1
^
|
b  3
^
|
a  2
val代表的是当前节点是直接父节点的多少倍，也就是 A/fatherA ，重点就是合并两个集合的时候需要注意：


a / fa = val[a]
b / fb = val[b]

val[fa] = fa/fb = a/b * b/fb * fa/a = value * (val[b] / val[a])


class Solution{
private HashMap<String,String> parent=new HashMap<>();

private HashMap<String,Double> quotient=new HashMap<>();

//不带路径压缩
public String find(String p){ //找根结点
while (parent.get(p)!=p) {
p=parent.get(p);
}
return p;
}

public void init(String s){ //初始化
if (!parent.containsKey(s)) {
parent.put(s,s);
quotient.put(s,1.0);
}
}

public void merge(String a,String b,Double value){
init(a);init(b);
String fa=find(a); // a/fa=val[a], b/fb=val[b]
String fb=find(b);
if (fa.equals(fb)) {
return;
}
parent.put(fa,fb);
quotient.put(fa,value*(cal(b)/cal(a))); //cal(a)和cal(b)代表a和b到根节点的总值
}

public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
for (int i=0;i<equations.size();i++) {
List<String> equation=equations.get(i);
merge(equation.get(0),equation.get(1),values[i]);
}
double[] res=new double[queries.size()];
int index=0;
for (List<String> query:queries) {
String a=find(query.get(0));
String b=find(query.get(1));
System.out.println(a+" "+b);
if (!parent.containsKey(query.get(0)) || !parent.containsKey(query.get(1)) || !a.equals(b)) {
res[index++]=-1;
}else{
//没有路劲压缩,需要遍历整个路劲求积
res[index++]=cal(query.get(0))/cal(query.get(1));
}
}
return res;
}

//计算当前节点到根节点的路径乘积
public double cal(String index){
double res=quotient.get(index);
while(parent.get(index)!=index){
index=parent.get(index);
res*=quotient.get(index);
}
return res;
}
}


09-22
05-06 8041

02-12 30
10-22 1198
11-29 3984
03-16 3871
04-01 2572
12-25 5万+
02-13 1922