Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25456 Accepted Submission(s): 8795
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. ^_^
Process to the end of file.
核心代碼:
for(i=1;i<=m;i++)
{ Max=-99999999; for(j=i;j<=n;j++) // 想想j爲什麼從=i開始 { now[j]=max(now[j-1]+a[j],pre[j-1]+a[j]); //now[j]有兩種來源,一種是直接在第i個子段之後添加a[j] //一種是是a[j]單獨成爲1個子段 pre[j-1]=Max; //更新pre使得pre是前j-1箇中最大子段和 if(now[j]>Max) Max=now[j]; }
}
代碼實現:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 1000000+10;
const int inf = -0x7fffffff;
int a[maxn];
int pre[maxn];
int now[maxn];
int MAX;
int main()
{
int m, n;
while( ~scanf("%d%d",&m,&n) )
{
memset(a,0,sizeof(a));
memset(pre,0,sizeof(pre));
memset(now,0,sizeof(now));
int i,j;
for( i=1; i<=n; i++ )
scanf("%d",&a[i]);
for( i=1; i<=m; i++ )
{
MAX = inf;
for( j=i; j<=n; j++ )
{ // 順序不能顛倒,想想顛倒的後果;
now[j] = max(now[j-1]+a[j], pre[j-1]+a[j]);
pre[j-1] = MAX;
MAX = max(MAX, now[j]);
}
}
printf("%d\n",MAX);
}
return 0;
}