Problem:


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

Single Source Shortest Path

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 100$

$0 \leq c_i \leq 100,000$

$|E| \leq 10,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:
import heapq


class SSST:
    """Given weighted graph, find minimum spanning tree.

    >>> st = SSST([[(2, 3), (3, 1), (1, 2)], \
                   [(0, 2), (3, 4)], \
                   [(0, 3), (3, 1), (4, 1)], \
                   [(2, 1), (0, 1), (1, 4), (4, 3)], \
                   [(2, 1), (3, 3)]])
    >>> [st.weight(n) for n in range(5)]
    [0, 2, 2, 1, 3]
    """
    def __init__(self, graph):
        self.size = len(graph)
        self.tree = []
        self.weights = [0] * self.size
        self._search(graph)

    def weight(self, n):
        return self.weights[n]

    def _search(self, graph):
        visited = [0]

        while len(visited) < self.size:
            h = []
            for node in visited:
                for i, w in graph[node]:
                    if i not in visited:
                        heapq.heappush(h, (w+self.weights[node], node, i))

            weight, src, dst = heapq.heappop(h)
            visited.append(dst)
            self.weights[dst] = weight
            self.tree.append((src, dst))


def run():
    n = int(input())

    nodes = [None] * n
    for _ in range(n):
        id_, deg, *edges = [int(i) for i in input().split()]
        nodes[id_] = []
        for _ in range(deg):
            tgt, wgt, *edges = edges
            nodes[id_].append((tgt, wgt))

    st = SSST(nodes)
    for node in range(n):
        print('{} {}'.format(node, st.weight(node)))


if __name__ == '__main__':
    run()

Submission status: Accepted

Solution code:
n = int(input())

graph = [[] for i in range(n)]

for i in range(n):
    a = list(map(int, input().split()))
    for j in range(a[1]):
        graph[a[0]].append(a[2+j*2:4+j*2])  #[頂点, cost]

memo = [10**10 for i in range(n)]
memo[0] = 0

import heapq
q = []
heapq.heappush(q, (0, 0))   #(それまでのcost, 頂点)
while len(q) != 0:
    top = heapq.heappop(q)
    for g in graph[top[1]]:
        cost = top[0] + g[1]
        if memo[g[0]] > cost:
            memo[g[0]] = cost
            heapq.heappush(q, (cost, g[0]))

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

Submission status: Accepted

Solution code:
# coding: utf-8

import heapq


class Dijkstra:

    """
    Dijkstra's algorithm: find the shortest path from a vertex
    Complexity: O(E + log(V))
    used in GRL1A(AOJ)
    """

    def __init__(self, V, G, INF=float("inf")):

        """
        V: the number of vertexes
        E: adjacency list (all edge in G must be 0 or positive)
        INF: Infinity distance
        """
        self.V = V
        self.G = G
        self.INF = INF
        self.distance, self.prev = list(), list()


    def dijkstra(self, start):

        Q = list()
        self.distance = [self.INF for _ in range(self.V)]
        self.prev = [-1 for _ in range(self.V)]

        self.distance[start] = 0
        heapq.heappush(Q, (0, start))

        while len(Q) > 0:
            dist, from_v = heapq.heappop(Q)
            if self.distance[from_v] < dist:
                continue
            for to_v, nxt_dist in self.G[from_v]:
                if self.distance[from_v] + nxt_dist >= self.distance[to_v]:
                    continue
                self.distance[to_v] = self.distance[from_v] + nxt_dist
                heapq.heappush(Q, (self.distance[to_v], to_v))
                self.prev[to_v] = from_v
        
        return self.distance


    def get_path(self, goal):

        path = [goal]
        while self.prev[goal] != -1:
            path.append(prev[goal])
            goal = self.prev[end]

        return path[::-1]


if __name__ == "__main__":
    
    n = int(input())
    g = [[] for _ in range(n)]
    for _ in range(n):
        v, _, *e = map(int, input().split())
        for u, d in zip(e[::2], e[1::2]):
            g[v].append((u, d))

    dist = Dijkstra(n, g).dijkstra(0)
    for i, d in enumerate(dist):
        print(i, d)

