from collections import deque
INF = 10**18
# Adjacency List to store the weighted graph
graph = [[] for _ in range(2501)]
# array to store the distance to any node
dist = [INF] * 2501
# array to store the parent of any node
par = [-1] * 2501
# array to store the number of times a node has been relaxed
cnt = [0] * 2501
n, m = 4, 5
# Function to run Shortest Path Fast Algorithm
def spfa(start):
global n
# Initialize the distance of starting node = 0
dist[start] = 0
# Initialize the parent of starting node = -1
par[start] = -1
# Queue to run SPFA
q = deque()
# Push the starting node in the queue
q.append(start)
while q:
# Pop the front element of the queue
ele = q.popleft()
# Iterate over all the children of the current node
for child, weight in graph[ele]:
# If the distance to the child node is greater
# than the distance of the current node + edge
# weight, then relax the child node
if dist[child] > dist[ele] + weight:
# Increment the relaxation count of the
# child node
cnt[child] += 1
# If the child has been relaxed more than n
# times, then there is a cycle
if cnt[child] > n:
return False, child
# Update the minimum distance to the child
# node
dist[child] = dist[ele] + weight
# Push the child node if it is not already
# in queue
if child not in q:
q.append(child)
# Update the parent of the child node with
# the current node
par[child] = ele
return True, -1
edges = [[1, 2, 1],
[2, 4, 1],
[3, 1, 1],
[4, 1, -3],
[4, 3, -2]]
# Create the graph from the given edges
for u, v, w in edges:
graph[u].append((v, w))
# Check for negative weight cycle using SPFA
for i in range(1, n + 1):
has_cycle, cycle_node = spfa(i)
if not has_cycle:
print("YES")
ele = cycle_node
st = []
is_stack = [False] * 2501
# Push all the elements in the stack using the
# parent array
while not is_stack[ele]:
is_stack[ele] = True
st.append(ele)
ele = par[ele]
# Print all the nodes in the negative weight
# cycle
print(ele, end=" ")
while st[-1] != ele:
print(st.pop(), end=" ")
print(ele)
break
else:
print("NO")