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:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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

output:
0 0
1 2
2 2
3 1
4 3
"""

import heapq as hp
import sys

WHITE, GRAY, BLACK = 0, 1, 2


class SingleSourceShortestPath(object):
    __slots__ = ('adj_table', 'distance', 'parent', 'visited')

    def __init__(self, in_data):
        v_num = int(in_data[0])
        vertices = map(lambda x: x.split(), in_data[1:])
        adj_table = [{} for _ in range(v_num)]

        for v_info in vertices:
            source, v_adj_length, *v_adj_list = map(int, v_info)
            # assert len(v_adj_list) == v_adj_length * 2
            for target, cost in zip(v_adj_list[::2], v_adj_list[1::2]):
                adj_table[source][target] = cost

        self.adj_table = adj_table
        self.distance = [float('inf')] * v_num
        self.parent = [-1] * v_num
        self.visited = [WHITE] * v_num

    def path_heap_dijkstra(self, root):
        # path search init
        self.distance[root] = 0
        path_heap = []
        # heapq: rank by tuple[0], at here it's d[u]
        hp.heappush(path_heap, (0, root))

        while path_heap:
            csp, current = hp.heappop(path_heap)
            self.visited[current] = BLACK

            for adj, cost in self.adj_table[current].items():
                if self.visited[adj] != BLACK:
                    # alt: d[u] + w[u,v]
                    alt_path = self.distance[current] + cost
                    if alt_path < self.distance[adj]:
                        # update path_list
                        self.distance[adj] = alt_path
                        # update heap
                        hp.heappush(path_heap, (alt_path, adj))
                        self.visited[adj] = GRAY
                        self.parent[adj] = current

        return self.distance


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    case = SingleSourceShortestPath(in_data=_input)
    ans = case.path_heap_dijkstra(root=0)
    for i, v in enumerate(ans):
        print(i, v)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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

output:
0 0
1 2
2 2
3 1
4 3
"""

import heapq as hp
import sys

WHITE, GRAY, BLACK = 0, 1, 2


class SingleSourceShortestPath(object):
    # __slots__ = ('adj_table', 'distance', 'parent', 'visited')

    def __init__(self, in_data):
        v_num = int(in_data[0])
        vertices = map(lambda x: x.split(), in_data[1:])
        adj_table = [{} for _ in range(v_num)]

        for v_info in vertices:
            source, v_adj_length, *v_adj_list = map(int, v_info)
            # assert len(v_adj_list) == v_adj_length * 2
            for target, cost in zip(v_adj_list[::2], v_adj_list[1::2]):
                adj_table[source][target] = cost

        self.adj_table = adj_table
        self.distance = [float('inf')] * v_num
        self.parent = [-1] * v_num
        self.visited = [WHITE] * v_num

    def path_heap_dijkstra(self, root):
        # path search init
        self.distance[root] = 0
        path_heap = []
        # heapq: rank by tuple[0], at here it's d[u]
        hp.heappush(path_heap, (0, root))

        while path_heap:
            csp, current = hp.heappop(path_heap)
            self.visited[current] = BLACK

            for adj, cost in self.adj_table[current].items():
                if self.visited[adj] != BLACK:
                    # alt: d[u] + w[u,v]
                    alt_path = self.distance[current] + cost
                    if alt_path < self.distance[adj]:
                        # update path_list
                        self.distance[adj] = alt_path
                        # update heap
                        hp.heappush(path_heap, (alt_path, adj))
                        self.visited[adj] = GRAY
                        self.parent[adj] = current

        return self.distance


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    case = SingleSourceShortestPath(in_data=_input)
    ans = case.path_heap_dijkstra(root=0)
    for i, v in enumerate(ans):
        print(i, v)

Submission status: Accepted

Solution code:
import heapq as pq
inf = float("inf")
n = int(input())
M = [None] * n

