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).
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.
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题目大意:给你n个数s1,s2,s3……,sn,求最大子串和,即求max{si + …… + sj }(1 <= i <= j <= n )。解题思路:这道题基础动态规划的典型问题,设f[i] 表示数列s0 , s1 ,…… , si 中 包含s[i] 的最大子串和,则由状态f[i - 1] 转移到 状态f[i] 共有两种决策:1、当f[i - 1] >= 0 时 ,f[i] = f[i - 1] + s[i] ;2、当f[i - 1] < 0 时 ,f[i] = s[i]。由于本题要记录起点和终点 , 所以需要一个标记数组p , p[i] == true表示数列s0 , s1 ,…… , si 中 包含s[i] 的最大子串和 由 f[i - 1] 和 s[i] 共同构成;否则,则表示只由s[i] 构成。具体请看代码:#include<iostream> #include<cstring> #include<cstdio> #include<string> #include<algorithm> #include<cmath> using namespace std ; const int MAXN = 1e6 + 5 ; int s[MAXN] ; int f[MAXN] ; bool p[MAXN] ; int start , end ; int MAX ; int n ; void init() { scanf("%d" , &n) ; int i ; for(i = 0 ; i < n ; i ++) { scanf("%d" , &s[i]) ; } } void solve() { MAX = s[0] ; end = 0 ; p[0] = false ; f[0] = s[0] ; int i ; for(i = 1 ; i < n ; i ++) { if(f[i - 1] >= 0) // 注意:题目中要求输出第一个符合条件的起始点,所以是 " >= " { f[i] = f[i - 1] + s[i] ; p[i] = true ; } else { f[i] = s[i] ; p[i] = false ; } if(MAX < f[i]) { MAX = f[i] ; end = i ; } } } int main() { int T ; scanf("%d" , &T) ; int ca = 0 ; int first = true ; while (T --) { init() ; solve() ; int i ; for(i = end ; i >= 0 ; i --) { if(p[i] == false) { start = i ; break ; } } if(first) { first = false ; } else puts("") ; printf("Case %d:\n" , ++ ca) ; printf("%d %d %d\n" , MAX , start + 1 , end + 1) ; } return 0 ; }