Max Sum (HDU - 1003 )
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
题目翻译:
给定一个序列a[1],a[2],a[3]a[n],你的工作是计算子序列的最大和。例如,给定(6,-1,5,4,-7),这个序列中的最大和是6 +(-1)+ 5 + 4 = 14。
输入
输入的第一行包含一个整数T(1<=T<=20),它表示测试用例的数量。然后是T行,每一行以一个数字N开头(1<=N<=100000),然后是N个整数(所有整数都在-1000到1000之间)。
输出
对于每个测试用例,您应该输出两行。第一行是“Case #:”,#表示测试用例的数量。第二行包含三个整数,序列中的最大和,子序列的起始位置,子序列的结束位置。如果有多个结果,输出第一个。在两种情况之间输出空行。
AC代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
int i,n,m,t;
int a;
int k=0;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int sum=0,maxsum=-1001,x=0,y=0,z=1;
for(i=0; i<n; i++)
{
scanf("%d",&a);
sum+=a;
if(sum>maxsum)
{
maxsum=sum;
x=z;
y=i+1;
}
if(sum<0)
{
sum=0;
z=i+2;
}
}
printf("Case %d:\n%d %d %d\n",++k,maxsum,x,y);
if(t)
{
printf("\n");
}
}
return 0;
}