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
题意:
给你一个序列,求最大连续子列和。
题解:
定义:dp[i]为从a[1~i]中以a[i]为结尾的最大连续子序列和。
那么状态转移方程:dp[i] = (dp[i-1]>=0) ? (dp[i-1]+a[i]) : (a[i]));
最后遍历dp数组,找到最大的那个值就是ans,那个位置就是子序列的末尾位置;
另外为了记录子序列的开始位置,不妨把dp数组定义成结构体,里面定义一个sum用来存最大的和,另外定义一个st来储存开始位置.
AC代码:
#include<bits/stdc++.h> using namespace std; const int maxn = 100000+10; int a[maxn]; struct DP{ int val; int st; }dp[maxn]; int main() { int t,n; scanf("%d",&t); for(int kase=1;kase<=t;kase++) { scanf("%d",&n); int maxi=-10000,maxi_idx; dp[0].val=-1, dp[0].st=0; for(int i=1;i<=n;i++) { scanf("%d",&a[i]); dp[i].val = dp[i-1].val>=0 ? (dp[i-1].val+a[i]) : a[i]; dp[i].st = dp[i-1].val>=0 ? (dp[i-1].st) : i; if(maxi<dp[i].val) { maxi = dp[i].val; maxi_idx = i; } } printf("%sCase %d: ",kase>1?" ":"",kase); printf("%d %d %d ",maxi,dp[maxi_idx].st,maxi_idx); } }
注:状态转移方程 dp[i] = (dp[i-1]>=0) ? (dp[i-1]+a[i]) : (a[i])); 和 dp[i] = (dp[i-1]>=0) ? (dp[i-1]+a[i]) : (a[i])); 是有区别的。