added:
这些评论让我很好奇pygraph的性能如何解决OP的顺序问题,所以我做了一个玩具程序来找出答案 . 这是问题的略小版本的输出:
$ python2.6 biggraph.py 4 6
biggraph generate 10000 nodes 00:00:00
biggraph generate 1000000 edges 00:00:00
biggraph add edges 00:00:05
biggraph Dijkstra 00:01:32
biggraph shortest_path done 00:04:15
step: 1915 2
step: 0 1
biggraph walk done 00:04:15
path: [9999, 1915, 0]
对于10k节点和1M边缘来说也不算太糟糕 . 重要的是要注意,由pygraph计算Dijkstra的方式产生了每个节点相对于一个目标(任意节点0,并且在图中没有特权位置)的所有生成树的字典 . 因此,花费3.75分钟计算的解决方案实际上得出了"what is the shortest path from all nodes to the target?"的答案 . 确实一旦 shortest_path 完成了,走的答案仅仅是字典查找,基本上没有时间 . 值得注意的是,在图表中添加预先计算的边缘在约1.5分钟时相当昂贵 . 这些时间在多次运行中是一致的 .
我仍然等待 biggraph 5 6 在一台闲置的计算机上(每台处理器的Athlon 64,4800 BogoMIPS,全部都是核心)已运行超过四分之一小时 . 至少内存使用稳定在约0.5GB . 结果如下:
biggraph generate 100000 nodes 00:00:00
biggraph generate 1000000 edges 00:00:00
biggraph add edges 00:00:07
biggraph Dijkstra 00:01:27
biggraph shortest_path done 00:23:44
step: 48437 4
step: 66200 3
step: 83824 2
step: 0 1
biggraph walk done 00:23:44
path: [99999, 48437, 66200, 83824, 0]
这是很长一段时间,但它也是一个繁重的计算(我真的希望我腌制结果) . 这是好奇的代码:
#!/usr/bin/python
import pygraph.classes.graph
import pygraph.algorithms
import pygraph.algorithms.minmax
import time
import random
import sys
if len(sys.argv) != 3:
print ('usage %s: node_exponent edge_exponent' % sys.argv[0])
sys.exit(1)
nnodes = 10**int(sys.argv[1])
nedges = 10**int(sys.argv[2])
start_time = time.clock()
def timestamp(s):
t = time.gmtime(time.clock() - start_time)
print 'biggraph', s.ljust(24), time.strftime('%H:%M:%S', t)
timestamp('generate %d nodes' % nnodes)
bg = pygraph.classes.graph.graph()
bg.add_nodes(xrange(nnodes))
timestamp('generate %d edges' % nedges)
edges = set()
while len(edges) < nedges:
left, right = random.randrange(nnodes), random.randrange(nnodes)
if left == right:
continue
elif left > right:
left, right = right, left
edges.add((left, right))
timestamp('add edges')
for edge in edges:
bg.add_edge(edge)
timestamp("Dijkstra")
target = 0
span, dist = pygraph.algorithms.minmax.shortest_path(bg, target)
timestamp('shortest_path done')
# the paths from any node to target is in dict span, let's
# pick any arbitrary node (the last one) and walk to the
# target from there, the associated distance will decrease
# monotonically
lastnode = nnodes - 1
path = []
while lastnode != target:
nextnode = span[lastnode]
print 'step:', nextnode, dist[lastnode]
assert nextnode in bg.neighbors(lastnode)
path.append(lastnode)
lastnode = nextnode
path.append(target)
timestamp('walk done')
print 'path:', path