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