Under construction

Still being built. Things may change

Splitting DNA

Interview

Time limit1sMemory limit512 MB

Summary
Given the lengths of N fragments in order, find the minimum total energy to split the original chain, where each cut costs the current chain length.
Level

Medium6 of 10

Topics
Dynamic programming, Intervals, Prefix sum, Greedy
Solved
No attempts yet

Problem

You are studying a protein that splits long chains of DNA into smaller chains. The protein works as follows. To split a long chain of DNA, the protein first "reads" the whole chain and cuts it into two parts (not necessarily equal), then recursively splits the two smaller chains.

Splitting a chain S1S2S_1S_2 into the two parts S1S_1 and S2S_2 takes an amount of energy proportional to the length of S1S2S_1S_2 (the sum of the lengths of S1S_1 and S2S_2). More generally, splitting a chain S1…SNS_1 \ldots S_N (N>1N > 1) takes an energy proportional to the length of S1…SNS_1 \ldots S_N to cut it into two, plus the energy required to recursively split the two smaller chains.

You know the original DNA chain S1…SNS_1 \ldots S_N and the NN fragments S1,…,SNS_1, \ldots, S_N obtained after the split. Since nature is usually very energy-efficient, you wonder what the minimal energy required to split the DNA chain is.

You noticed that the computation of this minimal energy only depends on L1,…,LNL_1, \ldots, L_N, where LiL_i is the length of SiS_i. Given these NN integers L1,…,LNL_1, \ldots, L_N, you want to compute the minimal energy required by the protein to split the long chain into these chunks.

Input

The input consists of two lines:

  • the first line contains the number NN of strings, an integer;
  • the second line contains NN space-separated integers representing L1,…,LNL_1, \ldots, L_N.

Output

Print a single line with a single integer: the minimal total energy required to split the original chain.

Constraints

  • 1≤N≤5001 \le N \le 500;
  • 0≤Li≤10140 \le L_i \le 10^{14} for all 1≤i≤N1 \le i \le N.

Examples2

  1. Example 1

    Input
    3
    1 2 1
    
    Expected output
    7
    
  2. Example 2

    Input
    3
    2 1 1
    
    Expected output
    6