Problem Descriptiongiven 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 is b etween-1000 and 1000).
Output
For the test case, you should output of the lines. The first line was "Case #:", # means the number of the the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end posi tion of the sub-sequence. If there is more than one result, output the first one. Output a blank line between 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
Approximate test instructions:
Give a sequence to find out his and the largest sub-sequences;
Problem Solving Ideas:
Here are two codes:
First code:
Greed, traverse all possible, find maximum, of course, will time out, so to prune; complexity O (n^2);
A second code:
Compare Magic, DP, complexity 0 (n);
Sub-sequence ending with a[0] only a[0]
Sub-sequences ending with a[1] have a[0]a[1] and a[1]
Sub-sequence ending with a[2] (a[0]a[1]a[2]/a[1]a[2]/a[2]
It is easy to conclude that the state transfer equation Sum_a[i]=max (sum_a[i-1]+a[i],a[i]);
1#include <iostream>2#include <cstdio>3 using namespacestd;4 intMain ()5 {6 intt,n,a[100005];7Cin>>T;8 for(intk=1; k<=t;k++)9 {TenCin>>N; One for(intI=1; i<=n;i++) ACin>>A[i]; - intmax,ans=-99999999, A1,A2; - for(intI=1; i<=n;i++) the { -max=0; - for(intj=i;j<=n;j++) - { +max+=A[j]; - if(max>ans) + { Aans=Max; ata1=i; -A2=J; - } - if(max<0) Break; - } - } inprintf"Case %d:\n", k); -printf"%d%d%d\n", ANS,A1,A2); to if(k<t) cout<<Endl; + } -}
1#include <cstdio>2 intMain () {3 intt,cas=0;4scanf"%d",&t);5 while(t--&&++CAs)6 {7 if(cas!=1) printf ("\ n");8printf"Case %d:\n", CAs);9 inta[100001],f[100001]={0};Ten intMax,maxl,maxr,l,r,n; Onescanf"%d",&n); AL=1; max=-100000; - for(intI=1; i<=n;i++){ -scanf"%d",&a[i]); the if(f[i-1]+a[i]<a[i]) {f[i]=a[i]; l=i; r=i;} - Else{f[i]=f[i-1]+a[i]; R=i;} - if(Max<f[i]) {max=f[i]; maxl=l; maxr=R;} -} printf ("%d%d%d\n", MAX,MAXL,MAXR); +}return 0; -}
HDU 1003-max Sum