/*Max Sum Plus Plus Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 18902 Accepted Submission(s): 6217 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. ^_^ Input Each test case will begin with two integers m and n, followed by n integers S1, S2, S3 ... Sn. 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. Author JGShining(极光炫影) Recommend We have carefully selected several similar problems for you: 1080 1078 1158 1058 1227 */ #include<stdio.h> #include<string.h> const int MAX = 1000005; int num[MAX], pre[MAX]; int max(int x, int y) { return x>y?x:y; } int DP(int n, int m) { for(int i = 1; i <= m; ++i)//段数 { int temp = 0; for(int j = 1; j <= i; ++j) temp += num[j];//即dp[i][j] j == i pre[n] = temp;//临时存放为下一个段数做准备 for(int k = i+1; k <= n; ++k)//算出dp[i][k]的最大值 { temp = max(pre[k-1], temp) + num[k];//dp[i][k] = max(dp[i][t], dp[i][k-1] )+num[k] pre[k-1] = pre[n];//保存dp[i][t]的最大值,为下个段数做准备 pre[n] = max(pre[n], temp);//更新pre为下一轮i做准备 } } return pre[n]; } int main() { int n, m, i; while(scanf("%d%d", &m, &n) != EOF) { for(i = 1; i <= n; ++i) scanf("%d", &num[i]); memset(pre, 0, sizeof(pre)); printf("%d\n", DP(n, m)); } return 0; }
题意:给出n个数,并且给出m条段数,要求每几个连续的数作为一个段,并且段与段之间没有交集,求着n个数中怎样的m段能获得最大的段和。
思路:dp【i】【j】代表前j个数分成i段所能获得的最大和并且最后一段必定包含num【j】,dp【i】【j】 = max(dp【i-1】【t】,dp【i】【j-1】)+num【j】, (i-1<=t<=j-1),dp【i-1】【t】表示当分成i-1段时所能获得的最大值加上当前的num【j】独立段,或者是前j-1个数分成了i段,将num【j】分入最后一段。
这个是整体的思路,但是由于数据量比较大所以这个方法这里要超时,所以需要优化,即将dp【i-1】【t】这个优化可以一边求dp【i】【j】一边求出下一轮i+1所需要的dp【i】【t】。具体求解看这个链接:http://www.cnblogs.com/dongsheng/archive/2013/05/28/3104629.html
难点:如何设计dp方程以及优化是本题的难点。