• 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]]))



  • 相关阅读:
    html Table实现表头固定
    Asp.net ORA-12154: TNS: 无法解析指定的连接标识符
    VS加载项目时报错 尚未配置为Web项目XXXX指定的本地IIS
    Sqlserver 导出insert插入语句
    RRAS
    MVC实例应用模式
    MVC概述
    23种设计模式
    XXX系统质量属性
    大型网站架构读后感
  • 原文地址:https://www.cnblogs.com/cong12586/p/14341609.html
Copyright © 2020-2023  润新知