Magical Bridges
Time limit8sMemory limit256 MB
Choose one shared length for all magical bridges so the shortest routes from two starts to the target differ as little as possible.
- Level
Hard8 of 10
- Topics
- Shortest path, Math
- Solved
- No attempts yet
Problem
A magician lives in a country made of islands and bridges. Some of the bridges are magical bridges that the magician built. Her magic changes the lengths of all magical bridges at once to the same value, which must be a non-negative integer.
The country has a famous race played by two people. Player 1 starts from island and player 2 starts from island . Whoever reaches island first wins.
The magician enjoys watching this race, so she sets the length of the magical bridges to make the race as close as possible: she minimizes the difference between the shortest-path distance from to and the shortest-path distance from to . Movement inside an island does not count.
Compute how small that difference can be.
The magician picks the length once before the race starts and never changes it during the race. All magical bridges share the same length. Every bridge can be crossed in either direction.
Input
The input holds several datasets. Each dataset has the format below. Every number in the input is an integer.
N M S1 S2 T
a1 b1 w1
a2 b2 w2
...
aM bM wM
means bridge connects island and island .
is either a non-negative integer or the letter x. If is an integer, bridge is a normal bridge of length . If is x, bridge is a magical bridge.
- , , are all different.
- for every normal bridge
- The number of magical bridges is at most 100.
- is reachable from and from .
The line after the last dataset holds five zeros separated by single spaces. That line marks the end of the input and is not processed.
Output
For each dataset, print the smallest possible difference between the two shortest-path distances on its own line.