您的位置:首页 > 其它

HDU 1003 Max Sum(最大连续子序列和 经典DP)

2013-08-20 17:06 531 查看

Max Sum

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 114678 Accepted Submission(s): 26580



[align=left]Problem Description[/align]
Given a sequence a[1],a[2],a[3]......a
, 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.

[align=left]Input[/align]
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).

[align=left]Output[/align]
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.

[align=left]Sample Input[/align]

2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5


[align=left]Sample Output[/align]

Case 1:
14 1 4

Case 2:
7 1 6


[align=left]Author[/align]
Ignatius.L
这道DP经典题(虽都说简单。。但是 我不敢动过许久。。。。。直至。。。水多了以后。。)
要求最大子序列的和,且要记录最大子序列的开始下标和结束下标,动态转移方程:sum[i]=max(sum[i-1]+a[i],a[i]);
sum[i]记录当前子序列的和,用一个变量记录即可。
然后当前的a[i]值如果符合条件,则sum[i-1]+a[i],如果不满足条件。。则更新sum[i]=a[i]以及开始和结束下标。。。。
#include<iostream>
using namespace std;
int main()
{
int t,n,s;
int i,k;
int a,b,A,B;//记录开始结束下标
int sum,max;
cin>>t;
for(k=1;k<=t;k++)
{
cin>>n;
sum=max=-1001;//取最小值。。因题目给出的是-1000到1000
for(i=1;i<=n;i++)
{
cin>>s;
if(sum+s<s)//子序列的和加上当前输入的值比S还小,更新SUM以及开结束下标
{
sum=s;a=b=i;
}
else //反之 子序列的和加上当前输入的值。。。更新结束下标。。
{
sum+=s;b++;
}
if(max<sum)//找到子序列最大的和。。记录其开结束下标。。。
{
max=sum;A=a;B=b;
}
}
cout<<"Case "<<k<<":"<<endl;
cout<<max<<' '<<A<<' '<<B<<endl;
if(k<t)
cout<<endl;

}
return 0;
}


/*优化算法:贪心

网上优化代码:hdu 1003

----------------------------------------------

算法:1.一直相加直到和出现负数,在相加期间能得到一个最大和,记录

2.重复1步骤,更新最大和,直到输入完毕

原理:如果在连续子串 <a1,a2,a3,...,an> 中Sn<0;S1,S2,...S(n-1)均大于或等于0

那么肯定存在一个最大的Si,Si也就是a1到an这段连续子串的最大和。

我们知道a1>0时任意的 <ai...an> (i>1) 的和都小于0,

所以这些元素就不能与an后的元素构成能获得最大和的子串(如果a1=0则a2>=0,情况类似);

同时在 <ai...aj> (i>1,j<=n) 也不能或得比Si大的和。

----------------------By G.wm----------------

#include<stdio.h>
int i,cas,j,k,t,max,s,e,n,x;
int main()
{
while(scanf("%d",&cas)!=EOF)
{
for(i=0;i<cas;i++)
{
if(i)printf("\n");
printf("Case %d:\n",i+1);
scanf("%d",&n);
max=-9999;
for(j=k=1,t=0;j<=n;j++)
{
scanf("%d",&x);
t+=x;
if(t>max) {max=t;s=k;e=j;}
if(t<0)      {k=j+1;t=0;}
}
printf("%d %d %d\n",max,s,e);
}
}
return 0;
}


*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: