Max Sum
Time Limit : 2000/1000ms (Java/Other) Memory Limit :65536/32768K (Java/Other)
Total Submission(s) : 6 Accepted Submission(s) : 0
Font:Times New Roman | Verdana | Georgia
Font Size:← →
Problem Description
Given asequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of asub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is6 + (-1) + 5 + 4 = 14.
Input
The firstline of the input contains an integer T(1<=T<=20) which means the numberof test cases. Then T lines follow, each line starts with a numberN(1<=N<=100000), then N integers followed(all the integers are between-1000 and 1000).
Output
For each testcase, you should output two lines. The first line is "Case #:", #means the number of the test case. The second line contains three integers, theMax Sum in the sequence, the start position of the sub-sequence, the endposition of the sub-sequence. If there are more than one result, output thefirst 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
//************************* //* 任务介绍:求最大的和 * //* 作者:何香 * //* 完成时间:2013.10.21 * //************************* #include <iostream> using namespace std; int main () { int T,N,temp,max,sum,end,start,x; /* T 测试数据组数 N 每组数据的长度 temp 当前取的数据 start 最后MAX SUM的起始位置 end 最后MAX SUM的结束位置 max 当前得到的MAX SUM sum 在读入数据时,能够达到的最大和 x 记录最大和的起始位置,因为不知道跟之前的max值的大小比,所以先存起来 */ int i,j; cin>>T; for(j=1;j<=T;++j) { cin>>N>>temp;//先输入第一个数据 sum=max=temp; end=1,start=1,x=1; for(i=2;i<=N;++i)//再从第二个数据开始输入 { cin>>temp; if(sum+temp<temp)//如果新输入的数据加上以前的变小了,则删除,并从现在这一项开始 { sum=temp; x=i;//开始的序号 } else sum+=temp; if(sum>max) { max=sum; //start=x; end=i;//结束的序号 } } cout<<"Case "<<j<<":"<<endl<<max<<" "<<start<<" "<<end<<endl; if(j!=T) { cout<<endl; } } return 0; }