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 <stdio.h>
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<number;i++)
            scanf("%d",&a[i]);
        int p1=0,p2=0,sum=0,maxsum=-100000000,maxp1=0,maxp2=0;
        for(int i=0;i<number;i++)
        {
            if(sum+a[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;i<number;i++)
            {
                if(a[i]>maxsum)
                {
                    maxsum=a[i];
                    maxp1=i;
                    maxp2=i;
                }
            }
        }
        printf("Case %d:\n",no);
        printf("%d %d %d\n",maxsum,maxp1+1,maxp2+1);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 自古以来无数的检测手段被发明的目的,是为了把人像东西一样分个三六九等。在这无数的手段中唯有科举制也就是现在我们手上...
    过往云烟w阅读 190评论 0 0
  • 最近几天渐渐地生活开始更加规律起来,当然不能100%认为是读了这本书以后的功劳,但是确实更加能够控制自己。 一般早...
    本来源起阅读 469评论 1 50
  • 看到来北京的相册我仿佛又回到了北京的课堂。 喻江江三个标签: 1.爱生活中所有美好的东西,旅行、摄影、跑步、鲜花等...
    辣妈喻江江Teresa阅读 610评论 3 8
  • 1最近自己一直忙于脐橙生意,把自己做的十分忙碌,那么从我到市区这几天我也发现,这个生意我可以百分之八十脱手了。所以...
    环保天使尹宏阅读 456评论 0 0

友情链接更多精彩内容