Bog of Eternal Stench
Time limit3sMemory limit1024 MB
Find the lowest stench reachable at the destination when directed bridges add or subtract stench, stench is clamped at zero, and detours through cycles are allowed.
- Level
Medium7 of 10
- Topics
- Shortest path, Graph
- Solved
- No attempts yet
Problem
You are trying to reach the center of a Labyrinth, so you must cross the Bog of Eternal Stench. Legend says that if you put so much as one toe in the Bog, you will smell bad forever. You would of course prefer to cross the Bog with the lowest stench possible.
Luckily, you have determined earlier that the stench does eventually wear off, and that some areas of the Bog transfer more stench to you than others. There are also small islands where you can rest without any effect on your stench level. The first island is where your journey through the Bog starts, and the last is your destination on the other side.
From each island, established bridges let you travel to other islands, but each bridge works in one direction only. Because this is the Bog of Eternal Stench, most bridges increase your overall stench by a fixed amount. Some bridges are pleasant, though, and decrease your overall stench when you cross them. Your stench level can never drop below : a bridge that would push it under sets it to instead.
You have mapped all islands and bridges and measured how much each bridge increases or decreases your stench. As a result, it may be possible to cross the Bog and come out with no stench at all!
Your top priority is reaching the destination island with the minimum stench. You are willing to take a circuitous path that visits some islands multiple times if that achieves this goal. Your path must end at the destination island, but you do not have to leave the Bog right away the first time you reach it, if a detour that returns to the island later would decrease your final stench value.
Input
The first line contains two integers and (), where is the number of islands and is the number of direct bridges.
Each of the next lines contains three integers , , and (, ), meaning there is a direct bridge from island to island that changes your overall stench by . It is guaranteed that , and that there is at most one direct bridge from to (but there can also be another direct bridge from to ).
Output
Output a single integer: the minimum stench level you can exit the Bog with, assuming you begin with stench.