题解 | #连通图#

连通图

https://www.nowcoder.com/practice/569e89823a5141fe8a11ab7d4da21edf

class UnionFind:#能不能改下样例自测
    def __init__(self, n):
        self.pt = [i for i in range(n)]
        self.h = [0 for i in range(n)]

    def find(self, x):
        if self.pt[x] != x:
            self.pt[x] = self.find(self.pt[x])
        return self.pt[x]

    def union(self, x, y):
        px, py = self.pt[x], self.pt[y]
        if px == py:  # 如果父节点一样
            return
        if self.h[px] > self.h[py]:
            self.pt[py] = self.find(self.pt[x])
        elif self.h[px] < self.h[py]:
            self.pt[px] = self.find(self.pt[y])
        else:
            self.pt[px] = self.find(self.pt[y])
            self.h[y] += 1


while True:
    try:
        n, m = map(int, input().split(" "))
        if m == 0:
            break
        v = UnionFind(n)
        s = "YES"
        ct = 0
        for i in range(m):
            a, b = map(int, input().split(" "))
            v.union(a - 1, b - 1)
        for i in range(n):
            if v.pt[i] == i:
                ct += 1
        if ct > 1:
            s = "NO"
        print(s)
    except:
        break

全部评论

相关推荐

03-03 10:35
3d人士会梦见住进比弗利山庄吗:这四个项目属于是初学者的玩具了。不知道面试官咋问,而且双非本搞算法除了9,还是保守至少c9
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务