hdu1003 java_hdu1003

Max Sum

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

Total Submission(s): 138410    Accepted Submission(s): 32144

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问题,dp思想在于把问题分解成若干个子问题,在子问题最优的情况下得出最终最优结果,所以我们每一步都是建立在前一步是最优的基础之上的。所以解决dp问题,最基本的要在某种情景下,想到当前状态的最优情况是什么样的,最优后,接下来怎么办,不是最优的该怎么变成最优的。这就是我们的状态转移方程。

对于本问题,首先明确,连续的子段! 和最大 ,一个数组给我们,第一个数肯定当前最大,毋庸置疑,那么遇到下一个数,怎么判断和是当前最大呢?我们遇到正数,那肯定直接加,因为加完肯定比不加大,如果是负数呢?加上去,原来的和肯定变小,但不加怎么办呢?

基于以上问题 可以得出状态方程 dp[i]=d[i-1]+a[i]>a[i]?dp[i-1]+a[i]:a[i]  (dp[i]表示当前i下最大的子段和,a[i]是需要处理的数字)什么意思呢,当前数字加到之前的和上面后,如果大于当前数字,那么就执行加的操作,如果小于当前数字,就把当前和最大值dp[i]设置为a[i],可能有人问为什么要设置为a[i]。。记住,如果a[i]你不加上去,意味着你需要从新开始累加和了,我们要求是连续的子段和!!!

利用dp数组的代码:

1 #include

2 #include

3 #include

4 //#define LOCAL

5 using namespacestd;6

7

8 intmain()9 {10 #ifdef LOCAL11 freopen("d:datain.txt","r",stdin);12 freopen("d:dataout.txt","w",stdout);13 #endif

14 intn;15 while(scanf("%d",&n)!=EOF)16 {17 inti,m;18 for(i =0 ; i< n;i++)19 {20 scanf("%d",&m);21 int dp[100000],a[100000];22 scanf("%d",&a[0]);23 dp[0] = a[0]; //当前最大

24 for(int j = 1; j

25 {26 scanf("%d",&a[j]);27 if(dp[j-1]+a[j]

28 dp[j]=a[j];29 else

30 dp[j]=dp[j-1]+a[j];31 }32 intMax,End;33 Max = dp[0];34 End = 0;35 for(int j = 1 ;j

36 if(Max=0;j--)44 {45 temp +=a[j];46 if(temp==dp[End])47 Begin =j;48 }49 cout<

简化后不带dp数组的,因为这题在dp问题中是比较简单的。

1 //hdu 1003

2

3 #include

4 intmain()5 {6

7 intn;8 while(scanf("%d",&n)!=EOF)9 {10 for(int i = 0;i

28 {29

30 sum=sum+a;31 }32 if(Max

44 }45 return 0;46 }

原文:http://www.cnblogs.com/jhldreams/p/3786478.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值