Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 180180 Accepted Submission(s): 42082
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
Recommend
一道很简单的dp,以前也写过很多次,一直是看着别人的代码写的,可是一直觉得自己对dp的理解不够深刻,每次不能独立的想出代码,于是决定把dp 的题再重新写一遍,加深自己的理解。。。。
题意:求一串数列中最大序列之和,并输出起始位置和结束位置,尽量保证序列最长(即如第二个例子:第一个数字为0,最大值可加可不加,但是就要从0开始计算起始位置)。
附上代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 int dp[100001],a[100001]; //a[]数组记录每个数字,dp[]数组记录到当前序列的最大序列和 6 int main() 7 { 8 int n,m,i,j,t=1; 9 scanf("%d",&n); 10 while(n--) 11 { 12 memset(dp,0,sizeof(dp)); //dp 全部初始化为0 13 scanf("%d",&m); 14 for(i=1; i<=m; i++) 15 scanf("%d",&a[i]); 16 dp[1]=a[1]; 17 for(i=2; i<=m; i++) 18 { 19 if(dp[i-1]<0) dp[i]=a[i]; // 若前列的数加起来之和小于0,则忽略前面的值 20 else dp[i]=dp[i-1]+a[i]; 21 } 22 int max=dp[1],e=1,f; 23 for(i=2; i<=m; i++) 24 { 25 if(max<dp[i]) 26 { 27 max=dp[i]; //找到最大的序列之和 28 e=i; // 记录末尾加到的数字 29 } 30 } 31 int s=0; 32 for(i=e; i>=1; i--) 33 { 34 s+=a[i]; 35 if(s==max) 36 f=i; //找到从哪个数开始的位置 37 } 38 printf("Case %d: ",t++); 39 printf("%d %d %d ",max,f,e); 40 if(n) 41 printf(" "); 42 } 43 return 0; 44 }