Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4521 Accepted Submission(s): 1476
Problem Description
Now I think you have got an AC in Ignatius.L's "Max Sum" problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem.
Given a consecutive number sequence S1, S2, S3, S4 ... Sx, ... Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + ... + Sj (1 ≤ i ≤ j ≤ n).
Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i1, j1) + sum(i2, j2) + sum(i3, j3) + ... + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx is not allowed).
But I`m lazy, I don't want to write a special-judge module, so you don't have to output m pairs of i and j, just output the maximal summation of sum(ix, jx)(1 ≤ x ≤ m) instead. ^_^
Author
JGShining(极光炫影)
思路:dp[i][j]表示前j个元素分成i段的最优解,同时这个最优解是由a[j]元素结束的。转移方程是dp[i][j]=max{f[i][j-1]+a[j],f[i-1][k]+a[j],(i-1<=k<j)} (i<=j<=n-m+i)
#include<bits/stdc++.h>
using namespace std;
const int N = 1001000;
const long long INF = 0x3f3f3f3f3f3f3f3f;
long long dp[2][N], maxn;//dp[i][j]表示前j个元素分成i段的最优解
int a[N];
int main( )
int m, n, t;
while(cin >> m >> n) {
t = 1; ///用来滚动数组
for(int i = 1; i <= n; ++i)
dp[0][i] = -INF;
for(int i = 1; i <= n; ++i)
cin >> a[i];
for(int i = 1; i <= m; ++i, t = 1 - t) { ///t=1-t就是在循环滚动
dp[t][i] = dp[1 - t][i - 1] + a[i]; ///对角线的值其实就是前n项和啦!!
maxn = dp[1 - t][i - 1]; ///别把这个忘了
for(int j = i + 1; j <= n - m + i; ++j) {
maxn = max(maxn, dp[1 - t][j - 1]); ///maxn更新记录max(dp[i-1][i-1]~dp[i-1][j-1])
dp[t][j] = max(dp[t][j - 1], maxn) + a[j]; ///状态的转移步骤
}
}
t = 1 - t; ///最后i>m时的那一个++i, t=1-t的影响要转过来
maxn = -INF;
/**
注意,dp[i][j]是表示前j个数在取a[j]情况下分i段的最大和;
也就是dp[m%2][n不一定是最优解,因为可能不加a[n]还更大;
**/
cout << *max_element(dp[t] + m, dp[t] + n + 1) << endl;
}
return 0;
}