hdu 1003

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 
題意:
給你n個數a[1],a[2],a[3]...a[n],要你求出最大連續子段和,並且輸出這個和,和這個子段的起始位置和終止位置,如果這個子段有多種可能,輸出第一種結果即可。
思路:
前段時間做個類似的題目,用的是暴力求解,用的兩重循環,但是這個題目要求是n<100000,用兩重循環肯定會超時,因此我們必須換一種思路,必須減少循環次數,當輸入的時候,累計求和,用pos記錄位置,star記錄起點,end記錄終點,如果sum小於0.就不必往下面累加了。
代碼:
#include<cstdio>
using namespace std;
#define INF 0x7fffffff
int const maxn=100000+10;
int a[maxn];
int main()
{
    int kcase=1;
    int T,n,max,star,end,pos,sum;//max爲最大字段和,star爲枚舉起始位置,end爲枚舉終止位置,sum爲字段和,pos用來更新枚舉起始位置
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        max=-INF;
        pos=sum=0;
        for(int i=0;i<n;i++)
            {
                scanf("%d",&a[i]);
                sum+=a[i];
                if(sum>max)
                {
                    max=sum;
                    star=pos;
                    end=i;

                }
                if(sum<0)
                {
                    sum=0;
                    pos=i+1;

                }
            }
        printf("Case %d:\n",kcase++);
        printf("%d %d %d\n",max,star+1,end+1);//數組下標是從0開始的,而數的位置是從1開始的
        if(T)
          printf("\n");
    }
    return 0;
}

發佈了76 篇原創文章 · 獲贊 7 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章