题解 | #连通图#

连通图

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

全部评论

相关推荐

我:“加班需要有加班工资。”&nbsp;hr:“为什么?”&nbsp;哈哈哈哈哈哈哈离大谱
juntenor:你确实太理想化了,对社会不了解呀。这个和HR没有关系,这是国内特色,不然怎么还会有外包就这种逆天的存在呢。
点赞 评论 收藏
分享
qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务