Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 103698 Accepted Submission(s): 23844
Problem 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
Author
Ignatius.L
这是一道简单的DP题。
解题思路:
题意:寻找所给数组的最大连续子序列和,并纪录始末位置。
如果从i到j(i《=j)的和为正则继续,并一直纪录最大值;为负则从j+1重新开始累加开始。同时纪录始末位置。
注意格式。其他就不多说了。
代码1、
#include<stdio.h> main() { int i,j=0,n,m,s,t,l,r,w; int a[100000],b[2]; scanf("%d",&n); w=n; while(n--) { s=0;r=0;l=0;b[0]=0;b[1]=0; scanf("%d",&m); for(i=0;i<m;i++) { scanf("%d",&a[i]); if(i==0) t=a[i]; s+=a[i]; if(s>t) { t=s; if(i>r) r=i; b[0]=l;b[1]=r; } if(s<0) {s=0;l=i+1;r=0;} } printf("Case %d:\n",++j); printf("%d %d %d\n",t,b[0]+1,b[1]+1); if(j<w) printf("\n"); } }
代码2、
(比前面的更简练,待续)
测试数据:
4 0 0 2 0 —— 2 1 3
6 2 7 -9 5 4 3 —— 12 1 6
4 0 0 -1 0 —— 0 1 1
7 -1 -2 -3 -2 -5 -1 -2 —— -1 1 1
6 -1 -2 -3 1 2 3 —— 6 4 6
5 -3 -2 -1 -2 -3 —— -1 3 3