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: Wrong Answer

Solution code:
v,e,r = map(int,input().split())
d = [float('inf')]*v
d[r] = 0
edges=[[]for i in range(v)]

for i in range(e):
  s,t,c = map(int,input().split())
  edges[s].append([t,c])

for i in range(v):
  min_d = 10**9
  if d[i] < min_d:
    dmin = d[i]
    u = d.index(dmin)
    for v,c in edges[u]:
      if d[v] > d[u]+c:
        d[v] = d[u]+c

for i in d:
  print(i)

Submission status: Wrong Answer

Solution code:
v,e,r = map(int,input().split())
d = [float('INF')]*v
d[r] = 0
edges=[[]for i in range(v)]

for i in range(e):
  s,t,c = map(int,input().split())
  edges[s].append([t,c])

for i in range(v):
  min_d = 10**9
  if d[i] < min_d:
    dmin = d[i]
    u = d.index(dmin)
    for v,c in edges[u]:
      if d[v] > d[u]+c:
        d[v] = d[u]+c

for i in d:
  if i == float('inf'):
    print('INF')
  else:
    print(i)

Submission status: Wrong Answer

Solution code:
v,e,r = map(int,input().split())
d = [float('INF')]*v
d[r] = 0
edges=[[]for i in range(v)]
visited = [False]*v

for i in range(e):
  s,t,c = map(int,input().split())
  edges[s].append([t,c])

for i in range(v):
  min_d = 10**9
  if d[i] < min_d:
    dmin = d[i]
    min_d = d[i]
    u = i
    visited[u] = True
    for v,c in edges[u]:
      if d[v] > d[u]+c:
        d[v] = d[u]+c

for i in d:
  if i == float('inf'):
    print('INF')
  else:
    print(i)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
v,e,r = map(int,input().split())
edges=[[] for i in range(v)]
d = [float('INF')]*v

for i in range(e):
  s,t,c = map(int,input().split())
  edges.append([t,c])

que = []
heappush(que,(0,r))
d[r] = 0

while que:
  c, u = heappop(que)
  for v, s in edges[u]:
    if d[v] > s + c:
      d[v] = s + c
      heappush(que,(d[v],v))
for i in d:
  if i == float('inf'):
    print('INF')
  else:
    print(i)

Submission status: Wrong Answer

Solution code:
# AOJ GRL_1_A
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_A

from heapq import heappush, heappop

INF = 100000000

def solve(r, v, dic):
    dp = []
    q = []
    dp = [INF] * v
    dp[r] = 0
    heappush(q, (0, r))
    while q:
        cost, vtx = heappop(q)
        if dp[vtx] < cost:
            continue
        if vtx not in dic:
            continue
        for vtx1, cost1 in dic[vtx]:
            if cost + cost1 < dp[vtx1]:
                dp[vtx1] = cost + cost1
                heappush(q, (cost + cost1, vtx1))
    return dp

dic = {}
dp = []
line = input()
v, e, r = list(map(int, line.split()))
for _ in range(0, e):
    line = input()
    s, t, d = list(map(int, line.split()))
    if s not in dic:
        dic[s] = [[t, d]]
    else:
        dic[s] += [[t, d]]
dp = solve(r, v, dic)
for t in range(0, v):
    print(dp[t] if dp[t] != INF else "INF")

Submission status: Wrong Answer

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK
    
    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """        
    def __init__(self):
        """ 重み付き有向辺 
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい
        """
        self.edges = {}  # edges[(u,v)] = cost := 辺(u,v)のコストcost
        self.v_set = set()  # 頂点の集合

    @property
    def E(self):
        """ 辺数 
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return len(self.edges)
    
    @property
    def V(self):
        """ 頂点数 """
        return len(self.v_set)
    
    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.edges[(_from, _to)] = _cost
        self.v_set.add(_from)
        self.v_set.add(_to)
        
    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す 
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短路
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [float("inf")] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # (最短距離, 頂点の番号)をヒープに追加する

        while len(que) != 0:
            prov_cost, v = heapq.heappop(que)
            # キューに格納されている最短距離が、現在計算できている最短距離より大きければ、dの更新をする必要はない
            if d[v] < prov_cost: continue

            # 他の頂点の探索
            for i in range(self.V):
                if not (v,i) in self.edges: continue

                cost = self.edges[(v,i)]  # vからiへのコスト
                if d[i] > d[v] + cost:
                    d[i] = d[v] + cost # dの更新
                    heapq.heappush(que, (d[i], i)) # キューに新たな仮の距離の情報をpush
        return d


