A-Maximum sub-segments andTime
limit:1000MS
Memory Limit:32768KB
64bit IO Format:%i64d &%i64 U
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 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 solving: Finding the maximum subsequence and its initial and ending positions. If there is more than one solution, the output is calculated first. Two ways, you can understand it at a glance.
#include <cstdio>intMain () {intT,k, R, L, Max, Sum, T, total=1, N; scanf ("%d", &T); while(t--) {sum= Max =- -;//It's small enough.scanf"%d", &N); for(intI=1; i<=n; i++) {scanf ("%d", &t); if(sum<0) {sum= T, k =i; } Elsesum+=T; if(Max < sum) Max = sum, L = k, R = i;//L R for initial and end positions, respectively} printf ("Case %d:\n", total++); printf ("%d%d%d\n", Max, L, R); if(T) printf ("\ n"); } return 0;}
#include <iostream>using namespacestd;inta[100010],b[100010];intMain () {intn,t,s,t,max,total,k=1; CIN>>T; while(t--) {cin>>N; for(intI=1; i<=n; i++) Cin>>A[i]; b[1]=a[1]; for(intI=2; i<=n; i++) { if(b[i-1]<0) B[i]=A[i]; ElseB[i]=b[i-1]+A[i]; } Max=b[1]; S=1; for(intI=2; i<=n; i++) { if(b[i]>max) {Max=[i]; S=i; }} t=s; Total=0; for(intk=1; i>=1; i--) { Total+=A[i]; if(Total==max) t=i; } cout<<" Case"<<k++<<":"<<Endl; cout<<max<<" "<<t<<" "<<s<<Endl; if(T) cout<<Endl; }}
hdu1003 Max Sum (classic DP)