Problem:


Single Source Shortest Path

  For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).

Input

An edge-weighted graph G (V, E) and the source r.

|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.

si and ti  represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.

Output

Print the costs of SSSP in the following format.

c0
c1
:
c|V|-1

The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF. 

Constraints

 1 ≤ |V| ≤ 100000

0 ≤ di ≤ 10000

 0 ≤ |E| ≤ 500000

 There are no parallel edges

 There are no self-loops

Sample Input 1

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

Sample Output 1

0
1
3
4

Sample Input 2

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

Sample Output 2

3
0
2
INF



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


Sample output:
0
1
3
4

Submission status: Accepted

Solution code:
from heapq import heapify, heappush, heappop
from collections import Counter, defaultdict, deque, OrderedDict
from sys import setrecursionlimit as setreclim
from sys import maxsize
from bisect import bisect_left, bisect, insort_left, insort
from math import ceil, log, factorial, hypot, pi
from fractions import gcd
from copy import deepcopy
from functools import reduce
from operator import mul
from itertools import product, permutations, combinations, accumulate, cycle
from string import ascii_uppercase, ascii_lowercase, ascii_letters, digits, hexdigits, octdigits
 
prod = lambda l: reduce(mul, l)
prodmod = lambda l, mod: reduce(lambda x, y: mul(x,y)%mod, l)
 
