Conveyor tolls
HardOnline Assessment
Find the best starting station on a conveyor network that charges tolls.
A depot has n conveyor stations numbered 0 to n - 1. Every station has exactly one outgoing belt: a box sitting at station i is carried to station next_station[i] (which may be i itself). Each station also charges a toll: whenever a box leaves station i along its belt, tolls[i] is paid.
A box starts at some station and travels exactly hops belt hops. The total it pays is the sum of the tolls of the stations it leaves, counting the starting station (and counting a station again every time the box leaves it, if the box passes through it repeatedly). The station where the box ends up after the last hop pays nothing, because the box never leaves it.
Input: next_station, a list of n integers (each a valid station number); tolls, a list of n non-negative integers; and hops, a non-negative integer.
Output: a list [station, total]: the starting station for which the box pays the most in total, and that total. If several stations tie for the largest total, return the one with the smallest station number. With hops = 0 every total is 0, so the answer is [0, 0].
hops can be as large as a trillion, so moving a box hop by hop from every station will be too slow.
Example 1
- Input:
- [[1,2,0],[5,1,1],2]
- Output:
- [0,6]
- Explanation
- With 2 hops, a box from station 0 pays 5 + 1 = 6, from station 1 pays 1 + 1 = 2, and from station 2 pays 1 + 5 = 6. Stations 0 and 2 tie, and the smaller number wins, so the answer is
[0, 6].
Example 2
- Input:
- [[0,0,1],[3,4,9],4]
- Output:
- [2,19]
- Explanation
- Station 0 sends boxes to itself. From station 2 a box leaves stations 2, 1, 0 and 0, paying 9 + 4 + 3 + 3 = 19. From station 1 it pays 4 + 3 + 3 + 3 = 13, and from station 0 it pays 12. The answer is
[2, 19].
Example 3
- Input:
- [[1,2,3,1],[10,1,1,1],1000000000000]
- Output:
- [0,1000000000009]
- Explanation
- Stations 1, 2 and 3 form a loop that charges 1 per hop, so a box that starts on the loop pays 1,000,000,000,000. A box from station 0 pays 10 once when it leaves, then 1 for each of the remaining 999,999,999,999 hops: 1,000,000,000,009. The answer is
[0, 1000000000009].
Constraints
1 <= n <= 1,200, wheren = next_station.length = tolls.length0 <= next_station[i] < nand0 <= tolls[i] <= 1,0000 <= hops <= 1,000,000,000,000