# UVa 10557

## Contents

## 10557 - XYZZY[edit]

http://uva.onlinejudge.org/external/105/10557.html

## Summary[edit]

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[edit]

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 applying Bellman-Ford's or 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[edit]

5 0 1 2 -60 1 3 -60 1 4 20 1 5 0 0 5 0 1 2 20 1 3 -60 1 4 -60 1 5 0 0 5 0 1 2 21 1 3 -60 1 4 -60 1 5 0 0 5 0 1 2 20 2 1 3 -60 1 4 -60 1 5 0 0 -1

## Output[edit]

hopeless hopeless winnable winnable