Given a sequence a[1],a[2],a[3]……a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Case 1:
14 1 4Case 2:
7 1 6
这是一道经典的基础动态规划题目,因此网上大多数的题解都是DP,只需要推导出简单的动归方程f[i]=Max{f[i-1]+a[i],a[i]}即可。
因此我在这里只详细介绍 模拟方法:
此算法效率与DP相同,为是O(n),代码复杂度也不高。算法的核心思想是:最大字串=Max{左端字串-左端字串的左端最小子串}
我们只需从左到右扫描一次,每一次处理首先纪录前i项和
重点在第二步,我们不能先先求左端最小子串,否则会导致当输入数据全为负的输出结果为错误答案零
我们应到首先进行MAX操作,并纪录起始结束点,最后在更新左端最小子串
下面分别附上我的模拟代码和DP代码,仅供大家参考。
// Created by Chlerry on 14-10-22.
// Copyright (c) 2014 Chlerry. All rights reserved.
// http://acm.hdu.edu.cn/showproblem.php?pid=1003
#include
#include
#include
#include
int t,n;
int a[100010];
int main(int argc,const char *argv[])
{
//freopen("out.txt","w",stdout);
scanf("%d",&t);
for(int ca=1;ca<=t;ca++)
{
int min=INT_MAX,minn;
int max=INT_MIN,start,end;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
a[i]+=a[i-1];
if(min>=0 && max1;
end=i;
}
if(min<0 && max1;
end=i;
}
if(min>a[i])
{
min=a[i];
minn=i;
}
}
printf("Case %d:\n%d %d %d\n",ca,max,start,end);
if(ca!=t)
printf("\n");
}
return 0;
}
// Created by Chlerry on 14-10-28.
// Copyright (c) 2014 Chlerry. All rights reserved.
// http://acm.hdu.edu.cn/showproblem.php?pid=1003
#include
#include
#include
int a[100010],f[100010],start[100010];
int main(int agrc,const char *argv[])
{
int t,n;
int max,maxn;
scanf("%d",&t);
start[0]=1;
for(int ca=1;ca<=t;ca++)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(f[i-1]>0)
{
f[i]=f[i-1]+a[i];
start[i]=start[i-1];
}
else
{
f[i]=a[i];
start[i]=i;
}
}
max=INT_MIN;
for(int i=1;i<=n;i++)
if(maxprintf("Case %d:\n%d %d %d\n",ca,max,start[maxn],maxn);
if(ca!=t)
printf("\n");
}
return 0;
}