Max Sum
Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 211310 Accepted Submission (s): 49611
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.
Inputthe 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).
Outputfor Each 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 Input25 6-1 5 4-77 0 6-1 1-6 7-5 sample outputcase 1:14 1 4 case 2:7 1 6
Tips for solving problems:This problem is a simple dynamic programming problem, test instructions: Enter n number, to find its largest sub-sequence and.
first write the state transfer equation: Sum[i]=max{sum[i-1]+a[i],a[i]}. The s array is the starting position of the record, whenever sum is added to a a[i], and the value is less than 0, S takes the new value. ans is the record end position, whenever sum plus a a[i], the value is greater than or equal to 0 times, update. I again in the format problem, the future to pay more attention to formatting problems, the last line does not need to wrap! You can also refer to this person's ideas, http://blog.csdn.net/code_pang/article/details/7772200, by enumerating the laws found. and
finally the code:
#include <iostream>#include<cstdio>using namespacestd;intMain () {intT; intN; inta[100005];//Storage Sequence intsum[100005];//stores the subsequence with the end of each number and ints[100005];//Store Start Location intAns//End Positionscanf"%d",&t); for(intI=1; i<=t;i++) {scanf ("%d",&N); for(inti1=0; i1<n;i1++) {scanf ("%d",&A[i1]); } ans=0; sum[0]=a[0]; s[0]=0; for(intj=1; j<n;j++){ if(sum[j-1]>=0) {Sum[j]=sum[j-1]+A[j]; S[J]=s[j-1]; }Else{Sum[j]=A[j]; S[J]=J; } if(sum[ans]<Sum[j]) ans=J; } if(i<t) {printf ("Case %d:\n%d%d%d\n", i,sum[ans],s[ans]+1, ans+1); printf ("\ n"); }Else{printf ("Case %d:\n%d%d%d\n", i,sum[ans],s[ans]+1, ans+1); } } return 0;}
View Code
HDU 1003 Max Sum