2015 HUAS Summer Trainning #5 A
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
题目大意:给你N个数,要你求最大的子段和(连续的)。
解题思路:
View Code
View Code
1 for(i=1;i<=n;i++) 2 { 3 cin>>d; 4 t+=d; 5 if(t>max) 6 { 7 start=k; 8 end=i; 9 max=t; 10 } 11 if(t<0) 12 { 13 t=0; 14 k=i+1; 15 } 16 }
每个数都加一次,遇到大的就储存它的起点和终点。当和小于0时,统计和的那个变量初始化为0。
代码:
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int T,i,d,p,start,end,k,t,max; 6 int n; 7 cin>>T; 8 d=0; 9 p=0; 10 while(T--) 11 { 12 cin>>n; 13 max=-9999; 14 start=end=k=1; 15 t=0; 16 for(i=1;i<=n;i++) 17 { 18 cin>>d; 19 t+=d; 20 if(t>max) 21 { 22 start=k; 23 end=i; 24 max=t; 25 } 26 if(t<0) 27 { 28 t=0; 29 k=i+1; 30 } 31 } 32 cout<<"Case "<<++p<<":"<<endl; 33 cout<<max<<" "<<start<<" "<<end<<endl; 34 if(T) 35 cout<<endl; 36 } 37 return 0; 38 }