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
【题意】 给n个数,求最大连续元素的和;并输出起点和终点。
【分析】
设d[i]为以第i个元素为终点的最大连续元素和。则
状态转移方程:d[i] = d[i-1] > 0 ? d[i-1]+a[i] : a[i];
思路应该比较好理解,如果d[i-1]<0, 那么无论a[i]为何值,其和总不如单独的a[i]大;反之如果d[i-1]>0, 那么无论a[i]为何值,其和总大于单独的a[i];
【代码】
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 using namespace std; 6 const int maxn = 100010; 7 int n, a[maxn]; 8 int d[maxn]; 9 void dp() 10 { 11 memset(d, 0, sizeof(d)); 12 d[0] = a[0]; 13 for(int i = 1; i < n; i++) 14 { 15 if(d[i-1] > 0) d[i] = d[i-1]+a[i]; 16 else d[i] = a[i]; 17 } 18 //cout << endl; 19 int st = 0, en = 0; 20 int max_ = d[0]; 21 for(int i = 1; i < n; i++) 22 { 23 if(d[i]>max_) 24 { 25 max_ = d[i]; 26 en = i; 27 } 28 } 29 st = en; 30 for(int j = en-1; j>=0; j--) 31 { 32 if(d[j] < 0) break; 33 else st = j; 34 } 35 printf("%d %d %d\n", max_, st+1, en+1); 36 } 37 38 int main() 39 { 40 int T; scanf("%d", &T); 41 for(int kase = 0; kase < T; kase++) 42 { 43 scanf("%d", &n); 44 for(int i = 0; i < n; i++) 45 scanf("%d", &a[i]); 46 if(kase) printf("\n"); 47 printf("Case %d:\n", kase+1); 48 dp(); 49 50 } 51 return 0; 52 }