Problem 176
Shortest Path with Negative Weights
Hard · 30 pts · Graph, Shortest Path, Bellman-Ford
Problem
You are given a directed graph with N nodes and M edges. Edge weights can be negative. Print the shortest distance from node 1 to node N. There are two special cases. If a cycle with negative total weight can be reached from node 1, distances are not well defined, so print NEGATIVE CYCLE (even if that cycle does not lead to node N). Otherwise, if node N cannot be reached from node 1, print UNREACHABLE. Dijkstra's algorithm does not work with negative weights. Use Bellman-Ford: relax every edge N - 1 times; if any edge reachable from node 1 can still be relaxed afterwards, a negative cycle exists.
Input
First line: integers N and M. Next M lines: a directed edge u v w (u -> v with weight w).
Output
Print the distance, NEGATIVE CYCLE or UNREACHABLE.
Constraints
1 <= N <= 500; 0 <= M <= 5000; -1000 <= w <= 1000
Example input
3 3 1 2 4 2 3 -2 1 3 5
Example output
2
Explanation
The direct edge 1 → 3 costs 5, but the route 1 → 2 → 3 costs 4 + (-2) = 2. There are no negative cycles, so the shortest distance is 2.