题目
代码:1.dfs
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
graph = collections.defaultdict(dict)
for (a, b), v in zip(equations, values):
graph[a][b] = v
graph[b][a] = 1/v
def dfs(s, e):
if s not in graph or s not in graph:
return -1
if s == e:
return 1
visited.add(s)
for i in graph[s]:
if i == e:
return graph[s][i]
if i not in visited:
ans = dfs(i, e)
if ans != -1:
return graph[s][i]*ans
return -1
res = []
for a,b in queries:
visited = set()
res.append(dfs(a, b))
return res
代码:2.并查集
class UnionFind:
def __init__(self, equations, values):
self.parent = {}
self.weight = {}
self.rank = {}
for (i, e), v in zip(equations, values):
self.parent[i], self.parent[e] = i, e # 是本身的父节点
self.weight[i] = self.weight[e] = 1
self.rank[i] = self.rank[e] = 1
def find(self, x):
if x not in self.parent:
return False
if self.parent[x] == x:
return x
else:
origin = self.parent[x]
self.parent[x] = self.find(self.parent[x])
self.weight[x] = self.weight[x]*self.weight[origin] # 权值路径压缩
return self.parent[x]
def union(self, x, y, value):
px = self.find(x)
py = self.find(y)
if px != py:
if self.rank[px] <= self.rank[py]:
self.parent[px] = py
self.weight[px] = value*self.weight[y]/self.weight[x] # 连接两颗树的同时,更新权值
else:
self.parent[py] = px
self.weight[py] = self.weight[x]/value/self.weight[y] # 连接两颗树的同时,更新权值
if self.rank[px] == self.rank[py]:
self.rank[py] += 1
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
uf = UnionFind(equations, values)
for (i, e), v in zip(equations, values):
uf.union(i, e, v)
res = []
for x, y in queries:
if uf.find(x) and uf.find(y) and uf.find(x) == uf.find(y):
res.append(uf.weight[x]/uf.weight[y])
else:
res.append(-1)
return res
思路:地址