class Dijkstra:
    """Dijkstra's algorithm : find the shortest path from a vertex
       used in GRL1A(AOJ)
    """
 
    def __init__(self, V, E, start, INF=10**9):
        """ V: the number of vertexes
            E: adjacency list
            start: start vertex
            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 # distance from start
        self.prev = [-1] * self.V # prev vertex of shortest path
        self.distance[start] = 0
        heappush(que, (0, start))
 
        while len(que) > 0:
            dist, v = heappop(que)
            if self.distance[v] < dist: continue
            for to, cost in self.E[v]:
                if self.distance[v] + cost < self.distance[to]:
                    self.distance[to] = self.distance[v] + cost
                    heappush(que, (self.distance[to], to))
                    self.prev[to] = v
 
    def getPath(self, end):
        path = [end]
        while self.prev[end] != -1:
            end = self.prev[end]
        return path[::-1]
 
V, E, r = map(int, input().split())
INF = 10**10
edge = [[] for _ in range(V)]
for i in range(E):
    s, t, cost = map(int, input().split())
    edge[s].append((t, cost))
sp = Dijkstra(V, edge, r, INF)
for d in sp.distance:
    print(d if d != INF else 'INF')

Submission status: Accepted

Solution code:
import heapq


class Edge:
    def __init__(self, dst, weight):
        self.dst, self.weight = dst, weight

    def __lt__(self, e):
        return self.weight > e.weight


class Graph:
    def __init__(self, V):
        self.V = V
        self.E = [[] for _ in range(V)]

    def add_edge(self, src, dst, weight):
        self.E[src].append(Edge(dst, weight))


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

    def __init__(self, G, INF=10**9):
        """ V: the number of vertexes
            E: adjacency list (all edge in E must be 0 or positive)
            start: start vertex
            INF: Infinity distance
        """
        self.G, self.INF = G, INF

    class Node:
        def __init__(self, v, cost):
            self.v, self.cost = v, cost

        def __lt__(self, n):
            return self.cost < n.cost

    def dijkstra(self, start, goal=None):
        que = list()
        self.dist = [self.INF] * self.G.V  # distance from start
        self.dist[start] = 0
        heapq.heappush(que, self.Node(start, 0))

        while len(que) > 0:
            n = heapq.heappop(que)
            if self.dist[n.v] < n.cost:
                continue
            if goal is not None and n.v == goal:
                return
            for e in self.G.E[n.v]:
                if self.dist[n.v] + e.weight < self.dist[e.dst]:
                    self.dist[e.dst] = self.dist[n.v] + e.weight
                    heapq.heappush(que, self.Node(e.dst, self.dist[e.dst]))

V, E, start = map(int, input().split())
G = Graph(V)
for _ in range(E):
    s, t, d = map(int, input().split())
    G.add_edge(s, t, d)
INF = 10**9
sp = ShortestPath(G, INF)
sp.dijkstra(start)
for i in range(G.V):
    print("INF" if sp.dist[i] == INF else sp.dist[i])

Submission status: Accepted

Solution code:
import heapq


class Edge:
    def __init__(self, dst, weight):
        self.dst, self.weight = dst, weight

    def __lt__(self, e):
        return self.weight > e.weight


class Graph:
    def __init__(self, V):
        self.V = V
        self.E = [[] for _ in range(V)]

    def add_edge(self, src, dst, weight):
        self.E[src].append(Edge(dst, weight))


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

    def __init__(self, G, INF=10**9):
        """ V: the number of vertexes
            E: adjacency list (all edge in E must be 0 or positive)
            start: start vertex
            INF: Infinity distance
        """
        self.G, self.INF = G, INF

    class Node:
        def __init__(self, v, cost):
            self.v, self.cost = v, cost

        def __lt__(self, n):
            return self.cost < n.cost

    def dijkstra(self, start, goal=None):
        que = list()
        self.dist = [self.INF] * self.G.V  # distance from start
        self.prev = [-1] * self.G.V  # prev vertex of shortest path
        self.dist[start] = 0
        heapq.heappush(que, self.Node(start, 0))

        while len(que) > 0:
            n = heapq.heappop(que)
            if self.dist[n.v] < n.cost:
                continue
            if goal is not None and n.v == goal:
                return
            for e in self.G.E[n.v]:
                if self.dist[n.v] + e.weight < self.dist[e.dst]:
                    self.dist[e.dst] = self.dist[n.v] + e.weight
                    heapq.heappush(que, self.Node(e.dst, self.dist[e.dst]))
                    self.prev[e.dst] = n.v

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

V, E, start = map(int, input().split())
G = Graph(V)
for _ in range(E):
    s, t, d = map(int, input().split())
    G.add_edge(s, t, d)
INF = 10**9
sp = ShortestPath(G, INF)
sp.dijkstra(start)
for i in range(G.V):
    print("INF" if sp.dist[i] == INF else sp.dist[i])

Submission status: Accepted

Solution code:
import heapq


class Edge:
    def __init__(self, dst, weight):
        self.dst, self.weight = dst, weight

    def __lt__(self, e):
        return self.weight > e.weight


class Graph:
    def __init__(self, V):
        self.V = V
        self.E = [[] for _ in range(V)]

    def add_edge(self, src, dst, weight):
        self.E[src].append(Edge(dst, weight))


class Node:
    def __init__(self, v, cost):
        self.v, self.cost = v, cost

    def __lt__(self, n):
        return self.cost < n.cost


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

    def __init__(self, G, INF=10**9):
        """ V: the number of vertexes
            E: adjacency list (all edge in E must be 0 or positive)
            start: start vertex
            INF: Infinity distance
        """
        self.G, self.INF = G, INF

    def dijkstra(self, start, goal=None):
        que = list()
        self.dist = [self.INF] * self.G.V  # distance from start
        self.prev = [-1] * self.G.V  # prev vertex of shortest path
        self.dist[start] = 0
        heapq.heappush(que, Node(start, 0))

        while len(que) > 0:
            n = heapq.heappop(que)
            if self.dist[n.v] < n.cost:
                continue
            if goal is not None and n.v == goal:
                return
            for e in self.G.E[n.v]:
                if self.dist[n.v] + e.weight < self.dist[e.dst]:
                    self.dist[e.dst] = self.dist[n.v] + e.weight
                    heapq.heappush(que, Node(e.dst, self.dist[e.dst]))
                    self.prev[e.dst] = n.v

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

V, E, start = map(int, input().split())
G = Graph(V)
for _ in range(E):
    s, t, d = map(int, input().split())
    G.add_edge(s, t, d)
INF = 10**9
sp = ShortestPath(G, INF)
sp.dijkstra(start)
for i in range(G.V):
    print("INF" if sp.dist[i] == INF else sp.dist[i])

Submission status: Accepted

Solution code:
import heapq


class Edge:
    def __init__(self, dst, weight):
        self.dst, self.weight = dst, weight

    def __lt__(self, e):
        return self.weight > e.weight


class Graph:
    def __init__(self, V):
        self.V = V
        self.E = [[] for _ in range(V)]

    def add_edge(self, src, dst, weight):
        self.E[src].append(Edge(dst, weight))


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

    def __init__(self, G, INF=10**9):
        """ V: the number of vertexes
            E: adjacency list (all edge in E must be 0 or positive)
            start: start vertex
            INF: Infinity distance
        """
        self.G, self.INF = G, INF

    class Node:
        def __init__(self, v, cost):
            self.v, self.cost = v, cost

        def __lt__(self, n):
            return self.cost < n.cost

    def dijkstra(self, start, goal=None):
        que = list()
        self.dist = [self.INF] * self.G.V  # distance from start
        self.prev = [-1] * self.G.V  # prev vertex of shortest path
        self.dist[start] = 0
        heapq.heappush(que, (0, start))

        while len(que) > 0:
            cost, v = heapq.heappop(que)
            if self.dist[v] < cost:
                continue
            if goal is not None and v == goal:
                return
            for e in self.G.E[v]:
                if self.dist[v] + e.weight < self.dist[e.dst]:
                    self.dist[e.dst] = self.dist[v] + e.weight
                    heapq.heappush(que, (self.dist[e.dst], e.dst))
                    self.prev[e.dst] = v

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

V, E, start = map(int, input().split())
G = Graph(V)
for _ in range(E):
    s, t, d = map(int, input().split())
    G.add_edge(s, t, d)
INF = 10**9
sp = ShortestPath(G, INF)
sp.dijkstra(start)
for i in range(G.V):
    print("INF" if sp.dist[i] == INF else sp.dist[i])

Submission status: Accepted

Solution code:
from heapq import heapify, heappush, heappop
from collections import Counter, defaultdict, deque, OrderedDict
from sys import setrecursionlimit as setreclim
from sys import maxsize
from bisect import bisect_left, bisect, insort_left, insort
from math import ceil, log, factorial, hypot, pi
from fractions import gcd
from copy import deepcopy
from functools import reduce
from operator import mul
from itertools import product, permutations, combinations, accumulate, cycle
from string import ascii_uppercase, ascii_lowercase, ascii_letters, digits, hexdigits, octdigits
  
prod = lambda l: reduce(mul, l)
prodmod = lambda l, mod: reduce(lambda x, y: mul(x,y)%mod, l)
  
class Dijkstra:
    """Dijkstra's algorithm : find the shortest path from a vertex
       used in GRL1A(AOJ)
    """
  
    def __init__(self, V, E, start, INF=10**9):
        """ V: the number of vertexes
            E: adjacency list
            start: start vertex
            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 # distance from start
        self.distance[start] = 0
        heappush(que, (0, start))
  
        while len(que) > 0:
            dist, v = heappop(que)
            if self.distance[v] < dist: continue
            for to, cost in self.E[v]:
                if self.distance[v] + cost < self.distance[to]:
                    self.distance[to] = self.distance[v] + cost
                    heappush(que, (self.distance[to], to))
  
