KY268 第一题

KY268 第一题

法二:并查集:

# 法二,并查集的方式
import sys
def getRoot(RootDict, child):
    if RootDict[child] == child:
        return child
    else:
        result = getRoot(RootDict, RootDict[child])
        RootDict[child] = result
        return result

def main():
    HeightDict, RootDict = dict(), dict()
    for line in sys.stdin:
        a, b = map(int, line.strip().split())
        if a not in HeightDict:
            HeightDict[a] = 1
        if a not in RootDict:
            RootDict[a] = a    
        if b not in HeightDict:
            HeightDict[b] = 1
        if b not in RootDict:
            RootDict[b] = b
        if a == b:
            continue
        # a != b 
        rootA, rootB = getRoot(RootDict,a), getRoot(RootDict,b)
        if rootA == rootB:
            continue
        # rootA != rootB
        heightA, heightB = HeightDict[rootA], HeightDict[rootB]
        if heightA == heightB:
            RootDict[rootB] = rootA
            HeightDict[rootA] += 1
        if heightA > heightB:
            RootDict[rootB] = rootA
        if heightA < heightB:
            RootDict[rootA] = rootB
    cntCC = 0  # count connected components
    for child, root in RootDict.items():
        if child == root:
            cntCC += 1
    print(cntCC)

if __name__ == "__main__":
    main()

法一:通过遍历所有节点至少需要从几个根节点出发,即为几个连通分支数

# 法一,通过遍历所有节点至少需要从几个根节点出发,即为几个连通分支数
import sys
def main():
    VertexSet, AdjVerDict = set(), dict()
    for line in sys.stdin:
        src, dst = map(int, line.strip().split())
        VertexSet.update({src, dst})
        if src != dst:
            if src in AdjVerDict:
                AdjVerDict[src].add(dst)
            else:
                AdjVerDict[src] = {dst}
            if dst in AdjVerDict:
                AdjVerDict[dst].add(src)
            else:
                AdjVerDict[dst] = {src}
    ###########################################
    VertexNum = len(VertexSet)
    if VertexNum == 0:
        print(0)
        return
    elif VertexNum == 1:
        print(1)
        return

    Visited, awaitVisited = set(), VertexSet.copy()
    cntCC = 0  # Count Connected Componet
    while len(awaitVisited) > 0:
        queue = list()
        temp = awaitVisited.pop()
        awaitVisited.add(temp)
        queue.append(temp)
        cntCC += 1
        while len(queue) > 0:
            v = queue.pop()
            if v in Visited:
                continue
            Visited.add(v)
            awaitVisited.remove(v)
            adjcentSet = AdjVerDict.get(v,set()) - Visited
            queue.extend(list(adjcentSet))
    print(cntCC)

if __name__ == "__main__":
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值