随笔-1  评论-0  文章-0  trackbacks-0
最大字段和问题
问题描述:
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.
输入:
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).
输出:
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.
#include<iostream>
using namespace std;
int main()
{
    int cas;
    cin>>cas;
    int index=1;
    while (index<=cas)
    {
        int n;
        cin>>n;
        int a[n];
        int b[n];
        int l[n];
        int r[n];
        for(int i=1;i<=n;i++)
          cin>>a[i];
        int sum=-1000010;
        b[0]=0;
        l[1]=1,r[1]=1;
        int tmp=1;
        for(int i=1;i<=n;i++)
        {
           if(b[i-1]>=0)
           {
              b[i]=b[i-1]+a[i];
              r[i]=i;
              l[i]=tmp;
           }
           else
           {
              b[i]=a[i];
              r[i]=i;
              l[i]=i;
              tmp=i;
           }
        }
        for(int i=1;i<=n;i++){
          if(b[i]>sum){
            sum=b[i];
            tmp=i;
          }
        }
    cout<<"Case "<<index<<":"<<endl;
    cout<<sum<<" "<<l[tmp]<<" "<<r[tmp]<<endl;
    if(index!=cas)
          cout<<endl;
    index++;
    }
    return 0;
}
posted on 2012-05-13 21:00 cc272301926 阅读(72) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理