DP动态规划--G - Max Sum

题目:
                                                    G - Max Sum
                                         Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u       hdu 1003
 

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
分析:
        在这一道动态规划题中,若前面的i-1个数之和为负,则记录前i个数之和dp[i]=s[i],反之,dp[i]=dp[i-1]+s[i];
用max去记录其最大值即可。
代码:
 1 #include<stdio.h>
2 #include<string.h>
3
4 int s[100001],dp[100001];
5 int main()
6 {
7 int n,m,k,i,j,max;
8 while(scanf("%d",&n)!=EOF)
9 {
10 k=1;
11 memset(dp,0,sizeof(dp));
12 while(n--)
13 {
14 scanf("%d",&m);
15 for(i=0;i<m;i++)
16 {
17 scanf("%d",&s[i]);
18 }
19 if(k!=1)
20 printf("\n");
21 dp[0]=s[0];
22 max=dp[0];
23 j=0;
24 for(i=1;i<m;i++)
25 {
26 if(dp[i-1]<0)
27 dp[i]=s[i];
28 else
29 dp[i]=dp[i-1]+s[i];
30 if(max<dp[i])
31 {
32 max=dp[i];
33 j=i;
34 }
35 }
36 if(max<0)
37 i=j-1;
38 else
39 {
40 for(i=j;i>=0;i--)
41 {
42 if(dp[i]<0)
43 break;
44 }
45 }
46 printf("Case %d:\n",k++);
47 printf("%d %d %d\n",max,i+2,j+1);
48 }
49 }
50 return 0;
51 }
PS:心情低谷,低啊,低~~~~~~~~
posted @ 2012-01-18 22:10  hankers  阅读(436)  评论(0编辑  收藏  举报