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: Accepted

Solution code:
from collections import deque

n = int(input())
g = []
d = [10**10] * n
d[0] = 0

for i in range(n):
    temp = list(map(int, input().split()))
    k = temp[1]
    temp = temp[2:]
    adj = []
    for j in range(k):
        v, c = temp[j*2], temp[j*2+1]
        adj.append([v, c])
    g.append(adj)

# for i in range(n):
#     print(g[i])

q = deque()
# Add tupple of prev and adj into Queue
q.append((0, g[0]))
done = set()

while q:
    node = q.popleft()
    prev = node[0]
    adj = node[1]
    # print('\nadj:', adj)

    for next in adj:
        v = next[0]
        w = next[1]
        # print('v:', v)
        # print('prev:', prev)

        # d[v] = min(d[v], d[prev] + w)
        if d[prev] + w < d[v]:
            d[v] = d[prev] + w
            # Need to add to Queue regardless of it's in done or not,
            # because the shortest path was updated.
            q.append((v, g[v]))
        if v not in done:
            done.add(v)
            q.append((v, g[v]))

# print('d:', d)

for i in range(len(d)):
    print(i, d[i])

Submission status: Accepted

Solution code:
import heapq


def dijkstra(adj_list, n):
    dist = [float("inf") for i in range(n)]
    visited = [False for _ in range(n)]
    parent = [-1 for _ in range(n)]
    start = 0
    dist[start] = 0
    dist_heap = []  # 距離が最小のノードをすぐに探せるようにするために使う。次のノードの候補を入れる。
    heapq.heappush(dist_heap, (dist[start], start))

    while len(dist_heap) > 0:
        cost, start = heapq.heappop(dist_heap)  # 一番近いノードがスタート地点となる
        visited[start] = True
        if dist[start] < cost:  # heapのコストが最短でなければ、distを更新する必要はない
            continue
        for end, weight in adj_list[start]:
            # startから出ているノードの距離を計算してheapqに入れる
            if not visited[end] and dist[start] + weight < dist[end]:
                dist[end] = dist[start] + weight
                parent[end] = start
                heapq.heappush(dist_heap, (dist[end], end))

    return parent, dist


def main():
    n = int(input())
    adj_list = []
    for _ in range(n):
        row = []
        line = input().split()
        dim = int(line[1])
        for i in range(dim):
            row.append((int(line[2 + i * 2]), int(line[2 + i * 2 + 1])))  # 番号, 重み
        adj_list.append(row)
    _, dist = dijkstra(adj_list, n)
    for i in range(n):
        print("{} {}".format(i, dist[i]))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import heapq

WHITE = 0
GRAY = 1
BLACK = 2

INF = 2000000000


def dijkstra():
    PQ = []
    heapq.heapify(PQ)
    color = [WHITE] * n
    d = [INF] * n
    
    d[0] = 0
    heapq.heappush(PQ, (0, 0))
    color[0] = GRAY
    
    while len(PQ) != 0:
        
        f = heapq.heappop(PQ)
        u = f[1]
        color[u] = BLACK
        
        if d[u] < f[0]:
            continue
        
        for j in range(len(adj[u])):
            v = adj[u][j][0]
            if color[v] == BLACK:
                continue
            if d[v] > d[u] + adj[u][j][1]:
                d[v] = d[u] + adj[u][j][1]
                heapq.heappush(PQ, (d[v], v))
                color[v] = GRAY
    for i in range(n):
        print(i, d[i])


n = int(input())

adj = [[] for j in range(n)]
for i in range(n):
    nums=list(map(int,input().split()))
    for j in range(nums[1]):
        adj[nums[0]].append((nums[2*j+2], nums[2*j+3]))
        

dijkstra()

Submission status: Accepted

Solution code:
n = int(input())
adjacents = []
inf =  999999999999999
distances = [inf] * n
colors  = ["white"] * n
from heapq import heappush, heappop

for i in range(n):
  u, k, *a = map(int, input().split())
  adjacents.append([])
  for l in range(k):
    v = a[(l * 2)]
    c = a[(l * 2 + 1)]
    adjacents[u].append([v, c])

