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: Accepted

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 _ 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()

Submission status: Accepted

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

	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"

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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()

Submission status: Accepted

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

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)


# Shortest Path Faster Algorithm??¬???
class ShortestPathFasterAlgorithm(object):

    def __init__(self, number_of_vertices, adjacency_list, costs, start):
        # ??????????????°
        self.max_v = number_of_vertices
        # ??£??\?????????
        # ?????????????????????????????£??\???????????????array????????¨????????????defaultdict
        self.adj = adjacency_list
        # (???????§????, ????????????)????????????????????????????????¨????????????defaultdict
        self.costs = costs
        # ??¢?´¢????§????
        self.start = start
        # ?§???????????????????????????????????????????????´???????defaultdict
        self.dist = None
        # ?????????????¨?????????°???????´???????defaultdict
        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()
        # ????????????????????????????????\???????????????????????¨??????defaultdict
        # ?????\??????????´?????????????????????¢????????????????????????????°???\??????
        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:
                    # |V| = 1, |E| = 0??¨????????????????????±??????????????????
                    # ????????´??????????????????
                    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()

Submission status: Accepted

Solution code:
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"

Submission status: Accepted

Solution code:
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")

Submission status: Accepted

Solution code:
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]

Submission status: Accepted

Solution code:
# Input acceptance
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())))


# Bellman???Ford algorithm
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


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

Submission status: Accepted

Solution code:
# Input acceptance
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())))


# Bellman???Ford algorithm
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


# Output
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')

Submission status: Accepted

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

"""
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:])
    # assert len(init_vertices_table) == vertices_num

    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)

Submission status: Accepted

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

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


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


def bellman_ford():
    distance[root] = 0

    for j in range(vertices - 1):
        for current, current_info in enumerate(adj_table):
            for adj, cost in current_info.items():
                if distance[current] + cost < distance[adj]:
                    distance[adj] = distance[current] + cost

    for current, current_info in enumerate(adj_table):
        for adj, cost in current_info.items():
            if distance[current] + cost < distance[adj]:
                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_adj_table = tuple(dict() for _ in range(vertices))

    adj_table = generate_adj_table(v_info)

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

Submission status: Accepted

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

"""
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:])
    # assert len(init_vertices_table) == vertices_num

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

    edge_table = generate_edge_table(v_info)

    res = bellman_ford()
    if res:
        print('\n'.join(('INF' if isinf(ele) else str(ele) for ele in res)))

Submission status: Accepted

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

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


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


def bellman_ford():
    distance[root] = 0

    for j in range(vertices - 1):
        for current, current_info in enumerate(adj_table):
            for adj, cost in current_info.items():
                if distance[current] + cost < distance[adj]:
                    distance[adj] = distance[current] + cost

    for current, current_info in enumerate(adj_table):
        for adj, cost in current_info.items():
            if distance[current] + cost < distance[adj]:
                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_adj_table = tuple(dict() for _ in range(vertices))

    adj_table = generate_adj_table(v_info)

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

Submission status: Accepted

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

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


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


def bellman_ford():
    distance[root] = 0

    for j in range(vertices - 1):
        for current, current_info in enumerate(adj_table):
            for adj, cost in current_info.items():
                if distance[current] + cost < distance[adj]:
                    distance[adj] = distance[current] + cost

    for current, current_info in enumerate(adj_table):
        for adj, cost in current_info.items():
            if distance[current] + cost < distance[adj]:
                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_adj_table = tuple(dict() for _ in range(vertices))

    adj_table = generate_adj_table(v_info)

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

Submission status: Accepted

Solution code:
nv, ne, r = map(int, input().split(' '))
dist = [float('inf')] * nv
dist[r] = 0
edges = []
for i in range(ne):
    s, t, w = map(int, input().split(' '))
    edges.append((s, t, w))

for i in range(nv - 1):
    for s, t, w in edges:
        if dist[t] > dist[s] + w:
            dist[t] = dist[s] + w

for s, t, w in edges:
    if dist[t] > dist[s] + w:
        print("NEGATIVE CYCLE")
        exit()

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

Submission status: Accepted

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

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


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

Submission status: Accepted

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

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


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

Submission status: Accepted

Solution code:
from sys import stdin
from collections import deque


V, E, R = [int(x) for x in stdin.readline().split()]
d = {}
tick = False
INF = float('inf')
for i in range(V):
    d[i] = INF
d[R] = 0
weight = {}
st = deque([])
for i in range(1, V+1):

    for j in range(E):
        if i == 1:
            s, t, w = [int(x) for x in stdin.readline().split()]
            weight[(s, t)] = w
            st.append((s, t))
        (s, t) = st.popleft()
        if d[t] > d[s] + weight[(s, t)]:
            d[t] = d[s] + weight[(s, t)]
            if i == V:
                print('NEGATIVE CYCLE')
                tick = True
                break
        st.append((s, t))


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

