石子合并
n=int(input())
a=[0]+list(map(int,input().split()))
for i in range(1,n+1):
a[i]+=a[i-1]
dp=[[1<<31 for i in range(n+1)]for j in range(n+1)]
for i in range(1,n+1):
dp[i][i]=0
for k in range(1,n):
for i in range(1,n+1):
l=i
r=i+k
if r>=n+1:
break
for j in range(l,r):
dp[l][r]=min(dp[l][r],dp[l][j]+dp[j+1][r]+a[r]-a[l-1])
print(dp[1][n])
环形石子合并
思路:讲环形拉直,并且延展一倍,在2*n长度的区间上进行dp,然后求长度为n的区别的情况
- 易错点: 从i开始的第n 个数,是i+n-1
n=int(input())
a=list(map(int,input().split()))
a=a+a
a=[0]+a
for i in range(1,2*n+1):
a[i]+=a[i-1]
dpmax=[[-1<<31 for i in range(2*n+1)]for j in range(2*n+1)]
dpmin=[[1<<31 for i in range(2*n+1)]for j in range(2*n+1)]
for i in range(1,2*n+1):
dpmax[i][i]=0
dpmin[i][i]=0
for k in range(1,n):
for i in range(1,2*n):
l=i
r=i+k
if r>2*n:
break
for j in range(l,r):
dpmax[l][r]=max(dpmax[l][r],dpmax[l][j]+dpmax[j+1][r]+a[r]-a[l-1])
dpmin[l][r]=min(dpmin[l][r],dpmin[l][j]+dpmin[j+1][r]+a[r]-a[l-1])
ansmax=-1<<31
ansmin=1<<31
for i in range(1,n+2):
ansmax=max(ansmax,dpmax[i][i+n-1])
ansmin=min(ansmin,dpmin[i][i+n-1])
print(ansmin)
print(ansmax)
能量项链
- 易错点:这里每次枚举必须枚举三个数字,所以j不能等于l或r
n=int(input())
a=list(map(int,input().split()))
a=[0]+a+a
dp=[[0 for i in range(2*n+1)]for j in range(2*n+1)]
for k in range(2,n+1):
for i in range(1,2*n):
l=i
r=i+k
if r>2*n:
break
for j in range(l+1,r):
dp[l][r]=max(dp[l][r],dp[l][j]+dp[j][r]+a[l]*a[j]*a[r])
ans=0
for i in range(1,n+1):
ans=max(ans,dp[i][i+n])
print(ans)
凸多边形的划分
这一题的本质居然就是一个最简单的区间dp,还得好好琢磨啊
n=int(input())
a=[0]+list(map(int,input().split()))
dp=[[0 for i in range(n+1)]for j in range(n+1)]
for k in range(2,n):
for i in range(1,n):
l=i
r=i+k
if r>n:
break
dp[l][r]=1<<31
for j in range(l+1,r):
dp[l][r]=min(dp[l][r],dp[l][j]+dp[j][r]+a[l]*a[j]*a[r])
print(dp[1][n])
加分二叉树
看起来是二叉树,但是dp的过程不需要和常规的二叉树题目一样遍历,只是最后需要dfs一下
def dfs(l,r):
if l>r:
return
print(fa[l][r],end=" ")
dfs(l,fa[l][r]-1)
dfs(fa[l][r]+1,r)
return
n=int(input())
a=[0]+list(map(int,input().split()))
dp=[[0 for i in range(n+1)]for j in range(n+1)]
fa=[[0 for i in range(n+1)]for j in range(n+1)]
for i in range(1,n+1):
dp[i][i]=a[i]
fa[i][i]=i
for k in range(1,n):
for i in range(1,n):
l=i
r=i+k
if r>n:
break
for j in range(l,r+1):
left,right=-1,-1
if j==l:
left=1
else:
left=dp[l][j-1]
if j==r:
right=1
else:
right=dp[j+1][r]
score=left*right+a[j]
if dp[l][r]<score:
dp[l][r]=score
fa[l][r]=j
print(dp[1][n])
dfs(1,n)