def dijkstra(u):
  distances[u] = 0
  queue = []
  heappush(queue, [0, u])

  while queue:
    w, u = heappop(queue)
    
    if distances[u] < w:
      continue
    
    colors[u] = "black"
    distances[u] = w

    for edge, weight in adjacents[u]:
      if colors[edge] != "black" and distances[edge] > weight + w:
        heappush(queue, [weight + w, edge])

dijkstra(0)

for index, edge in enumerate(distances):
  print(index, edge)

Submission status: Accepted

Solution code:
import heapq

MAX = 10000
WHITE = 0
GRAY = 1
BLACK = 2
INF = float('inf')
color = [WHITE for _ in range(MAX)]
d = [INF for _ in range(MAX)]
adj = [None for _ in range(MAX)]
n = 0


def main():
    global n
    n = int(input())

    for _ in range(n):
        u, k, *n_s = map(int, input().split(' '))
        adj[u] = ([(n_s[2*j], n_s[2*j+1]) for j in range(k)])

    dijkstra(0)

    for i in range(n):
        print(f'{i} {d[i] if d[i] != INF else -1}')


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

    pq = []

    heapq.heappush(pq, (0, s))

    while len(pq) > 0:
        f = heapq.heappop(pq)
        u = f[1]

        color[u] = BLACK
        if d[u] < f[0]:
            continue

        for j in range(len(adj[u])):
            v = adj[u][j][0]
            if color[v] == BLACK:
                continue
            if d[v] > d[u] + adj[u][j][1]:
                d[v] = d[u] + adj[u][j][1]
                heapq.heappush(pq, (d[v], v))
                color[v] = GRAY


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)

def dijkstra(n, start, nbl):
    """n: 頂点数, start: 始点, nbl: 隣接リスト"""
    import heapq
    WHITE = 1<<5
    GRAY = 1<<10
    BLACK = 1<<15
    INF = 1<<20
    color = [WHITE] * n
    distance = [INF] * n
    parent = [-1] * n
    q = []

    distance[start] = 0
    heapq.heappush(q, (0, start))
    while len(q) != 0:
        du, u = heapq.heappop(q)
        # print("u: {}, du: {}".format(u, du))
        color[u] = BLACK
        if distance[u] < du:
            continue
        for next, cost in nbl[u]:
            if color[next] != BLACK and distance[u] + cost < distance[next]:
                distance[next] = distance[u] + cost
                color[next] = GRAY
                heapq.heappush(q, (distance[next], next))
    return distance


def main():
    n = int(input().strip())
    nb = [[] for _ in range(n)]
    for i in range(n):
        l = list(map(int, input().strip().split()))
        for j in range(l[1]):
            nb[i].append((l[2 + 2 * j], l[3 + 2 * j]))
    d = dijkstra(n, 0, nb)
    for i, v in enumerate(d):
        print(i, v)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    G = [[] for _ in range(N)]
    for _ in range(N):
        u, k, *vc = (int(i) for i in input().split())
        for i in range(0, len(vc), 2):
            G[u].append((vc[i], vc[i+1]))
    d = [[(1 << 63)-1, i] for i in range(N)]
    from heapq import heapify, heappop, heappush

    def dijkstra(s):
        d[s][0] = 0
        que = [(d[s][0], s)]
        heapify(que)
        finished = set()
        while len(finished) < N:
            u = heappop(que)
            while u[1] in finished:
                u = heappop(que)
            if d[u[1]][0] < u[0]:
                print('yeah')
            for v, c in G[u[1]]:
                if v in finished:
                    continue
                if d[v][0] > u[0] + c:
                    d[v][0] = u[0] + c
                    heappush(que, (d[v][0], v))
            finished.add(u[1])
    dijkstra(0)
    for i, val in enumerate(d):
        print(i, val[0])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappush,heappop,heapify

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

for i in range(n):
    info =  list(map(int,(input().split())))[2:]
    for j in range(int((len(info))/2)):
        G[i].append((info[2*j],info[2*j+1]))

color = ["white" for _ in range(n)]
dist = [(1<<21) for _ in range(n)]
que = []

