Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Single Source Shortest Path II

  For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$.

Input

  In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format:

$u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$

  Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$).

Output

  For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 10,000$

$0 \leq c_i \leq 100,000$

$|E| < 500,000$

All vertices are reachable from vertex $0$

Sample Input 1

5
0 3 2 3 3 1 1 2
1 2 0 2 3 4
2 3 0 3 3 1 4 1
3 4 2 1 0 1 1 4 4 3
4 2 2 1 3 3

Sample Output 1

0 0
1 2
2 2
3 1
4 3

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
5
0 3 2 3 3 1 1 2
1 2 0 2 3 4
2 3 0 3 3 1 4 1
3 4 2 1 0 1 1 4 4 3
4 2 2 1 3 3


Sample output:
0 0
1 2
2 2
3 1
4 3

Submission status: Memory Limit Exceeded

Solution code:
import sys

def dijkstra(v_count: int, edges: list, start: int,
             *, adj_matrix: bool = False, unreachable=float("inf")) -> list:
    """ ダイクストラ法
    :param v_count: 頂点数
    :param edges: 辺のリスト(隣接リストor隣接行列)
    :param start: スタートする頂点
    :param adj_matrix: edgesに渡したリストが隣接行列ならTrue
    :param unreachable: 到達不能を表すコスト値
                        隣接行列の辺の有無の判定および返すリストの初期値に使用
    """
    from heapq import heappush, heappop

    vertices = [unreachable] * v_count
    vertices[start] = 0
    q, rem = [(0, start)], v_count - 1

    while q and rem:
        cost, v = heappop(q)
        if vertices[v] < cost:
            continue
        rem -= 1

        dests = (filter(lambda x: x[1] != unreachable, enumerate(edges[v]))
                 if adj_matrix else edges[v])

        for dest, _cost in dests:
            newcost = cost + _cost
            if vertices[dest] > newcost:
                vertices[dest] = newcost
                heappush(q, (newcost, dest))

    return vertices

n = int(input())
inf = float("inf")
edges = [[inf]*n for _ in [0]*n]
for a in (tuple(map(int, l.split())) for l in sys.stdin):
    _from = a[0]
    for to, cost in zip(a[2::2], a[3::2]):
        edges[_from][to] = cost
vertices = dijkstra(n, edges, 0, adj_matrix=True)
for i, n in enumerate(vertices):
    print(i, n)

Submission status: Memory Limit Exceeded

Solution code:
n = int(input())
G = [[-1 for i in range(n)] for j in range(n)]
d = [999999 for i in range(n)]
  
for i in range(n):
    v = input().split()
    for j in range(int(v[1])):
        G[int(v[0])][int(v[2+2*j])] = int(v[3+2*j])

d = [999999] * n
flag = [0] * n
d[0] = 0
while True:
    v = -1
    for j in range(n):
        if flag[j] != 1 and (v == -1 or d[j] < d[v]):
            v = j
    if v == -1:
        break
    flag[v] = 1
    for j in range(n):
        if G[v][j] == -1: continue
        d[j] = min(d[j], d[v] + G[v][j])

for i in range(n):
    print(str(i) + " " + str(d[i]))

Submission status: Memory Limit Exceeded

Solution code:
import sys

def dijkstra(W, n):
    U = [i for i in range(1, n)]
    D = [W[0][i] for i in range(n)]
    D[0] = 0

    while len(U) != 0:
        mind, minu = 200001, -1
        for u in U:
            if D[u] <= mind:
                mind, minu = D[u], u
        U.remove(minu)
        for i in range(1, n):
            D[i] = min(D[i], D[minu] + W[minu][i])

    return D

lines = sys.stdin.readlines()
n = int(lines.pop(0))

W = [[200001] * n for _ in range(n)]
for line in lines:
    l = map(int, line.split())
    for i in range(l[1]):
        W[l[0]][l[2 * i + 2]] = l[2 * i + 3]

D = dijkstra(W, n)

for i in range(n):
    print i, D[i]

Submission status: Memory Limit Exceeded

Solution code:
import sys
import heapq as hq

def dijkstra(W, n):
    D = [200001] * n
    D[0] = 0
    q = []
    hq.heappush(q, (0, 0))

    while len(q) != 0:
        prov_cost, src = hq.heappop(q)
        if D[src] < prov_cost:
            continue
        for dest in range(n):
            cost = W[src][dest]
            if D[dest] > D[src] + cost:
                D[dest] = D[src] + cost
                hq.heappush(q, (D[dest], dest))

    return D

