Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 21925 Accepted Submission(s): 7341
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.
题意就是在n个数中找出m段不相交的连续字段,使他们的和最大。
一开始没有信提示上说的动态规划...,因为状态数太多了。于是想贪心,就是把连续的正整数划到一块,把负数划到一块,然后分类:
if(正数块数大于m)答案就是最大的m块正整数段之和;
else
{
if(正整数的数量大于等于m)答案就是所有正整数的和 //因为每个正数段都可以分成单个数,最多分成每个都只有一个正数
else 答案就是所有正整数的和加上最大的(m-正数数量)个负数的和;
}
于是我信心满满地拿着这个O(n*lgn)的算法算样例
经过样例的洗礼,这个贪心方法显然错了,样例二最后三个数为 3 -2 3,显然看成一整块的和为4,但我的贪心并不允许正数可以和负数在一块内,失败...
去讨论区看了下,发现还是DP,据说数据并没有那么大,要不然光DP状态数就已经O(n^2)了;
DP[ i ][ j ]表示前 j 个数中找到 i 块并以第 j 个数结尾最大的和
DP[ i ][ j ]=max( DP[ i ][ j-1 ] , DP[ i-1 ][ k ] ); i-1<=k<j
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAXN 1000010
using namespace std;
long long dp[2][MAXN];
long long kkke[MAXN];
int n,m;
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
while(scanf("%d%d",&m,&n)==2)
{
for(int i=1;i<=n;i++)scanf("%I64d",&kkke[i]);
for(int i=1;i<=n;i++)
{
if(dp[1][i-1]>0LL)dp[1][i]=kkke[i]+dp[1][i-1];
else dp[1][i]=kkke[i];
}
for(int i=2;i<=m;i++)//找到i份
{
long long maxn=dp[(i&1)^1][i-1];
dp[i&1][i]=maxn+kkke[i];
for(int j=i+1;j<=n-m+i;j++)//前j个
{
maxn=max(maxn,dp[(i&1)^1][j-1]);
dp[i&1][j]=max(dp[i&1][j-1],maxn)+kkke[j];
/*for(int k=i-1;k<j;k++)
if(dp[i&1][j]<dp[(i&1)^1][k])
dp[i&1][j]=dp[(i&1)^1][k];
dp[i&1][j]+=kkke[j];*/
}
}
long long ans=dp[m&1][m];
for(int i=m+1;i<=n;i++)ans=max(ans,dp[m&1][i]);
printf("%I64d\n",ans);//杭电要使用%I64d而不是%lld
}
return 0;
}
其中可以优化求max(DP[ i-1 ][ k ]);的部分,用一个变量maxn保存,不然就多一重循环变成O(n^3)了
还有每次循环只用求到DP[ i ][ n-m+i ]因为再往后的部分不会影响到最后的答案了
最后最重要的是,杭电是%I64d,我找了好久错误的地方,最后发现是错在这...以后要小心评测环境了