def dijkstra():
    dist[0] = 0
    que.append((0,0)) #(dist,node)
    while que:
        # heapify(que)
        now = heappop(que)
        u = now[1]
        if dist[u] < now[0]:
            continue
        # print(u)
        color[u] = "black"
        for j in range(len(G[u])):
            if dist[u] + G[u][j][1] < dist[G[u][j][0]]:
                heappush(que,(dist[u] + G[u][j][1],G[u][j][0]))
                dist[G[u][j][0]] = dist[u] + G[u][j][1]

# for i in range(n):
#     print(*G[i])

dijkstra()

for i,dist in enumerate(dist):
    print(i,dist)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import heapq
input = lambda: sys.stdin.readline()[:-1]
sys.setrecursionlimit(10**8)
inf = float('inf')
mod = 10**9+7

n=int(input())
G=[[] for i in range(n)]
for _ in range(n):
    inp = list(map(int,input().split()))
    u,k=inp[:2]
    for i in range(k):
        G[u].append((inp[2+2*i],inp[3+2*i]))

def disktra(g,s):
    n=len(g)
    dist = [inf]*n
    dist[s] = 0
    hq=[]
    heapq.heappush(hq,(dist[s],s))
    while hq:
        cost,u =heapq.heappop(hq)
        if dist[u] < cost:
            continue
        for v,c in g[u]:
            if dist[v] <= dist[u] +c:
                continue
            dist[v] = dist[u] + c
            heapq.heappush(hq,(dist[v],v))
    return dist

d=disktra(G,0)
for i in range(n):
    print(i,d[i])

Submission status: Accepted

Solution code:
#ALDS_1_12_C Single Source Shortest Path II
import sys
import heapq

n = int(input())
G = [[] for _ in range(n)]
for i in range(n):
    u, k, *vc = list(map(int, sys.stdin.readline().strip().split()))
    for j in range(k):
        G[u].append([vc[j * 2], vc[j * 2 + 1]])

p = [] * n
c = ['white'] * n
d = [] * n
heapq.heappush(d, (0, 0))  # (distance, node)

mindist = [float('inf')] * n
mindist[0] = 0

while d:
    now = heapq.heappop(d)[1]

    #  色識別はなくても実行可能だが、枝刈りのために実行
    if c[now] == 'black':
        continue
    c[now] = 'black'

    for i in G[now]:
        if mindist[now] + i[1] < mindist[i[0]]:
            mindist[i[0]] = mindist[now] + i[1]
            heapq.heappush(d, [mindist[i[0]], i[0]])

for i in range(n):
    print('{} {}'.format(i, mindist[i]))

Submission status: Accepted

Solution code:
N = int(input())

E = [None] * N
for _ in range(N):
    u, k, *vs = map(int, input().split())
    E[u] = []
    for i in range(k):
        v, c = vs[i*2], vs[i*2+1]
        E[u].append((v, c))

import heapq

vis = [False] * N
inf = 1e9
d = [inf] * N
d[0] = 0
pq = [(0, 0)]
while pq:
    nv, ni = heapq.heappop(pq)
    if nv > d[ni]:
        continue
    d[ni] = nv
    vis[ni] = True
    for v, c in E[ni]:
        nc = d[ni] + c
        if not vis[v] and nc < d[v]:
            heapq.heappush(pq, (nc, v))

for v in range(N):
    print(v, d[v])

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
INF = 10**10
a = int(input())
d = [[] for i in range(a)]
for i in range(a):
    tl = list(map(int,input().split()))
    ta , tb = tl[0],tl[1]
    t = 2
    for j in range(tb):
        tta,ttb = tl[t],tl[t+1]
        d[i].append((tta,ttb))
        t+=2

def dijkstra(N, G, s):
    dist = [INF] * N
    que = [(0, s)]
    dist[s] = 0
    while que:
        c, v = heappop(que)
        if dist[v] < c:
            continue
        for t, cost in G[v]:
            if dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                heappush(que, (dist[t], t))
    for i in range(a):
        print(str(i)+" "+str(dist[i]))
dijkstra(a,d,0)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop

INF = 10000 * 100000

