Problem:


Single Source Shortest Path (Negative Edges)

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

If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value) which is reachable from the source r, print 

NEGATIVE CYCLE

in a line.

Otherwise, print

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| ≤ 1000

 0 ≤ |E| ≤ 2000

 -10000 ≤ di ≤ 10000

 There are no parallel edges

 There are no self-loops

Sample Input 1

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

Sample Output 1

0
2
-3
-1

Sample Input 2

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

Sample Output 2

NEGATIVE CYCLE

Sample Input 3

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

Sample Output 3

INF
0
-5
-3



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


Sample output:
0
2
-3
-1

Submission status: Wrong Answer

Solution code:
class BellmanFord:
    INF = int(1e18)
    N = -1
    edge = []
    
    def __init__(self, N):
        self.N = N
        
    def add_edge(self, frm, to, cost):
        self.edge.append((frm, to, cost));
        
    def add_bi_edge(self, a, b, cost):
        self.add_edge(a, b, cost)
        self.add_edge(b, a, cost)
    
    def calcD(self, start):
        D = [self.INF] * self.N
        D[start] = 0
        update, cnt = True, 0
        while update:
            update = False
            cnt = cnt + 1
            if cnt > self.N:
                return 'NegativeCycle'
            
            for frm, to, cost in self.edge:
                ncost = D[frm] + cost
                if ncost >= D[to]:
                    continue
                D[to] = ncost
                update = True
                
        return D

    
V, E, S = list(map(int, input().split()))
bf = BellmanFord(V)
for i in range(E):
    frm, to, cost = list(map(int, input().split()))
    bf.add_edge(frm, to, cost)
    

ans = bf.calcD(S)
if ans == 'NegativeCycle':
    print("NEGATIVE CYCLE")
else:
    for i in range(V):
        print ('INF' if ans[i] == bf.INF else ans[i])

Submission status: Wrong Answer

Solution code:
import sys

inf = sys.maxsize

def shortestPath(graph, s):
    n = len(graph)
    dist = [inf for _ in range(n)]
    dist[s] = 0

    for i in range(n):
        # すべての辺 u -> vについて
        for u in range(n):
            for v, cost in graph[u]:
                newDist = dist[u] + cost
                if newDist < dist[v]:
                    if i == n - 1:
                        return None
                    dist[v] = newDist
    return dist

def main():
    v, e, s = map(int, input().split())
    
    # 隣接リスト
    graph = [[] for _ in range(v)]
    
    for i in range(e):
        a, b, cost = map(int, input().split())
        graph[a].append((b, cost))
            
    c_dist = shortestPath(graph, s)

    if c_dist == None:
        print("NEGATIVE CYCLE")
    else:
        for d in c_dist:
            if d == inf:
                print("INF")
            else:
                print(d)
main()

Submission status: Wrong Answer

Solution code:
import sys

inf = 1e10

def shortestPath(graph, s):
    n = len(graph)
    dist = [inf for _ in range(n)]
    dist[s] = 0

    for i in range(n):
        # すべての辺 u -> vについて
        for u in range(n):
            for v, cost in graph[u]:
                newDist = dist[u] + cost
                if newDist < dist[v]:
                    if i == n - 1:
                        return None
                    dist[v] = newDist
    return dist

def main():
    v, e, s = map(int, input().split())
    
    # 隣接リスト
    graph = [[] for _ in range(v)]
    
    for i in range(e):
        a, b, cost = map(int, input().split())
        graph[a].append((b, cost))
            
    c_dist = shortestPath(graph, s)

    if c_dist == None:
        print("NEGATIVE CYCLE")
    else:
        for d in c_dist:
            if d == inf:
                print("INF")
            else:
                print(d)
main()

Submission status: Wrong Answer

Solution code:
import sys

inf = int(1e10)

def shortestPath(graph, s):
    n = len(graph)
    dist = [inf for _ in range(n)]
    dist[s] = 0

    for i in range(n):
        # すべての辺 u -> vについて
        for u in range(n):
            for v, cost in graph[u]:
                newDist = dist[u] + cost
                if newDist < dist[v]:
                    if i == n - 1:
                        return None
                    dist[v] = newDist
    return dist

def main():
    v, e, s = map(int, input().split())
    
    # 隣接リスト
    graph = [[] for _ in range(v)]
    
    for i in range(e):
        a, b, cost = map(int, input().split())
        graph[a].append((b, cost))
            
    c_dist = shortestPath(graph, s)

    if c_dist == None:
        print("NEGATIVE CYCLE")
    else:
        for d in c_dist:
            if d >= inf:
                print("INF")
            else:
                print(d)
