HDU_1003最大连续子段和(打印出最大子段区间端点)

Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 292939 Accepted Submission(s): 69525

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

原题传送
题目大意:
1:求出它的最大连续子序列的和。
2:输出它的区间,从L~R。
注意:题目输出要求,两组数据的结果之间要有一个空白行(要打印两个换行),而最后一组数据后打印一个换行即可。
刚开始交这个题一直PE,后来仔细分析,原来是这个样子。

最大连续子序列和AC代码

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<limits.h>
using namespace std;
const int maxn=1e5+7;
int a[maxn];
int main()
{
    int ans,mn,sum,s,start,end;
    int n,i,t,j;
    scanf("%d",&t);
    for(j=1;j<=t;j++)
    {
        memset(a,0,sizeof(a));
        sum=0;
        ans=INT_MIN;
        s=1;//刚开始的第一个子段的元素开始位置是1
        scanf("%d",&n);
        for(i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        for(i=1;i<=n;i++)
        {
            sum+=a[i];
            if(sum>ans)//ans相当于之前求的最大的sum,sum大于ans时则把ans更新
            {
                ans=sum;
                start=s;//更新结束和开始位置  
                end=i;
            }
            if(sum<0)//sum小于0时,不再进行该子段 
            {
                s=i+1;//下一子段从该子段的结尾的后一个元素位置开始 
                sum=0;//初始化sum,用来记录下一子段的和 
            }//元素全为负数时,每一个负数都是一个子段 
        }
      printf("Case %d:\n%d %d %d\n",j,ans,start,end);
      if(j!=t)
      printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42817826/article/details/81458301