V, E, r = map(int, input().split())
INF = 10**10
edge = [[] for _ in range(V)]
for i in range(E):
    s, t, cost = map(int, input().split())
    edge[s].append((t, cost))
sp = Dijkstra(V, edge, r, INF)
for d in sp.distance:
    print(d if d != INF else 'INF')

Submission status: Accepted

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

"""
input:
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5

output:
3
0
2
INF
"""

import sys
import heapq as hp
from math import isinf

WHITE, GRAY, BLACK = 0, 1, 2


def generate_adj_table(v_table):
    for each in v_table:
        source, target, cost = map(int, each)
        init_adj_table[source][target] = cost
    return init_adj_table


def dijkstra_path_heap():
    # path search init
    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:
        current = hp.heappop(path_heap)[1]

        color[current] = BLACK

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

    return distance


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices, edges, root = map(int, _input[0].split())
    v_info = map(lambda x: x.split(), _input[1:])
    # assert len(init_vertices_table) == vertices_num

    distance = [float('inf')] * vertices
    parents = [-1] * vertices
    color = [WHITE] * vertices
    init_adj_table = tuple(dict() for _ in range(vertices))

    adj_table = generate_adj_table(v_info)
    ans = dijkstra_path_heap()

    print('\n'.join(('INF' if isinf(ele) else str(ele) for ele in ans)))

