您的位置:首页 > 其它

练习三1001

2016-04-27 13:04 281 查看
Problem A
Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 142   Accepted Submission(s) : 21
[align=left]Problem Description[/align]
Given a sequence a[1],a[2],a[3]......a
, 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.<br>
 

[align=left]Input[/align]
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).<br>
 

[align=left]Output[/align]
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.<br>
 

[align=left]Sample Input[/align]

2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5

 

[align=left]Sample Output[/align]

Case 1:
14 1 4

Case 2:
7 1 6

 

Statistic |

Submit |
Back
题意:
给出一串数列,求其中和最大的子序列的值及其始末位置。
思路:
刚开始想以每一个数作为起始,计算以他开始的所有子序列的长度存入数组,但超时了。应该以他为末位置向前加,如果他前面的最大和小于零,则它变为起点。注意题目中说输出时每组后空一行,一开始没看到。
代码:
#include<iostream>

using namespace std;

int main()

{

    int t;

    cin>>t;

    for(int k=1;k<=t;k++)

    {

        int n,a[100001],b[100001],c[100001];

        cin>>n;

        for(int i=1;i<=n;i++)

        cin>>a[i];

        b[1]=a[1];

        c[1]=1;

        for(int i=2;i<=n;i++)

        {

            if(b[i-1]>=0)

            {

                b[i]=b[i-1]+a[i];

                c[i]=c[i-1];

            }

            else

            {

                b[i]=a[i];

                c[i]=i;

            }

        }

        int sum=b[1],sta=c[1],end=1;

        for(int i=2;i<=n;i++)

        {

            if(b[i]>sum)

            {

                sum=b[i];

                sta=c[i];

                end=i;

            }

        }

        cout<<"Case "<<k<<":"<<endl<<sum<<" "<<sta<<" "<<end<<endl;

        if(k!=t) cout<<endl;

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: