OPTCUT - Chặt cây

You have to cut a piece of wood into n smaller pieces, each piece is of length ai. The pieces must be cut in order exactly a1, a2 ... an from left to right.

At each step, you may cut a piece into two smaller pieces. The cost for that cut is the length of the piece before cutting.

Different cut order will result in different costs.

For example, you need to cut a wooden stick of length 20 into 4 pieces of length 3, 5, 2 and 10 in order.

When cutting from left to right:

  • 20 cuts into 3 and 17, cost 20.
  • 17 cuts into 5 and 12, cost 17.
  • 12 cuts into 2 and 10, cost 12.

Total cost: 49

When cutting from right to left:

  • 20 cuts into 10 and 10, cost 20.
  • 10 cuts into 8 and 2, cost 10.
  • 8 cuts into 3 and 5, cost 8.

Total cost: 38

Find the minimum cost to cut the initial piece into n given smaller pieces.

Input

Line 1: n (1 ≤ n ≤ 2000)
Line 2: n positive integers a1, a2 ... an, knowing that the length of the wooden bar a1 + a 2 + ... + an ≤ 500000

Output

A single integer which is the smallest cost found.

Example

Input:
4
3 5 2 10

Output:
37

Added by:Jimmy
Date:2009-03-03
Time limit:0.200s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ERL JS-RHINO PERL6

hide comments
2021-05-20 20:56:14 Simes
The order of the final sizes of the pieces of wood cannot vary, but the order of the cuts that produces those pieces can vary.
20 -> 3 + 17 -> 3 + 5 + 12 -> 3 + 5 + 2 + 10, for a cost of 20 + 17 + 12 = 49
20 -> 10 + 10 -> 8 + 2 + 10 -> 3 + 5 + 2 + 10, for a cost of 20 + 10 + 8 = 38
20 -> 10 + 10 -> 3 + 7 + 10 -> 3 + 5 + 2 + 10, for a cost of 20 + 10 + 7 = 37


Last edit: 2021-07-03 22:54:08
2021-05-20 11:39:47
I don't understand. The vietnamese statement translates:

Different cutting orders will result in different total costs when cutting the log into the required n segments.
(example of two different cutting orders)
Find the way to chop with the lowest total cost.

What can the cost depend on if the order does not vary?
2021-05-19 17:06:41 [Rampage] Blue.Mary
@nadstratosfer: The order can't be changed. So 10 -> 5 + (5) is invalid.
2021-05-19 15:30:27
(20) -> 10 + (10) -> 5 + (5) -> 3+2, total cost = 35. Why does the sample show 37?
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.