Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6725 Accepted Submission(s): 2251
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.
思考了很长很长时间,不过解决后放了一天,今天终于义无反顾的一起来就放博客了!!
昨天和舍友BR聊到4点左右,看来放假了也得早点回去了(避免落单在宿舍)
言归正传,卡了那么久,DP独立思考
#include//1000ms卡到984ms ^^ 故意的哈(几个月以前的记录,这句废话不打算删)
#include
#include
using namespace std;
int dp[1222222],alone[1222222],a[1222222];
int main()
{
int i,j,n,m;
while(~scanf("%d",&m))
{
scanf("%d",&n);
memset(dp,0,sizeof(dp));
memset(alone ,0,sizeof(alone));
for(i=1;i<=n;i++)scanf("%d",&a[i]);
int tmax;
//★循环i内的alone[j]:保存前j个数(含j)分i段时的最大和★
for(i=1;i<=m;i++)//★分i段
{
tmax=-(1<<30);
//printf("a[],alo[],dp[]\n");
for(j=i;j<=n;j++)//从i开始枚举:至少分i段,这里就直接前i个数i段
{
dp[j]=_cpp_max(dp[j-1],alone[j-1])+a[j];
/*★★dp前者表示a[j]与a[j-1]所在的一段合并成一段。al后者表示以a[j]为首开始第 i 段
★循环i内的alone[j]:保存前j个数(含j)分i段时的最大和★所以可以有alone[j-1]+a[j]
alone在同一次的j循环总是走不到一起,能走到一起的是下个i的"j循环"//*///\
printf("%2d %2d %2d\n",a[j],alone[j-1],dp[j]);
if(j>i)alone[j-1]=tmax;
//★循环i内的alone[j]:保存前j个数(含j)分i段时的最大和(所以答案是最后一次循环(分n段)时候的tmax)★//\
alone巧妙的保存赋值到i层j-1而又不影响当前i-1层的j-1的使用,代表前j-1个分i段最大和.//\
细心点会发现最大只保存到alone[n-1],reason:分i段时,枚举用的是分★i-1段层的alone[i-1至n-1](所以答案是最后一次循环时候( 可含a[n])的tmax)//\
比如分n-1段,最后第1次进内循环时起点是j=n-1,即前面n-2个数单独分成n-2段(所以答案是最后一次循环(分m段)时候的tmax)
if(tmax
/*
带★(写完解释的那天晚上想说,老人都看懂了......现在又+了些解释--发现不够精简!)
虽然表达能力很菜,不过已经讲得很清楚了,还不懂的话用下面的样例去运行观察吧(m改成6吧)
2 6
-1 4 -2 3 -2 3
取4再区3,-2,3 or 4,-2,3+3=8
*/