Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 25615 Accepted Submission(s): 8872
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. ^_^
Process to the end of file.
1 3 1 2 3 2 6 -1 4 -2 3 -2 3
6 8HintHuge input, scanf and dynamic programming is recommended.
Recommend
转:
题意就是求最大m子段和。
我们先用a[1e6+7]存入数据;
定义:DP[ i , j ] 为前 j 个元素的 i 个子段的最大和,且第 i 个子段中包含了元素 a[j]。
我们先来看:DP[ i , j ]状态方程由来;
对于一个元素 a[ j ] :
① 他可以自成一段;
②也可以包含第 i 段上,而且是第 i 段上的末尾元素;
那么:
对于①:DP[ i , j ]=max(DP[ i - 1 ,t ])+a[ j ]; t∈( i - 1 , j );
我把元素a[ j ]自成一段,我们的目的是要达到DP[ i , j ]最大,那么就是要使前面的 i - 1 段最大,所以需要找一下最大,而且第 i - 1 段中的末尾元素肯定是区间(i - 1 , j)上;
对于②:DP[ i , j ]=DP[ i , j - 1 ] + a[ j ];
其实一开始,我是不理解为什么就是DP[ i , j - 1 ]啊,为什么不可以是DP[ i , j - 2 ],DP[ i , j - 3 ],然后再举例子就真是自己sb了(T . T),因为前提是子段,是连续的!!然后现在我们的条件是元素a[ j ]在第 i 段上了,而且是该段上的最后一个元素;
那么就好了啊,已经搞好了;
=> DP[i,j]=max(max(DP[ i - 1 , t ] ) ,DP[ i , j - 1 ] )+a[ j ];
但是这样写,会发现。。。哇艹,他的n是1e6啊!!!你给我开个二维数组那样代表?这样是不行的;
我们可以看到DP[ i , j ] 的值只和 DP[ i , j - 1 ] 和DP[ i - 1 , t ] 这两个值相关,
因此不需要二维数组,可以用滚动数组,只需要两个一维数组,
用now[ j ] 表示现阶段的最大值,即 DP[ i , j − 1] + a[ j ]
用pre[ j ] 表示上阶段的最大值,即 max{DP[ i − 1,t ] )+ a[ j ]
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1e6+5;
const int INF = 0x3f3f3f3f;
int a[maxn], pre[maxn], cur[maxn];
int main(void)
{
int m, n, maxSum;
while(cin >> m >> n)
{
memset(pre, 0, sizeof(pre));
memset(cur, 0, sizeof(cur));
for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
int i, j;
for(i = 1; i <= m; i++)
{
maxSum = -INF;
for(j = i; j <= n; j++)
{
cur[j] = max(cur[j-1], pre[j-1])+a[j];
pre[j-1] = maxSum;
maxSum = max(maxSum, cur[j]);
}
pre[j-1] = maxSum;
}
printf("%d\n", maxSum);
}
return 0;
}