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
1,开始想法就是遍历,
#include<iostream>
using namespace std;
long a[100000];
int main(){
int T;
int N;
cin>>T;
int i=1;
while(i<=T){
cin>>N;
int j;
for(j=0;j<N;j++){
cin>>a[j];
}
long k,l,m=0,n=0,max=a[0];//k,对a数组遍历;max保存目前最大值,m开始位置,n结束位置
for(k=0;k<N;k++){
for(l=k;l<N;l++){
long tempMax=0;
int x;
for(x=k;x<=l;x++){
tempMax+=a[x];
}
if(tempMax>max){
max=tempMax;
m=k;
n=l;
}
}
}
cout<<"Case "<<i<<":"<<endl;
cout<<max<<" "<<++m<<" "<<++n<<endl;
i++;
if(i<=T)
cout<<endl;
}
return 0;
}
果然是时间超时。
2,查阅一些资料,对于最大子序列和的问题,已经找到的最大子序列的前部的和、后部的和都为负数,这样的才是最大子序列。算法思想:遍历数组a[],设定标志位sum(为遍历数组的和,初始为0),若sum值小于0,则将sum置为0,重新求和。遍历过程中对max、m、n进行保存。
#include<iostream>
using namespace std;
long a[100009];
int main(){
int T;
int N;
cin>>T;
int i=1;
while(i<=T){
cin>>N;
int j;
for(j=0;j<N;j++){
cin>>a[j];
}
long k,sum=0,m=0,n=0,max=a[0],p=0,q=0;//k,对a数组遍历;max保存目前最大值,
//m目前最大值开始位置,n目前最大值结束位置, p临时开始位置,q临时结束位置
for(k=0;k<N;k++){
q=k;
sum+=a[k];
if(sum>max){
max=sum;
m=p;
n=q;
}
if(sum<0){
p=k+1;
sum=0;
}
}
cout<<"Case "<<i<<":"<<endl;
cout<<max<<" "<<++m<<" "<<++n<<endl;
i++;
if(i<=T)
cout<<endl;
}
return 0;
}
时间复杂度n