HDU1003 MAX SUM 动态规划

先码题目
******Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 261092 Accepted Submission(s): 62075
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

大意是:给出来一个数字T,代表有多少组测试数据,再给出来一个N,表示每组测试数据中有多少数字,然后就在每一个N后面输入每一组的测试数据,要求求得从这一组测试数据第i个字符起到第j个字符的和并保证这个数是最大的。
题目给出来了例子:6,-1,5,4,-7,假如从第一个数字开始加,一直加到4,这时候如果再加上-7,那么总和反而不如加到4大,所以加到4就截止了,而从第2,3,4个数字开始往后加,都不如从第一个数字开始进行加法运算得到的结果大,所以这一组数据要输出的就是最大值14以及开始的位置1和结束的位置4。
然后再就是要注意输出格式,杭电的题目常常设置输出格式设置的比较严格,这一道题要求输出Case #:格式,并且要求每两行之间都要留下一行空行,如果不注意,很可能会不停的PE。

关于这道题的解题思路,基本上是暴力破解的,就是从第一个数字开始往后加,找到最大值,然后从第二个数字开始往后加,找到最大值……
例如:1 -1 3 -5 7 8
sum1=1
sum2=0
sum3=3
……
但是也有一个小技巧可以注意,那就是当sum<0时,这时候就可以把sum清零然后从下一位开始进行加法运算了。否则一个负数加上后面的正数,反而不如从0开始加来的方便。

贴代码

#include<iostream>
using namespace std;
int main()
{
 int f,l,temp;
 int t,n;
 int sum,num,max;
 cin>>t;
 for(int j=1;j<=t;j++)
 {
  f=l=temp=1;
  sum=0;
  max=-1010;
  cin>>n;
  for(int i=1;i<=n;i++)
  {
   cin>>num;
   sum+=num;
   if(max<sum)
   {
    f=temp;
    l=i;
    max=sum;
   }
   if(sum<0)
   {
    sum=0;
    temp=i+1;
   }
  }
  if(j<t)
  cout<<"Case " << j << ":" << endl << max << " " << f << " " << l << endl << endl;
  else
  cout<<"Case " << j << ":" << endl << max << " " << f << " " << l << endl;
 }
 return 0;
}

注意这里max=-1010,因为说整数的范围是从-1000开始的,所以max的初值应该设置的比-1000大一些。

还曾经在网上看到过另外一个解题思路,是讲从最后一个数开始往前加,每一组都是以这个数为终止点的一组数据求和,采用递归的方式。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值