D - 最大连续和 Easy

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

题意是要求最大连续和,与以往不同的是追加输出子串的头尾位置,这个可以用结构体记录,最坑的是没有注意到格式说每两个case间要空一行。

代码:

  1. #include <stdio.h>
    #include<string.h>
    #include<algorithm>
    using namespace std;
    int  a[100005];
    
    struct studen
    {
            long long sum;
            int l,r;
    }dp[100005];
    
    long long maxw(long long  x,long long  y)
    {
            if(x>y)
                    return x;
            else
                    return y;
    }
    int main()
    {
        int n,i,m,s=0;
        scanf("%d",&m);
        while(m--)
        {
                s++;
               scanf("%d",&n);
        for(i=1;i<=n;i++)
        {
                scanf("%d",&a[i]);
                dp[i].sum=a[i];dp[i].l=i;dp[i].r=i;
        }
       studen max1=dp[1]; 
    
         for(i=2;i<=n;i++)
        {
             dp[i].sum=maxw(a[i],dp[i-1].sum+a[i]);
            if(dp[i-1].sum>=0)
                    dp[i].l=dp[i-1].l;
            else
                      dp[i].l=i;
             dp[i].r=i;
              if(dp[i].sum>=max1.sum)
             {
                     max1=dp[i];
    
             }
        }
       
        printf("Case %d:\n",s);
        printf("%lld %d %d\n",max1.sum,max1.l,max1.r);
         if(m)
            printf("\n");
    
    
        }
    
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/intelligentgirl/article/details/81236200