题目: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
这题的核心就是求最大子串和,是经典动态规划算法,具体的算法核心可以参考该链接http://blog.nlogn.cn/programming-pearls-the-maximum-sum-of-substring/,该博主用图示的方法将算法过程讲的非常清晰透彻。我在这里用几句话简述就是:
对于第i个元素是否要添加入子串中,看前k个元素的和sum[k],与第i个元素的和是否小于0.
若sum[k]+a[i]<0;则不选择第i个元素,并重新定位子串开始位置。
若sum[k]+a[i]>0;则选择第i个元素加入子串中,若sum[k]+a[i]>maxsum,则更新maxsum的值,并更新子串end位置。
代码如下:
#include <iostream>
#include <vector>
using namespace std;
int main(){
int t,n,k;
int casenum = 0;
cin>>t;
while(t--){
cin>>n;
int copy_n = n;
casenum++;
int start = 0;
int end = 0;
int maxsum = -1000;
int sum = 0;//连续字串的和(不是最大和)
int temp =0;
int s=0;
vector<int> nums;
while(n--){
cin>>k;
nums.push_back(k);
}
int i ;
maxsum = nums[0];
for(i = 0;i<copy_n;i++){//找最大字串和
sum = sum+nums[i];
if(sum>=maxsum){
maxsum = sum;
start = s;
end = start + temp;
}
temp++;
if(sum<0){
sum = 0;
s = s+temp;
temp = 0;
}
}
cout<<"Case "<<casenum<<":"<<endl;
cout<<maxsum<<" "<<start+1<<" "<<end+1<<endl;
if(t!=0) cout<<endl;
}
}