Problem:
Single Source Shortest Path (Negative Edges) Input An edge-weighted graph G ( V , E ) and the source r . | V | | E | r  s 0  t 0  d 0  s 1  t 1  d 1 : 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.  s i and t i represent source and target vertices of i -th edge (directed) and d i 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   c 0  c 1 : 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 ≤ d i ≤ 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

Solution (Python):
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 D[frm] == self.INF or 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])

Solution (Python):
V, E, r = map(int, input().split())
nodes = [list(map(int, input().split())) for _ in range(E)] 

def shortest_path(s):
    d = [float('inf') for i in range(V)]
    d[s] = 0
    for _ in range(V):
        update = False
        for i in range(E):
            e = nodes[i]
            if d[e[0]] != float('inf') and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                update = True
    if update:
        return None
    else:
        return d

if not shortest_path(r):
    print('NEGATIVE CYCLE')
else:
    d = shortest_path(r)
    for i in range(V):
        if d[i] == float('inf'):
            print('INF')
        else:
            print(d[i])

Solution (Python):


import sys

sys.setrecursionlimit(10 ** 9)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
INF=float('inf')


def bellman_ford(N: int, edges: list, src: int) -> list:
    
    
    res = [INF] * N
    res[src] = 0
    
    for i in range(N-1):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                res[dest] = res[src] + cost
    
    for src, dest, cost in edges:
        if res[dest] > res[src] + cost:
            
            return []
    
    return res

N,M,r=MAP()
edges=[None]*M
for i in range(M):
    s,t,d=MAP()
    edges[i]=(s, t, d)

ans=bellman_ford(N, edges, r)

if not len(ans):
    print('NEGATIVE CYCLE')
    exit()

for i in range(N):
    if ans[i]==INF:
        ans[i]='INF'
for i in range(N):
    print(ans[i])

Solution (Python):
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 dist[u] != inf and 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()

Solution (Python):
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 dist[u] != inf and 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()

Solution (Python):
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] != (1 << 30) and 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')

Solution (Python):
class exist_negative_cycle(Exception):
    pass
def bellman_ford(g, size, start=0):
    d = [float('inf')] * size
    d[start] = 0
   
    for _ in range(size):
        for u in g:
            for length, v in g[u]:
                if d[v] > d[u] + length:
                    d[v] = d[u] + length

    for u in g:
        for length, v in g[u]:
            if d[v] > d[u] + length:
                raise exist_negative_cycle    
    return d
from sys import stdin
readline = stdin.readline
import math
from collections import defaultdict

vertex, edge, r = map(int, readline().split())

g = defaultdict(list)
for i in range(edge):
    s, t, length = map(int, readline().split())
    g[s].append((length, t))
try:
    d = bellman_ford(g, vertex, r)
    for di in d:
        print('INF' if math.isinf(di) else di)
except exist_negative_cycle:
    print('NEGATIVE CYCLE')

Solution (Python):
def bellman_ford(vertices, edges, source):
    for v in vertices:
        if v is source:
            v.distance = 0
        else:
            v.distance = Infinity()
        v.predecessor = None
    for _ in xrange(len(vertices)-1):
        for uv in edges:
            u = uv.source
            v = uv.destination
            if v.distance > u.distance + uv.weight:
                v.distance = u.distance + uv.weight
                v.predecessor = u
    for uv in edges:
        u = uv.source
        v = uv.destination
        if u.distance + uv.weight < v.distance:
            raise NegativeCycleError

def main():
    V, E, r = map(int, raw_input().split())
    vertices = [Vertex() for _ in xrange(V)]
    edges = []
    for _ in xrange(E):
        s, t, d = map(int, raw_input().split())
        edges.append(Edge(vertices[s], vertices[t], d))
    try:
        bellman_ford(vertices, edges, vertices[r])
        for v in vertices:
            print v.distance
    except NegativeCycleError:
        print "NEGATIVE CYCLE"

class Infinity(object):
    def __eq__(self, other):
        return other is self

    def __lt__(self, other):
        return False

    def __gt__(self, other):
        return True

    def __add__(self, other):
        return self

    def __radd__(self, other):
        return slef

    def __str__(self):
        return "INF"
    __repr__ = __str__

class NegativeCycleError(Exception):
    pass

class Edge(object):
    def __init__(self, source, destination, weight):
        self.source = source
        self.destination = destination
        self.weight = weight

class Vertex(object):
    def __init__(self, distance=None, predecessor=None):
        self.distance = distance
        self.predecessor = predecessor

if __name__ == "__main__":
    main()

