hdu Max Sum 1003

来源:互联网 发布:seo白帽优化 编辑:程序博客网 时间:2024/05/16 04:50

Max Sum

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


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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
 

Sample Output
Case 1:14 1 4Case 2:7 1 6
 


我觉得有必要将这题的逻辑真正完全理解清楚,不然怕第二次碰到可能就又乱了思绪,因为之前看多几次,第一次A了,但是思绪比较乱,没整理,第二次碰到时,代码不能快速打出来,和没做一样,所以决定整理出来,理解清清楚楚的。下次再碰到就能望文码字了。从这可以引申出,对于做过的任何一题,都应该要能清清楚楚的理解每一步,能够在第二次看到时,脑海里能快速的想到方法是什么,这样才算是没白做了这道题。更重要的就是要能举一反三,做出一道能悟出其他这一类题的解题方式。这样解一道题收获就会很大。


此题将问题分解为 求在累加和sum<0的时候那一段的最大连续子序列(代码中的if(sum < 0)。然后将各段sum<0的最大连续子序列的值进行个比较最大的那个就是全部序列的最大连续子序列和(代码中的if(sum > max)。

当sum值大于最大值时,就记下最大值以及这个值对应的左起和右终的下标。

当sum<0时,那就如代码上讲的。

值得提起的是,如果全是负数,那么就是说sum加上那一个负数sum就小于0了。因此每个负数都是一个连续子序列。就看那个负数最大了。因为每次只要sum<0就会将sum重新清0,原因代码上有解释。所以负数情况完全和正数一起处理了。


好了贴上代码:

#include <iostream>#include <stdio.h>using namespace std;#define N 100001#define MIN -100000001int a[N];void f(int n){    int max,sum,i,l = 1,r = 1,t = 1;    sum = 0;max = a[1];    for(i = 1; i <= n; i++){        sum += a[i];//一个一个数的加        if( sum > max){//只要相加的和大于现在所求的最大值,则更换数据            max = sum;//将所求的新的最大值存起来            l = t;//记下左起            r = i;//记下右终        }        if( sum < 0 ){//如果累加和小于0            sum = 0;//那么将累加的和清零 让它重新累加,这个赋0可以判断出                            //sum只能是加了负数才能变成负数,            t = i + 1;//此时是sum累加了几个负数导致值为负了所以此次循环加的数一定是负数。            //而在这之前的那个if绝对是已经成立过了的,即已经更换的数据了,存了最大值了            //所以现在碰到负数了,这个负数肯定不是下一个可能的最大连续子序列里的一个元素,            //所以左起肯定不会是它,因此右移一位。        }//sum 不可能从负数开始加,所以最长连续子序列的左起第一个数肯定是正数,//因此在sum累加到负数之前,那段连续的子序列里,一定有一段连续子序列是最大的。//而既然前一段的累加和是负数,那么之后的连续子序列肯定不能加上他们,那样他们划不来,//因为往左先加的肯定是负数,而这些负数的和比前面的最大连续子序和还大,所以加起来就会变小,即会加上个负数//因此前一段在累加和小于0时的最大连续子序列和后一段的累加和应该分开算,并且独立,因此sum要清零。    }    printf("%d %d %d\n",max,l,r);}int main(){    int T,n,j,i;    scanf("%d",&T);    for(j = 1; j <= T; j++){        scanf("%d",&n);        for(i = 1; i <= n; i++){            scanf("%d",&a[i]);        }        printf("Case %d:\n",j);        f(n);        if(j != T)putchar('\n');    }    return 0;}


原创粉丝点击