HDU 1003 Max Sum【最大连续和】

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
code:
View Code
#include<stdio.h>
int main()
{
int p,t,s,sum,tot,e,i,n,k=0,st;
scanf("%d",&t);
while(t--)
{
tot=0;
st=e=1;
sum=-9999;
if(k++)
putchar('\n');
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&p);
tot+=p;
if(tot>sum)
{
sum=tot;
s=st;
e=i;
}
if(tot<0)
{
tot=0;
st=i+1;
}
}
printf("Case %d:\n%d %d %d\n",k,sum,s,e);
}
return 0;
}
 附:分治法求最大和
code:
#include<stdio.h>
int s,e;
int maxsum(int* a,int x,int y) //返回数组左闭右开区间[x,y)中的最大连续和
{
int i,m,v,l,r,max;
if(y-x==1)
return a[x]; //只有一个元素,直接返回
m=x+(y-x)/2; //分治第一步:划分成[x,m)和[m,y)
max=maxsum(a,x,m)>maxsum(a,m,y)?maxsum(a,x,m):maxsum(a,m,y);//分治第二步:递归求解
v=0;
l=a[m-1]; //分治第三步:合并(1)—从分界点开始往左的最大连续和L
for(i=m-1;i>=x;i--)
{
v+=a[i];
l=l>v?l:v;
}
v=0;
r=a[m]; //分治第三步:合并(2)—从分解点开始往右的最大连续和R
for(i=m;i<y;i++)
{
v+=a[i];
r=r>v?r:v;
}
return max=max>(l+r)?max:(l+r);//把子问题的解与l和r比较
}
int main()
{
int n,i,k;
int a[1000];
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
scanf("%d",&a[i]);
k=maxsum(a,0,n);
printf("%d\n",k);
}
return 0;
}
posted @ 2012-03-14 17:32  'wind  阅读(751)  评论(0编辑  收藏  举报