8 0 3
推荐指数:※
来源:http://ac.jobdu.com/problem.php?pid=1372
这道题和PAThttp://blog.csdn.net/zhu_liangwei/article/details/9209979类似
在运算过程中记录到当前为止的最好值。sum<0,它与其他数在相加,一定小于被加的那个数 ,所以后重新计算。
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<limits.h> using namespace std; typedef struct sub{ long long sum; int start; int end; }sub; bool flag=false; sub* max_sub(long long *a,int len){ flag=false; sub *sum=new sub; sub *pre=new sub; sum->sum=0;sum->start=0;sum->end=0; pre->sum=LONG_MIN;pre->start=0;pre->end=0; sub* min_num=new sub; min_num->sum=LONG_MIN; for(int i=0;i<len;i++){ if(a[i]>=0) flag=true; else{ if(min_num->sum<a[i]&&false==flag){ min_num->sum=a[i]; min_num->start=i; min_num->end=i; } } sum->sum+=a[i]; if(sum->sum<0){ sum->sum=0; sum->start=i+1; sum->end=i+1; }else{ sum->end=i; if(sum->sum>pre->sum){ pre->sum=sum->sum; pre->start=sum->start; pre->end=sum->end; } } } sum=sum->sum>pre->sum?sum:pre; if(false==flag){ sum=min_num; } return sum; } int main() { int n ,i; while(scanf("%d",&n)!=EOF&&n>0){ long long *a=new long long[n]; for(i=0;i<n;i++){ scanf("%lld",&a[i]); } sub *s=max_sub(a,n); printf("%lld %d %d\n",s->sum,s->start,s->end); } return 0; }