图的遍历

from collections import defaultdict
d = defaultdict(list)
n = int(input())
for i in range(n-1):
    a,b = map(int,input().split())
    d[a].append(b)
    d[b].append(a)
#print(d)
visited = defaultdict(bool)
visited[1]=True
lenth = 0
stack = [1]
while stack:
    next_layer = []
    while stack: #explore current layer stack
        node = stack.pop()
        for nex in d[node]:#add all next layer nodes of current node to next_layer
            if not visited[nex]:
                next_layer.append(nex)
                visited[nex]=True
    stack = next_layer #set current layer as next_layer
    lenth +=1 #layer +1 
print(2*(n-1)-lenth+1) # lenth add 1 when next_layer is empty in last loop


全部评论

相关推荐

06-07 12:20
新余学院 Java
点赞 评论 收藏
分享
程序员牛肉:这一眼假啊,基本上都是骗人的,不然就涉及到职位贪腐了,就像之前华为的OD事件,看你运气好不好了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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