【问题标题】:Longest path in a undirected and unweighted tree - in python无向和未加权树中的最长路径 - 在 python 中
【发布时间】: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 自己查看。

标签: python algorithm


【解决方案1】:

您的代码中有不必要的检查。对于每个 A - B 边缘,您只需将 B 放入 A 的邻接列表中,并将 A 放入 B的邻接表:

d = {}
for i in range(m):
    u,v = map(int, raw_input().split())
    if u in d:
        d[u].append(v)
    else:
        d[u] = [v]
    if v in d:
        d[v].append(u)
    else:
        d[v] = [u]   

根据问题,每个节点在 1N 之间都有一个索引,因此您可以使用此事实并使用空列表预填充 dict。这样您就不必检查密钥是否在dict 中。还要让代码短一点:

N = input()
d = { i:[] for i in range(1, N+1) }
for i in range(N):
    u,v = map(int, raw_input().split())
    d[u].append(v)
    d[v].append(u)

【讨论】:

    【解决方案2】:

    在第一个 elif 条件下,您在 makedic 中使用 0 而不是 o。还对无向图进行了修正。

    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] = [o]
                 d[o] = [p]
            elif o not in d and p in d:
                 d[o] = [p]
                 d[p].append(o)
            elif p not in d and o in d:
                d[p] = [o]
                d[o].append(p)
            elif o in d:
                d[o].append(p)
                d[p].append(o)
        return d
    

    【讨论】:

    • @johnsmith,使用这些更正运行您的程序。我想这次会的。
    • 我的程序运行良好。但这不是最好的方法
    • @johnsmith,来吧,伙计,你的意思是“0 而不是 o”是对的。您现在在问题陈述中已更正
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多