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
题意:
给你一组序列,让你求最大子段和,最大子段和要求是在序列中连续的一段,并记录起始下标和终止位置的下标。我们用一个tmp变量记录加了当前元素之后的值,并和前面所得到的最大值res比较, 如果 那么就把该元素加起来,否则就以当前元素为起点,继续找最大的值。
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1e5+5;
long long A[maxn];
int main()
{
int t;
cin >> t;
int cnt = 0;
while(t--){
int n;
cin >> n;
++cnt;
memset(A,0,sizeof(A));
for (int i = 0; i < n; ++i) {
cin >> A[i];
}
int res = -1e9;
int st = 0;
int ed = 0;
int tmp = 0;
int l = 0;
for (int i = 0;i < n; ++i) {
tmp += A[i];
if (tmp > res) {
res = tmp;
st = l;
ed = i;
}
if (tmp < 0) {
tmp = 0;
l = i+1;
}
}
printf("Case %d:\n", cnt);
printf("%d %d %d\n", res, st+1, ed+1);
if(t>0) printf("\n");
}
return 0;
}