原题:
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 282943 Accepted Submission(s): 67221
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
Author
Ignatius.L
直接暴力写的话,时间复杂度为O(n^2),会超时。
用DP的思想:若我们已经找到一个最大的子序列a,其中m为其中最后一个元素,那么在m之前的元素和一定大于零,(如果小于零,那么最大子序列应该更新为m),所以我们可以从0-n-1遍历元素位置,然后用flag_start和flag_end维护最大子序列的初始元素与末尾元素,用_max维护子序列和的最大值。
下面上代码:(不懂可以看注释)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
int a[100010];
int sum=0;
int _max=0x80000000,flag_start,flag_end,here_start,here_end;//0x80000000就是16进制表示的int最小值
int main()
{
int t,_case;
cin>>t;
int caseNum=0;
while(t--)
{
caseNum++;
cin>>_case;
memset(a,0,100010);//清零数组
sum=0;
_max=0x80000000;
flag_start=flag_end=here_start=0;
here_end=-1;//因为在刚开始sum会加一次a[0]导致here_end++一次,所以这里要设为-1。
for(int i=0;i<_case;i++)
{
cin>>a[i];
}
for(int i=0;i<_case;i++)
{
//如果i位置之前sum<0则,更新sum值为a[i],同时here_start与here_end都要设置为i这个点
if(sum<0)
{
sum=a[i];
here_start=i;
here_end=i;
}
else{
sum+=a[i];
here_end++;//因为这里,here_end要预设为-1
}
//维护max的值和起点与终点
if(sum>_max)
{
_max=sum;
flag_end=here_end;
flag_start=here_start;
}
}
printf("Case %d:\n",caseNum);
printf("%d %d %d\n", _max,flag_start+1,flag_end+1);
if(t) cout<<endl; //最后一个case不需要再打印blank line
}
return 0;
}