lines = sys.stdin.readlines()
n = int(lines.pop(0))

W = [[200001] * n for _ in range(n)]
for line in lines:
    l = map(int, line.split())
    for i in range(l[1]):
        W[l[0]][l[2 * i + 2]] = l[2 * i + 3]

D = dijkstra(W, n)

for i in range(n):
    print i, D[i]

Submission status: Memory Limit Exceeded

Solution code:
import sys
import heapq as hq

def dijkstra(W, n):
    D = [float('inf')] * n
    D[0] = 0
    q = []
    hq.heappush(q, (0, 0))

    while len(q) != 0:
        prov_cost, src = hq.heappop(q)
        if D[src] < prov_cost:
            continue
        for dest in range(n):
            cost = W[src][dest]
            if cost != float('inf') and D[dest] > D[src] + cost:
                D[dest] = D[src] + cost
                hq.heappush(q, (D[dest], dest))

    return D

lines = sys.stdin.readlines()
n = int(lines.pop(0))

W = [[float('inf')] * n for _ in range(n)]
for line in lines:
    l = map(int, line.split())
    for i in range(l[1]):
        W[l[0]][l[2 * i + 2]] = l[2 * i + 3]

D = dijkstra(W, n)

for i in range(n):
    print i, D[i]

Submission status: Memory Limit Exceeded

Solution code:
import heapq as hq

INF = 100000000

def dijkstra(n):
    global INF, W
    D = [INF] * n
    D[0] = 0
    Q = []
    hq.heappush(Q, (0, 0))

    while len(Q) != 0:
        minw, i = hq.heappop(Q)
        if D[i] < minw:
            continue
        for j in range(n):
            w = W[i][j]
            if D[j] > D[i] + w:
                D[j] = D[i] + w
                hq.heappush(Q, (D[j], j))

    for i in range(n):
        print i, D[i]

n = int(input())
W = [[INF] * n for _ in range(n)]
for _ in range(n):
    l = map(int, raw_input().split())
    for i in range(l[1]):
        W[l[0]][l[2 * i + 2]] = l[2 * i + 3]

dijkstra(n)

Submission status: Memory Limit Exceeded

Solution code:
import heapq

INF = 100000000

def dijkstra(n):
    global INF, W
    D = [INF] * n
    D[0] = 0
    Q = []
    heapq.heappush(Q, (0, 0))

    while len(Q) != 0:
        minw, i = heapq.heappop(Q)
        if D[i] < minw:
            continue
        for j in range(n):
            w = W[i][j]
            if D[j] > D[i] + w:
                D[j] = D[i] + w
                heapq.heappush(Q, (D[j], j))

    for i in range(n):
        print i, D[i]

n = int(input())
W = [[INF] * n for _ in range(n)]
for _ in range(n):
    l = map(int, raw_input().split())
    for i in range(l[1]):
        W[l[0]][l[2 * i + 2]] = l[2 * i + 3]

dijkstra(n)

Submission status: Memory Limit Exceeded

Solution code:
n = int(input())

adj = [[100001 for j in range(n)] for i in range(n)]

for u in range(n):
    x = list(map(int, input().split()))
    for v, c in zip(x[2::2], x[3::2]):
        adj[u][v] = c

unvisited = [v for v in range(n)]

distance = [9900001] * n


def dijkstra(s):
    distance[s] = 0

    while True:
        mincost = 9900001
        for i in unvisited:
            if distance[i] < mincost:
                mincost = distance[i]
                u = i

        if mincost == 9900001:
            break

        unvisited.remove(u)

        for v in unvisited:
            weight_uv = adj[u][v]
            if weight_uv != 100001:
                t_d = distance[u] + weight_uv
                if t_d < distance[v]:
                    distance[v] = t_d



dijkstra(0)

for v, d in enumerate(distance):
    print(v, d)

Submission status: Memory Limit Exceeded

Solution code:
import sys

f_i = sys.stdin

n = int(f_i.readline())

adj = [[100001 for j in range(n)] for i in range(n)]

for x in f_i:
    x = list(map(int, x.split()))
    u = x[0]
    for v, c in zip(x[2::2], x[3::2]):
        adj[u][v] = c

