最大连续元素之和
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<cstdio> using namespace std; int main() { int n,t,i,c; int a[100002]; scanf("%d",&t); //数据的组数 for(c=1;c<=t;c++) //用c来记录数据的组数和循环次数,还有控制换行的输出 { int k=1,st=0,en=0,summax=-1000,sum=0; scanf("%d",&n); for(i=0;i<n;i++) //输入数据 { scanf("%d",&a[i]); } for(i=0;i<n;i++) //此循环控制连续元素相加,sum与summax的比较,sum<0的情况 { sum+=a[i]; //连续元素一个个加起来 if(sum>summax) //如果sum>summax,把sum赋值给summax(把最大的连续元素之和用summax来存) { summax=sum; st=k; //记录头位置 en=i+1; //记录尾位置 } if(sum<0) //若sum<0,则sum=0,且sum<0的这一连续元素不要了,从下一个元素开始 { sum=0; k=i+2; //从下一个元素开始,k是记录头位置,k=i+2即从尾位置的下一个元素开始算 } } printf("Case %d:\n%d %d %d\n",c,summax,st,en); if(c!=t) //换行的控制
cout<<endl; } return 0; }