您的位置:首页 > 其它

Max Sum(最大连续子序列)

2013-07-14 11:06 344 查看

Max Sum

Problem Description

Given a sequence a[1],a[2],a[3]......a
, 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

 

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1003

         http://acm.hdu.edu.cn/showproblem.php?pid=1231(同一类型)

 

解题思路:不断保存输入数据进行判断是否大于当前子序列,如果当前子序列小于0则重新寻找子序列(注意:一个小于0的数加上另一个小于0的数只会越来越小);另一种做法是DP解决(双重遍历)。

 

代码如下(C++):

#include<iostream>
using namespace std;

int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
int m;
cin>>m;
int sum,max=-99999;//初始化子序列之和max
        int t,c,d,a,b;
a=b=c=d=1;//初始化a、b分别为最大子序列的起始和结束位置 c、d为当前子序列的起始和结束位置
sum=0;
while(m--){
cin>>t;
sum+=t;
if(sum>=max){//判断当前子序列之和是否大于max
max=sum;
a=c;
b=d;
}
if(sum<0){//如果子序列之和小于0,则重新寻找新的序列
sum=0;
c=d+1;//当前序列初始位置改为下一个
            }
d++;
}
printf("Case %d:\n",i+1);
printf("%d %d %d\n",max,a,b);
if(i!=n-1)
cout<<endl;
}
return 0;
}
[align=center] [/align][align=center] [/align][align=center] [/align][align=center] [/align][align=center]
 [/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法