从hdu1003开始的一系列题目

hdu1003

 

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

 

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

分析:不是什么难题,就是让你求和最大的子数列;

代码其实不难,跑一遍应该就能懂,主要是思路就是不断变更起点。

从第一个数开始不断找出更大的子数列,并将子数列的起点和终点记录下来。

变更终点的条件是找到了一个更大的子序列,变更起点的条件是以当前起点的子序列的和已经成为负值,

最后要注意的就是,如果当前输出不是最后一个输出要输出两个换行符,即空行

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

int main()
{
   int n,i,j,m;
   int sum,max,temp;
   int x,y,k;
   int head;
   cin>>n;     表示有多少组输入
   for( k=1;k<=n;k++)
   {
       cin>>m>>temp;     m表示一组输入有多少个,temp存储当前输入
       max=sum=temp;     
       head=0;
       x=y=1;
       for(i=1;i<m;i++)
       {
           cin>>temp;
           if(sum+temp<temp)   sum如果小于零
           {
               sum=temp;       重新计算子序列
               head=i;            变更头结点
        }
           else 
           {
               sum+=temp;       如果sum大于零我们继续增长子数列
           }
           if(sum>max)          找到了一条比当前子数列更长的子数列
           {
               max=sum;            变更最大值
               x=head+1;            变记录新数列的头尾节点
               y=i+1;         
           }
    }
   
       cout<<"Case"<<" "<<k<<":"<<endl;
       cout<<max<<" "<<x<<" "<<y<<endl;
       if(k!=n)
       cout<<endl;                     输出如果不是最后一组我们需要空行不然oj会报错
    } 
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42105529/article/details/82927191