洛谷 P1775 石子合并(弱化版)(区间DP)

发布时间 2023-03-29 16:11:48作者: 高尔赛凡尔娟

洛谷题面

https://www.luogu.com.cn/problem/P1775

AcWing题面

https://www.acwing.com/problem/content/description/284/

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18,MINN=-MAXN,INF=0x3f3f3f3f;
const LL N=2e7+10,M=4023;
const LL mod=100000007;
const double PI=3.1415926535;
#define endl '\n'
LL n,a[N],s[N],f[M][M];

int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    LL T=1;
    //cin>>T;
    while(T--)
    {
        cin>>n;
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
        }
        for(int i=1;i<=n;i++)//前缀和
        {
            s[i]=s[i-1]+a[i];
        }
        for(int len=2;len<=n;len++)//枚举长度
        {
            for(int i=1;i+len-1<=n;i++)//枚举起点
            {
                int l=i,r=len+i-1;
                f[l][r]=INF;//初始化f为很大的数,因为要取最小值
                for(int j=l;j<r;j++)//枚举分界点
                {
                    f[l][r]=min(f[l][r],f[l][j]+f[j+1][r]+s[r]-s[l-1]);//状态转移方程
                }
            }
        }
        cout<<f[1][n]<<endl;
    }
    return 0;
}
```![](https://img2023.cnblogs.com/blog/2832235/202303/2832235-20230329160312426-1056253594.png)