Max Sum
Max Sum
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的一维数组a,找出此数组的一个子数组,使得此子数组的和sum=a[i]+a[i+1]+……+a[j]最大,其中i>=0,i<n,j>=i,j<n
设dp[i]表示以i为结尾的子段和,则状态转移方程为:
dp[i] = max{dp[i-1]+a[i],a[i]} i>=1
# include<stdio.h> struct node { int st;//开始位置 int en;//结束位置 int sum; node() { st=1; en=1; sum=0; } }dp[100002]; int main() { int nCase,nNum; int i,j; int ma,mx,sign; scanf("%d",&nCase); for(i=1;i<=nCase;i++) { scanf("%d",&nNum); ma=-99999; mx=1; dp[0].sum=-1; for(j=1;j<=nNum;j++) { scanf("%d",&sign); if(sign>dp[j-1].sum+sign)//记录的一定是以sign结尾的最大和 { dp[j].sum=sign; dp[j].st=j; dp[j].en=j; } else { dp[j].sum=dp[j-1].sum+sign; dp[j].st=dp[j-1].st; dp[j].en=j; } if(ma<dp[j].sum) { ma=dp[j].sum; mx=j; } } printf("Case %d:\n%d %d %d\n",i,ma,dp[mx].st,dp[mx].en); if(i!=nCase)printf("\n"); } return 0; }
浙公网安备 33010602011771号