CCCGuide

Problem S4: Floor is Lava

2025 · S4 · Original problem · DMOJ

Problem Description

You're trapped in a scorching dungeon with NN rooms numbered from 11 to NN connected by MM tunnels. The ii-th tunnel connects rooms aia_i and bib_i in both directions, but the floor of the tunnel is covered in lava with temperature cic_i.

To help you navigate the lavatic tunnels, you are wearing a pair of heat-resistant boots that initially have a chilling level of 00. In order to step through lava with temperature ℓ\ell, your boots must have the same chilling level ℓ\ell; 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 dd for a cost of dd coins. You start in room 11 and would like to reach the exit which you know is located in room NN. What is the minimum cost to do so?

Input Specification

The first line of input contains two integers NN and MM (1≤N,M≤200 000)(1 \le N, M \le 200\,000).

The next MM lines each contain three integers aia_i, bib_i, and cic_i (1≤ai,bi≤N,ai≠bi,1≤ci≤109)(1 \le a_i, b_i \le N, a_i \neq b_i, 1 \le c_i \le 10^9), describing the ii-th tunnel.

There is at most one tunnel connecting any pair of rooms, and it is possible to reach all other rooms from room 11.

The following table shows how the available 1515 marks are distributed:

MarksAdditional constraints
22M=N−1M=N-1
44For all tunnels, 1≤ci≤101 \le c_i \le 10
44Each room has at most 5 outgoing tunnels
55None

Output Specification

Output the minimum cost (in coins) to reach room NN from room 11.

Sample Input

5 7
1 2 3
2 3 2
1 3 6
3 4 3
4 5 7
2 4 1
2 5 10

Output for Sample Input

9

Explanation of Output for Sample Input

A diagram of the dungeon is shown below.

Five vertices labelled 1 through 5 connected by edges labelled with positive integers. 1 connects to 2 with label 3 and to 3 with label 6. Also, 2 connects to 3 with label 2, and to 4 with label 1, and to 5 with label 10. Also, 4 connects to 3 with label 3 and to 5 with label 7.

The optimal escape strategy is as follows:

  1. Increase the chilling level to 33 for a cost of 33 coins.

  2. Walk through the tunnel to room 22.

  3. Decrease the chilling level to 22 for a cost of 11 coin.

  4. Walk through the tunnel to room 33.

  5. Increase the chilling level to 33 for a cost of 11 coin.

  6. Walk through the tunnel to room 44.

  7. Increase the chilling level to 77 for a cost of 44 coins.

  8. Walk through the tunnel to room 55 and escape.

This has a total cost of 99 coins, and it can be shown that no cheaper route exists.