acwing 282 Stone merger (Interval DP)

Topic

Insert picture description here

answer

Insert picture description here
We enumerate the merged intervals from small to large, and divide the set by the dividing line of the last merge. For the interval [l,r] we assume that the last time is divided by k, then the minimum of this merge is equal to f[l][k] + f[k+1][r] +s[r] -s[l+1] (the smallest left part + the smallest right part + the value needed this time). With the state transition equation, we can enumerate

Code

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 310;
const int INF = 0x3f3f3f3f;

int n;
int a[N], s[N];
int f[N][N];

int main() {
    
    

    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 = i + len - 1;
            f[l][r] = INF;   //初始化最小
            for (int k = l; k < r; k++) {
    
       //合并的分解位置
                f[l][r] = min(f[l][r], f[l][k] + f[k + 1][r] + s[r] - s[l - 1]);
            }

        }
    }

    cout<<f[1][n]<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114819685