温故而知新
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 339728 Accepted Submission(s): 80646
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
最长子序列呢,最简单的应该就是在线处理法了吧,算法复杂度是O(n).
下面解释一下:
我们在读入数据的过程中,使用thissum累加和,如果thissum的值大于maxsum,我们将执行
maxstart=thisstart;
maxend=i;
maxsum=thissum;
记录最大值的下标和最大值
如果thissum的值小于0,我们就认为目前的序列只会让后面的序列减小,所以
thissum=0;
thisstart=i+1;
清空,并且将thisstart赋于下一个值。
上代码!!
#include<iostream>
using namespace std;
int main(){
int t,j=1;
cin>>t;
while(t--)
{
int n,maxsum,thissum,thisstart=0,maxstart=0,maxend=0;
cin>>n;
cin>>maxsum;//第一个数使为maxsum
thissum=maxsum;
if(thissum<0){thissum=0;thisstart=1;//第一个数小于0,舍弃
}
for(int i=1;i<n;i++)
{
int temp;
cin>>temp;
thissum+=temp;
if(thissum>maxsum){
maxstart=thisstart;
maxend=i;
maxsum=thissum;
}
if(thissum<0)
{
thissum=0;
thisstart=i+1;
}
}
cout<<"Case "<<j++<<":"<<endl<<maxsum<<" "<<maxstart+1<<" "<<maxend+1<<endl;//输出
if(t>0)
cout<<endl;
}
}
希望大佬指正!