Submission status: Accepted

Solution code:
from sys import stdin

def sp(G,R,V):
    d = {}
    INF = float('inf')
    for i in range(V):
        d[i] = INF
    d[R] = 0
    for i in range(1, V+1):
        for (u, v) in G.keys():
            if d[v] > d[u] + G[u, v]:
                d[v] = d[u] + G[u, v]
                if i == V:
                    print('NEGATIVE CYCLE')
                    quit()
    return d


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

Submission status: Accepted

Solution code:
from sys import stdin
from collections import deque

V, E, R = [int(x) for x in stdin.readline().split()]
d = {}
tick = False
INF = float('inf')
for i in range(V):
    d[i] = INF
d[R] = 0
weight = {}
st = []
for i in range(1, V+1):
    for j in range(E):
        if i == 1:
            s, t, w = [int(x) for x in stdin.readline().split()]
            weight[(s, t)] = w
            st.append((s, t))
        (s, t) = st[j]
        if d[t] > d[s] + weight[(s, t)]:
            d[t] = d[s] + weight[(s, t)]
            if i == V:
                print('NEGATIVE CYCLE')
                quit()

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

Submission status: Accepted

Solution code:
from collections import defaultdict
import heapq

vertice,edge,source = map(int,input().split(" "))
link = defaultdict(dict)
weight = defaultdict(dict)
cost = [float("inf") for n in range(vertice)]
cost[source] = 0
for e in range(edge):
    i,j,w = map(int,input().split(" "))
    link[i] = link.get(i,set()) | {j}
    weight[i].update({j:w})

vertice_cnt = 0
while True:
    if vertice_cnt >= vertice:
        print("NEGATIVE CYCLE")
        break
    update = False
    for k,val in link.items():
        for v in val:
            if cost[v] > cost[k] + weight[k][v]:
                cost[v] = cost[k] + weight[k][v]
                update = True
    if not(update):
        for c in cost:
            print(c if c != float("inf") else "INF")
        break
    vertice_cnt += 1

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
from sys import stdin
 
def sp(G,R,V):
    d = {}
    INF = float('inf')
    for i in range(V):
        d[i] = INF
    d[R] = 0
    for i in range(1, V+1):
        for ((u, v), c) in G.items():
            if d[v] > d[u] + c:
                d[v] = d[u] + c
                if i == V:
                    return 0
    return d
 
 
V, E, R = [int(x) for x in stdin.readline().split()]
G = {}
for case in range(E):
    s, t, w = [int(x) for x in stdin.readline().split()]
    G[(s, t)] = w
d = sp(G, R, V)
if d == 0:
    print('NEGATIVE CYCLE')
else:
    for k in range(V):
        if d[k] == float('inf'):
            print("INF")
        else:
            print(d[k])

Submission status: Accepted

Solution code:
import sys

inf = 1<<60

def solve():
    N, M, r = map(int, sys.stdin.readline().split())
    edges = [None] * M

    for i in range(M):
        si, ti, di = map(int, sys.stdin.readline().split())
        edges[i] = (si, ti, di)

    ans = BellmanFord(N, M, edges, r)

    print(*ans, sep='\n')

def BellmanFord(N, M, edges, r):
    d = [inf] * N
    d[r] = 0

    for i in range(N):
        flag = False

        for (u, v, c) in edges:
            if d[u] != inf and d[u] + c < d[v]:
                d[v] = d[u] + c
                flag = True

        if flag and i == N - 1:
            return ['NEGATIVE CYCLE']

    d = [di if di < inf else 'INF' for di in d]

    return d

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
inf = float("inf")

class edge():
    def __init__(self, start, target, cost):
        self.start = start
        self.target = target
        self.cost = cost

def bellman_ford(s):
    d = [inf] * V
    d[s] = 0
    cnt = 0
    updateflag = True
    while True:
        updateflag = False
        for i in es:
            if d[i.start] != inf and d[i.target] > d[i.start] + i.cost:
                d[i.target] = d[i.start] + i.cost
                updateflag = True
        if cnt == V-1: return False
        if not updateflag: break
        cnt += 1
    return d

V,E,r = map(int, input().split())
if E == 0: print(0)
else:
 es = [None] * E
 for i in range(E):
     s,t,cost = map(int, input().split())
     es[i] = edge(s, t, cost)
 ans = bellman_ford(r)
 if ans:
     for i in ans:
         if i == inf: print("INF")
         else: print(i)
 else:
    print("NEGATIVE CYCLE")