杭电1003 最大子串

  这道题开始的时候还真的没啥头绪,主要题目也少看了,然后自己也想得太多,所以就没想出好的思路,在问过一些dalao之后,思路也就清晰起来。

  其实,这题就只是需要两步,第一就是要个临时变量保存imax,还有就是如果sum<0了,我们就要把子串的first指针向后移动下,不然会影响imax。

     下面放上能ac的代码:

  

#include <iostream>

using namespace std;

int main()
{

    int n;
      int a[100001];
    int icount;     //用来搞输入次数
    int iicount=0; //用来搞case次数
   cin>>icount;

   while(icount--){

    int first=0;
    int last=0;
    int temp=0;

    int sum=0;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    int imax=a[0];  //开始就是订正这边的错 开始的最大值必须是第一个数
    for(int j=0;j<n;j++){
        sum=sum+a[j];
        if(sum>imax){
            imax=sum;
            first=temp;
            last=j;
        }
        if(sum<0){
            sum=0;
            temp=j+1;
        }

    }
      iicount++;
      cout<<"Case "<<iicount<<":"<<endl;//劳资这边少打一个空格……

    cout<<imax<<" "<<first+1<<" "<<last+1<<endl;

     if(icount!=0){
       cout<<endl;
   }

    }
    return 0;
}

其中我在写的时候出现了这么些个bug:

1.就是忘记用临时变量保存imax;

2.没有意识到要用临时变量来赋值first和last,因为你子串在增加的同时 first和last不一定会增加

3.就是imax开始应该要赋值为a[0],不然会出现bug:

4.输出格式问题,case后面少加了“ ”; 每相邻的两次输出要换行。

原文地址:https://www.cnblogs.com/William-xh/p/6740883.html