Submission status: Accepted

Solution code:
import heapq


def dijkstra(g, source):
    n = len(g)
    q = []
    heapq.heapify(q)
    heapq.heappush(q, (0, source))
    d = [float('inf') for _ in range(n)]
    d[source] = 0
    while len(q) > 0:
        cur = heapq.heappop(q)
        cur_pos = cur[1]
        for next in g[cur_pos]:
            next_pos = next[0]
            next_d = d[cur_pos] + next[1]
            if next_d < d[next_pos]:
                d[next_pos] = next_d
                heapq.heappush(q, (d[next_pos], next_pos))
    return d


def main():
    n = int(input())
    g = [[] for _ in range(n)]
    for _ in range(n):
        inp = list(map(int, input().split()))
        m = inp[0]
        k = inp[1]
        for i in range(k):
            g[m].append((inp[(i+1)*2], inp[(i+1)*2+1]))
    d = dijkstra(g, 0)
    for i in range(n):
        print(i, d[i])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())

INF = 2147483647
M = [[INF for j in range(n)] for i in range(n)]
check, dist = [0 for i in range(n)], [INF for i in range(n)]


def dijkstra(s):
    p = [-1 for i in range(n)]
    dist[s] = 0

    while True:
        min_cost = INF
        for i in range(n):
            if check[i] != 2 and dist[i] < min_cost:
                min_cost = dist[i]
                u = i

        if min_cost == INF:
            break

        check[u] = 2

        for v in range(n):
            if check[v] != 2 and M[u][v] != INF:
                if dist[u] + M[u][v] < dist[v]:
                    dist[v], p[v] = dist[u] + M[u][v], u
                    check[v] = 1


def main():
    for i in range(n):
        data = list(map(int, input().split()))
        for j in range(data[1]):
            M[data[0]][data[2*(j+1)]] = data[2*(j+1)+1]

    dijkstra(0)

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import heapq

class Dijkstra:
    """
        Dijkstra's algorithm: find the shortest paths from a vertex
        complexity:
            O(E + logV)
    """
    def __init__(self, V, E, start, INF=10**9):
        """
        :param V: the number of vertices
        :param E: adjacency list (all edge in E must be non negative)
        :param start: start vertex
        :param INF: Infinity distance
        """
        self.V = V
        self.E = E
        self.dijkstra(start, INF)

    def dijkstra(self, start, INF):
        que = list()
        self.distance = [INF] * self.V
        self.prev = [-1] * self.V
        self.distance[start] = 0
        heapq.heappush(que, (0, start))
        while len(que) > 0:
            dist, fr = heapq.heappop(que)
            if self.distance[fr] < dist:
                continue
            for to, cost in self.E[fr]:
                if self.distance[fr] + cost < self.distance[to]:
                    self.distance[to] = self.distance[fr] + cost
                    heapq.heappush(que, (self.distance[to], to))
                    self.prev[to] = fr

    def get_path(self, end):
        path = [end]
        while self.prev[end] != -1:
            end = self.prev[end]
            path.append(end)
            return path[::-1]


V = int(input())
edges = [[] for _ in range(V)]
for _ in range(V):
    u, _, *e = map(int, input().split())
    for t, d in zip(e[::2], e[1::2]):
        edges[u].append((t, d))

djk = Dijkstra(V, edges, 0)
for i, d in enumerate(djk.distance):
    print(i, d)

Submission status: Accepted

Solution code:
#coding:utf-8

inf = 1000000
n = int(input())
M = [[inf for i in range(n)] for j in range(n)]

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

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
    while True:
        mincost = inf
        for i in range(n):
            if color[i] != "black" and d[i] < mincost:
                mincost = d[i]
                u = i
        if mincost == inf:
            break
        color[u] = "black"

        for v in range(n):
            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"
    return d

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

Submission status: Accepted

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:
import sys
    
global nodes
nodes = {}

