Editorial for Merge Piles
Approach
The important observation is that after several moves, every group always contains a contiguous range of the original piles.
Let dpl,r be the minimum cost needed to merge piles l,l+1,…,r into one group. If l=r, the range is already one group, so dpl,r=0.
For a range with at least two piles, consider the final merge made inside that range. Immediately before that final merge, the range must be split into two adjacent merged groups: l,…,k and k+1,…,r for some l≤k<r.
The cost is:
dpl,k+dpk+1,r+al+al+1+⋯+ar
Try every possible split k and take the minimum. Prefix sums let us find each range sum in constant time.
Compute the values in increasing order of interval length, since shorter intervals are needed before longer intervals.
Time complexity is O(N3).
Solution (Python)
import sys
data = list(map(int, sys.stdin.buffer.read().split()))
n = data[0]
a = data[1:]
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + a[i]
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for left in range(n - length + 1):
right = left + length - 1
total = prefix[right + 1] - prefix[left]
best = 10**30
for split in range(left, right):
cost = dp[left][split] + dp[split + 1][right] + total
if cost < best:
best = cost
dp[left][right] = best
print(dp[0][n - 1])
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.