HDU - 1003 Max Sum
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问题,dp[i-1]代表的是前i-1项最大的连续和,dp[i]=max(dp[i-1],con[i])。
如果dp[i-1]比con[i]小,则dp[i]为con[i],舍弃dp[i-1]。
这样就保证了状态设计的正确性,关键是如何想出来要这样设计状态转移方程的?利用了负数的"切断性",该种性质导致了数列在某一步会减小,使得不如舍弃前几项的和,从新的地方另立门户。
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<math.h> 5 #include<algorithm> 6 #include<queue> 7 #include<stack> 8 #include<deque> 9 #include<iostream> 10 using namespace std; 11 typedef long long LL; 12 int con[100009]; 13 int dp[100009]; 14 int check[100009]; 15 int main() 16 { 17 int i,p,j,n,t; 18 int head,pen; 19 scanf("%d",&t); 20 for(i=1;i<=t;i++) 21 { 22 scanf("%d",&n); 23 for(j=1;j<=n;j++) 24 scanf("%d",&con[j]); 25 head=-1001; 26 pen=0; 27 memset(dp,0,sizeof(dp)); //初值应该赋为什么??????? 28 memset(check,0,sizeof(check)); 29 for(j=1;j<=n;j++) 30 { 31 dp[j]=max(dp[j-1]+con[j],con[j]); 32 if(con[j]>dp[j-1]+con[j]) 33 check[j]=1; 34 if(dp[j]>head) 35 { 36 head=dp[j]; 37 pen=j; 38 } 39 } 40 for(j=pen;j>=2;j--) 41 if(check[j]==1) 42 break; 43 44 printf("Case %d:\n",i); 45 printf("%d %d %d\n",head,j,pen); 46 if(i<t) 47 putchar('\n'); 48 } 49 return 0; 50 }