HDOJ 1003 Max Sum

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

分析:

计算整数数组的子序列的最大和,用贪心算法,如何总和大于0,就一直增加,如果小于0,直接舍弃。最后讲过程中的最大值输出即可。

#include 
int main()
{
    int a[100000];
    int n;
    scanf("%d",&n);
    int no=0;
    while(n--)
    {
        if(no!=0)
            printf("\n");
        no++;
        int number;
        scanf("%d",&number);
        for(int i=0;i=0)
            {
                p2=i;
                sum=sum+a[i];
                if(sum>maxsum)
                {
                    maxsum=sum;
                    maxp1=p1;
                    maxp2=p2;
                }
            }
            else
            {
                p1=i+1;p2=i+1;
                sum=0;
            }
        }
        if(maxsum==-100000000)
        {
            maxsum=a[0];
            for(int i=1;imaxsum)
                {
                    maxsum=a[i];
                    maxp1=i;
                    maxp2=i;
                }
            }
        }
        printf("Case %d:\n",no);
        printf("%d %d %d\n",maxsum,maxp1+1,maxp2+1);
    }
}

你可能感兴趣的:(HDOJ 1003 Max Sum)