【发布时间】:2016-09-30 02:17:55
【问题描述】:
我正在解决一个问题,我需要计算树的直径。我知道如何计算,首先使用 2 bfs 找到最远的节点,然后使用我们从第一个找到的节点进行第二个 bfs。
但是我很难实现一个非常简单的步骤 - 从输入中创建一个邻接列表(在 python 的情况下是字典)这很有效
输入
输入文件的第一行包含一个整数 N --- 个数 树中的节点(0
示例:
8
1 2
1 3
2 4
2 5
3 7
4 6
7 8
我的代码是:
def makedic(m):
d = {}
for i in range(m):
o, p = map(int, raw_input().split())
if o not in d and p not in d:
d[p] = []
d[o] = [p]
elif o not in d and p in d:
d[o] = []
d[p].append(o)
elif p not in d and o in d:
d[p] = []
d[o].append(p)
elif o in d:
d[o].append(p)
# d[p].append(o)
elif p in d:
d[p].append(o)
return d
这是我实现 bfs 的方式:
def bfs(g,s):
parent={s:None}
level={s:0}
frontier=[s]
ctr=1
while frontier:
next=[]
for i in frontier:
for j in g[i]:
if j not in parent:
parent[j]=i
level[j]=ctr
next.append(j)
frontier=next
ctr+=1
return level,parent
【问题讨论】:
-
请修正缩进。
-
@Jean-FrançoisFabre 对此感到抱歉。我这样做很匆忙
-
您的输入不一致:它有 8 个节点,而不是 7 个。
-
@trincot 进行了更正
-
和我的代码基本一样。但他只是使用
list而不是dict。首先,他列出了很多列表,然后为每个边 (1-2):A[0].append(1)和A[1].append(0)。因为他想用0-index。我看不出你不明白其中的哪一部分。复制这部分代码并在您的计算机中运行,然后print te自己查看。