功能需要很长时间

时间:2018-01-26 02:10:19

标签: python algorithm directed-acyclic-graphs longest-path weighted-graph

我正在尝试从节点1获取唯一路径的数量。加权有向无环图的最大长度为N,我已经计算出获得最大长度,但我仍然坚持获取路径数给定的最大长度...

数据输入如下:

91 120  # Number of nodes, number of edges

1 2 34

1 3 15

2 4 10

.... 作为节点1->节点2的权重为34,

I input my data using a diction so my dict looks like:
_distance = {}
_distance = {1: [(2, 34), (3, 15)], 2: [(4, 10)], 3: [(4, 17)], 4: [(5, 36), (6, 22)], 5: [(7, 8)],...ect

我已经研究了如何使用它来实现最长的路径:

首先我制作一个顶点列表

class Vertice:
    def __init__(self,name,weight=0,visted=False):
        self._n = name
        self._w = weight
        self._visited = visted
        self.pathTo

for i in range(numberOfNodes): # List of vertices (0-n-1)
  _V = Vertice(i) 
  _nodes.append(_V)

接下来,我遍历我的字典,将每个节点设置为最大权重

        for vert, neighbors in _distance.iteritems():
        _vert = _nodes[vert-1] # Current vertice array starts at 0, so n-1


        for x,y in neighbors:  # neighbores,y = weight of neighbors
            _v = _nodes[x-1]   # Node #1 will be will be array[0]

            if _v._visited == True:
                if _v._w > _vert._w+y:
                    _v._w = _v._w
                else:
                    _v._w = y + _vert._w

            else:

                _v._w = y + _vert._w
                _v._visited = True

完成此操作后,最后一个节点将具有最大权重,因此我可以调用

max = _nodes[-1]._w

获得最大重量。这似乎执行得很快,即使在较大的数据集上执行也没有找到最大长度路径的问题,然后我获取最大值并将其运行到此函数中:

#  Start from first node in dictionary, distances is our dict{}
#  Target is the last node in the list of nodes, or the total number of nodes.
numLongestPaths(currentLocation=1,target=_numNodes,distances=_distance,maxlength=max)

def numLongestPaths(currentLocation,maxlength, target, sum=0, distances={}):


    _count = 0

    if currentLocation == target:
        if sum == maxlength:
                _count += 1

    else:
        for vert, weight in distances[currentLocation]:
            newSum = sum + weight
            currentLocation = vert
            _count += numLongestPaths(currentLocation,maxlength,target,newSum,distances)

    return _count

如果我们当前的总和是最大值,我只需检查一下我们当前的总和是否为最大值,如果是,则在我们的计数中加一,如果没有通过。

这对于诸如8个节点和最长路径的输入是立即工作20,找到3个路径,并且对于诸如100个节点的输入,最长149并且仅有1个该长度的唯一路径,但是当我尝试做一个包含91个节点的数据集,如最长路径1338和唯一路径数为32,该功能需要非常长,它可以工作但速度很慢。

有人可以给我一些关于我的功能有什么问题的提示,以使它花费这么长时间从1..N找到路径长度为X的路径吗?我假设它有一个指数运行时间,但我不确定如何解决它

感谢您的帮助!

编辑:好的,我正在过度思考这个错误的方法,我重新构建了我的方法,我的代码现在如下:

# BEGIN SEARCH.
    for vert, neighbors in _distance.iteritems():
        _vert = _nodes[vert-1] # Current vertice array starts at 0, so n-1


        for x,y in neighbors:  # neighbores

            _v = _nodes[x-1]   # Node #1 will be will be array[0]

            if _v._visited == True:
                if _v._w > _vert._w+y:
                    _v._w = _v._w
                elif _v._w == _vert._w+y:
                        _v.pathsTo += _vert.pathsTo
                else:
                    _v.pathsTo = _vert.pathsTo
                    _v._w = y + _vert._w

            else:

                _v._w = y + _vert._w
                _v.pathsTo = max(_vert.pathsTo, _v.pathsTo + 1)
                _v._visited = True

我在我的Vertice类中添加了一个pathsTo变量,它将保存MAX长度的唯一路径数

2 个答案:

答案 0 :(得分:3)

你的numLongestPaths很慢,因为你递归地尝试了所有可能的路径,并且可能会有很多指数路径。找到一种避免为任何节点多次计算numLongestPaths的方法。

此外,您的原始_w计算已被破坏,因为当它计算节点的_w值时,它不会确保其他_w值的计算结果为&#39}。 s依靠自己计算。您将需要避免使用未初始化的值; topological sort可能很有用,虽然听起来顶点标签可能已经按拓扑排序顺序分配。

答案 1 :(得分:0)

除了@ user2357112的答案之外,还有两个额外的建议

语言

如果您的代码尽可能高效,我建议使用C. Python是一种很棒的脚本语言,但与编译的替代方案相比确实很慢

数据结构

节点以有序的方式命名,因此您可以使用列表而不是字典来优化代码。即。

_distance = [[] for i in range(_length)]
相关问题