UVa 10557 - XYZZY

10557 - XYZZY
http://acm.uva.es/p/v105/10557.html

Summary
The problem should be viewed as a weighted directed graph. You are going to solve a shortest path problem, with vertex 1 as the starting vertex and vertex n as the destination. It can be solved by the bellman-ford algorithm.

Explanation
In this shortest path problem, you are actually maximizing your energy in every node, just as you are minimizing the distance from the start node for every node in the ordinary Bellman-Ford's.

There are two cases: acyclic or cyclic graph input. The first case can be solved by apply the Bellman-Ford's/Floyd-Warshall's shortest path algorithm without difficulties. The second case is further divided into positive and non-positive cycles.

When there is a non-positive weight cycle, i.e. the total weight of the edges in a cycle is 0 or negative, it is trivial to see that you should pass through it as few as possible. In fact, it does not yield any problem using simple Bellman-Ford's or Floyd-Warshall's. So the problem is only on positive weight cycle.

So this is why Bellman-Ford works: do n-1 times looping for relaxing all edges, and by pigeonhole's principle, if there is no cycle there will not be any relaxing (remember now you're relaxing to get more energy for nodes) in the n'th loop. If you are still able to relax in the n'th loop, you are in the cycle. It provides you unlimited supply of energy and you can do a simple graph traversal from the edge and see if it is connected to the destination.

Input
Input Here

Output
Output Here