最大子串和(dp)

来源:互联网 发布:国内外治疗癌症知乎 编辑:程序博客网 时间:2024/05/17 07:52

http://blog.csdn.net/joylnwang/article/details/6859677关于最长子串和,这位博主讲的蛮好。

读完他的文章,我的理解就是,一段连续的序列,从一个数开始,始终找和大于或等于0的和,记录最大值,并记下左右端点,一旦小于0,便让和为0,重新开始。一直这样执行下去,遍历找最大值。

附赠一题和一个不错的虚拟oj:

http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1235

AC代码如下:

#include<stdio.h>#include<math.h>#include<string.h>#include<algorithm>using namespace std;int a[100000];int main(){    int n,L,R,sum,maxx,pL,pR,flag;    while(~scanf("%d",&n)&&n)    {        L=0,R=0,sum=0,maxx=-1e9,pR=0,pL=0,flag=0;        for(int i=0; i<n; i++)        {            scanf("%d",&a[i]);            if(a[i]>=0)                flag=1;        }        if(!flag)        {            printf("0 %d %d\n",a[0],a[n-1]);            continue;        }        for(int i=0; i<n; i++)        {            sum+=a[i];            if(sum>=0)            {                pR=i;                if(sum>maxx)                {                    maxx=sum;                    L=pL;                    R=pR;                }            }            else            {                sum=0;                pL=pR=i+1;            }        }        printf("%d %d %d\n",maxx,a[L],a[R]);    }}

又发现另外一种写法,相对简单,并且可以省去好多判断条件,代码如下:

#include<stdio.h>#include<algorithm>#include<math.h>#include<string.h>#include<iostream>using namespace std;#include<stdio.h>int main(){    int n;    while(~scanf("%d",&n)&&n)    {        int L,R,x,y,a,maxx,flag=0,k,t;        for(int i=0; i<n; i++)        {            scanf("%d",&x);            if(x>=0)                flag=1;            if(i==n-1)                k=x;            if(i==0)            {                L=R=a=x;                y=maxx=x;                t=x;            }            else            {                if(x>x+y)                    y=a=x;                else                    y+=x;            }            if(y>maxx)            {                maxx=y;                L=a;                R=x;            }        }        if(!flag)            printf("0 %d %d\n",t,k);        else            printf("%d %d %d\n",maxx,L,R);    }}



1 0
原创粉丝点击