unvisited = [v for v in range(n)]

distance = [999900001] * n
distance[0] = 0

class VCost:
    def __init__(self, v, cost):
        self.v = v
        self.cost = cost
    def __lt__(self, other):
        return self.cost < other.cost

import heapq

vcost = [VCost(v, 999900001) for v in range(n)]
vcost[0].cost = 0

def dijkstra():
    while vcost:
        uc = heapq.heappop(vcost)
        
        for vc in vcost:
            weight_uv = adj[uc.v][vc.v]
            if weight_uv != 100001:
                t_cost = uc.cost + weight_uv
                if t_cost < vc.cost:
                    distance[vc.v] = t_cost
                    vc.cost = t_cost
                    
        heapq.heapify(vcost)



dijkstra()

for v, d in enumerate(distance):
    print(v, d)

Submission status: Memory Limit Exceeded

Solution code:
import sys

f_i = sys.stdin

n = int(f_i.readline())

adj = [[100001 for j in range(n)] for i in range(n)]

for x in f_i:
    x = list(map(int, x.split()))
    u = x[0]
    for v, c in zip(x[2::2], x[3::2]):
        adj[u][v] = c

unvisited = [v for v in range(n)]

distance = [999900001] * n
distance[0] = 0

class VCost:
    def __init__(self, v, cost):
        self.v = v
        self.cost = cost
    def __lt__(self, other):
        return self.cost < other.cost

import heapq

vcost = [VCost(0, 0)]

def dijkstra():
    while vcost:
        uc = heapq.heappop(vcost)

        if uc.cost > distance[uc.v]:
            continue
        
        unvisited.remove(uc.v)
        
        for v in unvisited:
            weight_uv = adj[uc.v][v]
            if weight_uv != 100001:
                t_cost = uc.cost + weight_uv
                if t_cost < distance[v]:
                    distance[v] = t_cost
                    heapq.heappush(vcost, VCost(v, t_cost))



dijkstra()

for v, d in enumerate(distance):
    print(v, d)

Submission status: Memory Limit Exceeded

Solution code:
import heapq as pq
inf = float("inf")
n = int(input())
M = [[inf for i in range(n)] for i in range(n)]
for i in range(n):
    L = list(map(int, input().split()))
    for j in range(L[1]):
        M[L[0]][L[2 * j + 2]] = L[2 * j + 3]


def dijkstra(s):
    color = [0] * n
    d = [inf] * n
    d[s] = 0
    H =[]
    pq.heappush(H, [0, s])

    while len(H) != 0:
        u2,u1 = pq.heappop(H)
        color[u1] = 1
        if d[u1] < u2:
            continue
        for v in range(n):
            if color[v] != 1 and M[u1][v] != inf:
                if d[u1] + M[u1][v] < d[v]:
                    d[v] = d[u1] + M[u1][v]
                    pq.heappush(H, [d[v], v])
    return d

d = dijkstra(0)
for i,v in enumerate(d):
 print("{} {}".format(i,v))

Submission status: Memory Limit Exceeded

Solution code:
import heapq
inf = float('inf')

def main():
    n = input()
    M = [[inf]*n for i in xrange(n)]
    for i in xrange(n):
        Ai = map(int,raw_input().split())
        for j in xrange(Ai[1]):
            M[i][Ai[2+2*j]] = Ai[3+2*j]

    d = dijkstra(0,M,n)
    for i in xrange(n):
        print i, d[i]
    
def dijkstra(s,M,n):
    c = [-1]*n
    d = [inf]*n
    d[s] = 0
    H = zip(d,range(n))
    heapq.heapify(H)
    
    while (len(H) >= 1):
        di,u = heapq.heappop(H)
        c[u] = 1
        for v in xrange(n):
            if (c[v] != 1) & (M[u][v] != inf):
                if (d[u]+M[u][v] < d[v]):
                    d[v] = d[u] + M[u][v]
                    c[v] = 0
                    heapq.heappush(H,(d[v],v))
    return d

if __name__ == "__main__":
    main()

Submission status: Memory Limit Exceeded