if __name__ == "__main__":
    djk = Dijkstra()
    V, E, s = list(map(int, input().split()))
    if E == 0:
        print(0)
        exit()
    
    for i in range(E):
        _from, to, cost = list(map(int, input().split()))
        djk.add(_from, to, cost)

    d = djk.shortest_path(s)
    
    for cost in d:
        if cost == float("inf"):
            print("INF")
        else:
            print(cost)

Submission status: Wrong Answer

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK
    
    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """        
    def __init__(self):
        """ 重み付き有向辺 
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい
        """
        self.edges = {}  # edges[(u,v)] = cost := 辺(u,v)のコストcost
        self.v_set = set()  # 頂点の集合

    @property
    def E(self):
        """ 辺数 
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return len(self.edges)
    
    @property
    def V(self):
        """ 頂点数 """
        return len(self.v_set)
    
    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.edges[(_from, _to)] = _cost
        self.v_set.add(_from)
        self.v_set.add(_to)
        
    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す 
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短路
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [float("inf")] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # (最短距離, 頂点の番号)をヒープに追加する

        while len(que) != 0:
            prov_cost, v = heapq.heappop(que)
            # キューに格納されている最短距離が、現在計算できている最短距離より大きければ、dの更新をする必要はない
            if d[v] < prov_cost: continue

            # 他の頂点の探索
            for i in range(self.V):
                if not (v,i) in self.edges: continue

                cost = self.edges[(v,i)]  # vからiへのコスト
                if d[i] > d[v] + cost:
                    d[i] = d[v] + cost # dの更新
                    heapq.heappush(que, (d[i], i)) # キューに新たな仮の距離の情報をpush
        return d


if __name__ == "__main__":
    djk = Dijkstra()
    V, E, s = list(map(int, input().split()))
    if V == 1:
        print(0)
        exit()
        
    if E == 0:
        for i in range(V-1):
            djk.add(i, i+1, float("INF"))
    else:
        for i in range(E):
            _from, to, cost = list(map(int, input().split()))
            djk.add(_from, to, cost)

    d = djk.shortest_path(s)
    
    for cost in d:
        if cost == float("inf"):
            print("INF")
        else:
            print(cost)

Submission status: Wrong Answer

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK
    
    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """        
    def __init__(self, V=None):
        """ 重み付き有向辺 
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点数
                    - 頂点数が与えられたときは、すべての辺をINFで初期化する
        """
        self.edges = {}  # edges[(u,v)] = cost := 辺(u,v)のコストcost
        self.v_set = set()  # 頂点の集合

        if V is not None:
            for u in range(V):
                for v in range(V):
                    self.edges[(u,v)] = float("INF")

    @property
    def E(self):
        """ 辺数 
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return len(self.edges)
    
    @property
    def V(self):
        """ 頂点数 """
        return len(self.v_set)
    
    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.edges[(_from, _to)] = _cost
        self.v_set.add(_from)
        self.v_set.add(_to)
        
    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す 
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短路
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [float("inf")] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # (最短距離, 頂点の番号)をヒープに追加する

        while len(que) != 0:
            prov_cost, v = heapq.heappop(que)
            # キューに格納されている最短距離が、現在計算できている最短距離より大きければ、dの更新をする必要はない
            if d[v] < prov_cost: continue

            # 他の頂点の探索
            for i in range(self.V):
                if not (v,i) in self.edges: continue

                cost = self.edges[(v,i)]  # vからiへのコスト
                if d[i] > d[v] + cost:
                    d[i] = d[v] + cost # dの更新
                    heapq.heappush(que, (d[i], i)) # キューに新たな仮の距離の情報をpush
        return d


