class Solution:
def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]:
res = []
passIndex = set() #标记不能成立的请求
for i in range(len(requests)):
uf = UnionFind(n) #每轮创建一个并查集
for j in range(i+1):
if j in passIndex: #若该请求被标记不能成立,则跳过
continue
a, b = requests[j][0], requests[j][1]
uf.union(a,b)
flag = True
for c, d in restrictions: #测试所有限制条件
if uf.isConnected(c, d):
flag = False
passIndex.add(i)
break
res.append(flag)
return res
优化
每个集合内都是直接朋友或者间接朋友。
对于:x = requests[i][0], y = requests[i] 如果x所处的集合与y所处的集合相等,这样就意味着x和y已经是朋友了 如果x所处的集合与y所处的集合不等,需要判断x所处的集合与y所处的集合能否合并,可以遍历restrictions,具体如下:
# 并查集模板略
class Solution:
def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]:
res = []
uf = UnionFind(n)
for x, y in requests:
flag = True
if not uf.isConnected(x, y):
for p, q in restrictions:
if uf.isConnected(p, x) and uf.isConnected(q, y) or uf.isConnected(q, x) and uf.isConnected(p, y):
flag = False
break
if flag:
uf.union(x, y)
res.append(flag)
return res