Solution code:
def main():
    n = input()
    inf = float('inf')
    M = [[inf]*n for i in xrange(n)]
    for i in xrange(n):
        Ai = map(int,raw_input().split())
        for j in xrange(Ai[1]):
            M[i][Ai[2+2*j]] = Ai[3+2*j]

    d = dijkstra(0,M,n)
    for i in xrange(n):
        print i, d[i]

def dijkstra(s,M,n):
    inf = float('inf')
    c = [-1]*n
    d = [inf]*n
    p = [-1]*n
    d[s] = 0

    while(True):
        mincost = inf
        for i in xrange(n):
            if (c[i] != 1) & (d[i] < mincost):
                mincost = d[i]
                u = i
        if mincost == inf:
            break

        c[u] = 1

        for v in xrange(n):
            if (c[v] != 1) & (M[u][v] != inf):
                if d[u] + M[u][v] < d[v]:
                    d[v] = d[u] + M[u][v]
                    p[v] = u
                    c[v] = 0
    return d

if __name__ == "__main__":
    main()

Submission status: Memory Limit Exceeded

Solution code:
inf = float('inf')
n = int(input())
g = []
for i in range(n):
    line = list(map(int, input().split()))
    k = line[1]
    c = [inf] * n
    for j in range(k):
        v = line[2 + 2 * j]
        c[v] = line[3 + 2 * j]
    g.append(c)

distance = [inf] * n
distance[0] = 0
visited = [False] * n
current = 0

while not all(visited):
    visited[current] = True
    min_i = 0
    min_d = inf
    for i in range(n):
        if not visited[i]:
            if distance[current] + g[current][i] < distance[i]:
                distance[i] = distance[current] + g[current][i]
            if distance[i] < min_d:
                min_i = i
                min_d = distance[i]
    current = min_i

for i in range(n):
    print(i, distance[i])

Submission status: Memory Limit Exceeded

Solution code:
#coding:utf-8
inf = 1000000
n = int(input())
M = [[inf for i in range(n)] for j in range(n)]
vwMtrx = []
for i in range(n):
    data = list(map(int,input().split()))
    u = data[0]
    k = data[1]
    col = []
    for j in range(0,2*k,2):
        v, w = data[j+2], data[j+3]
        M[u][v] = w
        col.append([v,w])
    vwMtrx.append(col)

def dijkstra(s):
    color = ["white" for i in range(n)]
    d = [inf for i in range(n)]
    p = [-1 for i in range(n)]
    d[s] = 0
    Q = [[s,0]]
    while Q != []:
        u = min(Q, key=lambda x:x[1])
        Q = [List for List in Q if List != u]
        u = u[0]
        color[u] = "black"

        vwList = vwMtrx[u]
        
        for vw in vwList:
            v,w = vw[0],vw[1]
            if color[v] != "black" and M[u][v] != inf:
                if d[u] + M[u][v] < d[v]:
                    d[v] = d[u] + M[u][v]
                    p[v] = u
                    color[v] = "gray"
                    Q.append([v, d[v]])

    return d

dList = dijkstra(0)
for i, d in enumerate(dList):
    print(i,d)

Submission status: Accepted

Solution code:
#coding:utf-8
n = int(input())
inf = 1000000000000000

def minHeapify(Q,i):
    H = len(Q)
    l = 2*i
    r = 2*i + 1
    if l < H and Q[l][1] < Q[i][1]:
        smallest = l
    else:
        smallest = i
    if r < H and Q[r][1] < Q[smallest][1]:
        smallest = r

    if smallest != i:
        Q[i], Q[smallest] = Q[smallest], Q[i]
        minHeapify(Q,smallest)

