1579. 保证图可完全遍历

from typing import List
# 方法:使用并查集的想法,有个人那就是有两个组合,然后挨着判断
# 每个人的节点是否相连,是否相连后还有多余的连线。
# 定义一个并查集类,稍微改变了一下。
class UnionFind:
def __init__(self,size):
self.father = [None] * (size + 1)
self.num = size
# 查找父亲节点。
def find(self,x):
if self.father[x] is None:return x
self.father[x] = self.find(self.father[x])
return self.father[x]
# 判断是否是同一个父节点。
def is_connected(self,x,y):
return self.find(x) == self.find(y)
# 合并两个节点。
def merge(self,x,y):
self.father[self.find(x)] = self.find(y)
self.num -= 1
class Solution:
def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
# 定义两个并查集对象。
res = 0
uf_alice = UnionFind(n)
uf_bob = UnionFind(n)
# 遍历列表。
for _type,i,j in edges:
# 判断线的种类,这个边的种类,为3的话代表两个人都可以遍历。
# 注意这里一定要先判断类型为3的边。
if _type == 3:
# 将两个不想连的节点连接。
if not uf_alice.is_connected(i,j):
uf_alice.merge(i,j)
uf_bob.merge(i,j)
else:
res += 1
# 然后依次判断剩下两种类型的边。
for _type,i,j in edges:
if _type == 1:
if not uf_alice.is_connected(i,j):
uf_alice.merge(i,j)
else:
res += 1
if _type == 2:
if not uf_bob.is_connected(i,j):
uf_bob.merge(i,j)
else:
res += 1
if uf_alice.num * uf_bob.num > 1:
return -1
else:
return res
A = Solution()
print(A.maxNumEdgesToRemove(4,[[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]))



原文地址:https://www.cnblogs.com/cong12586/p/14341609.html