题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1231
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #define N 10010 6 using namespace std; 7 int main() 8 { 9 int n,i,a[N],s,m,e,k,MAX,sum,st,en; 10 while(scanf("%d",&n),n) 11 { 12 m=k=0; 13 memset(a,0,sizeof(a)); 14 for(i=0; i<n; i++) 15 { 16 scanf("%d",&a[i]); 17 if(a[i]<0) 18 m++; 19 if(a[i]==0) 20 k++; 21 } 22 if(m==n) 23 { 24 printf("0 %d %d ",a[0],a[n-1]); 25 continue; 26 } 27 if(m+k==n)//如果a中只有小数和0则输出三个0; 28 { 29 printf("0 0 0 "); 30 continue; 31 } 32 sum=s=st=en=e=MAX=0; 33 for(i=0; i<n; i++) 34 { 35 if(sum+a[i]<a[i])//当a[i]>a[i]+sum时,要从a[i]开始往下加,之前的不要 ; 36 { 37 sum=a[i]; 38 s=e=i; 39 } 40 else 41 { 42 sum+=a[i]; 43 e=i; 44 if(MAX<sum) 45 { 46 MAX=sum;//MAX是最终要输出的数,所以st和en要随之更新; 47 st=s; 48 en=e; 49 } 50 51 } 52 53 } 54 printf("%d %d %d ",MAX,a[st],a[en]); 55 }
56 return 0;
57 }
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> using namespace std; #define N 11000 int main() { int a[N],dp[N]; int n,i,m,MAX,INDEX,index; while(scanf("%d",&n),n) { m=0; for(i=0;i<n;i++) { scanf("%d",&a[i]); if(a[i]<0) m++; } if(m==n) { printf("%d %d %d ",0,a[0],a[n-1]); continue; } memset(dp,0,sizeof(dp)); dp[0]=MAX=a[0]; index=0; for(i=1;i<n;i++) { dp[i]=max(a[i],a[i]+dp[i-1]); if(MAX<dp[i]) { MAX=dp[i]; index=i; } } int sum=0; for(i=index;i>=0;i--) { sum+=a[i]; if(sum==MAX) { INDEX=i; break; } } printf("%d %d %d ",MAX,a[INDEX],a[index]); } return 0; }