if __name__ == "__main__":
    djk = Dijkstra()
    V, E, s = list(map(int, input().split()))
    if V == 1:
        print(0)
        exit()
        
    if E == 0:
        for i in range(V-1):
            djk.add(i, i+1, float("INF"))
    else:
        for i in range(E):
            _from, to, cost = list(map(int, input().split()))
            djk.add(_from, to, cost)

    d = djk.shortest_path(s)
    
    for cost in d:
        if cost == float("inf"):
            print("INF")
        else:
            print(cost)

Submission status: Wrong Answer

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK
    
    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """        
    def __init__(self, V=None):
        """ 重み付き有向辺 
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点数
                    - 頂点数が与えられたときは、すべての辺をINFで初期化する
        """
        self.edges = {}  # edges[(u,v)] = cost := 辺(u,v)のコストcost
        self.v_set = set()  # 頂点の集合

        if V is not None:
            for u in range(V):
                for v in range(V):
                    self.edges[(u,v)] = float("INF")

    @property
    def E(self):
        """ 辺数 
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return len(self.edges)
    
    @property
    def V(self):
        """ 頂点数 """
        return len(self.v_set)
    
    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.edges[(_from, _to)] = _cost
        self.v_set.add(_from)
        self.v_set.add(_to)
        
    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す 
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短路
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [float("inf")] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # (最短距離, 頂点の番号)をヒープに追加する

        while len(que) != 0:
            prov_cost, v = heapq.heappop(que)
            # キューに格納されている最短距離が、現在計算できている最短距離より大きければ、dの更新をする必要はない
            if d[v] < prov_cost: continue

            # 他の頂点の探索
            for i in range(self.V):
                if not (v,i) in self.edges: continue

                cost = self.edges[(v,i)]  # vからiへのコスト
                if d[i] > d[v] + cost:
                    d[i] = d[v] + cost # dの更新
                    heapq.heappush(que, (d[i], i)) # キューに新たな仮の距離の情報をpush
        return d


if __name__ == "__main__":
    V, E, s = list(map(int, input().split()))
    djk = Dijkstra(V)
    if V == 1:
        print(0)
        exit()
        
    if E == 0:
        for i in range(V-1):
            djk.add(i, i+1, float("INF"))
    else:
        for i in range(E):
            _from, to, cost = list(map(int, input().split()))
            djk.add(_from, to, cost)

    d = djk.shortest_path(s)
    
    for cost in d:
        if cost == float("inf"):
            print("INF")
        else:
            print(cost)

Submission status: Wrong Answer

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK
    
    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """        
    def __init__(self, V=None):
        """ 重み付き有向辺 
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点数
                    - 頂点数が与えられたときは、すべての辺をINFで初期化する
        """
        self.edges = {}  # edges[(u,v)] = cost := 辺(u,v)のコストcost
        self.v_set = set()  # 頂点の集合

        if V is not None:
            for u in range(V):
                for v in range(V):
                    self.edges[(u,v)] = float("INF")

    @property
    def E(self):
        """ 辺数 
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return len(self.edges)
    
    @property
    def V(self):
        """ 頂点数 """
        return len(self.v_set)
    
    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.edges[(_from, _to)] = _cost
        self.v_set.add(_from)
        self.v_set.add(_to)
        
    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す 
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短路
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [float("inf")] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # (最短距離, 頂点の番号)をヒープに追加する

        while len(que) != 0:
            prov_cost, v = heapq.heappop(que)
            # キューに格納されている最短距離が、現在計算できている最短距離より大きければ、dの更新をする必要はない
            if d[v] < prov_cost: continue

            # 他の頂点の探索
            for i in range(self.V):
                if not (v,i) in self.edges: continue

                cost = self.edges[(v,i)]  # vからiへのコスト
                if d[i] > d[v] + cost:
                    d[i] = d[v] + cost # dの更新
                    heapq.heappush(que, (d[i], i)) # キューに新たな仮の距離の情報をpush
        return d


