Max Sum题解

来源:互联网 发布:mysql使用教程 编辑:程序博客网 时间:2024/06/13 22:28

原题地址 http://acm.hdu.edu.cn/showproblem.php?pid=1003

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个数字5代表接下来有几个数字(这里是有5个数字,分别为6 -1 5 4 -7),然后他的最大连续子序列就6+(-1)+5+4=14,其中6的是第1个数,4是第4个数。

#include <iostream>#include <stdio.h>#include <string.h>#include <algorithm>#define inf 0x3f3f3f3fusing namespace std;int a[100005];int main(){    int t;    scanf("%d",&t);    for(int k=1; k<=t; k++)    {memset(a,0,sizeof(a));        int n;        scanf("%d",&n);        for(int i=1; i<=n; i++) scanf("%d",&a[i]);        int Max=-inf;        int sum=0;        int fn=1,fm=1,ln=1,lm=1;        for(int i=1; i<=n; i++)        {            sum+=a[i];            if(sum>Max)            {                Max=sum;                ln=fn;                lm=i;            }             if(sum<0)//这里不能用else if ,因为如果你输入的是全负数,那么sum就不能清为0            {                sum=0;                fn=i+1;            }        }        printf("Case %d:\n%d %d %d\n",k,Max,ln,lm);        if(k!=t) printf("\n");//第一次就在这pe了一次,当是最后一组数据的时候,不需要输出换行    }    return 0;}
原创粉丝点击