def dijkstra(s: int):
	d[s] = 0
	H = []
	for v in range(n):
		heappush(H, (d[v], v))
	while len(H) >= 1:
		_, u = heappop(H)
		color[u] = "BLACK"
		for v, c in M[u]:
			if color[v] != "BLACK" and d[u] + c < d[v]:
				d[v] = d[u] + c
				pi[v] = u
				color[v] = "GRAY"
				heappush(H, (d[v], v))

if __name__ == "__main__":
	n = int(input())
	G = []
	M = [[] for _ in range(n)]
	color = ["WHITE" for _ in range(n)]
	d = [INF for _ in range(n)]
	pi = [None for _ in range(n)]

	for _ in range(n):
		l = list(map(int, input().split()))
		u = l[0]
		k = l[1]
		for i in range(k):
			v = l[2 * (i + 1)]
			c = l[2 * (i + 1) + 1]
			M[u].append([v, c])
	dijkstra(0)
	for v in range(n):
		print(f"{v} {d[v]}")

Submission status: Accepted

Solution code:
import heapq
import sys

input = sys.stdin.readline
INF = 100100100

class Info:
    def __init__(self, argNodeId, argSumCost):
        self.nodeId = argNodeId
        self.sumCost = argSumCost
    def __lt__(self, arg):
        return self.sumCost < arg.sumCost


class Edge:
    def __init__(self, argTo, argCost):
        self.to = argTo
        self.cost = argCost


def main():
    n = int(input())
    minDist = [INF] * n
    graph = [[] for _ in range(n)]
    for _ in range (n):
        u, k, *cv = map(int, input().split())
        for i in range(k):
            graph[u].append(Edge(cv[2 * i], cv[2*i + 1]))
    minDist[0] = 0
    Q = []
    heapq.heappush(Q, Info(0, 0))
    while len(Q) > 0:
        u = heapq.heappop(Q)
        if u.sumCost > minDist[u.nodeId]:
            continue
        for edge in graph[u.nodeId]:
            if minDist[edge.to] > u.sumCost + edge.cost:
                minDist[edge.to] = u.sumCost + edge.cost
                heapq.heappush(Q, Info(edge.to, minDist[edge.to]))
    for i in range(n):
        print('{} {}'.format(i, minDist[i]))


if __name__ == '__main__': main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from collections import deque

def main():
    V = int(input())
    q = []
    G = [deque() for i in range(V)]
    
    for i in range(V):
        tmp = list(map(int, input().split()))
        
        if tmp[0] == 0:
            for j in range(tmp[1]): heappush(q, (tmp[2+2*j:4+2*j][::-1]))
                
        else:
            for j in range(tmp[1]): G[tmp[0]].append(tmp[2+2*j:4+2*j])
            
    dist = [float('inf')] * V
    visited = [False] * V
    dist[0], visited[0] = 0, True
    
    while q:
        cost, v = heappop(q)
        
        if visited[v]: continue
    
        dist[v], visited[v] = cost, True
        for u, c in G[v]:
            if visited[u] or dist[u] < cost + c: continue
            heappush(q, [c+cost, u])
        
    for i in range(V): print(i, dist[i])
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import heapq as hq

n=int(input())
da=[[] for i in range(n)]
for i in range(n):
    li=list(map(int,input().split()))
    for i in range(li[1]):
        da[li[0]].append([li[i*2+3],li[i*2+2]])
q=[]
ans=[-1 for i in range(n)]
ans[0]=0
for i in da[0]:
    hq.heappush(q,i)
while len(q)!=0:
    no=hq.heappop(q)
    if ans[no[1]] < 0:
        ans[no[1]]=no[0]
        for i in da[no[1]]:
            hq.heappush(q,[no[0]+i[0],i[1]])
for i in range(n):
    print("{} {}".format(i,ans[i]))

Submission status: Accepted

