![]() |
VOOZH | about |
Given a directed graph with N nodes and M edges determine if there exists a negative cycle in the graph. If a negative cycle exists print "YES" and output any vertex sequence that forms the cycle; otherwise print "NO".
Examples:
Input:
4 5
1 2 1
2 4 1
3 1 1
4 1 -3
4 3 -2
Output:
YES
1 2 4 1
Approach:
To determine if there exists a negative cycle in the graph we can use the Shortest Path Faster Algorithm. We perform the relaxation on the all edges repeatedly for the n-1 iterations where n is the number of the nodes. If on the nth iteration we still find a relaxation and it indicates the presence of the negative cycle.
Step-by-step approach:
Below is the implementation of the algorithm:
YES 2 4 1 2
Time Complexity: O(n * m)
Auxiliary Space: O(n)