最大和问题

来源:互联网 发布:北京程序员培训 编辑:程序博客网 时间:2024/05/16 13:59

连接:http://acm.hdu.edu.cn/showproblem.php?pid=1003


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


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
 


如果按照最原始,最机械的算法的话那就是两个for循环去做,但是一考虑时间,那就绝对不可以。

从题目中看 n最多有100000个,那么那种方法的时间复杂度应该是O(n^2);


所以我们换一个角度来考虑。


我们要我们的和最大那么我们应该在加的过程中应该一直保持着前面的加和为正或者刚好等于0,否则的话,我们加上下一个值以后会得不到该有的结果。

例如 : -1 -2 -3 4 5

如果我们的加和把-1 -2 -3 算上的话那么我们的结果肯定得不到最大和

再如:-1 3 -3 4 5

在前三个数的加和已经是负数的情况在加上4 的话。那么结果还是会小

所以我们应该判断我们的加和是否已经小于0,如果小于0,那么该从当前值进行累加,如果大于0 ,继续累加当前值


具体见代码:

#include <stdio.h>
using namespace std;


int a[1000003];
int main(){

int t;
int n;
scanf("%d",&t);
    int c=1;
    while(t--){
     scanf("%d",&n);
     for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
      }
      int sum,s,e,st,ed;
      st=ed=s=e=0;
      sum=a[0];
      int max=sum;
     for(int i=1;i<n;i++){
          if(sum>=0){
            sum+=a[i];
            ed=i;
          }
          else if(sum<0){
            sum=a[i];
            st=i;
            ed=i;
          }
          if(max<=sum){
            max=sum;
            s=st;
            e=ed;
          }
     }
     if(c!=1)
        printf("\n");
     printf("Case %d:\n",c);
     printf("%d %d %d\n",max,s+1,e+1);
     c++;
    }
return 0;
}

注意max的取值问题,还有空行的输出










0 0
原创粉丝点击