题目大意:给出一个n*n的矩阵,求这个矩阵的最大和。这个矩阵不是连通的,只能在这个矩阵内找子矩阵,不能越过边界。
解题思路:枚举起点和终点,每个起点和终点就是一个矩阵,每个矩阵都算矩阵和,然后保留最大值。每个矩阵的值只要横着相加一遍,再竖着相加一遍,就可以得出以这个矩阵为起点的所有的子矩阵的和(这里可以直接要这个矩阵的和,因为里面的子矩阵枚举起和终点的时候都会算到),然后记录最大值。
例如 : 2 2 3
3 3 4
横着相加 2 4 7
3 6 10
再竖着相加 2 4 7
5 10 17
整个矩阵的和是17
两行一列的和是5
两行两列的和是10
...
只要求以这个起点和终点的矩阵的和就可以了。
代码:
#include <stdio.h>
#include <string.h>
const int N = 150;
const int INF = 0x3f3f3f3f;
int mat[N][N], temx[N], temy[N];
int Max (const int x, const int y) {return x > y? x: y;}
int main () {
int n;
while (scanf ("%d", &n) != EOF) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf ("%d", &mat[i][j]);
int mm = -INF;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
memset (temx, 0, sizeof (temx));
for (int x = i; x < n; x++)
for (int y = j; y < n; y++) {
if (y == j)
temy[y] = mat[x][y];
else
temy[y] = temy[y - 1] + mat[x][y];
temx[y] += temy[y];
mm = Max (mm, temx[y]);
mm = Max (mm, temy[y]);
}
}
printf ("%d\n", mm);
}
return 0;
}