https://www.51nod.com/Challenge/Problem.html#!#problemId=1052
一道神奇的dp题,留着以后分析一下。
思考一下动态规划的优化(dp套dp)、初始化、消维和滚动数组。
const int maxn = 5e3 + 5;
ll sum[maxn], dp[2][maxn], f[2][maxn];
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; ++i) cin >> sum[i];
for (int i = 2; i <= n; ++i) sum[i] += sum[i - 1];
for (int i = 2; i <= n; ++i) dp[0][i] = dp[1][i] = f[0][i] = f[1][i] = -INF;
f[0][0] = f[1][1] = f[1][0] = dp[0][0] = dp[1][0] = 0, dp[1][1] = sum[1];
for (int i = 2; i <= n; ++i){
for (int j = 1; j <= i && j <= m; ++j){
///dp[i][j] = dp[i - 1][j];
///dp[i][j] = max{dp[k][j - 1] + sum[i] - sum[k]}, (k < i)
///dp[i][j] = sum[i] + max{dp[k][j - 1] - sum[k]}, (k < i)
///f[i][j] = max{dp[k][j - 1] - sum[k]}, (k < i)
///f[i - 1][j] = max{dp[k][j - 1] - sum[k]}, (k < i - 1)
///f[i][j] = max(f[i - 1][j], dp[i - 1][j - 1] - sum[i - 1]);
///dp[i][j] = sum[i] + max(dp[i][j], f[i][j]);
f[i & 1][j] = max(f[(i - 1) & 1][j], dp[(i - 1) & 1][j - 1] - sum[i - 1]);
dp[i & 1][j] = max(dp[(i - 1) & 1][j], sum[i] + f[i & 1][j]);
}
}
cout << dp[n & 1][m] << endl;
return 0;
}