AcWing 1068. 环形石子合并 python
原题链接
简单
作者:
小沈____
,
2020-08-30 16:15:31
,
所有人可见
,
阅读 599
python 解
n = int(input())
nums = list(map(int,input().split()))
nn = n * 2
nums += nums
min_dp = [[float("inf")]*(nn+1) for _ in range(nn+1)]
max_dp = [[-float("inf") ]*(nn+1) for _ in range(nn+1)]
#: 前缀和
for i in range(1,nn):
nums[i] += nums[i-1]
nums = [0] + nums
#: DP
for len in range(1,n+1):
for l in range(1,nn-len+2):
r = l+len-1
if len == 1:
min_dp[l][r],max_dp[l][r] = 0 ,0
#: 区间DP 重要模板!!下面很关键
for k in range(l,r):
min_dp[l][r] = min(min_dp[l][r],min_dp[l][k] + min_dp[k+1][r] + nums[r]-nums[l-1])
max_dp[l][r] = max(max_dp[l][r],max_dp[l][k] + max_dp[k+1][r] + nums[r]-nums[l-1])
min_r,max_r = float("inf"),-float("inf")
for l in range(1,n+1):
r = l+n-1
min_r = min(min_r,min_dp[l][r])
max_r = max(max_r,max_dp[l][r])
print(min_r)
print(max_r)