Submission status: Accepted

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

"""
input:
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5

output:
3
0
2
INF
"""

import sys
import heapq as hp
from math import isinf

WHITE, GRAY, BLACK = 0, 1, 2


def generate_adj_table(v_table):
    for each in v_table:
        source, target, cost = map(int, each)
        init_adj_table[source][target] = cost
    return init_adj_table


def dijkstra_path_heap():
    # path search init
    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:
        current = hp.heappop(path_heap)[1]

        color[current] = BLACK

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

    return distance


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices, edges, root = map(int, _input[0].split())
    v_info = map(lambda x: x.split(), _input[1:])
    # assert len(init_vertices_table) == vertices_num

    distance = [float('inf')] * vertices
    parents = [-1] * vertices
    color = [WHITE] * vertices
    init_adj_table = tuple(dict() for _ in range(vertices))

    adj_table = generate_adj_table(v_info)
    ans = dijkstra_path_heap()

    # print('\n'.join(('INF' if isinf(ele) else str(ele) for ele in ans)))
    for ele in ans:
        if isinf(ele):
            print("INF")
        else:
            print(ele)

Submission status: Accepted

Solution code:
import heapq

maxd = float('inf')
nv, ne, r = [int(n) for n in input().split(' ')]
vertices = {k: {} for k in range(nv)}
for i in range(ne):
    s, t, w = [int(n) for n in input().split(' ')]
    vertices[s][t] = w

q = []
heapq.heappush(q, (0, r))

dist = {v: maxd for v in vertices}
dist[r] = 0

while len(q):
    u = heapq.heappop(q)[1]

    for v in vertices[u]:
        alt = dist[u] + vertices[u][v]
        if alt < dist[v]:
            dist[v] = alt
            heapq.heappush(q, (alt, v))

[print(d) if d < maxd else print("INF") for v, d in dist.items()]

Submission status: Accepted

Solution code:
import heapq

nv, ne, r = map(int, input().split(' '))
vertices = [[] for i in range(nv)]
for i in range(ne):
    s, t, w = map(int, input().split(' '))
    vertices[s].append((t, w))

q = []
heapq.heappush(q, (0, r))

dist = [float('inf')] * nv
dist[r] = 0

while len(q):
    u = heapq.heappop(q)[1]

    for t, w in vertices[u]:
        alt = dist[u] + w
        if alt < dist[t]:
            dist[t] = alt
            heapq.heappush(q, (alt, t))

[print(d) if d < float('inf') else print("INF") for d in dist]

Submission status: Accepted

Solution code:
from collections import defaultdict

def main():
    #Read stdin
    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    #Adjacency list
    G = defaultdict(list)
    for i in range(int(E)):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s].append((t,w))

    #initialized
    d = {}
    INF = float('inf')
    #INF = 20000
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = [R]
    while q:
        u = q.pop(0)
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]
                q.append(v[0])

    for k in d.keys():
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

from collections import defaultdict
from heapq import heappush, heappop

def main():
    #Read stdin
    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    #Adjacency list
    G = defaultdict(list)
    for i in range(int(E)):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s].append((t,w))

    #initialized
    d = {}
    INF = float('inf')
    #INF = 10001
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = [R]
    while q:
        u = heappop(q)
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]
                heappush(q, v[0])

    for k in d.keys():
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

from collections import defaultdict
from heapq import heappush, heappop

