Max Sum Plus Plus
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 S 1, S 2, S 3, S 4 ... S x, ... S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + ... + S j (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(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + ... + sum(i m, j m) maximal (i x ≤ i y≤ j x or i x ≤ j y ≤ j x 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(i x, j x)(1 ≤ x ≤ m) instead. ^_^
Input
Each test case will begin with two integers m and n, followed by n integers S 1, S 2, S 3 ... S n. Process to the end of file.
Output
Output the maximal summation described above in one line.
Sample Input
1 3 1 2 3
2 6 -1 4 -2 3 -2 3
Sample Output
6 8
Hint
Huge input, scanf and dynamic programming is recommended. 题意:在长度为n的数列中选取k个不重叠的区间,使这k区间和之和最大。输出这个最大值。
思路:定义dp[i][j]为用前j个数取得i个区间,并且第j个数包含在最后一个区间时的最优解,则有递推式:dp[i][[j]=max(dp[i][j-1]+a[j], dp[i-1][t]+a[j]),即这里有两种情况,
一种是直接在前j-1个数形成i个区间末尾加上a[j],因为dp[i][j-1]的最后一个区间包含a[j-1],所以这种情况区间数是不增加的。
第二种情况,是在形成i-1个区间的情况下,以a[j]为一个新区间,这样就有了i个区间,这里i-1<=t<=j-1。
但是如果这么做复杂度会达到O(n^3),需要降低复杂度。
我们发现,dp[i-1][t]最大值可以同样的以dp的思路记录下来,保存在M[]数组内,每次求dp[i][j]时不用在[i-1, j-1]枚举dp[i-1][t]直接拿M[j-1]就行了。
优化一下代码,dp[i-2][j]在后面的计算用不到了,dp[i-1][j]的最大值被存了下来,于是可以把dp[i][j]改成dp[i]节省空间。
AC代码:
1 #include2 #include 3 #include 4 using namespace std; 5 const int MAXN=1e6+10; 6 const long long INF=1e12+10; 7 long long dp[MAXN]; 8 long long a[MAXN],M[MAXN]; 9 int main()10 {11 int k,n;12 while(~scanf("%d %d", &k, &n))13 {14 for(int i=1;i<=n;i++){15 scanf("%lld", &a[i]);16 }17 memset(dp, 0, sizeof(dp));18 memset(M, 0, sizeof(M));19 long long res;20 for(int i=1;i<=k;i++){21 res=-INF;22 for(int j=i;j<=n;j++){23 dp[j]=max(dp[j-1], M[j-1])+a[j];24 M[j-1]=res;25 res=max(res, dp[j]);26 }27 }28 printf("%d\n", res);29 30 }31 }