Solution code:
class RadixHeap:
    __slots__ = ["data", "last", "siz", "used"]

    # (max_key - min_key) <= C
    def __init__(self, N, C):
        self.data = [[] for i in range(C.bit_length() + 1)]
        self.last = self.siz = 0
        self.used = [0]*N

    def push(self, x, key):
        #assert self.last <= x
        self.siz += 1
        self.data[(x ^ self.last).bit_length()].append((x, key))

    def pop(self):
        data = self.data
        used = self.used
        #assert self.siz > 0
        if not data[0]:
            i = 1
            while not data[i]:
                i += 1
            d = data[i]
            new_last, new_key = min(d)
            used[new_key] = 1
            for val in d:
                x, key = val
                if used[key]:
                    self.siz -= 1
                    continue
                data[(x ^ new_last).bit_length()].append(val)
            self.last = new_last
            data[i] = []
        else:
            new_last, new_key = data[0].pop()
            used[new_key] = 1
            self.siz -= 1
        return new_last, new_key

    def __len__(self):
        return self.siz

import sys
readline = sys.stdin.readline
write = sys.stdout.write


N = int(readline())
G = [None] * N
for i in range(N):
    u, k, *V = map(int, readline().split())
    G[i] = [(v, c) for v, c in zip(V[::2], V[1::2])]

def dijkstra(N, G, s):
    que = RadixHeap(N, 10**9 + 1)

    dist = [10**18]*N
    dist[s] = 0
    que.push(0, s)
    while que:
        cost, v = que.pop()
        if dist[v] < cost:
            continue
        for w, c in G[v]:
            if cost + c < dist[w]:
                dist[w] = r = cost + c
                que.push(r, w)
    return dist
dist = dijkstra(N, G, 0)
write("\n".join("%d %d" % (i, d) for i, d in enumerate(dist)))
write("\n")

Submission status: Accepted

Solution code:
import heapq


def dijkstra(adj, s):
    INF = 200000
    n = len(adj)
    state, d, p = [False] * n, [INF] * n, [-1] * n
    d[s] = 0
    pq = [(d[s], s)]
    while pq:
        f, u = heapq.heappop(pq)
        state[u] = True
        if d[u] < f:
            continue
        for v, c in adj[u]:
            if state[v]:
                continue
            if d[u] + c < d[v]:
                d[v] = d[u] + c
                p[v] = u
                heapq.heappush(pq, (d[v], v))
    return d


def main():
    n = int(input())
    adj = [[] for _ in range(n)]
    for _ in range(n):
        u, _, *vc = map(int, input().split())
        for v, c in zip(vc[::2], vc[1::2]):
            adj[u].append((v, c))
    dist = dijkstra(adj, 0)
    for i, d in enumerate(dist):
        print(i, d)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from typing import List, Tuple
import sys


if __name__ == "__main__":
    num_vertices = int(input())
    adj_list: List[List[Tuple[int, int]]] = [[] for _ in range(num_vertices)]

    for _ in range(num_vertices):
        vertex, adj_num, *adjs = map(lambda x: int(x), input().split())
        for i in range(adj_num):
            # (cost, adj)
            adj_list[vertex].append((adjs[2 * i + 1], adjs[2 * i]))

    distances: List[int] = [sys.maxsize] * num_vertices
    distances[0] = 0
    que: List[Tuple[int, int]] = []
    heappush(que, (0, 0))

    while [] != que:
        base_distance, parent = heappop(que)
        for cost, adj in adj_list[parent]:
            distance = base_distance + cost
            if distance < distances[adj]:
                distances[adj] = distance
                heappush(que, (distance, adj))

    for vertex, distance in enumerate(distances):
        print(f"{vertex} {distance}")

Submission status: Accepted

Solution code:
import heapq


INFINITY = 10 ** 10
WHITE = 0
GRAY = 1
BLACK = 2


n = int(input())
dict_adjacency = {}

for _ in range(n):
    u, k, *list_num = map(int, input().split())

    list_temp = []

    dict_adjacency[str(u)] = {}

    for i in range(0, k * 2, 2):
        dict_adjacency[str(u)][str(list_num[i])] = list_num[i + 1]


d = [INFINITY] * n