main()

Submission status: Wrong Answer

Solution code:
import sys

inf = int(1e10)

def shortestPath(graph, s):
    n = len(graph)
    dist = [inf for _ in range(n)]
    dist[s] = 0

    for i in range(n):
        for u in range(n):
            for v, cost in graph[u]:
                newDist = dist[u] + cost
                if newDist < dist[v]:
                    if i == n - 1:
                        return None
                    dist[v] = newDist
    return dist

def main():
    v, e, s = map(int, input().split())
    
    graph = [[] for _ in range(v)]
    
    for i in range(e):
        a, b, cost = map(int, input().split())
        graph[a].append((b, cost))
            
    dist = shortestPath(graph, s)

    if not dist:
        print("NEGATIVE CYCLE")
    else:
        for d in dist:
            if d >= inf:
                print("INF")
            else:
                print(d)
main()

Submission status: Wrong Answer

Solution code:
import sys

inf = int(1e12)

def shortestPath(graph, s):
    n = len(graph)
    dist = [inf for _ in range(n)]
    dist[s] = 0

    for i in range(n):
        for u in range(n):
            for v, cost in graph[u]:
                newDist = dist[u] + cost
                if newDist < dist[v]:
                    if i == n - 1:
                        return None
                    dist[v] = newDist
    return dist

def main():
    v, e, s = map(int, input().split())
    
    graph = [[] for _ in range(v)]
    
    for i in range(e):
        a, b, cost = map(int, input().split())
        graph[a].append((b, cost))
            
    dist = shortestPath(graph, s)

    if not dist:
        print("NEGATIVE CYCLE")
    else:
        for d in dist:
            if d >= inf:
                print("INF")
            else:
                print(d)
main()

Submission status: Wrong Answer

Solution code:
import sys

inf = int(1e12)

def shortestPath(graph, s):
    n = len(graph)
    dist = [inf for _ in range(n)]
    dist[s] = 0

    for i in range(n):
        for u in range(n):
            for v, cost in graph[u]:
                newDist = dist[u] + cost
                if  newDist < dist[v]:
                    if i == n - 1:
                        return None
                    dist[v] = newDist
    return dist

def main():
    v, e, s = map(int, input().split())
    
    graph = [[] for _ in range(v)]
    
    for i in range(e):
        a, b, cost = map(int, input().split())
        graph[a].append((b, cost))
            
    dist = shortestPath(graph, s)

    if not dist:
        print("NEGATIVE CYCLE")
    else:
        for d in dist:
            if d >= inf / 2:
                print("INF")
            else:
                print(d)
main()

Submission status: Wrong Answer

Solution code:
import sys

inf = int(1e14)

def shortestPath(graph, s):
    n = len(graph)
    dist = [inf for _ in range(n)]
    dist[s] = 0

    for i in range(n):
        for u in range(n):
            for v, cost in graph[u]:
                newDist = dist[u] + cost
                if  newDist < dist[v]:
                    if i == n - 1:
                        return None
                    dist[v] = newDist
    return dist

def main():
    v, e, s = map(int, input().split())
    
    graph = [[] for _ in range(v)]
    
    for i in range(e):
        a, b, cost = map(int, input().split())
        graph[a].append((b, cost))
            
    dist = shortestPath(graph, s)

    if not dist:
        print("NEGATIVE CYCLE")
    else:
        for d in dist:
            if d >= inf / 2:
                print("INF")
            else:
                print(d)
main()

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappush, heappop


def bellman_ford(V, Edges, start):
    dis = {}
    
    for i in range(V): dis[i] = (1 << 30)
    
    dis[start] = 0
    
    for i in range(V):
        for a, b, w in Edges:
            if dis[a] + w < dis[b]:
                dis[b] = dis[a] + w
    
    for a, b, w in Edges:
        if dis[a] + w < dis[b]:
            return ('NEGATIVE CYCLE', dis)
    
    return ('No NEGATIVE CYCLE', dis)
    
    
