[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

AC代码:

#include<stdio.h>
int main(){
    int i,j,k,t,arr[100000],sum,max_sum,a,b,temp;

    scanf("%d",&t);
    for(i=1;i<=t;i++)
    {
        scanf("%d",&k);
        for(j=0;j<k;j++)
        {
            scanf("%d",arr+j);
        }
        a=b=sum=temp=0;
        max_sum=-1001;
        for(j=0;j<k;j++)
        {
            sum+=arr[j];
            if(sum>=max_sum)
            {
                max_sum=sum;
                b=j;
                a=temp;
            }
            if(sum<0)
            {
                temp=j+1;
                sum=0;
            }
        }
    printf("Case %d:\n",i);
    printf("%d %d %d\n",max_sum,a+1,b+1);
    if(i<=t-1) printf("\n");
    }
}

总结:

本题解决思路为

一行中的数字a,b,c,d,e,f
若其中连续的a+b+c+d<0,即可将这几项合为一项 T
则可得,
T<0;
对任意的x
T+x 必定会使x得值减小,
故T直接舍弃

即因为d的出现,导致前几项的和变成负数,那么这个连续序列的价值就变成了负的,故被舍弃;
即舍弃a,b,c,d,重新从e开始取连续的子序列

过程中,若sum>max_sum,则swap(sum,max_sum);

其中有一个小点,若此序列全部为负数会不会影响呢,因为此时任意子序列组成的T都是小于0的啊?
答案是不会的,T只是一个连续序列的和,可以把它当做数组元素的一项看待,舍弃的原因是任一项加负数都会使其值减小,但在判断T<0?之前,先进行的是判断sum 和 max_sum大小的比较,当一个全部为负数的序列,可以想象最大值是其中最大的负数,那么自然,他会因为这个比较而赋值给max_sum。

猜你喜欢

转载自blog.csdn.net/liuHuaWei5909/article/details/81486288