def main():
    #Read stdin
    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    #Adjacency list
    G = defaultdict(list)
    for i in range(int(E)):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s].append((t,w))

    #initialized
    d = {}
    INF = float('inf')
    #INF = 10001
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = [R]
    while q:
        #u = heappop(q)
        u = q.pop(0)
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]
                #heappush(q, v[0])
                q.append(v[0])


    for k in d.keys():
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict

def main():
    #Read stdin
    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    #Adjacency list
    G = defaultdict(list)
    for i in range(int(E)):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s].append((t,w))

    #initialized
    d = {}
    INF = float('inf')
    #INF = 10001
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = [R]
    while q:
        u = q.pop(0)
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]
                q.append(v[0])



    for k in d.keys():
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict

def main():
    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    #Adjacency list
    G = defaultdict(dict)
    for i in range(int(E)):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s][t] = w
    #initialized
    d = {}
    INF = float('inf')
    #INF = 10001
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = [R]
    while q:
        u = q.pop(0)
        for v in G[u].keys():
            if d[v] > d[u] + G[u][v]:
                d[v] = d[u] + G[u][v]
                q.append(v)

    for k in range(V):
        if d[k] == float('inf'):
            
            print("INF")
        else:
            print(d[k])



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!usr/bin/env python3

from collections import defaultdict


def main():
    #Read stdin

    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    #Adjacency list
    G = defaultdict(list)
    for i in range(int(E)):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s].append((t,w))
    #initialized
    d = {}
    INF = float('inf')
    #INF = 10001
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = [R]
    while q:
        u = q.pop(0)
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]

                q.append(v[0])

    for k in range(V):
        if d[k] == float('inf'):
            
            print("INF")
        else:
            print(d[k])



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
#import time

def main():
    # Read stdin
    #start = time.clock()
    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    # Adjacency list
    G = defaultdict(list)
    for i in range(int(E)):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s].append((t, w))
    # initialized
    d = {}
    INF = float('inf')
    # INF = 10001
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = deque([R])
    while q:
        # u = heappop(q)
        u = q.popleft()
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]
                # heappush(q, v[0])
                q.append(v[0])
    #end = time.clock() - start
    for k in range(V):
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])
    #print('Computation time : {}'.format(end))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

from collections import defaultdict
from collections import deque
#import time

def main():
    # Read stdin
    #start = time.clock()
    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    # Adjacency list
    G = defaultdict(dict)
    for i in range(E):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s][t] = w
    # initialized
    d = {}
    INF = float('inf')
    # INF = 10001
    for i in range(V):
        d[i] = INF
    d[R] = 0
    # deque is better than list aka double link list O(1) for pop head and append
    q = deque([R])
    while q:
        # u = heappop(q)
        u = q.popleft()
        for v in G[u].keys():
            if d[v] > d[u] + G[u][v]:
                d[v] = d[u] + G[u][v]
                # heappush(q, v[0])
                q.append(v)
    #end = time.clock() - start
    for k in range(V):
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])
    #print('Computation time : {}'.format(end))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!usr/bin/env python3

'''
time score 7.88 for list
time score 03.17 for deque
time score 03.22 for defaultdict(dict)

''' 

from collections import defaultdict
from collections import deque
#import time

def main():
    # Read stdin
    #start = time.clock()
    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    # Adjacency list
    G = defaultdict(list)
    for i in range(E):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s].append((t, w))
    # initialized
    d = {}
    INF = float('inf')
    # INF = 10001
    for i in range(V):
        d[i] = INF
    d[R] = 0
    # deque is better than list aka double link list O(1) for pop head and append
    q = deque([R])
    while q:
        # u = heappop(q)
        u = q.popleft()
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]
                # heappush(q, v[0])
                q.append(v[0])
    #end = time.clock() - start
    for k in d.keys():
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])
    #print('Computation time : {}'.format(end))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!usr/bin/env python3

'''
time score 7.88 for list
time score 03.17 for deque
time score 03.22 for defaultdict(dict)

''' 

from collections import defaultdict
from collections import deque
#import time

