[动态规划](3)区间DP

区间DP

引言

所有的区间dp问题,第一维都是枚举区间长度,一般 len = 1 用来初始化,枚举从 len = 2 开始,第二维枚举起点 i (右端定 j 自动获取 j = i + len - 1)

常用套路模板:

```C++ for (int i = 1; i <= n; i++) { dp[i][i] = 初始值 } for (int len = 2; len <= n; len++) //区间长度 for (int i = 1; i + len - 1 <= n; i++) { //枚举起点 int j = i + len - 1; //区间终点 for (int k = i; k < j; k++) { //枚举分割点,构造状态转移方程 dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j] + w[i][j]); } }


#### 模板题:[282. 石子合并 - AcWing题库](https://www.acwing.com/problem/content/284/)

![image-20210707150746448](https://axuannote-1304271763.cos.ap-nanjing.myqcloud.com/image-20210707150746448.png)

#### 思维导图:

![image-20210707150832444](https://axuannote-1304271763.cos.ap-nanjing.myqcloud.com/image-20210707150832444.png)

#### 代码:

```C++
#include <iostream>

using namespace std;

const int N = 307;

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

int main() {
    int n;
    cin >> n;

    //s为前缀和数组,求这个区间内的和
    for (int i = 1; i <= n; i ++) {
        cin >> a[i];
        s[i] += s[i - 1] + a[i];
    }

    // 区间 DP 枚举套路:长度+左端点 
    for (int len = 1; len < n; len ++) { // len表示i和j堆下标的差值
        for (int i = 1; i + len <= n; i ++) {
            int j = i + len; // 自动得到右端点
            f[i][j] = 1e8;
            for (int k = i; k <= j - 1; k ++) { // 必须满足k + 1 <= j
                f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j] + s[j] - s[i - 1]);
            }
        }
    }

    cout << f[1][n] << endl;

    return 0;
}

loding...

本文链接:

https://nullcode.fun/152.html
1 + 2 =
快来做第一个评论的人吧~