To find the maximum sub-matrix and is a class of topics in DP, today we will talk about one-dimensional (sequence) and two-dimensional (matrix) the most large and
I. To find the maximal continuous subsequence and
Simply define sum, sweep once, sum is negative when sum=0, see Code
#include <cstdio>#include<algorithm>using namespacestd;Const intn= +;intX,SUM,N,MAXN;intMain () { while(SCANF ("%d",&N), n) {sum=0, maxn=-0x3f3f3f3f; for(intI=1; i<=n;++i) {scanf ("%d",&x); Sum+=x; if(sum<0) sum=0; MAXN=Max (maxn,sum); } printf ("%d\n", MAXN); }}
View Code
Cases:
Input
8
1-3-5 2 6-1 4 9
Output
20
Two. Find the maximum sub-matrix and
It is necessary to compress the matrix into one dimension and then apply a one-dimensional method, first defining A[i][j], which represents the number of rows of the first I row in column J ,
Then I and J are enumerated, representing the matrix and maximum values from line I to line J, and finally the maximum value in these maximums is the desired answer
As an example:
1-1 2
4 9 15
-7 1 10
First time Take
1-1 2, this one-dimensional array to the maximum continuous and, get 2, update the maximum value of 2
Second time take
1-1 2
4 9 15,
SUM (sum of columns) to get
5 8 17, for this one-dimensional array to maximize continuous and, get 30, update the maximum value is 30
Third time take
1-1 2
4 9 15
-7 1 10
Sum to get
-2 9 27, for this one-dimensional array to maximize continuous and, get 36, update the maximum value is 36
Fourth time take
4 9 15, for this one-dimensional array to maximize continuous and, get 28, update the maximum value is 36
Fifth time take
4 9 15
-7 1 10
Sum to get
-3 10 25, for this one-dimensional array to maximize continuous and, get 35, update the maximum value is 36
Sixth time Take
-7 1 10, for this one-dimensional array to maximize continuous and, get 11, update the maximum value is 36
So finally get the answer to 36, see the code for details
//To find the maximum sub-matrix and//record columns and either rows and//The two-dimensional transformation to one-dimensional, according to one-dimensional method of seeking#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;intn,a[ Max][ Max],sum,x,sum1[ Max];//A[i][j] Records the sum of the number of rows of the first I row in column J andintGet_max_sum ()//get the maximum continuous sequence and{ intmaxsum=0, ret=-0x3f3f3f3f; for(intI=1; i<=n;++i) {maxsum+=Sum1[i]; if(maxsum<0) maxsum=0; RET=Max (ret,maxsum); } returnret;}intMain () { while(SCANF ("%d", &n) = =1) { for(intI=1; i<=n;++i) for(intj=1; j<=n;++j) {scanf ("%d",&x); A[I][J]=a[i-1][j]+x; } Sum=-0x3f3f3f3f; for(intI=1; i<=n;++i) for(intj=i;j<=n;++j) { for(intk=1; k<=n;++k) {Sum1[k]=a[j][k]-a[i-1][K];//in the K column from the I~j and} sum=max (Sum,get_max_sum ());//update the maximum value for each matrix and} printf ("%d\n", sum); }}
View Code
The relation and implementation of maximal continuous sub-series and maximal continuous sub-matrix in "algorithm small sum"