Загрузка данных


import heapq

g = {}
for s in open('demo_23.txt'):
    a, b, w = map(float, s.split())
    a, b = int(a), int(b)
    g.setdefault(a, []).append((b, w))

def f(start, end):
    q = [(0, start)]
    d = {}

    while q:
        w, x = heapq.heappop(q)
        if x == end:
            return w
        if x == 4 or x in d:
            continue
        d[x] = w
        for y, v in g.get(x, []):
            heapq.heappush(q, (w + v, y))
    return float('inf')

print(f(298, 400) + f(400, 96))