def dijkstra(top_start):
    color = [WHITE] * n

    d[top_start] = 0
    h = []

    heapq.heappush(h, (d[top_start], top_start))

    while len(h) >= 1:
        cost_now, top_now = heapq.heappop(h)

        color[top_now] = BLACK

        if d[top_now] < cost_now:
            continue

        for top_next in dict_adjacency[str(top_now)].keys():
            top_next = int(top_next)
            if color[top_next] == BLACK:
                continue


            cost_next = d[top_now] + dict_adjacency[str(top_now)][str(top_next)]
            if cost_next < d[top_next]:
                d[top_next] = cost_next
                color[top_next] = GRAY
                heapq.heappush(h, (d[top_next], top_next))


dijkstra(top_start = 0)

for i, cost in enumerate(d):
    print(i, cost)

Submission status: Accepted

Solution code:
import heapq
WHITE = 0
GRAY = 1
BLACK = 2
INFTY = 10**13
def dijkstra(s):
    color = [WHITE for i in range(N)]
    d = [INFTY for i in range(N)]
    d[s] = 0
    pq = []
    heapq.heappush(pq, (0, s))

    while len(pq) != 0:
        u = heapq.heappop(pq)[1]
        color[u] = BLACK

        for v, c in VC[u]:
            if color[v] != BLACK:
                if d[u] + c < d[v]:
                    d[v] = d[u] + c
                    color[v] = GRAY
                    heapq.heappush(pq, (d[v], v))

    return d

N = int(input())
VC = [[] for i in range(N)]
for i in range(N):
    ukvc = list(map(int, input().split()))
    u, k, vc = ukvc[0], ukvc[1], ukvc[2:]
    for v, c in zip(vc[0::2], vc[1::2]):
        VC[u].append([v, c])

d = dijkstra(0)

for i in range(N):
    print(i, d[i])

Submission status: Accepted

Solution code:
from collections import defaultdict
import heapq
n = int(input())
global S, Q, l
S = [0]
Q = [(0, 0)]
l = [1000000 for _ in range(n)]
l[0] = 0
w_graph = [defaultdict(int) for _ in range(n)]
graph = [[] for _ in range(n)]
G = [None] * n
def input_graph(n):
  for i in range(n):
    node_id, k, *v_list = list(map(int, input().split()))
    G[i] = [(v, c) for v, c in zip(v_list[::2], v_list[1::2])]

heapq.heapify(Q)
def dijkstra():
  c = 0
  while Q and c < 10:
    u_c, u = heapq.heappop(Q)
    for v, v_c in G[u]:
      """if v not in S:
        S.append(v)
        l[v] = l[u] + v_c
        heapq.heappush(Q, (l[v], v))"""
      if  (l[v] > l[u] + v_c):
        l[v] = l[u] + v_c
        heapq.heappush(Q, (l[v], v))


if __name__ == "__main__":
  input_graph(n)
  dijkstra()
  for i, c in enumerate(l):
    print(i, c)

Submission status: Accepted

Solution code:
import heapq

n = int(input())
G = [[] for i in range(n)]
for ni in range(n):
    u, k, *tmp = [int(i) for i in input().split()]
    for ki in range(k):
        G[ni].append(tmp[:2])
        del tmp[:2]

INF = 100*100000
D = [INF for i in range(n)]
D[0] = 0
C = [0 for i in range(n)]
U = []
u = 0
while 0 in C:
    i = 0
    while U != []:
        u = heapq.heappop(U)[1]
        if C[u] == 0:
            break

    for i in range(len(G[u])):
        v = G[u][i][0]
        if D[u] + G[u][i][1] < D[v]:
            D[v] = D[u] + G[u][i][1]
            heapq.heappush(U, [D[v], v])
    C[u] = 1

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

Submission status: Accepted

Solution code:
import heapq


n = int(input())
M = {}
for _ in range(n):
    u, k, *line = map(int, input().split())
    tmp = []
    for i in range(k):
        v, w = line[2*i:2*i+2]
        tmp.append((v, w))
    M[u] = tmp

INF = 10**10
WHITE = 0
GREY = 1
BLACK = 2
d = [INF for i in range(n)]
d_heap = []
color = [WHITE]*n
p = [-1]*n