Solution (Python):
def bellman_ford(vertices, edges, source):
    for v in vertices:
        if v is source:
            v.distance = 0
        else:
            v.distance = Infinity()
        v.predecessor = None
    for _ in xrange(len(vertices)-1):
        for uv in edges:
            u = uv.source
            v = uv.destination
            if v.distance > u.distance + uv.weight:
                v.distance = u.distance + uv.weight
                v.predecessor = u
    for uv in edges:
        u = uv.source
        v = uv.destination
        if u.distance + uv.weight < v.distance:
            raise NegativeCycleError

def main():
    V, E, r = map(int, raw_input().split())
    vertices = [Vertex() for _ in xrange(V)]
    edges = []
    for _ in xrange(E):
        s, t, d = map(int, raw_input().split())
        edges.append(Edge(vertices[s], vertices[t], d))
    try:
        bellman_ford(vertices, edges, vertices[r])
        for v in vertices:
            print v.distance
    except NegativeCycleError:
        print "NEGATIVE CYCLE"

class Infinity(object):
    def __eq__(self, other):
        return other is self

    def __lt__(self, other):
        return False

    def __gt__(self, other):
        return True

    def __add__(self, other):
        return self

    def __radd__(self, other):
        return self

    def __str__(self):
        return "INF"
    __repr__ = __str__

class NegativeCycleError(Exception):
    pass

class Edge(object):
    def __init__(self, source, destination, weight):
        self.source = source
        self.destination = destination
        self.weight = weight

class Vertex(object):
    def __init__(self, distance=None, predecessor=None):
        self.distance = distance
        self.predecessor = predecessor

if __name__ == "__main__":
    main()

Solution (Python):
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 
        self.prev = [-1] * self.V 
        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[v] != 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')

Solution (Python):
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 
        self.prev = [-1] * self.V 
        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[v] != 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:
    for dist in sp.distance:
        print(dist if dist != INF else 'INF')

Solution (Python):
inf = float("inf")
def bellman_ford(es, s):
    d[s] = 0
    for cnt in xrange(V):
        update = False
        for e in es:
            frm, to, cost = e
            if d[frm] != inf and d[to] > d[frm] + cost:
                d[to] = d[frm] + cost
                update = True
                if cnt == i - 1:
                    return True
    return False

V, E, r = map(int, raw_input().split())
es = [map(int, raw_input().split()) for i in xrange(E)]
d = [inf for i in xrange(V)]
negative = bellman_ford(es, r)
if negative:
    print "NEGATIVE CYCLE"
else:
    for i in d:
        if i < inf:
            print i
        else:
            print "INF"

Solution (Python):

from math import isinf


def main():
    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

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

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

main()

Solution (Python):
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 _ in xrange(V-1):
		for i, node in enumerate(graph):
			for edge in node:
				if d[i] != INF and 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] != INF and 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()

Solution (Python):
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

	
	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

	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["negcicle"] = False
	for (x, y, w) in graph["edges"]:
		if dis[x] + w < dis[y] and x in connect:
			dis["negcicle"] = True

	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"

Solution (Python):
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
f = False
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: f = True 
if f: print "NEGATIVE CYCLE"
else:
    for i in dist: print "INF" if i == INF else i

Solution (Python):
V, E, root = map(int, input().split())
visited = [False] * V
nodes = [[] for i in range(V)]
cost = [[] for i in range(V)]
for i in range(E):
    s, t, d = map(int, input().split())
    nodes[s].append(t)
    cost[s].append(d)

dist = [float('inf')] * V
dist[root] = 0

negative_cycle = False

for k in range(V):
    for i in range(V):
        for j in range(len(nodes[i])):
            if dist[nodes[i][j]] > dist[i] + cost[i][j]:
                dist[nodes[i][j]] = dist[i] + cost[i][j]
                if k == V - 1:
                    dist[nodes[i][j]] = -float('inf')
                    negative_cycle = True
if negative_cycle:
    print('NEGATIVE CYCLE')
else:
    for i in range(V):
        if dist[i] == float('inf'):
            print('INF')
        else:
            print(dist[i])

Solution (Python):
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:
        if costs[s] is None:
            continue
        cost = costs[s] + d
        if costs[t] is None or costs[t] > cost:
            costs[t] = cost

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

Solution (Python):



import array
import collections


G_INF = 2 ** 31


class GraphError(Exception):
    pass


class GraphSearchError(GraphError):

    def __init__(self, reason):
        self.reason = reason

    def __str__(self):
        return str(reason)


