Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 33207 Accepted Submission(s): 11817
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. ^_^
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.
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 8HintHuge input, scanf and dynamic programming is recommended.dp[i][j]表示把前j个数分成i段,必须以第j个数为末尾的最大和 那么有两种可能: 1.dp[i][j]=dp[i][j-1]+a[j],即前j-1个数已经分成 i段,在j-1之后接上j。 2.dp[i][j]=MAXN[i-1][j-1]+a[j],MAXN[i-1][j-1]表示将前j-1个数 分成i-1段所能得到的最大和。注意这里不能用dp[i-1][j-1]+a[j]. 因为此条件下a[j]不与前一个元素相接,而dp[i-1][j-1]表示的是 以第j-1个数为结尾的分为i-1段的最大值,因此这里用MAXN[i-1][j-1]; 而MAXN[i][j]即是dp[i][i]~dp[i][j]中的最大值。 代码: #include<bits/stdc++.h> int a[1000002],dp[1000002],MAXN[100002];//为了节省内存,这里全部转 //化成一维数组求解 using namespace std; int main() { int n,m; while(~scanf("%d%d",&m,&n)) { memset(dp,0,sizeof(dp)); memset(MAXN,0,sizeof(MAXN)); int i,j; for(i=1;i<=n;i++) scanf("%d",&a[i]); int mm; for(i=1;i<=m;i++) { mm=-1e9; for(j=i;j<=n;j++) { dp[j]=max(dp[j-1]+a[j],MAXN[j-1]+a[j]); MAXN[j-1]=mm;//这里的mm是上一次循环得到的,即 //前j-1的最大值,赋给MAXN给下一曾 //i的循环使用。 mm=max(mm,dp[j]);//更新mm给下一次使用。 //本来我是用的滚动数组,后来看了大神的博客眼前一亮 //还有这般奇妙的解法。 } } printf("%d\n",mm); } return 0; }