def dijkstra():
    d[0] = 0
    p[0] = -1
    heapq.heappush(d_heap, (0, 0))

    while len(d_heap):
        # 最も小さいnodeを持ってくる、これもheapで処理したい。
        _, u = heapq.heappop(d_heap)
        color[u] = BLACK

        # heapで距離更新
        for v, w in M[u]:
            if color[v] != BLACK:
                if d[u]+w < d[v]:
                    d[v] = d[u]+w
                    p[v] = u
                    heapq.heappush(d_heap, (d[v], v))


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

Submission status: Accepted

Solution code:
from heapq import heappop, heappush

n = int(input())
g = [[] for i in range(n)]
for i in range(n):
    u, k, *l, = map(int, input().split())
    for j in range(k):
        v, c = l[j*2], l[j*2+1]
        g[u].append([v, c])

'''
ダイクストラ法による単一始点最短経路
二分ヒープ（優先度付きキュー）による高速化
'''
d = [2**64]*n
d[0] = 0
h = []
heappush(h, (0, 0))

m = [False]*n
while len(h) > 0:
    c, u = heappop(h)
    m[u] = True
    if d[u] < c:
        continue
    for gv, gc in g[u]:
        if not m[gv] and d[u]+gc < d[gv]:
            d[gv] = d[u]+gc
            heappush(h, (d[u]+gc, gv))

for i in range(n):
    print(f"{i} {d[i]}")

Submission status: Accepted

Solution code:
#single source shotest path 2

from heapq import heappush, heappop

n = int(input())
a = [None]*n
for i in range(n):
    u, k, *V = map(int, input().split())
    a[i] = [(p, q) for p, q in zip(V[::2], V[1::2])]

dist = [10**6]*n
dist[0] = 0
que = []
heappush(que,(0,0))

while que:
    cost, v = heappop(que)
    for w, c in a[v]:
        if cost + c < dist[w]:
            dist[w] = r = cost + c
            heappush(que, (r,w))
            
for i in range(n):
    print(f"{i} {dist[i]}")

Submission status: Accepted

Solution code:
n=int(input())
g=[[]for i in range(n)]
for i in range(n):
    d=list(map(int,input().split()))
    for j in range(d[1]):
        g[d[0]].append((d[2+j*2+1],d[2+j*2]))

def dijkstra(g,st,ed):
    from heapq import heappush, heappop, heapify
    inf=10**18
    dist=[inf for i in range(len(g))]
    visited=[False for i in range(len(g))]
    dist[st]=0
    que=[]
    heappush(que,(0,st))
    while que:
        c,v=heappop(que)
        if visited[v]:
            continue
        visited[v]=True
        for x in g[v]:
            tmp=x[0]+c
            if tmp<dist[x[1]] and not visited[x[1]]:
                dist[x[1]]=tmp
                heappush(que,(tmp,x[1]))
    return dist

dist=dijkstra(g,0,n-1)
for i in range(n):
    print(i,dist[i])

Submission status: Accepted

Solution code:
import heapq


class Graph(object):

    class Node:
        def __init__(self, dist: int, number: int):
            self.dist = dist
            self.number = number

        def __lt__(self, other):
            return self.dist < other.dist \
                   or (self.dist == other.dist
                       and self.number < other.number)

        def __le__(self, other):
            return self.dist <= other.dist

        def __gt__(self, other):
            return other <= self

        def __ge__(self, other):
            return other < self

        def __str__(self):
            return "Node: (" + str(self.number) + ", " \
                   + str(self.dist) + ")"

    class Edge:
        def __init__(self, to: int, cost: int):
            self.to = to
            self.cost = cost

        def __str__(self):
            return "Edge: (" + str(self.to) + ", " \
                   + str(self.cost) + ")"

    INF = 10e10

    def __init__(self, node_n: int, start: int):
        self.node_n = node_n
        self.start = start
        self.edges = [{} for _ in range(self.node_n)]
        self.dist = [self.INF for _ in range(self.node_n)]

    def set_edge(self, from_pos: int, to_pos: int, cost: int, reversible: bool) -> None:
        self.edges[from_pos][to_pos] = (self.Edge(to_pos, cost))
        if reversible:
            self.edges[to_pos][from_pos] = (self.Edge(from_pos, cost))

    def solve(self) -> list:
        raise NotImplementedError


