1.6区间DP
作者:互联网
\(1068\).环形石子合并
题目描述:
给定\(n\)堆石子,围成一个圆环,要求合并成一堆石子,每次只能合并相邻两堆,每合并两堆都要花费体力,问最大的体力和最小的体力。
思路:
将长度为\(N\)的圆环变成长度为\(2n\)的序列,然后使用\(y\)式\(DP\)分析法。
状态表示:\(f[i,j]\)表示从\(i\)到\(j\)合并的最小体力值。
\(s[i,j]\)表示从\(i\)到\(j\)的前缀和。
状态转移方程:\(f[i,j]=min(f[i,j],f[i,k]+f[k+1,j]+s_r-s_{l-1})\)。
Code:
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 410, INF = 0x3f3f3f3f;
int n;
int w[N], s[N];
int f[N][N], g[N][N];
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++ )
{
cin >> w[i];
w[i + n] = w[i];
}
for (int i = 1; i <= n * 2; i ++ ) s[i] = s[i - 1] + w[i];
memset(f, 0x3f, sizeof f);
memset(g, -0x3f, sizeof g);
for (int len = 1; len <= n; len ++ )
for (int l = 1; l + len - 1 <= n * 2; l ++ )
{
int r = l + len - 1;
if (l == r) f[l][r] = g[l][r] = 0;
else
{
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]);
g[l][r] = max(g[l][r], g[l][k] + g[k + 1][r] + s[r] - s[l - 1]);
}
}
}
int minv = INF, maxv = -INF;
for (int i = 1; i <= n; i ++ )
{
minv = min(minv, f[i][i + n - 1]);
maxv = max(maxv, g[i][i + n - 1]);
}
cout << minv << endl << maxv << endl;
return 0;
}
标签:体力,1.6,int,石子,合并,区间,include,DP 来源: https://www.cnblogs.com/AndyLJX/p/15151754.html