class ShortestPathFasterAlgorithm(object):

    def __init__(self, number_of_vertices, adjacency_list, costs, start):
        self.max_v = number_of_vertices
        self.adj = adjacency_list
        self.costs = costs
        self.start = start
        self.dist = None
        self.visits = None

    def initialize(self):
        self.dist = collections.defaultdict(lambda: G_INF)
        self.dist[self.start] = 0
        self.visits = collections.defaultdict(int)

    def single_source_shortest_path(self):
        self.initialize()
        q = collections.deque()
        q.append(self.start)
        while q:
            u = q.popleft()
            self.visits[u] += 1
            if self.visits[u] >= self.max_v:
                if self.max_v == 1:
                    return [0]
                raise GraphSearchError("A negative cycle was detected.")
            for v in self.adj[u]:
                new_length = self.dist[u] + self.costs[(u, v)]
                if new_length < self.dist[v]:
                    self.dist[v] = new_length
                    if v not in q:
                        q.append(v)
        return self.dist


def main():
    max_v, max_e, start = map(int, input().split())
    adjacency_list = collections.defaultdict(lambda: array.array("L"))
    costs = collections.defaultdict(lambda: G_INF)
    for _ in range(max_e):
        s, t, d = map(int, input().split())
        adjacency_list[s].append(t)
        costs[(s, t)] = d
    spfa = ShortestPathFasterAlgorithm(max_v, adjacency_list, costs, start)
    try:
        dist = spfa.single_source_shortest_path()
        for v in range(max_v):
            result = dist[v]
            if result < G_INF:
                print(result)
            else:
                print("INF")
    except GraphSearchError as gse:
        print("NEGATIVE CYCLE")


if __name__ == '__main__':
    main()

Solution (Python):



import array
import collections


G_INF = 2 ** 31



class GraphError(Exception):
    pass



class GraphSearchError(GraphError):

    def __init__(self, reason):
        self.reason = reason

    def __str__(self):
        return str(reason)



class ShortestPathFasterAlgorithm(object):

    def __init__(self, number_of_vertices, adjacency_list, costs, start):
        
        self.max_v = number_of_vertices
        
        
        self.adj = adjacency_list
        
        self.costs = costs
        
        self.start = start
        
        self.dist = None
        
        self.visits = None

    def initialize(self):
        self.dist = collections.defaultdict(lambda: G_INF)
        self.dist[self.start] = 0
        self.visits = collections.defaultdict(int)

    def single_source_shortest_path(self):
        self.initialize()
        
        
        in_q = collections.defaultdict(bool)
        
        q = collections.deque()
        q.append(self.start)
        in_q[self.start] = True
        while q:
            u = q.popleft()
            in_q[u] = False
            self.visits[u] += 1
            if self.visits[u] >= self.max_v:
                if self.max_v == 1:
                    
                    
                    return [0]
                raise GraphSearchError("A negative cycle was detected.")
            for v in self.adj[u]:
                new_length = self.dist[u] + self.costs[(u, v)]
                if new_length < self.dist[v]:
                    self.dist[v] = new_length
                    if not in_q[v]:
                        q.append(v)
                        in_q[v] = True
        return self.dist


def main():
    max_v, max_e, start = map(int, input().split())
    adjacency_list = collections.defaultdict(lambda: array.array("L"))
    costs = collections.defaultdict(lambda: G_INF)
    for _ in range(max_e):
        s, t, d = map(int, input().split())
        adjacency_list[s].append(t)
        costs[(s, t)] = d
    spfa = ShortestPathFasterAlgorithm(max_v, adjacency_list, costs, start)
    try:
        dist = spfa.single_source_shortest_path()
        for v in range(max_v):
            result = dist[v]
            if result < G_INF:
                print(result)
            else:
                print("INF")
    except GraphSearchError as gse:
        print("NEGATIVE CYCLE")


if __name__ == '__main__':
    main()

Solution (Python):
V, E, r = map(int, raw_input().split())
g = [[] for i in xrange(V)]
for i in xrange(E):
    s, t, d = map(int, raw_input().split())
    g[s].append((t, d))

INF = 10**18
dist = [INF] * V
dist[r] = 0
update = 1
for _ in xrange(V):
    update = 0
    for v, e in enumerate(g):
        for t, cost in e:
            if dist[v]!=INF and dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                update = 1
    if not update:
        break
else:
    print "NEGATIVE CYCLE"
    exit(0)
for i in xrange(V):
    print dist[i] if dist[i]<INF else "INF"

