Problem 578860 · hard · Phase 05 Advanced Algorithms & Graphs

A Training Ride That Only Gets Harder

graphs · shortest paths · sorting · dynamic programming over edges

A cycling coach plans a training ride through n villages 0 .. n-1. The roads are undirected: roads[i] = [u, v, grade, minutes] joins villages u and v, has difficulty grade, and takes minutes to ride in either direction (parallel roads and loops are possible).

To build up strength, every road on the ride must have a strictly higher grade than the road ridden just before it. Villages may be visited more than once. Return the minimum total minutes of a ride from src to dst, or -1 if no such ride exists. If src == dst the answer is 0.

Examples

Input:  n = 4, roads = [[0,1,1,5],[1,2,2,5],[2,3,3,5],[0,3,2,20],[1,3,1,1]],
        src = 0, dst = 3
Output: 15
Explanation: 0-1-2-3 has grades 1, 2, 3. The quick road 1-3 has grade 1,
so it cannot follow road 0-1, which also has grade 1.

Input:  n = 3, roads = [[0,1,3,1],[1,2,2,1]], src = 0, dst = 2
Output: -1

Input:  n = 3, roads = [[0,1,3,1],[1,2,2,1]], src = 2, dst = 0
Output: 2

Constraints

  • 1 <= n <= 3 * 10**4, 0 <= len(roads) <= 6 * 10**4
  • 0 <= grade <= 10**6, 1 <= minutes <= 10**5

Goals

  • Notice that a constraint on consecutive edges makes the node alone an insufficient state
  • Process roads in order of grade instead of nodes in order of distance
  • Handle roads of equal grade as one batch so two of them are never chained
Starting Python…