【区间dp】- P1880 [NOI1995] 石子合并

记录一下第一道ac的区间dp

题目:P1880 [NOI1995] 石子合并 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

代码:

#include <iostream>
using namespace std;
typedef long long ll;
int a[210], dpmax[210][210], dpmin[210][210], sum[210], ma = -1, mi = 1000000000;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++i)
    {
        cin >> a[i];
        sum[i] = sum[i - 1] + a[i];
    }
    for (int i = n + 1; i <= 2 * n; ++i)
    {
        a[i] = a[i - n];
        sum[i] = sum[i - 1] + a[i];
    }
    for (int len = 2; len <= n; ++len)
    {
        for (int i = 1; i <= 2 * n - len + 1; ++i) //延长了一倍,以解决石子成环的问题
        {
            int j = i + len - 1;
            dpmin[i][j] = 1000000000;
            for (int k = i; k < j; ++k)
            {
                dpmax[i][j] = max(dpmax[i][j], dpmax[i][k] + dpmax[k + 1][j] + sum[j] - sum[i - 1]);
                dpmin[i][j] = min(dpmin[i][j], dpmin[i][k] + dpmin[k + 1][j] + sum[j] - sum[i - 1]);
            }
        }
    }
    for (int i = 1; i <= n; ++i)
    {
        ma = max(ma, dpmax[i][i + n - 1]);
        mi = min(mi, dpmin[i][i + n - 1]);
    }
    cout << mi << endl
         << ma << endl;
    return 0;
}

 

  

posted @ 2021-11-22 19:38  blockche  阅读(29)  评论(0编辑  收藏  举报