Solution (Python):
def bellmanford(s,v,es):
    n=len(es)
    negative=False
    d=[inf for _ in xrange(v)]
    d[s]=0
    for i in xrange(n):
        update=False
        for fr,to,cost in es:
            if fr!=float('inf') and d[to]>d[fr]+cost:
                d[to]=d[fr]+cost
                update=True
                if i==n-1:
                    negative=True
        if not update:
            break
    return d,negative

inf=float('inf')
V,E,r=map(int,raw_input().split())
es=[map(int,raw_input().split()) for _ in xrange(E)]
d,negative=bellmanford(r,V,es)
if negative:
    print("NEGATIVE CYCLE")
else:
    for i in d:
        print(i if i<inf else "INF")

Solution (Python):
import sys

def bellmanford(N, s, graph):
  dist = [sys.maxint] * N
  dist[s] = 0
  for i in xrange(N):
    for v in xrange(N):
      if v not in graph: continue
      for k in xrange(len(graph[v])):
        edge = graph[v][k]
        if dist[v] != sys.maxint and dist[edge[0]] > dist[v] + edge[1]:
          dist[edge[0]] = dist[v] + edge[1]
          if i == N-1: return []
  return dist

V,E,r = map(int, raw_input().split())
graph = {}
for _ in xrange(E):
  s,t,d = map(int, raw_input().split())
  if s not in graph:
    graph[s] = []
  graph[s].append([t,d])
costs = bellmanford(V, r, graph)
if len(costs) == 0:
  print "NEGATIVE CYCLE"
else:
  for i in xrange(V):
    if costs[i] == sys.maxint:
      print "INF"
    else:
      print costs[i]

Solution (Python):

import sys

file_input = sys.stdin

V, E, r = map(int, file_input.readline().split())

edges = []

for line in file_input:
    edges.append(tuple(map(int, line.split())))



distance = [float("inf")] * V
distance[r] = 0

for i in range(V):
    notUpdated = True
    for e in edges:
        t = e[1]
        temp_d = distance[e[0]] + e[2]
        if temp_d < distance[t]:
            distance[t] = temp_d
            notUpdated = False
    if notUpdated:
        break



if i == V - 1 and V != 1:
    print("NEGATIVE CYCLE")
else:
    print(*map(lambda x: str(x).upper(), distance), sep = '\n')

Solution (Python):

import sys

file_input = sys.stdin

V, E, r = map(int, file_input.readline().split())

edges = []

for line in file_input:
    edges.append(tuple(map(int, line.split())))



distance = [float("inf")] * V
distance[r] = 0
notUpdated = True

for i in range(V - 1):
    notUpdated = True
    for s, t, w in edges:
        temp_d = distance[s] + w
        if temp_d < distance[t]:
            distance[t] = temp_d
            notUpdated = False
    if notUpdated:
        break



if notUpdated:
    print(*map(lambda x: str(x).upper(), distance), sep = '\n')
else:
    flag = True
    for s, t, w in edges:
        temp_d = distance[s] + w
        if temp_d < distance[t]:
            print("NEGATIVE CYCLE")
            flag = False
            break
    if flag:
        print(*map(lambda x: str(x).upper(), distance), sep = '\n')

Solution (Python):



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

output:
INF
0
-5
-3

OR
input:
4 6 0
0 1 2
0 2 3
1 2 -5
1 3 1
2 3 2
3 1 0

output:
NEGATIVE CYCLE
"""

import sys
from math import isinf


class Edge(object):
    __slots__ = ('source', 'target', 'cost')

    def __init__(self):
        self.cost = float('inf')
        self.source, self.target = None, None


def generate_edge_table(_v_info):
    for index, each in enumerate(_v_info):
        edge = init_edge_table[index]
        source, target, cost = map(int, each)
        edge.source = source
        edge.target = target
        edge.cost = cost
    return init_edge_table


def bellman_ford():
    distance[root] = 0

    for j in range(vertices - 1):
        for edge in edge_table:
            source, target, cost = edge.source, edge.target, edge.cost
            if distance[source] + cost < distance[target]:
                distance[target] = distance[source] + cost

    for edge in edge_table:
        source, target, cost = edge.source, edge.target, edge.cost
        if distance[source] + cost < distance[target]:
            print('NEGATIVE CYCLE')
            return list()

    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:])
    

    distance = [float('inf')] * vertices
    init_edge_table = tuple(Edge() for _ in range(edges))

    edge_table = generate_edge_table(v_info)

    res = bellman_ford()
    for ele in res:
        if isinf(ele):
            print('INF')
        else:
            print(ele)