class Dijkstra(Graph):
    hq = []
    prev: list

    def __init__(self, node_n: int, start: int):
        super(Dijkstra, self).__init__(node_n, start)
        self.dist[self.start] = 0
        self.prev = [None for _ in range(node_n)]

    def solve(self) -> list:
        heapq.heappush(self.hq, self.Node(0, self.start))

        while len(self.hq) != 0:
            node = heapq.heappop(self.hq)
            if node.dist > self.dist[node.number]:
                continue

            for edge in self.edges[node.number].values():
                alt = self.dist[node.number] + edge.cost
                if self.dist[edge.to] > alt:
                    self.dist[edge.to] = alt
                    self.prev[edge.to] = node.number
                    heapq.heappush(self.hq, self.Node(alt, edge.to))

        return self.dist


if __name__ == '__main__':
    n = int(input())
    graph = Dijkstra(n, 0)

    for _ in range(n):
        buff = list(map(int, input().split()))
        u = buff[0]
        k = buff[1]
        for i in range(k):
            graph.set_edge(u,
                           buff[2 + i * 2],
                           buff[3 + i * 2],
                           False)
    dist = graph.solve()
    for i, d in enumerate(dist):
        print(i, d)

Submission status: Accepted

Solution code:
import sys
import heapq

n = int(sys.stdin.readline())

Q = []
adj = [[] for _ in range(n)]
for _ in range(n):
    cols = list(map(int, sys.stdin.readline().split()))
    for j in range(cols[1]):
        adj[cols[0]].append([cols[2+2*j], cols[2+2*j+1]])

d = [0] + [1e10] * (n-1)
color = [1] + [0] * (n-1)
heapq.heappush(Q, [0, 0])

while len(Q)>0:
    t, u = heapq.heappop(Q)
    color[u] = 2
    if d[u] < t: continue
    for v, w in adj[u]:
        if color[v] == 2: continue
        if d[v] > d[u] + w:
            d[v] = d[u] + w
            heapq.heappush(Q, [d[v], v])
            color[v] = 1

i=0
for e in d:
    print(i, e)
    i += 1

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
from typing import Dict


def find_shortest_distance(start_vertex: int, n: int,  relations: Dict[int, Dict]) -> Dict[int, int]:
    unreached_vertices = [x for x in range(1, n)]
    distance = {x: sys.maxsize for x in range(n)}
    distance[start_vertex] = 0
    vtx = None
    tmp_distance = [sys.maxsize for x in range(n)]
    for k, v in relations[start_vertex].items():
        tmp_distance[k] = v

    while True:
        min_dist = sys.maxsize
        for i in unreached_vertices:
            dist = tmp_distance[i]
            if dist < min_dist:
                min_dist = dist
                vtx = i
        if min_dist == sys.maxsize:
            break
        unreached_vertices.remove(vtx)
        distance[vtx] = min_dist
        neighbor_vertices = relations[vtx]
        for n_vtx, n_dist in neighbor_vertices.items():
            n_dist_from_start = distance[vtx] + n_dist
            tmp_dist = tmp_distance[n_vtx]
            if tmp_dist == sys.maxsize:
                tmp_distance[n_vtx] = n_dist_from_start
            else:
                if n_dist_from_start < tmp_dist:
                    tmp_distance[n_vtx] = n_dist_from_start
    return distance


def main():
    n = int(input())
    relations = defaultdict(dict)

    lines = sys.stdin.readlines()
    for i in range(n):
        u, k, *vtx_wght = map(int, lines[i].split())
        for v_i in range(k):
            relations[u][vtx_wght[2*v_i]] = vtx_wght[2*v_i+1]

    dist_from_0 = find_shortest_distance(0, n, relations)

    answers = [None] * n
    sorted_dist = sorted(dist_from_0.items(), key=lambda x: x[0])
    for i in range(n):
        answers[i] = f"{sorted_dist[i][0]} {sorted_dist[i][1]}"
    [print(ans) for ans in answers]
    return


main()