放宽图形中的多个边缘(Dijkstra' s)

时间:2017-02-21 23:24:29

标签: algorithm graph python-2.x shortest-path dijkstra

我最近遇到problem,我必须找到无向加权多图中两个节点之间的最短路径。我是多图的新手,所以多边的概念对我来说仍然是新的。我使用了Dijkstra,最初只考虑了权重最小的边缘,忽略了给定节点对之间的所有其他多边缘。但令我惊讶的是,算法并没有产生正确的结果。直到我考虑了一对节点中的所有多个边缘并相应地放松它们才能找到最佳答案。为什么我必须包括所有多边?仅仅采用最轻的边缘更有意义吗?提前谢谢!

这是我的初始实现(Python 2.7)

from heapq import heappop,heappush
import sys

inf = float('inf')
def relax(Weight,u,v,Dist):
    d = Dist.get(u,inf) + Weight
    if d < Dist.get(v,inf):
        Dist[v] = d

def dijkstra(g,s):
    Dist,visited,priority_q = {s:0},set(),[(0,s)]
    while priority_q:
        _,u = heappop(priority_q)
        if u in visited: continue
        visited.add(u)
        for i in g[u]:
            relax(g[u][i],u,i,Dist)
            heappush(priority_q,(Dist[i],i))
    return Dist 

T = input()
for i in xrange(T):
    N,M = map(int,raw_input().split())
    graph = {k:{} for k in xrange(1,N+1)}
    for j in xrange(M):
        a,b,cost = map(int,raw_input().split())
        try:
            graph[a][b] = min(cost,g[a][b])
            graph[b][a] = min(cost,g[b][a])
        except KeyError:
            graph[a][b] = cost
            graph[b][a] = cost
    start = input()
    output, output_str = dijkstra(graph,start),[]
    for j in graph:
        if j!=start:
            try:
                output_str.append(str(output[j]))
            except KeyError:
                output_str.append('-1')
    print " ".join(output_str).rstrip()

这是我的最终实施。我只发布了它的一部分,因为其他一切都是一样的。

'''EVERYTHING ABOVE IS THE SAME'''

def dijkstra(g,s):
    Dist,visited,priority_q = {s:0},set(),[(0,s)]
    while priority_q:
        _,u = heappop(priority_q)
        if u in visited: continue
        visited.add(u)
        for i in g[u]:
            if g[u][i]:
                for k in g[u][i]:
                    relax(k,u,i,D)
                    heappush(priority_q,(D[i],i))
    return Dist 

T = input()
for i in xrange(T):
    N,M = map(int,raw_input().split())
    graph = {k:{j:[] for j in xrange(1,N+1) if j!=k} for k in xrange(1,N+1)}
    for j in xrange(M):
        a,b,cost = map(int,raw_input().split())
        graph[a][b].append(cost)
        graph[b][a].append(cost)

''' EVERYTHING BELOW IS THE SAME '''

0 个答案:

没有答案