if __name__ == "__main__":
    V, E, s = list(map(int, input().split()))
    djk = Dijkstra()
    if V == 1:
        print(0)
        exit()
        
    if E == 0:
        for i in range(V-1):
            djk.add(i, i+1, float("INF"))
    else:
        for i in range(E):
            _from, to, cost = list(map(int, input().split()))
            djk.add(_from, to, cost)

    d = djk.shortest_path(s)
    
    for i in range(V):
        if i >= len(d):
            print("INF")
            continue

        cost = d[i]
        if cost == float("inf"):
            print("INF")
        else:
            print(cost)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import Queue
INF = 1000000

# ?¨??????\???????????\????????¢?????§????????????
# |V| |E|
# ai bi wi
V,E,r = map(int,raw_input().split())
edges = [[] for i in range(V)]	# ??£??\?????????

for i in xrange(E):
	a,b,w = map(int,raw_input().split())
	edges[a].append({'to':b,'weight':w})
	# edges[b].append({'to':a,'weight':w})

distance = [INF] * V
visited = [False] * V

distance[r] = 0
pq = Queue.PriorityQueue()
pq.put((0,r))
while not pq.empty():
	d,v = pq.get()
	visited[v] = True
	for e in edges[v]:
		if visited[e['to']] or distance[v]+e['weight'] > distance[e['to']]: continue
		distance[e['to']] = distance[v] + e['weight']
		pq.put((d+e['weight'],e['to']))

for d in distance:
	if d >= INF:
		print "INF"
	else:
		print d

# for i in range(V):
# 	min_v = -1
# 	for v in range(V):
# 		if not visited[v] and (min_v == -1 or distance[v] < distance[min_v]):
# 			min_v = v

# 	visited[min_v] = True
# 	for e in edges[min_v]:
# 		distance[e['to']] = min(distance[min_v] + e['weight'],distance[e['to']])

# for d in distance:
# 	if d >= INF:
# 		print "INF"
# 	else:
# 		print d

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# dijkstra algorithm
import heapq

v,e,r = map(int,raw_input().split())
adjacent = [[[2<<31,i,j] for j in range(v)] for i in range(v)]
for i in range(e):
    s,t,d = map(int,raw_input().split())
    adjacent[s][t]=[d,s,t]
for i in range(v):
    adjacent[i][i]=[0,i,i]

C = adjacent[r]  # cost table
S = []
for item in C:
    heapq.heappush(S,item)
visited = [r]
while S!= []:
    w = heapq.heappop(S)
    if w[2] not in visited:
        visited.append(w[2])
        for item in adjacent[w[2]]:
            heapq.heappush(S,item)
        for v in S:
            C[v[2]][0] = min(C[v[2]][0], C[v[1]][0]+adjacent[v[1]][v[2]][0]) 
        
for k in C:
    if k[0]==2<<31:
        print 'INF'
    else:    
        print k[0]

Submission status: Wrong Answer

Solution code:
INF = 1000000000
class Edge:
	def __init__(self, to, cost):
		self.to = to
		self.cost = cost


def dijkstra(graph, start):
	V = len(graph)
	d = [INF for _ in xrange(V)]
	d[start] = 0

	done = [False for _ in xrange(V)]
	while True:
		mini = INF
		min_i = -1
		for i, node in enumerate(graph):
			if done[i] == False:
				if d[i] < mini:
					min_i = i
					mini = d[i]

		print min_i
			
		if min_i == -1:
			return d
			
		done[min_i] = True
			
		node = graph[min_i]
		for edge in node:
			if d[min_i] + edge.cost < d[edge.to]:
				d[edge.to] = d[min_i] + edge.cost

def main():
	V, E, r = map(int, raw_input().split())

	graph = [[] for _ in xrange(V)]
	for i in xrange(E):
		_s, _t, _c = map(int, raw_input().split())
		graph[_s].append(Edge(_t, _c))


	distance = dijkstra(graph, r)
	for d in distance:
		if d == INF:
			print "INF"
		else:
			print d