def shortest_path(GRAPH):
    global nodes
    
    p1 = 0
    nodes[p1][1] = 0;

    edge={}
    total = 0
    mini = 0
    while True:
        nodes[p1][0]=True
        for p2 in range(len(nodes)):
            if nodes[p2][0]==False and GRAPH.has_key((p1, p2)):
                tmp = nodes[p1][1] + GRAPH[(p1, p2)]
                if tmp < nodes[p2][1]:
                    nodes[p2][1] = tmp

        p1 = -1
        mini = 1000000
        for p2 in range(len(nodes)):
            if nodes[p2][0]==False and nodes[p2][1]<mini:
                p1 = p2
                mini = nodes[p2][1]
        if mini == 1000000:
            break
    return

def resultout():
    for i in range(len(nodes)):
        print "%d %d" %(i, nodes[i][1])
    return

n = int(raw_input())
x = {}
for i in range(n):
    seq = map(int,raw_input().split())
    i2 = seq.pop(0)
    n2 = seq.pop(0)
    for j in range(n2):
        j2 = seq.pop(0)
        weight = seq.pop(0)
        x[(i2, j2)] = weight
    nodes[i2] = [False, 1000000]

shortest_path(x)
resultout()

Submission status: Accepted

Solution code:
import sys
    
def shortest_path(GRAPH, distance):
    
    nodes = set()
    p1 = 0
    distance[p1] = 0

    while True:
        dp1 = distance[p1]
        gp1 = GRAPH[p1]
        status[p1]=1
        for p2 in gp1.keys():
            tmp = gp1[p2] + dp1
            if status[p2]==0 and tmp < distance[p2]:
                distance[p2] = tmp
                nodes.add(p2)

        p1 = -1
        mini = 1000000
            
        for p2 in nodes:
            if distance[p2]<mini:
                p1 = p2
                mini = distance[p2]
        if mini == 1000000:
            break
        nodes.remove(p1)
    return

def resultout(distance):
    for i in xrange(len(distance)):
        print "%d %d" %(i, distance[i])
    return

n = int(raw_input())
x = [{} for i in xrange(n)]
status = [0 for i in xrange(n)]
distance = [1000000 for i in xrange(n)]

for i in xrange(n):
    seq = map(int, raw_input().split())
    tmp={}
    for j in xrange(2, len(seq), 2):
        j2, weight = seq[j:j+2]
        tmp[j2] = weight
    x[seq[0]] = tmp
    status[i] = 0

shortest_path(x, distance)
resultout(distance)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin, maxint


def main():
    num = int(stdin.readline())

    L = []
    for _ in xrange(num):
        L.append([int(s) for s in stdin.readline().split()])

    weight = [maxint] * num
    weight[0] = 0
    V = set(xrange(1, num))
    index = 0

    while V:
        Li = L[index]
        for i in xrange(Li[1]):
            v = Li[i*2+2]
            if v not in V:
                continue
            c = Li[i*2+3]
            weight[v] = min(weight[v], c + weight[index])

        index = min(V, key=lambda i: weight[i])
        V.remove(index)

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


main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin, maxint


def main():
    num = int(stdin.readline())

    L = []
    for _ in xrange(num):
        it = iter(int(s) for s in stdin.readline().split()[1:])
        L.append([(next(it), next(it)) for _ in xrange(next(it))])

    weight = [maxint] * num
    weight[0] = 0
    V = set(xrange(1, num))
    index = 0

    while V:
        for v, cost in L[index]:
            if v not in V:
                continue
            weight[v] = min(weight[v], cost + weight[index])

        index = min(V, key=lambda i: weight[i])
        V.remove(index)

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


main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
import math
def dijkstra(N, G, s):
    dist = [math.inf] * N
    que = [(0,s)]
    dist[s] = 0
    ans = [[] for i in range(N)]
    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))
    return dist
n = int(input())

g = [[]for i in range(n)]
for i in range(n):
    nums=list(map(int,input().split()))
    node=nums[0]
    for j in range(nums[1]):
        t=nums[j*2+2]
        c=nums[j*2+3]
        g[node].append([t,c])
   
ans = dijkstra(n,g,0)
for i in range(n):
    print(f'{i} {ans[i]}')

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heappushpop, heapreplace, heapify

#隣接リスト作成
v = int(input())
edge_list = [[] for _ in range(v)]
for i in range(v):
    l = list(map(int, input().split()))
    for j in range(1,l[1]+1):
        edge_list[l[0]].append([l[2*j+1],l[2*j]])

