Problem Description
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.
Input
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).
Output
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.
Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Sample Output
Case 1:
14 1 4
Case 2:
7 1 6
Author
Ignatius.L
Recommend
We have carefully selected several similar problems for you: 1176 1087 1069 1058 1159
题意:求连续子序列的最大和并且输出最大值与起始于终了的位置。
思路:dp嘛,连续求和就好结果超时了,发现给的是100000,两个for循环就报了,看了别人的处理办法。。。。。
看代码说好了:
#include<stdio.h>
#include<string.h>
int a[100005];
int main()
{
int i,n,m,j,h,start,end,b;
int sum;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=-100000;//最大值
scanf("%d",&m);
b=0;//求和
h=0;
start=0;
end=0;
for(j=0;j<m;j++)
{
scanf("%d",&a[j]);
b=b+a[j];
if(b>sum)
{
sum=b;
start=h;
end=j;
}
if(b<0)//这一步很重要,当计算到这一步发现小于0,就从下一个位置重新连续相加。。。
{
h=j+1;
b=0;
}
}
printf("Case %d:\n%d %d %d\n",i,sum,start+1,end+1);
if(i<n)
{
printf("\n");
}
}
return 0;
}//
看见水题一激动就错,以后敲代码前自己先仔细想想好了,想清楚再做。。。。。