if __name__ == '__main__':
    line = sys.stdin.readline()
    V, E, start = line.split()
    V, E, start = int(V), int(E), int(start)
    Es = []
    for i in range(E):
        line = sys.stdin.readline()
        a, b, w = line.split()
        a, b, w = int(a), int(b), int(w)
        Es.append((a,b,w))
        
    judge, dis = bellman_ford(V, Es, start)
    
    if judge == 'NEGATIVE CYCLE':
        sys.stdout.write(judge + '\n')
    else:
        for i in range(V):
            if dis[i] == (1 << 30):
                sys.stdout.write('INF\n')
            else:
                sys.stdout.write(str(dis[i]) + '\n')

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappush, heappop


def bellman_ford(V, Edges, start):
    dis = {}
    
    for i in range(V): dis[i] = (1 << 30)
    
    dis[start] = 0
    
    for i in range(V):
        for a, b, w in Edges:
            if dis[a] + w < dis[b]:
                dis[b] = dis[a] + w
    
    for a, b, w in Edges:
        if dis[a] + w < dis[b]:
            return ('NEGATIVE CYCLE', dis)
    
    return ('No NEGATIVE CYCLE', dis)
    
    
if __name__ == '__main__':
    line = sys.stdin.readline()
    V, E, start = line.split()
    V, E, start = int(V), int(E), int(start)
    Es = []
    for i in range(E):
        line = sys.stdin.readline()
        a, b, w = line.split()
        a, b, w = int(a), int(b), int(w)
        Es.append((a,b,w))
        
    judge, dis = bellman_ford(V, Es, start)
    
    if judge == 'NEGATIVE CYCLE':
        sys.stdout.write(judge + '\n')
    else:
        for i in range(V):
            if dis[i] > 20000000:
                sys.stdout.write('INF\n')
            else:
                sys.stdout.write(str(dis[i]) + '\n')

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappush, heappop


def bellman_ford(V, Edges, start):
    dis = {}
    
    for i in range(V): dis[i] = (1 << 30)
    
    dis[start] = 0
    
    for i in range(V):
        for a, b, w in Edges:
            if dis[a] != (1 << 30) and dis[a] + w < dis[b]:
                dis[b] = dis[a] + w
    
    for a, b, w in Edges:
        if dis[a] + w < dis[b]:
            return ('NEGATIVE CYCLE', dis)
    
    return ('No NEGATIVE CYCLE', dis)
    
    
if __name__ == '__main__':
    line = sys.stdin.readline()
    V, E, start = line.split()
    V, E, start = int(V), int(E), int(start)
    Es = []
    for i in range(E):
        line = sys.stdin.readline()
        a, b, w = line.split()
        a, b, w = int(a), int(b), int(w)
        Es.append((a,b,w))
        
    judge, dis = bellman_ford(V, Es, start)
    
    if judge == 'NEGATIVE CYCLE':
        sys.stdout.write(judge + '\n')
    else:
        for i in range(V):
            if dis[i] == (1 << 30):
                sys.stdout.write('INF\n')
            else:
                sys.stdout.write(str(dis[i]) + '\n')

Submission status: Wrong Answer

