一 描述
矩阵的最大子矩阵和。比如:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
拥有最大和的子矩阵为:
9 2
-4 1
-1 8
其和为15。
二 代码
#include <iostream>
#include <cstdio>
using namespace std;
int r[1002][1002];
int main()
{
freopen("in.txt", "r", stdin);
int n;
int i,j,k;
cin >> n;
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j)
cin >> r[i][j];
for (i = 2; i <= n; ++i)
for (j = 1; j <= n; ++j)
r[i][j] += r[i-1][j];
int max = -10000;
for (i = 1; i <= n; ++i)
{
for (j = i; j <= n; ++j)
{
int tmp = -1;
for (k = 1; k <= n; ++k)
{
if (tmp > 0)
tmp += r[j][k] - r[i-1][k];
else
tmp = r[j][k] - r[i-1][k];
if (max < tmp)
max = tmp;
}
}
}
cout << max << endl;
return 0;
}