def dijkstra(v, edges, start):
    d = [float("inf")] * v
    visited = [False] * v
    d[start] = 0
    visited[start] = 0
    hq = []
    for i in edges[start]:
        d[i[1]] = i[0]
        heappush(hq, i)

    while hq:
        x, y = heappop(hq)
        #もし更新する必要がないならこれ以降の処理を行わない
        if d[y] < x:
            continue
        d[y] = x
        visited[y] = True
        for n in edges[y]:
            if not visited[n[1]]:
                hq.append([x + n[0], n[1]])
        heapify(hq)
    return d

for index, d in enumerate(dijkstra(v, edge_list,0)):
    print(index,d)

Submission status: Accepted

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


class Dijkstra:
    """Graph input:
    {
    node:{node:cost,node:cost...},
    node:{node:cost,node:cost...},
    ...
    }
    """

    def __init__(self, graph: dict, N: int):
        self.graph = graph
        self.costs = [float("inf")] * N

    def calculate(self, start):
        queue = list()

        # step1: push the start point into the priority queue
        self.costs[start] = 0
        heappush(queue, (0, start))  # (cost,node)

        while queue:
            # step2: get the minimum cost node from unfixed node and fix the cost
            cost_from_start, min_node = heappop(queue)

            # step3: update the direct connected nodes
            for link, cost in self.graph[min_node].items():
                if cost_from_start + cost < self.costs[link]:
                    self.costs[link] = cost_from_start + cost
                    heappush(queue, (self.costs[link], link))

        return self.costs


n = int(input())
graph = defaultdict(dict)

for _ in range(n):
    data = [int(i) for i in input().split()]
    u = data[0]
    count = data[1]
    for j in range(1, count + 1):
        v = data[2 * j]
        w = data[2 * j + 1]
        graph[u][v] = w

dijkstra = Dijkstra(graph, n)
costs = dijkstra.calculate(0)

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

Submission status: Accepted

Solution code:
from sys import stdin
input = stdin.readline

infty = 100_000_00

def dijkstra(N):
    d[0] = 0
    p[0] = -1
    u = 0

    while True:
        mincost = infty
        for i in range(N):
            if color[i] != 2 and d[i] < mincost:
                mincost = d[i]
                u = i
        color[u] = 2
        if mincost == infty:
            break

        for v in range(N):
            if M[u][v] != infty and color[v] != 2 :
                if M[u][v] + d[u] < d[v]:
                    d[v] = M[u][v] + d[u]
                    p[v] = u
                    color[v] = 1

N = int(input())
M = [[infty] * N for i in range(N)]
d = [infty] * N #V-T間の重み最小辺の記録
p = [-1] * (N)
color = [0] * N

