nyoj104 Max and

Source of the topic: http://acm.nyist.net/JudgeOnline/problem.php?pid=104

max sum

Time Limit: 1000  ms | Memory Limit: 65535  KB
Difficulty: 5
describe

Given a two-dimensional matrix (r*c) composed of integers, it is now necessary to find a sub-matrix of it, so that the sum of all elements in this sub-matrix is ​​the largest, and this sub-matrix is ​​called 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 sum of its elements is 15. 

enter
Enter an integer n (0<n<=100) in the first line, indicating that there are n groups of test data;
each group of test data:
the first line has two integers r, c (0<r, c<=100), r, c represent the rows and columns of the matrix, respectively;
followed by r rows, each row has c integers;
output
Sum of elements of the largest submatrix of the output matrix.
sample input
1
4 4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
Sample output
15
source
[Miao Dongdong] Original
Uploaded by
Miao Dongdong

这个题一开始我只一直在想怎么把矩阵弄成子矩阵, 后来实在太麻烦, 后来搜了一下答案,发现原来这么简单。

哎,做的题太少,想法太死板,代码借鉴了http://blog.chinaunix.net/uid-22263887-id-1778903.html 

记得前面做了一个最大连续子段和的题,这题就跟那个题一个解法,只不过你需要先把矩阵转化为一维的数据

//先求第一行最大子段和,再求第一行跟第二行合起来的最大子段和,如a21+a11, a22+a12, a23+a13  的最大子段和,
//再求第一到第三合起来的最大子段和,如a11+a21+a31,  a12+a22+a32, a13+a23+a33的最大子段和,

然后从第二行开始 继续这样操作

//直到求出整个矩阵的合起来的最大子段和,求出他们之中最大的那个和就是解. 
# include <stdio.h>

# include <stdio.h>
# include <memory.h>
const int Max = 100;
int array[Max][Max];
int temp[Max];
int main()
{
int n, r, c, i, j, k, l, b, max_sum;
freopen("in.txt", "r", stdin);
scanf("%d", &n);
while(n--){
scanf("%d %d", &r, &c);

for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
scanf("%d",&array[i][j]);
}
}
max_sum = -100000;
//从第一层开始,每一层都作为一个起点 
for(i = 0; i < r; i++){
memset(temp, 0, sizeof(temp));
for(j = i; j < r; j++){

//这里就是那个求最大子段和的算法。
for(l = 0, b = 0; l < c; l++){
temp[l] += array[j][l];
if(b > 0) b += temp[l];
else b = temp[l];
if(b > max_sum) max_sum = b;
}
}
}
printf("%d\n", max_sum);
}
return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325564828&siteId=291194637