HDU 1003 最大连续字数段问题

来源:互联网 发布:2015年癌症数据 编辑:程序博客网 时间:2024/05/16 12:02
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
35 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
13 1 2 3 -100 1 2 3 -100 1 2 1 1 1
 

Sample Output
Case 1:14 1 4Case 2:7 1 6
Case 3:
6 1 3
这个题要注意一句:如果有相等的,输出最靠前的一个
这个是正确的代码:
#include <stdio.h>#include <iostream>using namespace std;int a[100005];int main(){    int t;    cin >> t;    for(int j=1;j<=t;j++)    {        int n;        cin >> n;        for(int i=0;i<n;i++)        {            cin >> a[i];        }        int x=0;//必须初始化,防止全是负数的数据        int y=0;        int start=0;        int end=0;        int max=a[0];        int sum=a[0];        for(int i=1;i<n;i++)        {            if(sum<0)            {                sum=a[i];                x=y=i;            }            else            {              sum+=a[i];              y++;            }            if(sum>max)            {                max=sum;                start=x;                end=y;            }        }        cout << "Case "<<j<<":\n";        if(j==t)          cout << max<<" "<<start+1 << " "<< end+1 <<endl;        else          cout << max<<" "<<start+1 << " "<< end+1 <<endl << endl;    }    return 0;}

如果没有这句话,代码可以写为:
#include <stdio.h>#include <iostream>using namespace std;int a[100005];int main(){    int t;    cin >> t;    for(int j=1;j<=t;j++)    {        int n;        cin >> n;        for(int i=0;i<n;i++)        {            cin >> a[i];        }        int start=0;        int end=0;        int max=a[0];        int sum=a[0];        for(int i=1;i<n;i++)        {            if(sum<0)            {                start=i;                sum=0;            }            sum+=a[i];            if(sum>=max)            {                max=sum;                end=i;               // cout << end << endl;            }        }        cout << "Case"<<" "<<j<<":\n";        if(j==t)          cout << max<<" "<<start+1 << " "<< end+1 <<endl;        else          cout << max<<" "<<start+1 << " "<< end+1 <<endl << endl;    }    return 0;}


0 0