for i in range(N):
    a = list(map(int, input().split()))
    for k in range(1, len(a)//2):
        M[i][a[2*k]] = a[2*k+1]


dijkstra(N)

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

Submission status: Accepted

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
INF = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()

    # N個の頂点を持つ有向グラフのデータを生成
    # 辺が存在しない場合には値をinfinityとする
    graph = [[INF] * N for _ in range(N)]
    for _ in range(N):
        v1, k, *vertices = il()
        for idx in range(0, k * 2, 2):
            v2, c = vertices[idx:idx + 2]
            graph[v1][v2] = c

    # ダイクストラ法
    dist = [INF] * N  # 各頂点までの距離を保持する配列
    dist[0] = 0       # 開始始点の頂点は距離をゼロとする
    visited = [0] * N # 各頂点の訪問状態を保持する配列[0: 未訪問, 1: 訪問済み]
    while True:
        min_cost, u = INF, INF
        # 起点となる頂点の探索
        for i in range(N):
            if min_cost > dist[i] and visited[i] != 1:
                u = i
                min_cost = dist[i]

        # 起点となる頂点が存在しない場合には処理を終了
        if u == INF: break
        visited[u] = 1  # 起点を訪問済みにする

        # 起点から次の頂点までの距離を更新
        for v in range(N):
            if graph[u][v] != INF and visited[v] != 1:
                if dist[v] > dist[u] + graph[u][v]:
                    dist[v] = dist[u] + graph[u][v]

    # 回答
    for n in range(N):
        print(n, dist[n])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/12/ALDS1_12_B
# プリムのアルゴリズムと似ているが、求めているものが異なる(MSTの経路は必ずしも任意の点と点をつなぐ最小経路とはならない)。
# 次手の候補となるリストDの更新の仕方がprimとは異なる

INF = 10**6 + 1

# load datas
N = int(input())
M = [[INF] * N for _ in range(N)]  # 隣接行列
for _ in range(N):
    tmp = list(map(int, input().split()))
    if tmp[1] != 0:
        node = tmp[0]
        for i, t in enumerate(tmp[2:]):
            if i % 2 == 0:
                idx = t
            else:
                M[node][idx] = t


def dijkstra(adj_mat: list, s: int):
    Color = [0] * N  # 0:未訪問 1:訪問経験あり 2:訪問済み(そこまでの最短経路は確定済み)
    D = [INF] * N  # 本のdと同じ 始点からの距離を記録する
    P = [None] * N  # 本のpと同じ 最短経路木における親を記録する

    # スタートとするノードについて初期化
    D[s] = 0  # スタートまでの距離は必ず0
    P[s] = None  # 親がない(ROOTである)ことを示す

    while True:
        # 最短経路候補の中で一番コストの少ないノードを選ぶ、あとその時のコストも
        min_cost = INF
        for i in range(N):
            if Color[i] != 2 and D[i] < min_cost:
                # 訪問済みでなく、最小コストを更新したら
                min_cost = D[i]
                u = i
        # uには次に確定するノードが入っている

        if min_cost == INF:
            # これ以上辺がない or すべて訪問済みなら
            break

        Color[u] = 2  # uは訪問済み これから最短経路木に突っ込む作業をする

        # 以下のforではsからの最短経路木にuを追加したときの更新、uまわりで次の最短経路になる候補の更新をしている
        for v in range(N):
            if Color[v] != 2 and adj_mat[u][v] != INF:
                # 訪問済みでなく、u→vへの経路が存在するならば
                if D[u] + adj_mat[u][v] < D[v]:  # ココがprimと異なる点である
                    # 今までのs→vへの距離の候補(D[v])よりも、
                    # 新しいuを用いた経路(D[u] + M[u][v]はs→u→vの距離を示す)のほうが小さければ更新する
                    D[v] = D[u] + adj_mat[u][v]  # u周りにおける最短経路の候補の更新
                    P[v] = u  # sからの最短経路木の更新
                    Color[v] = 1  # 訪問経験ありに更新(この処理に関しては意味はない)

    return D, P


D, P = dijkstra(M, 0)

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

Submission status: Accepted

Solution code:
import heapq

n = int(input())

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

for _ in range(n):
    tmp = list(map(int, input().split()))
    if tmp[1] != 0:
        node = tmp[0]
        for i in range(2, 2 + tmp[1] * 2, 2):
            adj[node].append((tmp[i], tmp[i + 1]))

def dijkstra(s):
    visited = [0]*n
    d = [float("inf")]*n
    
    visited[s] = 1
    d[s] = 0
    queue = [(0, s)]
    heapq.heapify(queue)
    
    while queue:
        mincost, u = heapq.heappop(queue)
        visited[u] = 2

        if d[u] >= mincost:
            for idx, i in adj[u]:
                if visited[idx] != 2 and d[idx] > d[u] + i:
                    d[idx] = d[u] + i
                    heapq.heappush(queue, (d[idx], idx))
                    visited[idx] = 1
                    
    for i in range(n):
        print(i, -1 if d[i] == float("inf") else d[i])


dijkstra(0)

Submission status: Accepted

Solution code:
n=int(input())
inf=10000000
p=[-1 for i in range(n)]
M=[[inf for j in range(n)] for i in range(n)]
d=[inf for i in range(n)]
color=["white" for i in range(n)]
for i in range(n):
    tmp=list(map(int,input().split()))
    root=tmp[0]
    k=tmp[1]
    for j in range(k):
        v=tmp[2*(j+1)]
        M[root][v]=tmp[2*(j+1)+1]

def dijkstra(s):
    d[s]=0
    while True:
        mincost=inf
        for i in range(n):
            if color[i] is not "black" and d[i]<mincost:
                mincost=d[i]
                u=i
        if mincost is inf:
            break
        color[u]="black"
        for j in range(n):
            if color[j] is not "black" and M[u][j] is not inf:
                if d[u]+M[u][j]<d[j]:
                    d[j]=d[u]+M[u][j]
                    color[j]="gray"
                    p[j]=u

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

Submission status: Accepted

Solution code:
n = int(input())
INF = float("inf")
M = [[INF for _ in range(n)] for _ in range(n)]
for _ in range(n):
    a,*b = map(int,input().split())
    if b[0] != 0:
        c = b[1:]
        for i in range(len(c)//2):
            k,w = c[2*i],c[2*i+1]
            M[a][k] = w
searched = [0]*n
d = [INF]*n
p = [None]*n
d[0] = 0
p[0] = -1
while 1:
    mc = INF
    for i in range(n):
        if not searched[i] and d[i] < mc:
            mc = d[i]
            u = i
    if mc == INF:
        break
    searched[u] = 1
    for v in range(n):
        if not searched[v] and M[u][v] != INF:
            if d[u]+M[u][v] < d[v]:
                d[v] = d[u]+M[u][v]
                p[v] = u
for i in range(n):
    print(i,d[i])

Submission status: Accepted

Solution code:
import heapq

N = int(input())
A = [[]for i in range(N)]

for i in range(N):
    u, k, *nums = list(map(int,input().split()))
    for j in range(k):
        t = nums[j*2]
        c = nums[j*2+1]
        A[u].append([t, c])

memo = [1E18] * N
memo[0] = 0
qu = []
heapq.heappush(qu,(0,0))
while len(qu) != 0:
    atop = heapq.heappop(qu)
    for ne in A[atop[1]]:
        next_cost = atop[0] + ne[1]
        if(memo[ne[0]] > next_cost):
            memo[ne[0]] = next_cost
            heapq.heappush(qu, (next_cost,ne[0]))
for i in range(N):
    print(i, memo[i])

Submission status: Accepted

Solution code:
import queue
from sys import maxsize as INFTY
from collections import namedtuple
Q = namedtuple("Q", "u c")

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

for _ in range(n):
    a = [int(x) for x in input().split()]
    a.reverse()

    u, k = a.pop(), a.pop()
    for _ in range(k):
        v, c = a.pop(), a.pop()
        dic[(u, v)] = c


def bfs(n, s):
    res = [INFTY] * n
    q = queue.Queue()
    q.put(Q(s, 0))

    while q.qsize() != 0:
        p = q.get()
        if res[p.u] <= p.c: continue
        res[p.u] = p.c

        for i in range(n):
            if i == p.u: continue
            v = (p.u, i)
            if v not in dic: continue
            q.put(Q(i, p.c + dic[v]))
    return res


ans = bfs(n, 0)
for i in range(n):
    print(i, ans[i])

Submission status: Accepted

Solution code:
import sys, collections, heapq
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def dijkstra(G, s):
    que = []
    d = [INF]*len(G)
    d[s] = 0
    heapq.heappush(que, (d[s], s))

    while que:
        p = heapq.heappop(que)
        v = p[1]
        if d[v] < p[0]: continue
        for e in G[v]:
            if d[e[0]] > d[v] + e[1]:
                d[e[0]] = d[v] + e[1]
                heapq.heappush(que, (d[e[0]], e[0]))
    return d

def resolve():
    n = I()
    G = [[] for _ in range(n)]
    for i in range(n):
        ukvc = LI()
        u = ukvc[0]
        k = ukvc[1]
        for j in range(k):
            v = ukvc[2*j+2]
            c = ukvc[2*j+3]
            G[u].append((v, c))

    ans = dijkstra(G, 0)
    for i, e in enumerate(ans):
        print(i, e)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: 	single_source_shortest_path
# CreatedDate:  2020-06-08 21:54:58 +0900
# LastModified: 2020-06-08 22:28:47 +0900
#


import os
import sys
from collections import deque
#import numpy as np
#import pandas as pd


def main():
    n = int(input())
    graph = [[] for _ in range(n)]
    for _ in range(n):
        line = list(map(int,input().split()))
        u,k = line[0],line[1]
        path = line[2:]
        for i in range(0,2*k,2):
            graph[u].append([path[i+1],path[i]])
    
#    print(graph)
    s=0
    distance=[-1]*n
    Q = deque([s])
    distance[0]=0
    

    while Q:
        u = Q.popleft()
        for dis,v in graph[u]:
            if distance[v]==-1:
                distance[v]=distance[u]+dis
                Q.append(v)

            if distance[v]>distance[u]+dis:
                distance[v]=distance[u]+dis
                Q.append(v)
            


    for i,dis in enumerate(distance):
        print(i,dis)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

INFTY=sys.maxsize
WHITE=0
GRAY=1
BLACK=2

def readinput():
    n=int(input())
    nMap=[]
    for _ in range(n):
        nMap.append([INFTY]*n)

    for _i in range(n):
        l=list(map(int,input().split()))
        i=l[0]
        for jj in range(l[1]):
            j=l[2+jj*2]
            w=l[2+jj*2+1]
            nMap[i][j]=w
    return n, nMap

color=[]
d=[]
p=[]

def dijkstra(s,n,nMap):
    global color
    global d
    global p
    
    color=[WHITE]*n
    d=[INFTY]*n
    p=[-1]*n

    d[s]=0
    p[s]=-1

    while True:
        mincost=INFTY
        for i in range(n):
            if color[i]!=BLACK and d[i] < mincost:
                mincost=d[i]
                u=i
        if mincost==INFTY:
            break
        color[u]=BLACK

        for v in range(n):
            if color[v]!=BLACK and nMap[u][v]!=INFTY:
                if d[u]+nMap[u][v] < d[v]:
                    d[v]=d[u]+nMap[u][v]
                    p[v]=u
                    color[v]=GRAY

def main(n,nMap):

    dijkstra(0,n,nMap)
    for i in range(n):
        print('{} {}'.format(i,d[i]))

if __name__=='__main__':
    n,nMap=readinput()
    main(n,nMap)

Submission status: Accepted

Solution code:
import sys
import heapq
input=sys.stdin.readline
INF=2<<28

def dijkstra(G,start,n):#グラフ,初期頂点,頂点数

    dist=[INF]*n;dist[start]=0
    used=[False]*n;used[0]=True
    q=[]

    for v in G[start]:
        heapq.heappush(q,v)
    
    while len(q)>0:
        now=heapq.heappop(q)
        if used[now[1]]:
            continue
        v=now[1]
        dist[v]=now[0]
        used[v]=True

        for e in G[v]:
            if not used[e[1]]:
                heapq.heappush(q,(e[0]+dist[v],e[1]))

    return dist

N=int(input().rstrip())
g=[[] for _ in range(N)]
for _ in range(N):
    u,k,*c=map(int,input().split())
    for j in range(0,k*2,2):
        g[u].append((c[j+1],c[j]))

ans=dijkstra(g,0,N)
for i,x in enumerate(ans):
    print(i,x)

Submission status: Accepted

Solution code:
def shortest_path(V,uvc,start=0):
    distances = [INF]*V
    distances[start] = 0
    parents = list(range(V))

    for _ in range(V):
        modified = False
        for src,dst,cost in uvc:
            if distances[dst] > distances[src] + cost:
                distances[dst] = distances[src] + cost
                parents[dst] = src
                modified = True
        if modified == False:
            return distances,parents
    return None,None
import sys
INF = float("inf")
N = int(sys.stdin.readline())
G = tuple(tuple(map(int,sys.stdin.readline().rstrip().split()))[2:] for _ in range(N))
uvc = []
for i in range(N):
    for j in range(0,len(G[i]),2):
        uvc.append([i,G[i][j],G[i][j+1]])  
a,_ = shortest_path(N,uvc,0)
for i,v in enumerate(a):
    print(i,v)