River Crossing
InterviewTime limit1sMemory limit128 MB
Split N cows into consecutive groups, each crossing costs M plus the cumulative marginal cost, and add M for every return trip; minimize the total time.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Prefix sum, Array, Greedy
- Solved
- No attempts yet
Problem
Farmer John needs to move his cows () across a river. Only a single raft is available, and Farmer John must be aboard for every crossing.
Adding cows to the raft slows it down. With Farmer John alone, the raft crosses the river in minutes (). Loading cows one at a time, the -th cow added makes the crossing take more minutes () than it would with cows. So a raft carrying cows crosses in minutes. The cows are interchangeable: only how many ride together matters, and the marginal costs apply in the given order
Farmer John may ferry the cows over in several trips; after each trip except the last he rows back alone, which also takes minutes. Determine the minimum total time to get all cows across, including the return trips.
Input
- Line 1: two space-separated integers and .
- Lines 2 to : line contains a single integer .
Output
- A single line: the minimum total time to move all cows across the river.
Hint
Suppose there are five cows and the crossing times build up like this: Farmer John alone takes 10 minutes, with one cow 13, with two 17, with three 23, with four 123, and with all five 124. One good plan is to cross with three cows (23 minutes), return alone (10 minutes), then cross with the remaining two (17 minutes), for a total of minutes.