题目描述
https://leetcode-cn.com/problems/evaluate-division/
思路题解
这道题差点没把我送走
https://leetcode-cn.com/problems/evaluate-division/solution/399-chu-fa-qiu-zhi-nan-du-zhong-deng-286-w45d/
还要考虑一种情况
合并的时候按照四边形法则
代码如下:
class Solution:
class UnionFind:
def __init__(self):
self.parent={}
self.weight={}
def find(self,index):
if index not in self.parent:
self.parent[index]=index
self.weight[index]=1.0
return index
# 自己就是根节点
if self.parent[index]==index:
return index
# 查找根节点+路径压缩
origin_p=self.parent[index]
self.parent[index]=self.find(self.parent[index])
self.weight[index]*=self.weight[origin_p]
return self.parent[index]
def union(self,index1,index2,w):
p1,p2=self.parent[index1],self.parent[index2]
self.parent[p1]=p2
self.weight[p1]=w*self.weight[index2]/self.weight[index1]
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
uf=Solution.UnionFind()
ans=[]
for i in range(len(equations)):
if uf.find(equations[i][0])!=uf.find(equations[i][1]):
uf.union(equations[i][0],equations[i][1],values[i])
for i in range(len(queries)):
if queries[i][0] not in uf.weight or queries[i][1] not in uf.weight or uf.find(queries[i][0])!=uf.find(queries[i][1]):
ans.append(-1.0)
else:
ans.append(uf.weight[queries[i][0]]/uf.weight[queries[i][1]])
return ans
对红框部分的路径压缩进行优化,减少递归次数
class Solution:
class UnionFind:
def __init__(self):
self.parent={}
self.weight={}
def find(self,index):
if index not in self.parent:
self.parent[index]=index
self.weight[index]=1.0
return index
root=index #root代表根
base=1.0 #base代表路径上(index,root]所有权重的乘积
while self.parent[root]!=root:
root=self.parent[root]
base*=self.weight[root]#index节点不乘进去
# 查找根节点+路径压缩
while index!=root:
self.weight[index]*=base
origin_p=self.parent[index]
base/=self.weight[origin_p]
self.parent[index]=root
index=origin_p
return self.parent[index]
def union(self,index1,index2,w):
p1,p2=self.parent[index1],self.parent[index2]
self.parent[p1]=p2
self.weight[p1]=w*self.weight[index2]/self.weight[index1]
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
uf=Solution.UnionFind()
ans=[]
for i in range(len(equations)):
if uf.find(equations[i][0])!=uf.find(equations[i][1]):
uf.union(equations[i][0],equations[i][1],values[i])
for i in range(len(queries)):
if queries[i][0] not in uf.weight or queries[i][1] not in uf.weight or uf.find(queries[i][0])!=uf.find(queries[i][1]):
ans.append(-1.0)
else:
ans.append(uf.weight[queries[i][0]]/uf.weight[queries[i][1]])
return ans
并查集总结:
https://blog.csdn.net/anan15151529/article/details/118416802