题目:
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.<br>
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).<br>
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.<br>
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
题意:
求最大子段和;
思路:
输入数组的同时记录子段的和,并将当前子段的和与当前输入的数作比较,使子段和等于两者之间最大的数,当子段的和小于等于当前输入的数时,记录新的起点,并当新的最大子段和出现时,使用该新的起点。最初对这类题理解的不是很深刻,看着题中没有“如果某子序列全是负数.....”这个条件,就以为这个题和例题是不一样的,做完之后,仔细一想,不管这个条件有没有,都可以让子段和与0进行比较!
感想:
做题时的思路是正确的,但在输出起点和重点,尤其是起点的问题上浪费了太多太多太多的时间,虽然说这道题是最基础的。!!
一下午就搞出来了这一道题,饿死了,吃饭去!
代码:
# include <iostream>
# include <string.h>
# include <stdio.h>
using namespace std;
int max(int a, int b)
{
return a>b? a:b;
}
int main()
{
int T ,ccc = 0;
cin >> T;
for(int j = 1; j <= T; j++)
{
if (ccc)
cout << endl;
ccc = 1;
int N;
cin >> N;
int a[100090], b[100090], be = 0, k = 0, maxx = 0;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
cin >> a[0];
b[0] = a[0];
for (int i = 1; i < N; i++)
{
cin >> a[i];
b[i] = max(b[i-1]+a[i],a[i]);
if (b[i] <= a[i] )
{
k = i;
}
if (b[i] > b[maxx])
{
maxx = i; //
be = k;
}
}
cout << "Case " <<j <<":"<<endl;
cout <<b[maxx] <<" " << be +1 << " " << maxx +1 << endl;
}
return 0;
}