Heavy Stones
Time limit2sMemory limit512 MB
For each starting pile k, find the minimum total cost of merging all piles into one when every merge must extend the currently selected pile to a neighbor.
- Level
Hard9 of 10
- Topics
- Greedy, Dynamic programming
- Solved
- No attempts yet
Problem
After learning the Garsia-Wachs algorithm, you came up with the following problem.
There are piles of stones in a line. The -th pile contains stones. You want to merge all the stones into one pile.
At first, you select the -th pile. Then you perform the following operation on the selected pile: choose the left or right adjacent pile of the selected one, and merge them into one pile. The new pile becomes the selected pile after the operation. After performing this operation times, only one pile is left. The cost of each merge operation is the number of stones in the new pile.
You want to know the smallest total cost if you select the -th pile initially. For , output the answer.
Input
The first line contains an integer ().
The second line contains integers ().
Output
Output integers. The -th number is the smallest total cost if you select the -th pile initially.
Hint
If you select the 4th pile initially, the process can go as follows:
{2, 1, 3, 5, 4} → {2, 1, 8, 4} → {2, 9, 4} → {11, 4} → {15}
The total cost is 8 + 9 + 11 + 15 = 43.