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
最大子段和问题
最开始想到的解决方法是老师讲过的分治法,将数组中 的元素不断的二分法,直到问题的规模足够小,可以直接处理:
但是在杭电的系统上就是无法ac,不知道哪里的问题。。。
//求最大子段和
#include "stdio.h"
#define MAX_SIZE 100
int maxSum(int a[],int left,int right,int *start,int *end)
{
int mid,lsum,rsum,lefts,rights,i,s1,s2,s,e;
int sl1,sr1,sl2,sr2;
if (left==right)
{
*start = *end = left;
return a[left];
}
else
{
mid = (left+right)/2;
lsum = maxSum(a,left,mid,&sl1,&sr1);//情形1,最大子段在左
rsum = maxSum(a,mid+1,right,&sl2,&sr2);//情形2,最大子段在右
//情形3,最大子段在左右都有
s1=a[mid];
lefts=0;
s=mid;
e=mid+1;
for (i=mid;i>=left;i--)
{
lefts=lefts+a[i];
if (lefts>=s1)
{
s1=lefts;
s=i;
}
}
s2=a[mid+1];
rights=0;
for (i=mid+1;i<=right;i++)
{
rights=rights+a[i];
if (rights>=s2)
{
s2=rights;
e=i;
}
}
if(s1+s2<=lsum && rsum<=lsum)
{
*start = sl1;
*end = sr1;
return lsum;
}
if(s1+s2<rsum)
{
*start = sl2;
*end = sr2;
return rsum;
}
*start = s;
*end = e;
return s1+s2;
}
}
int main()
{
int T,i,j,a[MAX_SIZE],start,end,result;
scanf("%d",&T);
for (i=1;i<=T;i++)
{
scanf("%d",&a[0]);
for (j=1;j<=a[0];j++)
{
scanf("%d",&a[j]);
}
result = maxSum(a,1,a[0],&start,&end);
printf("Case %d:\n",i);
printf("%d %d %d\n",result,start,end);
if (i<T)
{
printf("\n");
}
}
return 0;
}
下面这段代码是在网上看到的,用动态规划的方法求解:
#include <stdio.h>
#define MAX_SIZE 100000
int main()
{
int i,j,T,a[MAX_SIZE],sum,term,begin,end,temp;
scanf("%d",&T);
for (i=1;i<=T;++i)
{
scanf("%d",&a[0]);
sum = -1002;
term = -1001;
begin=end=0;
temp = 1;
for (j=1;j<=a[0];++j)
{
scanf("%d",&a[j]);
if(term>=0)
term += a[j];
else
{
term = a[j];
temp = j;
}
if(term>sum)
{
sum = term;
begin = temp;
end = j;
}
}
printf("Case %d:\n%d %d %d\n",i,sum,begin,end);
if(i<T)
printf("\n");
}
return 0;
}
还是无法完全领会动态规划的精髓啊!!!