问题描述
给你一个变量对数组 equations 和一个实数值数组 values 作为已知条件,其中 equations[i] = [Ai, Bi] 和 values[i] 共同表示等式 Ai / Bi = values[i] 。每个 Ai 或 Bi 是一个表示单个变量的字符串。另有一些以数组 queries 表示的问题,其中 queries[j] = [Cj, Dj] 表示第 j 个问题,请你根据已知条件找出 Cj / Dj = ? 的结果作为答案。返回 所有问题的答案 。如果存在某个无法确定的答案,则用 -1.0 替代这个答案。
注意:输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。
思路1:图论问题 Floyd算法
这道题可以转化为一个 带权图问题。
a/b = 2, b/c=3 => a/c=6
可以抽象为 a到b的边权重为2,b到c的边权重为3, a到c的边权重为2*3=6,图中任意2点的距离用2点之间边的权重乘积表示.
如此,问题归为,如何求图中任意两点的距离,可以使用Floyd算法解决。
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
from collections import defaultdict
graph=defaultdict(int) #graph为一个字典
set1=set()
for i in range(len(equations)):
a,b=equations[i]
graph[(a,b)]=values[i] #获取顶点(a,b)间边的权值
graph[(b,a)]=1/values[i]
set1.add(a)
set1.add(b)
# Floyd算法,求图中任意两点距离
arr=list(set1) #集合转换为列表
for k in arr:
for i in arr:
for j in arr:
if graph[(i,k)] and graph[(k,j)]: #若值存在
graph[(i,j)] = graph[(i,k)]*graph[(k,j)]
res=[]
for x,y in queries:
if graph[(x,y)]:
res.append(graph[(x,y)])
else:
res.append(-1)
return res
作者:jun-heng
来源:力扣
思路2:图论问题 并查集
无权重的并查集
class UnionFind:
def __init__(self):
"""
记录每个节点的父节点
"""
self.father = {}
def find(self,x):
"""
查找根节点
路径压缩
"""
root = x
while self.father[root] != None:
root = self.father[root]
# 路径压缩
while x != root:
original_father = self.father[x]
self.father[x] = root
x = original_father
return root
def merge(self,x,y,val):
"""
合并两个节点
"""
root_x,root_y = self.find(x),self.find(y)
if root_x != root_y:
self.father[root_x] = root_y
def is_connected(self,x,y):
"""
判断两节点是否相连
"""
return self.find(x) == self.find(y)
def add(self,x):
"""
添加新节点
"""
if x not in self.father:
self.father[x] = None
带权值的并查集
被除数当作子节点,除数当作父节点
class UnionFind:
def __init__(self):
"""
记录每个节点的父节点
记录每个节点到根节点的权重
"""
self.father = {}
self.value = {}
def find(self,x):
"""
查找根节点
路径压缩
更新权重
"""
root = x
# 节点更新权重的时候要放大的倍数
base = 1
while self.father[root] != None:
root = self.father[root]
base *= self.value[root]
while x != root:
original_father = self.father[x]
##### 离根节点越远,放大的倍数越高
self.value[x] *= base
base /= self.value[original_father]
#####
self.father[x] = root
x = original_father
return root
def merge(self,x,y,val):
"""
合并两个节点
"""
root_x,root_y = self.find(x),self.find(y)
if root_x != root_y:
self.father[root_x] = root_y
##### 四边形法则更新根节点的权重
self.value[root_x] = self.value[y] * val / self.value[x]
def is_connected(self,x,y):
"""
两节点是否相连
"""
return x in self.value and y in self.value and self.find(x) == self.find(y)
def add(self,x):
"""
添加新节点,初始化权重为1.0
"""
if x not in self.father:
self.father[x] = None
self.value[x] = 1.0
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
uf = UnionFind()
for (a,b),val in zip(equations,values):
uf.add(a)
uf.add(b)
uf.merge(a,b,val)
res = [-1.0] * len(queries)
for i,(a,b) in enumerate(queries):
if uf.is_connected(a,b):
res[i] = uf.value[a] / uf.value[b]
return res
作者:MiloMusiala
来源:力扣
并查集的构造过程说明
来源:力扣