if __name__ == '__main__':
	main()

Submission status: Wrong Answer

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

class UnionFindSet:
	def __init__(self, nodes):
		self.fa = {}
		for n in nodes:
			self.fa[n] = n

	def find(self, x):
		if self.fa[x] == x:
			return x
		else:
			self.fa[x] = self.find(self.fa[x])
			return self.fa[x]

	def union(self, x, y):
		fx = self.find(x)
		fy = self.find(y)
		if fx == fy:
			return fx
		else:
			self.fa[fx] = fy
			return fy


"""
graph is a hash
graph["nodes"] is a list of all nodes in the graph
graph["edges"] is a list of all edges in the graph in (x, y, w) form
  - x is the first nodes
  - y is the second nodes
  - w is the weight of the edges
graph["relation"] is the graph relation of the graph
"""

def kruscal(graph):
	"kruscal minimum spanning tree algorithm"
	ufset = UnionFindSet(graph["nodes"])

	ret = 0

	for (x, y, w) in sorted(graph["edges"], key = lambda x: x[-1]):
		fx = ufset.find(x)
		fy = ufset.find(y)
		if fx != fy:
			ret += w
			ufset.union(fx, fy)
		else:
			pass
	return ret


def dijkstra(graph, root):
	dis, vis = {}, {}
	for n in graph["nodes"]:
		dis[n] = 10 ** 9
		vis[n] = False

	heap = []
	dis[root] = 0
	heappush(heap, root)

	while heap:
		n = heappop(heap)
		vis[n] = True
		for (y, w) in graph["adj"][n]:
			if not vis[y]:
				dis[y] = min(dis[y], dis[n] + w)
				heappush(heap, y)

	return dis

if __name__ == '__main__':
	V, E, root = map(int, raw_input().strip().split())
	graph = {}
	graph["nodes"] = [i for i in range(V)]
	graph["edges"] = []
	graph["adj"] = defaultdict(list)
	for _ in range(E):
		x, y, w = map(int, raw_input().strip().split())
		graph["edges"].append((x, y, w))
		graph["adj"][x].append((y, w))

	dis = dijkstra(graph, root)

	for n in graph["nodes"]:
		print dis[n] if dis[n] < 10 ** 9 else "INF"

Submission status: Wrong Answer

Solution code:
from Queue import PriorityQueue
INF = 1<<29
v, e, r = map(int, raw_input().split())
edge = [[] for i in range(v)]
for i in xrange(e):
    a, b, w = map(int, raw_input().split())
    edge[a].append((b,w))
q = PriorityQueue()
q.put((0,r))
dist = [INF]*v
visited = [False]*v
dist[r] = 0
while not q.empty():
    d, V = q.get()
    visited[V] = True
    for t, w in edge[V]:
        if visited[t] or dist[t] < d + w: continue
        dist[t] = d + w
        q.put((d + w, t))
for i in dist:
    print "INF" if i == INF else i

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python
from collections import defaultdict
import sys,csv,math,heapq
if sys.version_info[0]>=3: raw_input=input
INF=1<<29

def shortestPath(g,s,dist,prev):
	n = len(g)
	dist[s] = 0
	Q=[]
	heapq.heappush(Q,(0,-2,s))
	while Q:
		e=heapq.heappop(Q)
		if prev[e[2]]!=-1: continue
		prev[e[2]]=e[1]
		for f in g[e[2]]:
			if dist[f[2]]>e[0]+f[0]:
				dist[f[2]]=e[0]+f[0]
				heapq.heappush(Q,(e[0]+f[0],f[1],f[2]))

V,E,R=map(int,raw_input().split())
dist=[INF]*V
prev=[-1]*V
G=defaultdict(list)
for _ in range(E):
	s,t,d=map(int,raw_input().split())
	G[s].append([d,s,t])
	G[s].append([d,t,s])
shortestPath(G,R,dist,prev)
for e in dist:
	print('INF' if e==INF else e)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python
