A ski resort's cable-car network descends through m altitude tiers, each tier offering n stations side by side. Every station (i, j) — tier i, station j — has an integer congestion level g[i][j], where 0 <= g[i][j] <= L - 1 for some fixed number of possible congestion levels L. Riding the cable car away from a station whose congestion level is v, at some tier, down to station k of the very next tier, always charges a transfer toll of transferFee[v][k] — the toll depends only on the departing station's congestion level and the arriving station's index, never on which tier the move happens at.
A rider starts by choosing any single station on tier 1 and must ride down exactly one tier at a time until reaching tier m, ending at any station there. The total cost of a ride is the sum of the congestion levels of every station visited (one per tier, including the very first and the very last) plus the sum of every transfer toll paid along the way. The rider wants to choose a starting station and a full descent path that minimizes this total cost.
Determine that minimum possible total cost.
Example 1
Input
3 2 3 2 1 0 2 1 0 4 6 3 5 7 2
Expected
8
Explanation
Start at tier-1 station 0, congestion level 2, cost 2. Ride down to tier-2 station 1: the departing congestion level is 2, so the toll is transferFee[2][1] = 2, and station 1 of tier 2 has congestion level 2, adding 2. Ride down again to tier-3 station 1: the departing congestion level is still 2, so the toll is again transferFee[2][1] = 2, and station 1 of tier 3 has congestion level 0, adding 0. Total = 2 + 2 + 2 + 2 + 0 = 8, which is the minimum over all starting stations and paths.
Example 2
Input
2 2 2 0 1 1 0 5 1 3 2
Expected
1
Explanation
Start at tier-1 station 0, congestion level 0, cost 0. Ride down to tier-2 station 1: the departing congestion level is 0, so the toll is transferFee[0][1] = 1, and station 1 of tier 2 has congestion level 0, adding 0. Total = 0 + 1 + 0 = 1, the minimum possible.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →