HDU1003(动态规划+对0的思考)

这题本不是一道难题,简单的动态规划,由于每个人都接触过所以思路都知道,但如果不知道思路的话想到用动态规划对我来说还是很难的,动态规划什么时候使用也没有一个大概的概念,只是有的时候有感觉是动态规划(每一步的决策在改变),这题我还错在一个小细节上是0,sum我默认是0,在sum最后总和大于0是我像是成立的,但是当sum总和小于0是却不可以,平时总喜欢把0当最小值,看来并不好,干脆最小值总是默认第一个数可以避免很多错误,当然有一些情况是不可以的,我暂时也不能总结出来。

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
 这里发一下我认为美观的代码。
 1 #include<stdio.h>
 2 int a[101000],b[100100];
 3 int main()
 4 {
 5     int step;
 6     scanf("%d",&step);
 7     for(int step1=1;step1<=step;step1++)
 8     {
 9         int n;
10         scanf("%d",&n);
11         for(int i=1;i<=n;i++)
12             scanf("%d",&a[i]);
13         int sum=a[1],l=1,r=1,l1=1;
14         b[1]=a[1];
15         for(int i=2;i<=n;i++)
16         {
17             if(b[i-1]+a[i]>=a[i]) b[i]=b[i-1]+a[i];
18 
19             else{
20                 b[i]=a[i];
21                 l1=i;
22             }
23             if(sum<b[i]){
24                 sum=b[i];
25                 r=i;
26                 l=l1;
27             }
28         }
29         printf("Case %d:\n%d %d %d\n",step1,sum,l,r);
30         if(step1!=step) printf("\n");
31     }
32 }

 

posted @ 2016-02-19 20:56  Alan2  阅读(311)  评论(0编辑  收藏  举报