def buildMinHeap(Q):
    H = len(Q)
    for i in range(H // 2, -1, -1):
        minHeapify(Q,i)

def Insert(Q,key):
    v = key[0]
    Q.append([v,inf])
    lens = len(Q)
    heapIncreaseKey(Q,lens-1,key)

def heapIncreaseKey(Q,i,key):
    Q[i][1] = key[1]
    while i > 0 and Q[i // 2][1] > Q[i][1]:
        Q[i], Q[i // 2] = Q[i // 2], Q[i]
        i //= 2

def heapExtractMin(Q):
    H = len(Q)
    minv = Q[0][0]
    Q[0] = Q[H-1]
    Q.pop()
    minHeapify(Q,0)
    return minv




def dijkstra(s):
    color = ["white" for i in range(n)]
    d = [inf for i in range(n)]
    d[s] = 0
    Q = [[s,0]]
    while Q != []:
        u = heapExtractMin(Q)
        color[u] = "black"
        for vw in mtrx[u]:
            [v,w] = vw
            if color[v] != "black":
                if d[u] + w < d[v]:
                    d[v] = d[u] + w
                    color[v] = "gray"
                    Insert(Q,[v,d[v]])
    return d



mtrx = [[] for i in range(n)]
for i in range(n):
    col = list(map(int,input().split()))
    u,k = col[0], col[1]
    for j in range(k):
        [v,w] = col[2*j+2: 2*j+4]
        mtrx[u].append([v,w])



d = dijkstra(0)
for i,j in enumerate(d):
    print(i,j)

Submission status: Accepted

Solution code:
# coding: utf-8

import heapq

def dj(adjm, start):
    n = len(adjm)
    d = [float("inf")] * n
    d[start] = 0
    q = []
    heapq.heappush(q, (0, start))

    while(q):
        td, v = heapq.heappop(q)
        for k in adjm[v].keys():
            nd = td + adjm[v][k]
            if d[k] > nd:
                d[k] = nd
                heapq.heappush(q, (nd, k))
    return d


def main():
    n = int(input())
    # 隣接行列
    adjm = [{} for _ in range(n)]
    for i in range(n):
        vdata = list(map(int, input().split()))
        for j in range(vdata[1]):
            v, c = vdata[j * 2 + 2], vdata[j * 2 + 3]
            adjm[i][v] = c
    ans = dj(adjm, 0)
    for i, d in enumerate(ans):
        print(i, d)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from heapq import heappop, heappush


def dijkstra(edges, start, *, adj_matrix=False, default_value=float('inf')):
    '''
    Returns best costs to each node from 'start' node in the given graph.
    (Single Source Shortest Path - SSSP)

    If edges is given as an adjacency list including costs and destination nodes on possible edges, adj_matrix should be False(default), and it is generally when this functions works much faster.

    Note that costs in edges should follow the rules below
    1. The cost from a node itself should be 0,
    2. If there is no edge between nodes, the cost between them should be default_value
    3. The costs can't be negative

    # sample input when given as adjacency list (adj_matrix=False)
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5

    # sample input when given as adjacency matrix (adj_matrix=True)
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5
    '''

    n = len(edges)

    inf = float('inf')
    costs = [inf] * n
    costs[start] = 0
    pq, rem = [(0, start)], n - 1

    while pq and rem:
        tmp_cost, tmp_node = heappop(pq)
        if costs[tmp_node] < tmp_cost:
            continue
        rem -= 1

        nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value) if adj_matrix else\
                    edges[tmp_node]

        for nxt_node, nxt_cost in nxt_edges:
            new_cost = tmp_cost + nxt_cost
            if costs[nxt_node] > new_cost:
                costs[nxt_node] = new_cost
                heappush(pq, (new_cost, nxt_node))

    return costs


def dijkstra_route(edges,
                   start,
                   goal,
                   *,
                   adj_matrix=False,
                   default_value=float('inf'),
                   verbose=False):
    '''
    Trys to find the best route to the 'goal' from the 'start'
    '''

    n = len(edges)

    inf = float('inf')
    costs = [inf] * n
    costs[start] = 0
    pq, rem = [(0, start)], n - 1
    prevs = [-1 for _ in [None] * n]

    while pq and rem:
        tmp_cost, tmp_node = heappop(pq)
        if costs[tmp_node] < tmp_cost:
            continue
        rem -= 1

        nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value) if adj_matrix else\
                    edges[tmp_node]

        for nxt_node, nxt_cost in nxt_edges:
            new_cost = tmp_cost + nxt_cost
            if costs[nxt_node] > new_cost:
                costs[nxt_node] = new_cost
                heappush(pq, (new_cost, nxt_node))
                prevs[nxt_node] = tmp_node

    min_route = []
    prev = goal
    cnt = 0
    while prev != start:
        min_route.append(prev)
        prev = prevs[prev]

        cnt += 1
        if prev == -1 or cnt > n:
            raise NoRouteError(
                'There is no possible route in this graph \nedges: {} \nstart: {} \ngoal: {}'.
                format(edges, start, goal))

    else:
        min_route.append(prev)
    min_route = min_route[::-1]
    min_cost = costs[goal]

    if verbose:
        print('---route---')
        for node in min_route[:-1]:
            print('{} -> '.format(node), end='')
        else:
            print(min_route[-1])

        print('---distance---')
        print(min_cost)

    return costs, min_route


class NoRouteError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_C
    '''

    n = int(input())
    edges = [[] for i in range(n)]
    for i in range(n):
        i, k, *kedges = map(int, input().split())
        for edge in zip(kedges[::2], kedges[1::2]):
            edges[i].append(edge)

    for i, cost in enumerate(dijkstra(edges, 0)):
        print(i, cost)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 19:11:44 2018

@author: maezawa
"""
infinity = 2*10**9

n = int(input())
adj = [[] for _ in range(n)]

for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(2,2+2*k,2):
        adj[u].append([ain[i],ain[i+1]])
    #print(*adj[u])

color = [0]*n
d = [infinity for _ in range(n)]
p = [0]*n
p[0] = -1
d[0] = 0

def dyk(s):
    cnt = 1
    cur = s
    candidates = set() # remaining nodes
    while True:
        for i, w in adj[cur]:
            if color[i] == 2:
                continue
            if d[i] > d[cur] + w:
                d[i] = d[cur] + w
                color[i] = 1
            candidates.add(i)
        min_d = infinity
        for j in candidates:
            if min_d > d[j]:
                min_node = j
                min_d = d[j]
        candidates.remove(min_node)
        p[min_node] = cur
        color[cur] = 2
        cur = min_node
        cnt += 1
        #print(cur, d)
        #print(candidates)
        if cnt == n:
            break
    return

dyk(0)
for i in range(n):
    print(i, d[i])
    
#print(*p, sep = '\n')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from collections import defaultdict
from heapq import heappop, heappush


def dijkstra(edges, start, *, adj_matrix=False, default_value=float('inf')):
    '''
    Returns best costs to each node from 'start' node in the given graph.
    (Single Source Shortest Path - SSSP)

    If edges is given as an adjacency list including costs and destination nodes on possible edges, adj_matrix should be False(default), and it is generally when this functions works much faster.

    Note that costs in edges should follow the rules below
    1. The cost from a node itself should be 0,
    2. If there is no edge between nodes, the cost between them should be default_value
    3. The costs can't be negative

    # sample input when given as adjacency list (adj_matrix=False)
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5

    # sample input when given as adjacency matrix (adj_matrix=True)
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5
    '''

    n = len(edges)

    inf = float('inf')
    # costs = [inf] * n
    costs = defaultdict(lambda: inf)
    costs[start] = 0
    pq, rem = [(0, start)], n - 1

    while pq and rem:
        tmp_cost, tmp_node = heappop(pq)
        if costs[tmp_node] < tmp_cost:
            continue
        rem -= 1

        nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value) if adj_matrix else\
                    edges[tmp_node]

        for nxt_node, nxt_cost in nxt_edges:
            new_cost = tmp_cost + nxt_cost
            if costs[nxt_node] > new_cost:
                costs[nxt_node] = new_cost
                heappush(pq, (new_cost, nxt_node))

    return costs


def dijkstra_route(edges,
                   start,
                   goal,
                   *,
                   adj_matrix=False,
                   default_value=float('inf'),
                   verbose=False):
    '''
    Trys to find the best route to the 'goal' from the 'start'
    '''

    n = len(edges)

    inf = float('inf')
    # costs = [inf] * n
    costs = defaultdict(lambda: inf)
    costs[start] = 0
    pq, rem = [(0, start)], n - 1
    # prevs = [-1 for _ in [None] * n]
    prevs = defaultdict(lambda: -1)

    while pq and rem:
        tmp_cost, tmp_node = heappop(pq)
        if costs[tmp_node] < tmp_cost:
            continue
        rem -= 1

        nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value) if adj_matrix else\
                    edges[tmp_node]

        for nxt_node, nxt_cost in nxt_edges:
            new_cost = tmp_cost + nxt_cost
            if costs[nxt_node] > new_cost:
                costs[nxt_node] = new_cost
                heappush(pq, (new_cost, nxt_node))
                prevs[nxt_node] = tmp_node

    min_route = []
    prev = goal
    cnt = 0
    while prev != start:
        min_route.append(prev)
        prev = prevs[prev]

        cnt += 1
        if prev == -1 or cnt > n:
            raise NoRouteError(
                'There is no possible route in this graph \nedges: {} \nstart: {} \ngoal: {}'.
                format(edges, start, goal))

    else:
        min_route.append(prev)
    min_route = min_route[::-1]
    min_cost = costs[goal]

    if verbose:
        print('---route---')
        for node in min_route[:-1]:
            print('{} -> '.format(node), end='')
        else:
            print(min_route[-1])

        print('---distance---')
        print(min_cost)

    return costs, min_route


class NoRouteError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_C
    '''

    n = int(input())
    edges = [[] for i in range(n)]
    for i in range(n):
        i, k, *kedges = map(int, input().split())
        for edge in zip(kedges[::2], kedges[1::2]):
            edges[i].append(edge)

    # for i, cost in enumerate(dijkstra(edges, 0)):
    #     print(i, cost)
    for i, cost in sorted(dijkstra(edges, 0).items(), key=lambda x: x[0]):
        print(i, cost)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from heapq import heappop, heappush


def dijkstra(edges, start, *, adj_matrix=False, default_value=float('inf')):
    '''
    Returns best costs to each node from 'start' node in the given graph.
    (Single Source Shortest Path - SSSP)

    If edges is given as an adjacency list including costs and destination nodes on possible edges, adj_matrix should be False(default), and it is generally when this functions works much faster.

    Note that costs in edges should follow the rules below
    1. The cost from a node itself should be 0,
    2. If there is no edge between nodes, the cost between them should be default_value
    3. The costs can't be negative

    # sample input when given as adjacency list (adj_matrix=False)
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5

    # sample input when given as adjacency matrix (adj_matrix=True)
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5
    '''

    n = len(edges)

    costs = [float('inf')] * n
    costs[start] = 0

    pq = [(0, start)]
    rem = n - 1

    while pq and rem:
        tmp_cost, tmp_node = heappop(pq)
        if costs[tmp_node] < tmp_cost:
            continue
        rem -= 1

        nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value) if adj_matrix else\
                    edges[tmp_node]

        for nxt_node, nxt_cost in nxt_edges:
            new_cost = tmp_cost + nxt_cost
            if costs[nxt_node] > new_cost:
                costs[nxt_node] = new_cost
                heappush(pq, (new_cost, nxt_node))

    return costs


