专题三1001

本文解析了一个经典的编程问题——如何寻找给定序列中拥有最大和的子序列及其位置。通过一个直观且易于理解的算法实现,展示了如何一步步找出最优解。

*题意:求给定序列的子序列的最大和,并输出最大和子序列的起始位置和结束位置

*解题思路:首先,这题是一道水题,首先将第一位数的和记为最大和以及sum,也记作起始位置和终止位置,如果sum加上后面一位数小于后面一个数本身,则sum=这个数,起始位置与终止位置也是这个数,反之,则sum+=这个数,终止位置变成这个数,然后比较sum与max,如果sum>max,则max=sum,就这样依次向后,最终就能求出最大和以及初始位置和结束为止

*感想:第一次提交,因为输出格式上 case后面漏了个:,结果提示我答案错误,我还以为是逻辑写错了,找了半天也没找到,又运行了一边程序,结果才发现输出有 错误,也是醉了,以后写完的程序一定要在本地运行一遍再交。

*源码

# include <iostream>
using namespace std;  
int main()  
{  
    int T,n,i,j,ans,start,end,p,sum,a[100001];  
    cin>>T;
    for(i=1;i<=T;i++)  
    {  
        if(i!=1)  
            cout<<endl;  
        cin>>n;
        for(j=1;j<=n;j++)  
            cin>>a[j];  
        ans=0;  
        start=end=p=1;  
        ans=sum=a[1];  
        for(j=2;j<=n;j++)  
        {  
            if(sum<0)  
            {  
                sum=a[j];  
                p=j;  
            }  
            else  
            {  
                sum+=a[j];  
            }  
            if(sum>ans)  
            {  
                ans=sum;  
                start=p;  
                end=j;  
            }  
        }  
       cout<<"Case "<<i<<":"<<endl;  
       cout<<ans<<" "<<start<<" "<<end<<endl;  
    }  
    return 0;  
 }   



Problem A

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 148   Accepted Submission(s) : 23
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.<br>
 

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).<br>
 

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.<br>
 

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
 

Statistic |  Submit |  Back

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值