HDOJ 1003 MaxSum

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 59034    Accepted Submission(s): 13417

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
      这道题很简单,我将其作为动态规划专题的开山之题。容易出现的错误是输入实例个数不限制,开始总是WA。
本题的状态方程为Sum[i] = Sum[i-1] >= 0 ? Sum[i-1] + p[i] : p[i],当然网上也有人说Sum[i] = max( Sum[i-1] + p[i] , p[i] ),其实是一样的。还有一个易错点是当出现多个相同子段和且共同最大时起始位置的确定。闲言不表,代码如下:
 1#include <iostream>
 2int main()
 3{
 4    int num , n , p , sum , max , x , a , b;
 5    while ( ~scanf( "%d" , &num ) )
 6    {
 7        forint i = 1 ; i <= num ; i++ )
 8        {
 9            scanf( "%d" , &n );
10            sum = 0;
11            max = INT_MIN;
12            x = 1;
13            b = 1;
14            forint j = 1 ; j <= n ; j++ )
15            {
16                scanf( " %d" , &p );
17                if ( sum >= 0 )
18                {
19                    sum += p;
20                }

21                else
22                {
23                    sum = p;
24                    x = j;
25                }

26                if ( sum > max )
27                {
28                    max = sum;
29                    a = x;
30                    b = j;
31                }

32            }

33            printf( "Case %d:\n%d %d %d\n" , i , max , a , b );
34            if ( i == num )
35                break;
36            else
37                printf("\n");
38        }

39    }

40    return 0;
41}

posted on 2011-09-24 13:57  GQHero  阅读(331)  评论(0编辑  收藏  举报

导航