def dijkstra_route(edges,
                   start,
                   goal,
                   *,
                   adj_matrix=False,
                   default_value=float('inf'),
                   verbose=False):
    '''
    Trys to find the best route to the 'goal' from the 'start'
    '''

    n = len(edges)

    costs = [float('inf')] * n
    costs[start] = 0
    pq = [(0, start)]
    rem = n - 1
    prevs = [-1 for _ in [None] * n]

    while pq and rem:
        tmp_cost, tmp_node = heappop(pq)
        if costs[tmp_node] < tmp_cost:
            continue
        rem -= 1

        nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value) if adj_matrix else\
                    edges[tmp_node]

        for nxt_node, nxt_cost in nxt_edges:
            new_cost = tmp_cost + nxt_cost
            if costs[nxt_node] > new_cost:
                costs[nxt_node] = new_cost
                heappush(pq, (new_cost, nxt_node))
                prevs[nxt_node] = tmp_node

    min_route = []
    prev = goal
    cnt = 0
    while prev != start:
        min_route.append(prev)
        prev = prevs[prev]

        cnt += 1
        if prev == -1 or cnt > n:
            raise NoRouteError(
                'There is no possible route in this graph \nedges: {} \nstart: {} \ngoal: {}'.
                format(edges, start, goal))

    else:
        min_route.append(prev)
    min_route = min_route[::-1]
    min_cost = costs[goal]

    if verbose:
        print('---route---')
        for node in min_route[:-1]:
            print('{} -> '.format(node), end='')
        else:
            print(min_route[-1])

        print('---distance---')
        print(min_cost)

    return costs, min_route


class NoRouteError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_C
    '''

    n = int(input())
    edges = [[] for i in range(n)]
    for i in range(n):
        i, k, *kedges = map(int, input().split())
        for edge in zip(kedges[::2], kedges[1::2]):
            edges[i].append(edge)

    costs = dijkstra(edges, 0)
    for i, cost in enumerate(costs):
        print(i, cost)