这道题之后才逐渐步入佳境,但这道题可谓是拖后了我Rank的元凶了,在这道莫名其妙的题上WA了十多次了吧,才知道杭电的题有时候的空行不是那种结尾的空行,还有些小操作,那么上题再说:
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.
InputThe 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).
OutputFor 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.
Sample Input
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5Sample Output
Case 1: 14 1 4 Case 2: 7 1 6
这是一道求子序列和的问题,不过这题还真心不好过,说真的,若要认真判的话,除了后面几个是PE前面的WA不为过。
题解:这道题给我的思路就是,处理“>=0”与“<0”之间的关系,因为当这段公共子序列“<0”的话那么链接上下面的一段只会拖累下面的序列,对于这种在序列尾部或者头部存在的“<0”的序列可以直接删除,当然,有人会想那么遇到整串序列均为“<0”的数列如何?当然是直接找到其中的那一个最大的负值直接输出它所在的位置就是answer了啊!回归正题,我们除去了这个特殊情况,那么接下来就是判断了,对于每一个子序列,我定义出它的当前左端点和当前右端点以便用于记忆,而当此时的子序列和大于目前几率的ans时候,那么当前端点就能转正为当前ans的端点了。
完整代码
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int N;
int a[100001];
int l,r;
int ans=-1001;
int sum;
int main()
{
int T;
scanf("%d",&T);
for(int CASE=1; CASE<=T; CASE++)
{
int now_l,now_r;
now_l=now_r=0;
sum=0;
ans=-1001;
scanf("%d",&N);
for(int i=1; i<=N; i++)
{
scanf("%d",&a[i]);
if(i==1)
{
now_l=now_r=1;
sum=a[1];
ans=a[1];
l=r=1;
}
else
{
if(sum<0)
{
now_l=i;
sum=a[i];
}
else sum+=a[i];
}
if(sum>ans)
{
ans=sum;
l=now_l;
r=i;
}
}
if(CASE>1) cout<<endl;
printf("Case %d:\n",CASE);
printf("%d %d %d\n",ans,l,r);
}
return 0;
}