for i in range(n):
    L = list(map(int, input().split()))
    M[L[0]] = []
    for j in range(L[1]):
        M[L[0]].append([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 v1,v2 in M[u1]:
            if color[v1] == 1: continue
            if d[u1] + v2 < d[v1]:
                d[v1] = d[u1] + v2
                pq.heappush(H, [d[v1], v1])
    return d

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

Submission status: Accepted

Solution code:
import heapq as hp

INF = 1000000

def diikstraMethd(G, s):
    # ?????????
    n = len(G)
    d = [INF for _ in range(n)]
    d[s] = 0
    PQ = [(d[s], s)]

    while PQ:
        u = hp.heappop(PQ)[1]
        for v, c in G[u]:
            alt = d[u] + c
            if d[v] > alt:
                d[v] = alt
                hp.heappush(PQ, (alt, v))

    return d


if __name__ == '__main__':
    n = int(input())
    G = [ [] for _ in range(n)]
    for _ in range(n):
        tmp = list(map(int, input().split()))
        u = tmp.pop(0)
        k = tmp.pop(0)
        for i in range(k):
            v = tmp.pop(0)
            c = tmp.pop(0)
            G[u].append((v, c))

    d = diikstraMethd(G, 0)

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

Submission status: Accepted

Solution code:
from sys import stdin
import heapq
INF = 1<<21
n = int(stdin.readline())
adj = [[]] * n
for u in range(0, n):
    U = list(map(int, stdin.readline().split()[2:]))
    adj[u] = list(zip(U[0::2], U[1::2]))
def dijkstra():
    d = [0] + [INF] * (n - 1)
    hq = [(0, 0)]
    while hq:
        u = heapq.heappop(hq)[1]
        for v, c in adj[u]:
            alt = d[u] + c
            if d[v] > alt:
                d[v] = alt
                heapq.heappush(hq, (alt, v))
    for i, c in enumerate(d):
        print(i, c)
dijkstra()

Submission status: Accepted

Solution code:
from sys import stdin
import heapq
INF = 1<<21
n = int(stdin.readline())
adj = [[]] * n
for u in range(0, n):
    U = list(map(int, stdin.readline().split()[2:]))
    adj[u] = [e for e in zip(U[0::2], U[1::2])]
def dijkstra():
    d = [0] + [INF] * (n - 1)
    hq = [(0, 0)]
    while hq:
        u = heapq.heappop(hq)[1]
        for v, c in adj[u]:
            alt = d[u] + c
            if d[v] > alt:
                d[v] = alt
                heapq.heappush(hq, (alt, v))
    for i, c in enumerate(d):
        print(i, c)
dijkstra()

Submission status: Accepted

Solution code:
from sys import stdin
import heapq
INF = 1<<21
n = int(stdin.readline())
adj = [[]] * n
for u in range(0, n):
    U = list(map(int, stdin.readline().split()[2:]))
    adj[u] = (e for e in zip(U[0::2], U[1::2]))
def dijkstra():
    d = [0] + [INF] * (n - 1)
    hq = [(0, 0)]
    while hq:
        u = heapq.heappop(hq)[1]
        for v, c in adj[u]:
            alt = d[u] + c
            if d[v] > alt:
                d[v] = alt
                heapq.heappush(hq, (alt, v))
    for i, c in enumerate(d):
        print(i, c)
dijkstra()

Submission status: Accepted

Solution code:
from sys import stdin
import heapq
INF = 1<<21
n = int(stdin.readline())
adj = [[]] * n
for u in range(0, n):
    U = list(map(int, stdin.readline().split()[2:]))
    adj[u] = zip(U[0::2], U[1::2])
def dijkstra():
    d = [0] + [INF] * (n - 1)
    hq = [(0, 0)]
    while hq:
        u = heapq.heappop(hq)[1]
        for v, c in adj[u]:
            alt = d[u] + c
            if d[v] > alt:
                d[v] = alt
                heapq.heappush(hq, (alt, v))
    for i, c in enumerate(d):
        print(i, c)
dijkstra()

Submission status: Accepted

Solution code:
from sys import stdin
import heapq
INF = 1<<21
n = int(stdin.readline())
adj = [[]] * n
for u in range(0, n):
    U = list(map(int, stdin.readline().split()))
    adj[u] = zip(U[2::2], U[3::2])
def dijkstra():
    d = [0] + [INF] * (n - 1)
    hq = [(0, 0)]
    while hq:
        u = heapq.heappop(hq)[1]
        for v, c in adj[u]:
            alt = d[u] + c
            if d[v] > alt:
                d[v] = alt
                heapq.heappush(hq, (alt, v))
    for i, c in enumerate(d):
        print(i, c)
dijkstra()

Submission status: Accepted

Solution code:
import heapq
class Edge:
    src=-1
    dest=-1
    cost=-1

def Dijkstra(graph,s):
    INF=int(1e9)
    d=[INF]*len(graph)
    d[s]=0
    used=[False]*len(graph)
    que=[]
    heapq.heappush(que,(0,s))
    while len(que)!=0:
        val=heapq.heappop(que)
        v=val[1]
        if used[v] : continue
        used[v]=True
        for i in range(0,len(graph[v])):
            e=graph[v][i]
            if d[v]+e.cost<d[e.dest]:
                d[e.dest]=d[v]+e.cost
                heapq.heappush(que,(d[e.dest],e.dest))
    return d

V=int(input())
graph=[[] for i in range(0,V)]
for i in range(0,V):
    vals=list(map(int,input().split(" ")))
    k=vals[1]
    for j in range(0,k):
        v=vals[2+j*2]
        c=vals[3+j*2]
        e=Edge()
        e.src=i
        e.dest=v
        e.cost=c
        graph[i].append(e)

d=Dijkstra(graph,0)
for i in range(0,V):
    print(str(i)+" "+str(d[i]))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from heapq import heapify, heappop, heappush
 
N = int(input())
INF = float("inf")
d = [INF for n in range(N)]
d[0] = 0
adj = [[] for _ in range(N)]
 
searched = [False for _ in range(N)]
searched[0] = True
 
for n in range(N):
    inp = tuple(map(int, input().split()))
    assert n == inp[0]
    adj[n] = list(zip(inp[2::2], inp[3::2]))
 
heap = [[0, 0]]
 
while len(heap):
    pcost, p = heappop(heap)
    searched[p] = True
     
    if d[p] < pcost:
        continue
     
    for v, c in adj[p]:
        if not searched[v]:
            new_cost = pcost + c
            if new_cost < d[v]:
                d[v] = new_cost
                heappush(heap, [new_cost, v])
 
for n in range(N):
    print("{} {}".format(n, d[n]))

Submission status: Accepted

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

N = int(input())
INF = float("inf")
adj = []
for _ in range(N):
    inp = tuple(map(int, input().split()))
    adj.append(tuple(zip(inp[2::2], inp[3::2])))

checked = [False for _ in range(N)]
d = [float("inf") for _ in range(N)]
d[0] = 0

heap = [[0, 0]] # cost, vec

while heap:
    c, u = heappop(heap)
    if d[u] < c or checked[u]:
        continue
    for nu, nc in adj[u]:
        new_d = d[u] + nc
        if new_d < d[nu]:
            d[nu] = new_d
            heappush(heap, [d[nu], nu])
    checked[u] = True

for n in range(N):
    print("{} {}".format(n, d[n]))

Submission status: Accepted

Solution code:
from heapq import heappush, heappop

def dijkstra(G, s):
    n = len(G)
    fixed = set()
    d = {}
    for i in range(n):
        d[i] = 9999999999999999999999999999999999999
    d[s] = 0
    heap = [(0, s)]
    while len(fixed) < n:
        du, u = heappop(heap)
        for v in G[u]:
            if v in fixed:
                continue
            if du + G[u][v] < d[v]:
                d[v] = du + G[u][v]
                heappush(heap, (d[v], v))
        fixed.add(u)
    return d




n = int(raw_input())
G = {}
for _ in range(n):
    entries = map(int, raw_input().split(' '))
    u = entries[0]
    k = entries[1]
    G[u] = {}
    for i in range(k):
        v = entries[i*2+2]
        c = entries[i*2+3]
        G[u][v] = c

d = dijkstra(G, 0)

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

Submission status: Accepted

Solution code:
import heapq

INF = 1e9

n = int(input())
adj_list = [[]] * n

for u in range(n):
    U = list(map(int, input().split()[2:]))
    adj_list[u] = zip(U[0::2], U[1::2]) # adj_list[u] = (v, cost)


def dijkstra(x):
    d = [INF] * x
    d[0] = 0
    hq = [(0, 0)] # (distance, v)??????????????¬??????????????????(key, ????´?)???????????????push, pop?????????
    
    while hq:
        u = heapq.heappop(hq)[1]
        for v, c in adj_list[u]:
            if d[v] > d[u] + c:
                d[v] = d[u] + c
                heapq.heappush(hq, (d[u] + c, v))
                
    return d

for i, di in enumerate(dijkstra(n)):
    print(i,di)

Submission status: Accepted

Solution code:
import heapq

INF = 1e9

n = int(input())
adj_list = [[]] * n

for u in range(n):
    U = list(map(int, input().split()[2:]))
    adj_list[u] = zip(U[0::2], U[1::2]) # adj_list[u] = (v, cost)


def dijkstra(x):
    d = [INF] * x
    d[0] = 0
    isVisited = [False] * x
    hq = [(0, 0)] # (distance, v)??????????????¬??????????????????(key, ????´?)???????????????push, pop?????????
    
    while hq:
        u = heapq.heappop(hq)[1]
        isVisited[u] = True
        
        for v, c in adj_list[u]:
            if not isVisited[v] and d[v] > d[u] + c:
                d[v] = d[u] + c
                heapq.heappush(hq, (d[u] + c, v))
                
    return d

for i, di in enumerate(dijkstra(n)):
    print(i,di)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_12_C

???????§????????????????II
"""
from enum import Enum
from heapq import heappush, heappop, heapify
import itertools


class Priority_queue():
    # https://docs.python.jp/3/library/heapq.html
    def __init__(self):
        self.pq = []                         # list of entries arranged in a heap
        self.entry_finder = {}               # mapping of tasks to entries
        self.REMOVED = '<removed-task>'      # placeholder for a removed task
        self.counter = itertools.count()     # unique sequence count

    def add_task(self, task, priority=0):
        'Add a new task or update the priority of an existing task'
        if task in self.entry_finder:
            self.remove_task(task)
        count = next(self.counter)
        entry = [priority, count, task]
        self.entry_finder[task] = entry
        heappush(self.pq, entry)

    def remove_task(self, task):
        'Mark an existing task as REMOVED.  Raise KeyError if not found.'
        entry = self.entry_finder.pop(task)
        entry[-1] = self.REMOVED

    def pop_task(self):
        'Remove and return the lowest priority task. Raise KeyError if empty.'
        while self.pq:
            priority, count, task = heappop(self.pq)
            if task is not self.REMOVED:
                del self.entry_finder[task]
                return task
        raise KeyError('pop from an empty priority queue')

    def top_task(self):
        return self.pq[0][-1]

    def get_length(self):
        return len(self.pq)

    def is_empty(self):
        return self.get_length()==0


class Sssp(object):
    """ single source shortest path """
    INFINITY = 999999999
    class Status(Enum):
        """ ?????????????¨??????¶??? """
        white = 1  # ????¨????
        gray = 2  # ?¨???????
        black = 3  #?¨???????

    def __init__(self, data):
        num_of_nodes = len(data)
        self.color = [Sssp.Status.white] * num_of_nodes  # ????????????????¨??????¶???
        self.d = [Sssp.INFINITY] * num_of_nodes  # ?§???????????????????
        self.p = [-1] * num_of_nodes  # ????????????????????????????¨?????????????????????????
        self.adj = [[] for _ in range(num_of_nodes)]
        self.make_adj(data)


    def make_adj(self, data):
        # ??£??\??????????????????
        for d in data:
            my_id = d[0]
            d = d[2:]
            while len(d) > 1:
                to_node, cost = d[0], d[1]
                self.adj[my_id].insert(0, (to_node, cost))
                d = d[2:]


    def dijkstra(self, start):
        self.d[start] = 0
        pq = Priority_queue()
        pq.add_task((0, 0), 0)

        while not pq.is_empty():
            cost, u = pq.pop_task()
            self.color[u] = Sssp.Status.black
            if self.d[u] < cost:
                continue

            for v, cost in self.adj[u]:
                if self.color[v] == Sssp.Status.black:
                    continue
                if self.d[v] > self.d[u] + cost:
                    self.d[v] = self.d[u] + cost
                    pq.add_task((self.d[v], v), self.d[v])
                    self.color[v] = Sssp.Status.gray


if __name__ == '__main__':
    # ??????????????\???
    num = int(input())
    data = []
    for i in range(num):
        data.append(list(map(int, input().split(' '))))

    # ???????????¢?´¢
    s = Sssp(data)
    s.dijkstra(0)

    # ???????????¨???
    for i in range(num):
        print('{0} {1}'.format(i, s.d[i]))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_12_C

???????§????????????????II
"""
from enum import Enum
from heapq import heappush, heappop, heapify


class Sssp(object):
    """ single source shortest path """
    INFINITY = 999999999
    class Status(Enum):
        """ ?????????????¨??????¶??? """
        white = 1  # ????¨????
        gray = 2  # ?¨???????
        black = 3  #?¨???????

    def __init__(self, data):
        num_of_nodes = len(data)
        self.color = [Sssp.Status.white] * num_of_nodes  # ????????????????¨??????¶???
        self.d = [Sssp.INFINITY] * num_of_nodes  # ?§???????????????????
        self.p = [-1] * num_of_nodes  # ????????????????????????????¨?????????????????????????
        self.adj = [[] for _ in range(num_of_nodes)]
        self.make_adj(data)


    def make_adj(self, data):
        # ??£??\??????????????????
        for d in data:
            my_id = d[0]
            d = d[2:]
            while len(d) > 1:
                to_node, cost = d[0], d[1]
                self.adj[my_id].insert(0, (to_node, cost))
                d = d[2:]


    def dijkstra(self, start):
        self.d[start] = 0
        pq = []
        heappush(pq, (0, 0))

        while pq:
            cost, u = heappop(pq)
            self.color[u] = Sssp.Status.black
            if self.d[u] < cost:
                continue

            for v, cost in self.adj[u]:
                if self.color[v] == Sssp.Status.black:
                    continue
                if self.d[v] > self.d[u] + cost:
                    self.d[v] = self.d[u] + cost
                    heappush(pq, (self.d[v], v))
                    self.color[v] = Sssp.Status.gray


if __name__ == '__main__':
    # ??????????????\???
    num = int(input())
    data = []
    for i in range(num):
        data.append(list(map(int, input().split(' '))))

    # ???????????¢?´¢
    s = Sssp(data)
    s.dijkstra(0)

    # ???????????¨???
    for i in range(num):
        print('{0} {1}'.format(i, s.d[i]))

Submission status: Accepted

Solution code:
n = int(input())
import heapq
G = {}
for i in range(n):
    i = [int(i) for i in input().split()]
    k = i[1]
    G[i[0]] = list(zip(i[2::2],i[3::2]))

def dijkstra(G):
    d = [0] + [float('inf')] * (n - 1)
    Q = [(d[i], i) for i in range(n)]
    heapq.heapify(Q)
    while len(Q) != 0:
        _, u = heapq.heappop(Q)
        for v, c in G[u]:
            if d[v] > d[u] + c:
                d[v] = d[u] + c
                heapq.heappush(Q, (d[v], v))
    return d

for i,j in enumerate(dijkstra(G)):
    print(i, j)

Submission status: Accepted

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

def main():
    n = input()
    A = []
    for i in xrange(n):
        A.append(map(int,raw_input().split()))

    d = dijkstra(0,A,n)
    for i in xrange(n):
        print i, d[i]
    
def dijkstra(s,A,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 i in xrange(A[u][1]):
            v = A[u][2+2*i]
            l = A[u][3+2*i]
            if (c[v] != 1):
                if (d[u]+l < d[v]):
                    d[v] = d[u] + l
                    c[v] = 0
                    heapq.heappush(H,(d[v],v))
    return d

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
import heapq
v_num = int(input())
connect = defaultdict(list)

for _ in range(v_num):
    que = [int(n) for n in input().split(" ")]
    connect[que[0]] = [[v, w] for v, w in zip(que[2:len(que):2], que[3:len(que):2])]
    # weight_edge[que[0]] = {k:v for k, v in zip(que[2:len(que):2], que[3:len(que):2])}
queue = []
heapq.heapify(queue)
heapq.heappush(queue, [0, 0])
distance = [-1 for n in range(v_num)]
went = 0
visited = set()
while went < v_num:
    q = heapq.heappop(queue)
    weight, here = q
    if here in visited:
        continue
    visited |= {here}
    went += 1
    distance[here] = weight
    for conn in connect[here]:
        if conn[0] not in visited:
            heapq.heappush(queue, [weight + conn[1], conn[0]])
for i in range(v_num):
    print(i, distance[i])

Submission status: Accepted

Solution code:
import heapq

n = int(input())
d = [float("inf") for i in range(n)]
d[0] = 0
g = []
q = []

for i in range(n):
    heapq.heappush(q, (d[i], i))
    inp = list(map(int, input().split()))
    tmp = []
    for j in range(inp[1]):
        tmp.append(inp[2*j+2:2*j+4])
    g.append(tmp)

while q:
    q_pop = heapq.heappop(q)
    i = q_pop[1]
    if q_pop[0] > 100000*100000:
        continue
    for node in g[i]:
        d_tmp = d[i] + node[1]
        if d_tmp < d[node[0]]:
            d[node[0]] = d_tmp
            heapq.heappush(q, (d_tmp, node[0]))

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

Submission status: Accepted

Solution code:
from heapq import heappush, heappop

inf = float('inf')
n = int(input())
g = []
for i in range(n):
    line = list(map(int, input().split()[2:]))
    g.append(zip(line[0::2], line[1::2]))

dist = [inf] * n
dist[0] = 0
heap = [(0, 0)]

while heap:
    current = heappop(heap)[1]
    for v, c in g[current]:
        new_dist = dist[current] + c
        if new_dist < dist[v]:
            dist[v] = new_dist
            heappush(heap, (new_dist, v))

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

Submission status: Accepted

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

if __name__ == '__main__':

    n = int(input())
    M = [set() for i in range(n)]

    for i in range(n):
        l = list(map(int, input().split(" ")))
        for k in range(l[1]):
            j = l[2 + 2 * k]
            c = l[2 + 2 * k + 1]
            M[i].add((j, c))

    d = [float("inf")] * n
    h = []

    def dijkstra(s):
        color = [0] * n
        p = [None] * n
        d[s] = 0
        heappush(h, (d[s], s))

        while h:
            _, u = heappop(h)

            color[u] = 2

            for v, c in M[u]:
                if color[v] != 2:
                    if d[u] + c < d[v]:
                        d[v] = d[u] + c
                        color[v] = 1
                        heappush(h, (d[v], v))

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

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from heapq import heapify, heappush, heappop
INF = float("inf")
def MAIN():
    n = int(input())
    G = [[i, INF] for i in range(n)]
    G[0][1] = 0
    m = {}
    for _ in range(n):
        A = list(map(int, readline().split()))
        m[A[0]] = {}
        for i in range(2, len(A), 2):
            m[A[0]][A[i]] = A[i + 1]
    dp = [(0, 0)]
    while dp:
        cost, u = heappop(dp)
        for v, c in m[u].items():
            if G[v][1] > G[u][1] + c:
                G[v][1] = G[u][1] + c
                heappush(dp, (G[v][1], v))
    print("\n".join(" ".join(map(str, a)) for a in G))
MAIN()

Submission status: Accepted

Solution code:
import heapq
import sys
readline = sys.stdin.readline
def dijkstra(n):
    inf = 10 ** 6 + 1
    dist = [0] + [inf] * (n - 1)
    q = [(0, 0)]
    while q:
        u = heapq.heappop(q)[1]
        for (v, c) in edge[u]:
            alt = dist[u] + c
            if dist[v] > alt:
                dist[v] = alt
                heapq.heappush(q, (alt, v))
    return dist
n = int(input())
edge = [[]] * n
for _ in range(n):
    l = list(map(int, readline().split()))
    edge[l[0]] = (e for e in zip(l[2::2], l[3::2]))
for i, c in enumerate(dijkstra(n)):
    print(i, c)

Submission status: Accepted

Solution code:
from heapq import heapify, heappush, heappop
INF = float("inf")
def MAIN():
    n = int(input())
    G = [[i, INF] for i in range(n)]
    G[0][1] = 0
    m = {}
    for _ in range(n):
        A = list(map(int, input().split()))
        m[A[0]] = {}
        for i in range(2, len(A), 2):
            m[A[0]][A[i]] = A[i + 1]
    dp = [(0, 0)]
    while dp:
        cost, u = heappop(dp)
        for v, c in m[u].items():
            if G[v][1] > G[u][1] + c:
                G[v][1] = G[u][1] + c
                heappush(dp, (G[v][1], v))
    print("\n".join(" ".join(map(str, a)) for a in G))
MAIN()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from heapq import heapify, heappush, heappop
INF = float("inf")
def MAIN():
    n = int(input())
    adj = [[]] * n
    for _ in range(0, n):
        U = list(map(int, input().split()))
        adj[U[0]] = zip(U[2::2], U[3::2])
    def dijkstra():
        d = [0] + [INF] * (n - 1)
        hq = [(0, 0)]
        while hq:
            u = heappop(hq)[1]
            for v, c in adj[u]:
                alt = d[u] + c
                if d[v] > alt:
                    d[v] = alt
                    heappush(hq, (alt, v))
        print("\n".join(f"{i} {c}" for i, c in enumerate(d)))
    dijkstra()
MAIN()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from heapq import heapify, heappush, heappop
INF = float("inf")
def MAIN():
    n = int(input())
    adj = [[]] * n
    for _ in range(0, n):
        U = list(map(int, readline().split()))
        adj[U[0]] = zip(U[2::2], U[3::2])
    def dijkstra():
        d = [0] + [INF] * (n - 1)
        hq = [(0, 0)]
        while hq:
            u = heappop(hq)[1]
            for v, c in adj[u]:
                alt = d[u] + c
                if d[v] > alt:
                    d[v] = alt
                    heappush(hq, (alt, v))
        print("\n".join(f"{i} {c}" for i, c in enumerate(d)))
    dijkstra()
MAIN()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from heapq import heapify, heappush, heappop
INF = float("inf")
def MAIN():
    n = int(input())
    adj = [[]] * n
    for _ in range(0, n):
        U = list(map(int, input().split()))
        adj[U[0]] = zip(U[2::2], U[3::2])
    def dijkstra():
        d = [0] + [INF] * (n - 1)
        hq = [(0, 0)]
        while hq:
            u = heappop(hq)[1]
            for v, c in adj[u]:
                alt = d[u] + c
                if d[v] > alt:
                    d[v] = alt
                    heappush(hq, (alt, v))
        print("\n".join(str(i) + " " + str(c) for i, c in enumerate(d)))
    dijkstra()
MAIN()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from heapq import heapify, heappush, heappop
INF = float("inf")
def MAIN():
    n = int(input())
    adj = [[]] * n
    for _ in range(0, n):
        U = list(map(int, input().split()))
        adj[U[0]] = zip(U[2::2], U[3::2])
    def dijkstra():
        d = [0] + [INF] * (n - 1)
        hq = [(0, 0)]
        while hq:
            u = heappop(hq)[1]
            for v, c in adj[u]:
                alt = d[u] + c
                if d[v] > alt:
                    d[v] = alt
                    heappush(hq, (alt, v))
        print("\n".join(" ".join(map(str, (i, c))) for i, c in enumerate(d)))
    dijkstra()
MAIN()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from heapq import heapify, heappush, heappop
INF = float("inf")
def MAIN():
    n = int(input())
    adj = [[]] * n
    for _ in range(0, n):
        U = list(map(int, input().split()))
        adj[U[0]] = zip(U[2::2], U[3::2])
    def dijkstra():
        d = [INF] * n
        d[0] = 0
        hq = [(0, 0)]
        while hq:
            u = heappop(hq)[1]
            for v, c in adj[u]:
                alt = d[u] + c
                if d[v] > alt:
                    d[v] = alt
                    heappush(hq, (alt, v))
        print("\n".join(f"{i} {c}" for i, c in enumerate(d)))
    dijkstra()
MAIN()

Submission status: Accepted

Solution code:
from heapq import*
n=int(input())
A=[[]for _ in[0]*n]
for _ in[0]*n:
 e=list(map(int,input().split()))
 for i in range(e[1]):k=2*-~i;A[e[0]]+=[(e[k],e[k+1])]
H=[[0,0]]
d=[0]+[1e6]*n
c=[1]*n
while H:
 f=heappop(H)
 u=f[1]
 c[u]=0
 if d[u]>=f[0]:
  for s in A[u]:
   v=s[0]
   if c[v]and d[v]>d[u]+s[1]:
    d[v]=d[u]+s[1]
    heappush(H,[d[v],v])
for i in range(n):print(i,d[i])

Submission status: Accepted

Solution code:
import sys
from heapq import*
e=sys.stdin.readline
n=int(e())
A=[[]for _ in[0]*n]
for _ in[0]*n:
 b=list(map(int,e().split()))
 for i in range(b[1]):k=2*-~i;A[b[0]]+=[(b[k],b[k+1])]
H=[[0,0]]
d=[0]+[1e6]*n
c=[1]*n
while H:
 f=heappop(H)
 u=f[1]
 c[u]=0
 if d[u]>=f[0]:
  for s in A[u]:
   v=s[0]
   if c[v]and d[v]>d[u]+s[1]:
    d[v]=d[u]+s[1]
    heappush(H,[d[v],v])
for i in range(n):print(i,d[i])

Submission status: Accepted

Solution code:
from heapq import*
def m():
 n=int(input())
 A=[[]for _ in[0]*n]
 for _ in[0]*n:
  e=list(map(int,input().split()))
  for i in range(e[1]):k=2*-~i;A[e[0]]+=[(e[k],e[k+1])]
 H=[[0,0]]
 d=[0]+[1e6]*n
 c=[1]*n
 while H:
  f=heappop(H)
  u=f[1]
  c[u]=0
  if d[u]>=f[0]:
   for s in A[u]:
    v=s[0]
    if c[v]and d[v]>d[u]+s[1]:
     d[v]=d[u]+s[1]
     heappush(H,[d[v],v])
 for i in range(n):print(i,d[i])
m()