1. 程式人生 > >最大連續子段和

最大連續子段和

img ans define open space sed 表示 max get

最大連續子段和
sum表示以當前數a[i]結尾的最大子段和,
如果sum<0,那麽它對後面就沒有積極作用,不如拋棄。
所以
sum+=a[i]
維護最大值
sum=max(sum,0)

技術分享
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue>
 4 #include<algorithm>
 5 #include<cmath>
 6 #include<ctime>
 7 #include<cstring>
 8 #define inf 2147483647
 9
#define For(i,a,b) for(register int i=a;i<=b;i++) 10 #define p(a) putchar(a) 11 #define g() getchar() 12 //by war 13 //2017.10.19 14 using namespace std; 15 int n; 16 int a[200][200]; 17 int f[200]; 18 int x; 19 int ans; 20 int sum; 21 int Max; 22 void in(int &x) 23 { 24 int y=1; 25 char c=g();x=0;
26 while(c<0||c>9) 27 { 28 if(c==-) 29 y=-1; 30 c=g(); 31 } 32 while(c<=9&&c>=0)x=x*10+c-0,c=g(); 33 x*=y; 34 } 35 void o(int x) 36 { 37 if(x<0) 38 { 39 p(-); 40 x=-x; 41 } 42 if(x>9)o(x/10); 43 p(x%10+
0); 44 } 45 int main() 46 { 47 in(n); 48 For(i,1,n) 49 For(j,1,n) 50 { 51 in(x); 52 a[i][j]=a[i][j-1]+x; 53 } 54 ans=-inf; 55 For(l,1,n) 56 For(r,l,n) 57 { 58 Max=-inf; 59 sum=0; 60 For(i,1,n) 61 { 62 sum+=a[i][r]-a[i][l-1]; 63 Max=max(Max,sum); 64 sum=max(sum,0); 65 } 66 ans=max(ans,Max); 67 } 68 o(ans); 69 return 0; 70 }
View Code

最大連續子段和