Merge Piles
View as PDF
Submit solution
Points:
100
Time limit:
1.0s
PyPy 3
3.0s
Python 3
3.0s
Memory limit:
500M
Problem type
You are given a sequence of piles. The
-th pile contains
stones.
In one move, you may merge two adjacent groups of piles into one larger group. The cost of the move is the total number of stones in the newly merged group.
After exactly moves, all piles will be merged into one group. Find the minimum possible
total cost.
Input
The first line contains an integer , the number of piles.
The second line contains integers:
.
Output
Print one integer: the minimum possible total cost to merge all piles into one group.
Constraints
Example 1
Input
4
10 20 30 40
Output
190
Explanation
One optimal sequence is:
- Merge piles with
and
stones, paying
.
- Merge the new group with the pile containing
stones, paying
.
- Merge the new group with the pile containing
stones, paying
.
The total cost is .
Example 2
Input
5
1 100 1 100 1
Output
507
Comments