All problems

Problem 462

Minimum Cost to Cut a Stick

Hard · 30 pts · Array, Dynamic Programming, Interval DP, Sorting

Problem

A wooden stick has length L, with positions marked 0 to L. You must cut it at every one of the given positions, in an order you choose. Each cut costs the length of the piece being cut at that moment, and splits it into two pieces. Find the minimum total cost of making all the cuts. Sort the cut positions, add the two ends 0 and L, and let cost[i][j] be the cheapest way to make every cut strictly between points i and j.

Input

First line: L and N. Second line: the N cut positions.

Output

Print the minimum total cost.

Constraints

2 <= L <= 1000000; 1 <= N <= 100; 0 < position < L; positions are distinct

Example input

7 4
1 3 4 5

Example output

16

Explanation

For L = 7 and cuts at 1 3 4 5, cutting in the order 3, 5, 1, 4 costs 7 + 4 + 3 + 2 = 16, and no order is cheaper.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Boolean Parenthesization Next: Optimal Strategy for a Coin Game