Maximum SumTime Limit: 1000 MS | memory limit: 65535 kb difficulty: 5
-
Description
-
Given a two-dimensional matrix composed of Integers (R * C), we need to find a sub-matrix to maximize the sum of all elements in this sub-matrix and call this sub-matrix the largest sub-matrix.
Example:
0-2-7 0
9 2-6 2
-4 1-4 1
-1 8 0-2
Its maximum submatrix is:
9 2
-4 1
-1 8
The total number of elements is 15.
-
Input
-
Enter an integer N (0 <n <= 100) In the first line, indicating that N groups of test data exist;
Test data for each group:
The first row has two integers, R and C (0 <R, C <= 100). R and C represent the rows and columns of the matrix respectively;
Then there is the R row, and each row has a C integer;
-
Output
-
The sum of elements in the maximum submatrix of the output matrix.
-
Sample Input
-
14 40 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2
-
Sample output
-
15
-
Source
-
[Miao Dongdong] original
-
Uploaded
-
Miao Dongdong
-
Problem solving: a difficult and simple question. The difficulty lies in the clever Processing Method of converting a two-dimensional plane into a one-dimensional interval, which is easy to find the maximum child segment and. The essence is violence + dp.
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <climits> 5 using namespace std; 6 int main() { 7 int table[110][110],i,j,ks,n,m,k,temp,ans; 8 scanf("%d",&ks); 9 while(ks--) {10 scanf("%d %d",&n,&m);11 memset(table,0,sizeof(table));12 for(i = 1; i <= n; i++)13 for(j = 0; j < m; j++) {14 scanf("%d",table[i]+j);15 table[i][j] += table[i-1][j];16 }17 ans = INT_MIN;18 for(i = 0; i < n; i++) {19 for(j = i+1; j <= n; j++) {20 for(temp = k = 0; k < m; k++) {21 if(temp >= 0) temp += table[j][k]-table[i][k];22 else temp = table[j][k]-table[i][k];23 if(temp > ans) ans = temp;24 }25 }26 }27 printf("%d\n",ans);28 }29 return 0;30 }View code