Solution code:
class BellmanFord:
    """Bellman-Ford algorithm : find the shortest path from a vertex
       Complexity: O(VE)
       used in GRL1A(AOJ)
    """

    def __init__(self, V, E, start, 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.V = V
        self.E = E
        self.bellman_ford(start, INF)

    def bellman_ford(self, start, INF):
        self.distance = [INF] * self.V # distance from start
        self.prev = [-1] * self.V # prev vertex of shortest path
        self.distance[start] = 0
        self.negativeCycle = False
        
        for i in range(V):
            update = False
            for v in range(V):
                for to, cost in self.E[v]:
                    if self.distance != INF and self.distance[v] + cost < self.distance[to]:
                        self.distance[to] = self.distance[v] + cost
                        self.prev[to] = v
                        update = True
                        if i == V - 1:
                            self.negativeCycle = True
            if update == False:
                break

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

    def hasNegativeCycle(self):
        return self.negativeCycle

V, E, r = map(int, input().split())
INF = 10**9
edge = [[] for _ in range(V)]
for _ in range(E):
    s, t, d = map(int, input().split())
    edge[s].append((t, d))

sp = BellmanFord(V, edge, r, INF)
if sp.hasNegativeCycle():
    print('NEGATIVE CYCLE')
else:
    print(*[dist if dist != INF else 'INF' for dist in sp.distance], sep='\n')

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from math import isinf

V, E, r = map(int, input().split())
vertices = [float('inf')] * V
vertices[r] = 0
edges = []
for i in range(E):
    s, t, d = map(int, input().split())
    edges.append((s, t, d))

for i in range(V - 1):
    for s, t, d in edges:
        if vertices[t] > vertices[s] + d:
            vertices[t] = vertices[s] + d

neg = False
for s, t, d in edges:
    if vertices[t] > vertices[s] + d:
        print("NEGATIVE CYCLE")
        neg = True

if not neg:
    for v in vertices:
        print('INF' if isinf(v) else v)

Submission status: Wrong Answer

Solution code:
import sys
INF = 1000000000

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


def bellman_ford(graph, start):
	V = len(graph)
	d = [INF for _ in xrange(V)]
	d[start] = 0
	
	for i in xrange(V-1):
		for i, node in enumerate(graph):
			for edge in node:
				if d[i] + edge.cost < d[edge.to]:
					d[edge.to] = d[i] + edge.cost

	for i, node in enumerate(graph):
		for edge in node:
			if d[i] + edge.cost < d[edge.to]:
				print "NEGATIVE CYCLE"
				sys.exit()

	return d




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 = bellman_ford(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
from sys import stdin

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):
	"dijkstra algorithm for single source shortest algorithm"
	dis, vis = {}, {}
	for n in graph["nodes"]:
		dis[n] = 10 ** 9
		vis[n] = False

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

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

	return dis

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

	dis[root] = 0

	# update for n - 1 times
	for _ in range(len(graph["nodes"]) - 1):
		for (x, y, w) in graph["edges"]:
			if dis[x] + w < dis[y]:
				dis[y] = dis[x] + w

	dis["negcicle"] = False
	for (x, y, _) in graph["edges"]:
		if dis[x] + w < dis[y]:
			dis["negcicle"] = True
	return dis

if __name__ == '__main__':
	V, E, root = map(int, stdin.readline().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, stdin.readline().strip().split())
		graph["edges"].append((x, y, w))
		graph["adj"][x].append((y, w))

	dis = belmanFord(graph, root)
	if dis["negcicle"]:
		print "NEGATIVE CYCLE"
	else:
		for n in graph["nodes"]:
			print dis[n]

Submission status: Wrong Answer

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

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):
	"dijkstra algorithm for single source shortest algorithm"
	dis, vis = {}, {}
	for n in graph["nodes"]:
		dis[n] = 10 ** 9
		vis[n] = False

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

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

	return dis

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

	dis[root] = 0

	# update for n - 1 times
	for _ in range(len(graph["nodes"]) - 1):
		for (x, y, w) in graph["edges"]:
			if dis[x] + w < dis[y]:
				dis[y] = dis[x] + w

	dis["negcicle"] = False
	for (x, y, _) in graph["edges"]:
		if dis[x] + w < dis[y]:
			dis["negcicle"] = True
	return dis

if __name__ == '__main__':
	V, E, root = map(int, stdin.readline().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, stdin.readline().strip().split())
		graph["edges"].append((x, y, w))
		graph["adj"][x].append((y, w))

	dis = belmanFord(graph, root)
	if dis["negcicle"]:
		print "NEGATIVE CYCLE"
	else:
		for n in graph["nodes"]:
			print dis[n] if dis[n] < 10 ** 9 else "INF"

Submission status: Wrong Answer

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

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):
	"dijkstra algorithm for single source shortest algorithm"
	dis, vis = {}, {}
	for n in graph["nodes"]:
		dis[n] = 10 ** 9
		vis[n] = False

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

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

	return dis

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

	dis[root] = 0

	# update for n - 1 times
	for _ in range(len(graph["nodes"]) - 1):
		for (x, y, w) in graph["edges"]:
			if dis[x] + w < dis[y]:
				dis[y] = dis[x] + w

	dis["negcicle"] = False
	for (x, y, w) in graph["edges"]:
		if dis[x] + w < dis[y]:
			dis["negcicle"] = True
	return dis

if __name__ == '__main__':
	V, E, root = map(int, stdin.readline().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, stdin.readline().strip().split())
		graph["edges"].append((x, y, w))
		graph["adj"][x].append((y, w))

	dis = belmanFord(graph, root)
	if dis["negcicle"]:
		print "NEGATIVE CYCLE"
	else:
		for n in graph["nodes"]:
			print dis[n] if dis[n] < 10 ** 9 else "INF"

