link:http://acm.hdu.edu.cn/showproblem.php?pid=1003
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
题解:最大子序列和
这道题需要记录这段子序列的起始和结束位置,注意需要在判断前给位置变量赋初值1,不然会WA
AC代码:
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int num[100010];
int main()
{
int t,c=1,n,x1,y2,x2;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&num[i]);
}
long long sum=0;
long long Max=-0x3f3f3f3f;
x2=y2=x1=1;//赋初值,x1是重新开一个字段时存储起始位置的
for (int i=1,x1=1;i<=n;i++)
{
sum +=num[i];
if(sum>Max)//当前字段大于已有的最大和时
{
Max=sum;
x2=x1;//记录起始位置
y2=i;//记录结束位置
}
if(sum<0)//小于0尝试重新开一个字段
{
sum=0;
x1=i+1;//起始位置从下一个元素开始
}
}
printf ("Case %d:\n%lld %d %d\n",c++,Max,x2,y2);
if(t) printf("\n");
}
return 0;
}