/*Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 142622 Accepted Submission(s): 33185
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
*/
题意:求所给数列的最大连续和。
令初始sum为数列第一位,以大于0 的第一个数为起始, 每加上一个数判断sum与max的大小, 记录max以及当前sum的始末位置。
若sum加到某项为负数时,初始化sum为数列的下一项,初始化初位置,并继续求和,求最大的max
#include<stdio.h>
int a[100010];
int main()
{
int i, j, k = 1, fir, la, n;
scanf("%d", &n);
while(n--)
{
scanf("%d", &a[0]);
for(i = 1; i <= a[0]; i++)
scanf("%d", &a[i]);
int sum , max, x, y;
max = a[1];
sum = a[1];
fir = x = 1;
la = y = 1;
for(i = 2; i <= a[0]; i++)
{
if( sum < 0)
{
sum = a[i];
x = i;
y = i;
}
else
{
sum += a[i];
y = i;
}
if( sum > max )
{
max = sum;
fir = x;
la = y;
}
}
printf("Case %d:\n%d %d %d\n", k++, max, fir, la);
if(n) printf("\n");
}
return 0;
}
//以下为常规的超时解法......
/*
#include<stdio.h>
int a[100000];
int main()
{
int T, i, j, fir, la, num = 1, k;
scanf("%d", &T);
while(T--)
{
int max = -1;
scanf("%d", &a[0]);
for( i = 1; i <= a[0] ; i++)
scanf("%d", &a[i]);
for( i = 1; i <= a[0]; i++)//start
{
for( j = i; j<= a[0]; j++)//end
{
int sum = 0;
for(k = i; k <= j; k++)//max
sum += a[k];
if( sum > max )
{
max = sum;
fir = i;
la = j;
}
}
}
printf("Case %d:\n%d %d %d\n", num++, max, fir, la);
if( T )
printf("\n");
}
return 0;
}
*/