Problem S4: Floor is Lava
2025 · S4 · Original problem · DMOJProblem Description
You're trapped in a scorching dungeon with rooms numbered from to connected by tunnels. The -th tunnel connects rooms and in both directions, but the floor of the tunnel is covered in lava with temperature .
To help you navigate the lavatic tunnels, you are wearing a pair of heat-resistant boots that initially have a chilling level of . In order to step through lava with temperature , your boots must have the same chilling level ; if the chilling level is too low then the lava will melt your boots, and if it's too high then your feet will freeze as you cross the tunnel.
Luckily, when you're standing in a room, you can increase or decrease the chilling level of your boots by for a cost of coins. You start in room and would like to reach the exit which you know is located in room . What is the minimum cost to do so?
Input Specification
The first line of input contains two integers and .
The next lines each contain three integers , , and , describing the -th tunnel.
There is at most one tunnel connecting any pair of rooms, and it is possible to reach all other rooms from room .
The following table shows how the available marks are distributed:
| Marks | Additional constraints |
|---|---|
| For all tunnels, | |
| Each room has at most 5 outgoing tunnels | |
| None |
Output Specification
Output the minimum cost (in coins) to reach room from room .
Sample Input
5 7
1 2 3
2 3 2
1 3 6
3 4 3
4 5 7
2 4 1
2 5 10Output for Sample Input
9
Explanation of Output for Sample Input
A diagram of the dungeon is shown below.

The optimal escape strategy is as follows:
-
Increase the chilling level to for a cost of coins.
-
Walk through the tunnel to room .
-
Decrease the chilling level to for a cost of coin.
-
Walk through the tunnel to room .
-
Increase the chilling level to for a cost of coin.
-
Walk through the tunnel to room .
-
Increase the chilling level to for a cost of coins.
-
Walk through the tunnel to room and escape.
This has a total cost of coins, and it can be shown that no cheaper route exists.