Algorithms: Design and Analysis, Part 1, Programming Assignment #5

来源:互联网 发布:张国荣和四大天王 知乎 编辑:程序博客网 时间:2024/05/29 08:43
import heapqimport sysfname = 'dijkstraData.txt'#fname = "tc.txt"fh = open(fname)lines = [line.rstrip('\n') for line in fh]# Generate graph as a list of dictionaries.# Index of list is the vertex, value is a disctionary where key is the outgoing vertex and value is the length of the edge.neighbor = []d = dict()neighbor.append(d)for line in lines:    part = line.split()    v = int(part[0])    d = dict()    for i in part[1:]:        values = map(int, i.split(','))        d[values[0]] = values[1]    neighbor.append(d)# Generating graph ends# Dijkstras = 1dest = [7,37,59,82,99,115,133,165,188,197]#dest = range(12)res = []# vertices processded so far in a dictionaryx = dict()# Computed shortest path distances in a dictionary/heapa = dict()x[s] = 0a[s] = 0while len(x) != len(neighbor):    f = False    for v in x.keys():        for w, e in neighbor[v].items():            if w in x:                continue            f = True            cur = a[v] + e            if w in a:                a[w] = min(cur, a[w])            else:                a[w] = cur            #print "v:a[%d]:%d, e:%d, w:a[%d]:%d" % (v, a[v], e, w, a[w])    if f:        min_e = sys.maxint        min_v = 0        for w, e in a.items():            if (w not in x) and (e < min_e):                min_e = e                min_v = w        x[min_v] = min_e        #print "x[%d]:%d" % (min_v, x[min_v])    else:        for w, e in a.items():            x[w] = e        #print "exit"        break    #print "end of loop, a", afor d in dest:    res.append(x.get(d, 0))print res

0 0