from collections import defaultdict
import sys,csv,math,heapq
if sys.version_info[0]>=3: raw_input=input
INF=1<<29

def shortestPath(g,s,dist,prev):
	n = len(g)
	dist[s] = 0
	Q=[]
	heapq.heappush(Q,(0,-2,s))
	while Q:
		e=heapq.heappop(Q)
		if prev[e[2]]!=-1: continue
		prev[e[2]]=e[1]
		for f in g[e[2]]:
			if dist[f[2]]>e[0]+f[0]:
				dist[f[2]]=e[0]+f[0]
				heapq.heappush(Q,(e[0]+f[0],f[1],f[2]))

V,E,R=map(int,raw_input().split())
dist=[INF]*V
prev=[-1]*V
G=defaultdict(list)
for _ in range(E):
	s,t,d=map(int,raw_input().split())
	G[s].append([d,s,t])
	G[s].append([d,t,s])
shortestPath(G,R,dist,prev)
for e in dist:
	print('INF' if e>=INF else e)

Submission status: Wrong Answer

Solution code:
import heapq

l = input().split()
V = int(l[0])
E = int(l[1])
r = int(l[2])

graph = [[0 if i==j else -1  for j in range(V)] for i in range(V)] # [[source, target, cost]]
for i in range(E):
    l = input().split()
    graph[int(l[0])][int(l[1])] = int(l[2])

heap = [(0,r)]
dist = [float("inf") for _ in range(V)]
visited = [False for _ in range(V)]
while heap:
    pop = heapq.heappop(heap)
    if dist[pop[1]] > pop[0]:
        dist[pop[1]] = pop[0]
    edges = [(w,i) for (i,w) in enumerate(graph[pop[1]]) if i != pop[1] and w > 0 and not visited[i]]
    for (weight, target) in edges:
        heapq.heappush(heap, (pop[0]+weight, target))
        visited[target] = True

for d in dist:
    if d == float("inf"):
        print("INF")
    else:
        print(d)

Submission status: Wrong Answer

Solution code:
import heapq

l = input().split()
V = int(l[0])
E = int(l[1])
r = int(l[2])

graph = [[0 if i==j else -1  for j in range(V)] for i in range(V)] # [[source, target, cost]]
for i in range(E):
    l = input().split()
    graph[int(l[0])][int(l[1])] = int(l[2])

heap = [(0,r)]
dist = [float("inf") for _ in range(V)]
visited = [False for _ in range(V)]
while heap:
    pop = heapq.heappop(heap)
    visited[pop[1]] = True
    if dist[pop[1]] > pop[0]:
        dist[pop[1]] = pop[0]
    edges = [(w,i) for (i,w) in enumerate(graph[pop[1]]) if i != pop[1] and w > 0 and not visited[i]]
    for (weight, target) in edges:
        heapq.heappush(heap, (pop[0]+weight, target))

for d in dist:
    if d == float("inf"):
        print("INF")
    else:
        print(d)

Submission status: Wrong Answer

Solution code:
import heapq

l = input().split()
V = int(l[0])
E = int(l[1])
r = int(l[2])

graph = [[0 if i==j else -1  for j in range(V)] for i in range(V)] # [[source, target, cost]]
for i in range(E):
    l = input().split()
    graph[int(l[0])][int(l[1])] = int(l[2])

heap = [(0,r)]
dist = [float("inf") for _ in range(V)]
visited = [False for _ in range(V)]
while heap:
    pop = heapq.heappop(heap)
    if dist[pop[1]] < pop[0]:
        continue
    dist[pop[1]] = pop[0]
    edges = [(w,i) for (i,w) in enumerate(graph[pop[1]]) if i != pop[1] and w > 0 and not visited[i]]
    for (weight, target) in edges:
        heapq.heappush(heap, (pop[0]+weight, target))
    print(dist)
    print(visited)
    print(heap)

for d in dist:
    if d == float("inf"):
        print("INF")
    else:
        print(d)

Submission status: Wrong Answer

Solution code:
import heapq

l = input().split()
V = int(l[0])
E = int(l[1])
r = int(l[2])

