hud1003Max Sum 最大连续子序列的和

版权声明:转载注明出处!!! https://blog.csdn.net/xhpaqh/article/details/81462381

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

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
题目大意给出一行数,找出连续最大子序列的和。这个题要求打印下标,所以要注意下标问题,具体实现请看代码,,,orz。

#include<stdio.h>
int n,k,m,num=0;
int main(){
    scanf("%d",&n);
    while(n--){
        num++;
        int p1=1,p2=1,x=1,max=-1000000,sum=0;
        scanf("%d",&k);
        for(int i=1;i<=k;i++){
            scanf("%d",&m);
            if(sum>=0){
                sum+=m;
            }
            else{
                sum=m;x=i;//找出子序列起始位置
            }
            if(max<sum){
                max=sum;//每次循环判断是否为最大子序列,记录始末位置
                p1=x;
                p2=i;
            }
        }
        printf("Case %d:\n",num);
        printf("%d %d %d\n",max,p1,p2);
        if(n!=0)
        printf("\n");
    }
}

还有一种直接打印最大子序列的和,不用打印子序列的始末位置。这个方法如下。

#include<stdio.h>
#include<algorithm>
using namespace std;
int main(){
    int T,n,m;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        int sum=0,maxn=-1000000,mn=0;
        for(int i=1;i<=n;i++){
            scanf("%d",&m);
            sum+=m;
            mn=min(mn,sum);
            maxn=max(maxn,sum-mn);
        }
        printf("%d\n",maxn);
    }
}

猜你喜欢

转载自blog.csdn.net/xhpaqh/article/details/81462381