def main():
    # Read stdin
    #start = time.clock()
    fl = input().split(" ")
    V = int(fl[0])
    E = int(fl[1])
    R = int(fl[2])
    # Adjacency list
    G = defaultdict(list)
    for i in range(E):
        s, t, w = [int(x) for x in input().split(" ")]
        G[s].append((t, w))
    # initialized
    d = {}
    INF = float('inf')
    # INF = 10001
    nodes_list = range(V)
    for i in nodes_list:
        d[i] = INF
    d[R] = 0
    # deque is better than list aka double link list O(1) for pop head and append
    q = deque([R])
    while q:
        # u = heappop(q)
        u = q.popleft()
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]
                # heappush(q, v[0])
                q.append(v[0])
    for k in nodes_list:
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])
    #end = time.clock() - start
    #print('Computation time : {}'.format(end))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
from sys import stdin

def sp(G,R,V):
    d = {}
    INF = float('inf')
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = deque([(R)])
    while q:
        u = q.popleft()
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]
                q.append(v[0])
    return d


V, E, R = tuple(int(x) for x in stdin.readline().split(' '))
G = defaultdict(list)
for case in range(E):
    s, t, w = tuple(int(x) for x in stdin.readline().split(' '))
    G[s].append((t,w))
d = sp(G, R, V)
for k in range(V):
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
from sys import stdin


def sp(G,R,V):
    d = {}
    INF = float('inf')
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = deque([(R)])
    while q:
        u = q.popleft()
        for v in G[u]:
            if d[v[0]] > d[u] + v[1]:
                d[v[0]] = d[u] + v[1]
                q.append(v[0])
    return d


V, E, R = [int(x) for x in stdin.readline().split(' ')]
G = defaultdict(list)
for case in range(E):
    s, t, w = [int(x) for x in stdin.readline().split(' ')]
    G[s].append((t,w))
d = sp(G, R, V)
for k in range(V):
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
from sys import stdin


def sp(G,R,V):
    d = {}
    INF = float('inf')
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = deque([(R)])
    while q:
        u = q.popleft()
        for v in G[u].keys():
            if d[v] > d[u] + G[u][v]:
                d[v] = d[u] + G[u][v]
                q.append(v)
    return d


V, E, R = [int(x) for x in stdin.readline().split(' ')]
G = defaultdict(dict)
for case in range(E):
    s, t, w = [int(x) for x in stdin.readline().split(' ')]
    G[s][t] = w
d = sp(G, R, V)
for k in range(V):
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
from sys import stdin

def sp(G,R,V):
    d = {}
    INF = float('inf')
    for i in range(V):
        d[i] = INF
    d[R] = 0
    q = deque([(R)])
    while q:
        u = q.popleft()
        for v in G[u].keys():
            if d[v] > d[u] + G[u][v]:
                d[v] = d[u] + G[u][v]
                q.append(v)
    return d


V, E, R = [int(x) for x in stdin.readline().split()]
G = defaultdict(dict)
for case in range(E):
    s, t, w = [int(x) for x in stdin.readline().split()]
    G[s][t] = w
d = sp(G, R, V)
for k in range(V):
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])

Submission status: Accepted

Solution code:
from collections import defaultdict
import heapq

vertice,edge,source = map(int,input().split(" "))
link = defaultdict(dict)
weight = defaultdict(dict)
answer = [-1] * vertice
for e in range(edge):
    i,j,w = map(int,input().split(" "))
    link[i] = link.get(i,set()) | {j}
    weight[i].update({j:w})
queue = []
heapq.heappush(queue,(0,source))
heapq.heapify(queue)
while queue:
    #print(queue)
    now_cost,here = heapq.heappop(queue)
    #print(now_cost,here,queue)
    if answer[here] > -1:
        continue
    answer[here] = now_cost

    #print(v,here,now_cost,not_went,queue)
    for nw in link[here]:
        if answer[nw] == -1:
            heapq.heappush(queue,(now_cost + weight[here][nw],nw))

for a in answer:
    print(a if a != -1 else "INF")