Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25639 Accepted Submission(s): 8884
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. ^_^
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.
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
#include<iostream> #include<stdio.h> #include<string> #include<cstring> using namespace std; const int maxn = 1000010; int dp[maxn]; int pri[maxn]; int a[maxn]; int main() { int n,m; while(~scanf("%d%d",&m,&n)) { for(int i=1;i<=n;i++) scanf("%d",a+i); int tmp_max=-0x3fff; dp[0]=0; //pri[0]=0; memset(pri,0,sizeof(pri)); for(int i=1;i<=m;i++) { tmp_max=-0x3fffffff; for(int j=i;j<=n;j++) { dp[j]=max(dp[j-1],pri[j-1])+a[j]; pri[j-1]=tmp_max; if(tmp_max<dp[j]) tmp_max=dp[j]; } } printf("%d ",tmp_max); } return 0; }
设输入的数组为a[1...n],从中找出m个段,使者几个段的和为最大
dp[i][j]表示前j个数中取i个段的和的最大值,其中最后一个段包含a[j]。(这很关键)
则状态转移方程为:
dp[i][j]=max{dp[i][j-1]+a[j],max{dp[i-1][t]}+a[j]} i-1=<t<j-1
因为dp[i][j]中a[j]可能就自身一个数组成最后一段,或者a[j]与a[j-1]等前面的数组成最后一段。
此题n数据太大,二维数组开不下,而且三重循环,想到状态转移方程后还是困难重重。
想想,二维数组不行的话,肯定要压缩成一维数组:
因为dp[i-1][t]的值只在计算dp[i][j]的时候用到,那么没有必要保存所有的dp[i][j] for i=1 to m,这样我们可以用一维数组存储。
用pre[j]表示j之前一个状态dp[i-1][]中1-j之间,不一定包含a[j]的最大字段和,然后推dp[i][j]状态时,dp[i][j]=max{pre[j-1],dp[j-1]}+a[j];
褐色的为了方便理解,其实不存在。