graph = [[0 if i==j else -1  for j in range(V)] for i in range(V)] # [[source, target, cost]]
for i in range(E):
    l = input().split()
    graph[int(l[0])][int(l[1])] = int(l[2])

heap = [(0,r)]
dist = [float("inf") for _ in range(V)]
visited = [False for _ in range(V)]
while heap:
    pop = heapq.heappop(heap)
    if dist[pop[1]] < pop[0]:
        continue
    dist[pop[1]] = pop[0]
    edges = [(w,i) for (i,w) in enumerate(graph[pop[1]]) if i != pop[1] and w > 0 and not visited[i]]
    for (weight, target) in edges:
        heapq.heappush(heap, (pop[0]+weight, target))

for d in dist:
    if d == float("inf"):
        print("INF")
    else:
        print(d)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3
inf = float('inf')

def inf_matrix(n):
    return [[inf for i in range(n)] for j in range(n)]

def sssp(r, w):
    V = len(w)
    result = inf_matrix(V)
    rest = list(range(V))
    rest.remove(r)
    var = [r]
    result[r][r] = 0

    while len(rest) > 0:
        costs = []
        for v in var:
            for res in rest:
                costs.append((result[r][v] + w[v][res], res))
        min_w, min_r = min(costs)
        if min_w == inf:
            break
        rest.remove(min_r)
        var.append(min_r)
        result[r][min_r] = min_w
        result[min_r][r] = min_w

    return result


def main():
    V, E, r = map(int, input().split())
    w = inf_matrix(V)
    for e in range(E):
        s, t, d = map(int, input().split())
        w[s][t] = w[t][s] = d

    result = sssp(r, w)
    for i in range(V):
        print(result[r][i])

main()

Submission status: Wrong Answer

Solution code:
maxd = 10001
nv, ne, r = [int(n) for n in input().split(' ')]
vertices = {}
for i in range(ne):
    s, t, w = [int(n) for n in input().split(' ')]
    if s in vertices:
        vertices[s][t] = w
    else:
        vertices[s] = {t: w}
    if t not in vertices:
        vertices[t] = {}

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

while len(q):
    min = maxd
    u = nv
    for v in q:
        if dist[v] <= min:
            min = dist[v]
            u = v

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

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

Submission status: Wrong Answer

Solution code:
maxd = 10001
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 = {v for v in vertices}
dist = {v: maxd for v in vertices}
dist[r] = 0

while len(q):
    min = maxd
    u = nv
    for v in q:
        if dist[v] <= min:
            min = dist[v]
            u = v

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

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

Submission status: Wrong Answer

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 = []
for v in vertices:
    heapq.heappush(q, (maxd, v))

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

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

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3

from collections import defaultdict
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))
    print(G)

    #initialized
    visited = []
    #unseen = [R]
    d = {}
    d[0] = 0
    q = [R]
    while q != []:
        u = q.pop(0)
        if u not in visited:
            for v in G[u]:
                if v[0] not in visited:
                    d[v[0]] = d[u] + v[1]
                    q.append(v[0])
            visited.append(u)

    for k in d.keys():
        print(d[k])

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3

'''This method compute single source shortest path and then out put the costs 
to reach each nodes.

|V| |E| r
s_0 t_0
...
s_|E|-1 t_|E|-1

Constraints
    1 ??? |V| ??? 100000
    0 ??? di ??? 10000
    0 ??? |E| ??? 500000
    There are no parallel edges
    There are no self-loops

Example

Input:
4 5 
0 1 
0 2 
1 2 
2 3 
1 3 

Output:
0
1
3
4
'''

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 = 20000
    for i in range(V):
        d[i] = INF
    d[0] = 0
    q = [R]
    while q:
        u = q.pop(0)
        for v in G[u]:
            if d[v[0]] > d[u] + 1:
                d[v[0]] = d[u] + v[1]
                q.append(v[0])

    for k in d.keys():
        if d[k] > 10000:
            print("INF")
        else:
            print(d[k])

if __name__ == '__main__':
    main()