HDU 1003 MAXSUM(最大子序列和)

时间:2021-03-25 15:56:20

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
 
题目主要是求连续最大子序列的和,并输出最大子序列的左边界和右边界。
注意输出的格式为每两组数据之间输出一个空行,最后一组数据没有。
 
 #include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
int main()
{
int t,n;
int i,j,k=;
int Max,sum,x,y,l,d;
scanf("%d",&t);
while(t--)
{
Max=sum=-INF;
scanf("%d",&n);
for(i=; i<=n; i++)
{
scanf("%d",&d);
if(sum+d<d)
sum=d,l=i;
else
sum+=d;
if(Max<sum)
{
x=l;
y=i;
Max=sum;
}
}
if(k)
printf("\n");
printf("Case %d:\n",++k);
printf("%d %d %d\n",Max,x,y);
}
return ;
}