Submission status: Wrong Answer

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

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):
	"dijkstra algorithm for single source shortest algorithm"
	dis, vis = {}, {}
	for n in graph["nodes"]:
		dis[n] = 10 ** 9
		vis[n] = False

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

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

	return dis

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

	dis[root] = 0

	# update for n - 1 times
	for _ in range(len(graph["nodes"]) - 1):
		for (x, y, w) in graph["edges"]:
			if dis[x] + w < dis[y]:
				dis[y] = dis[x] + w

	dis["negcicle"] = False
	for (x, y, w) in graph["edges"]:
		if dis[x] + w < dis[y]:
			dis["negcicle"] = True

	connect = set([root])
	que = deque([root])

	while que:
		n = que.popleft()
		for (y, _) in graph["adj"][n]:
			if not y in connect:
				connect.add(y)
				que.append(y)

	dis["con"] = connect
	return dis

if __name__ == '__main__':
	V, E, root = map(int, stdin.readline().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, stdin.readline().strip().split())
		graph["edges"].append((x, y, w))
		graph["adj"][x].append((y, w))

	dis = belmanFord(graph, root)

	print dis
	if dis["negcicle"]:
		print "NEGATIVE CYCLE"
	else:
		for n in graph["nodes"]:
			print dis[n] if dis[n] < 10 ** 9 and n in dis["con"] else "INF"

Submission status: Wrong Answer

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

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):
	"dijkstra algorithm for single source shortest algorithm"
	dis, vis = {}, {}
	for n in graph["nodes"]:
		dis[n] = 10 ** 9
		vis[n] = False

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

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

	return dis

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

	dis[root] = 0

	# update for n - 1 times
	for _ in range(len(graph["nodes"]) - 1):
		for (x, y, w) in graph["edges"]:
			if dis[x] + w < dis[y]:
				dis[y] = dis[x] + w

	dis["negcicle"] = False
	for (x, y, w) in graph["edges"]:
		if dis[x] + w < dis[y]:
			dis["negcicle"] = True

	connect = set([root])
	que = deque([root])

	while que:
		n = que.popleft()
		for (y, _) in graph["adj"][n]:
			if not y in connect:
				connect.add(y)
				que.append(y)

	dis["con"] = connect
	return dis

if __name__ == '__main__':
	V, E, root = map(int, stdin.readline().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, stdin.readline().strip().split())
		graph["edges"].append((x, y, w))
		graph["adj"][x].append((y, w))

	dis = belmanFord(graph, root)

	if dis["negcicle"]:
		print "NEGATIVE CYCLE"
	else:
		for n in graph["nodes"]:
			print dis[n] if dis[n] < 10 ** 9 and n in dis["con"] else "INF"

Submission status: Wrong Answer

Solution code:
INF = 1<<31
V, E, r = map(int, raw_input().split())
edge = [map(int, raw_input().split()) for i in range(E)]
dist = [INF]*V
dist[r] = 0
for i in xrange(V):
    for u, v, w in edge:
        if dist[u] != INF and dist[v] > dist[u] + w:
            dist[v] = dist[u] + w
            if i == V - 1: print "NEGATIVE CYCLE"
else:
    for i in dist: print "INF" if i == INF else i

Submission status: Wrong Answer

Solution code:
import heapq

nv, ne, r = map(int, input().split())

edges = [set() for _ in range(nv)]
costs = [None] * nv

while ne:
    s, t, d = map(int, input().split())
    edges[s].add((d, t))
    ne -= 1

queue = list(edges[r])
heapq.heapify(queue)
costs[r] = 0

while queue:
    total_cost, idx = heapq.heappop(queue)
    if costs[idx] is not None:
        if costs[idx] > total_cost:
            print('NEGATIVE CYCLE')
            break
        else:
            continue
    costs[idx] = total_cost
    for cost, idx2 in edges[idx]:
        heapq.heappush(queue, (total_cost + cost, idx2))
else:
    for cost in costs:
        print(cost if cost is not None else 'INF')

Submission status: Wrong Answer

Solution code:
nv, ne, r = map(int, input().split())

edges = set(tuple(map(int, input().split())) for _ in range(ne))
costs = [None] * nv
costs[r] = 0

for _ in range(nv - 1):
    for s, t, d in edges:
        cost = d if costs[s] is None else costs[s] + d
        if costs[t] is None or costs[t] > cost:
            costs[t] = cost

for s, t, d in edges:
    cost = d if costs[s] is None else costs[s] + d
    if cost < costs[t]:
        print('NEGATIVE CYCLE')
        break
else:
    for cost in costs:
        print('INF' if cost is None else cost)