This page is still under construction.

Parts of this page are still being built. What you see may change.

River Crossing

Interview

Time limit1sMemory limit128 MB

Summary
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 NN cows (1≤N≤25001 \le N \le 2500) 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 MM minutes (1≤M≤10001 \le M \le 1000). Loading cows one at a time, the ii-th cow added makes the crossing take MiM_i more minutes (1≤Mi≤10001 \le M_i \le 1000) than it would with i−1i-1 cows. So a raft carrying kk cows crosses in M+M1+M2+⋯+MkM + M_1 + M_2 + \cdots + M_k minutes. The cows are interchangeable: only how many ride together matters, and the marginal costs apply in the given order M1,M2,…M_1, M_2, \ldots

Farmer John may ferry the cows over in several trips; after each trip except the last he rows back alone, which also takes MM minutes. Determine the minimum total time to get all NN cows across, including the return trips.

Input

  • Line 1: two space-separated integers NN and MM.
  • Lines 2 to N+1N+1: line i+1i+1 contains a single integer MiM_i.

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 23+10+17=5023 + 10 + 17 = 50 minutes.

Examples2

  1. Example 1

    Input
    5 10
    3
    4
    6
    100
    1
    
    Expected output
    50
    
  2. Example 2

    Input
    1 10
    5
    
    Expected output
    15