求矩阵的最大子矩阵。
代码如下:
方法一(普通方法效率较低,跑了1秒多):
#include <iostream>
#include <cstdio>
using namespace std;
int a[110][110] = {{0}};
int main()
{
int n, i, j, k, tmp, sum;
while (scanf("%d", &n) == 1)
{
for (j = 1; j <= n; j++)
for (i = 1; i <= n; i++)
{
cin >> a[i][j];
a[i][j] += a[i-1][j];
}
sum = a[1][1];
for (i = 0; i <= n; i++)
for (j = i; j <= n; j++)
{
tmp = 0;
for (k = 1; k <= n; k++)
{
if (tmp < 0) tmp = a[j][k] - a[i][k];
else if (i != j) tmp += a[j][k] - a[i][k];
if (tmp > sum && tmp != 0) sum = tmp;
}
}
cout << sum << endl;
}
}
方法二(动规优化版,0.012秒):
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<ctime>
using namespace std;
int a[102][102] = {{0}};
int main()
{
#ifdef test
freopen("in.txt", "r", stdin);
#endif
int n;
while(scanf("%d", &n) != EOF)
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
scanf("%d", &a[i][j]);
a[i][j] += a[i - 1][j];
}
int max = a[1][1];
for(int i = 0; i <= n; i++)
for(int j = i; j <= n; j++)
{
int sum = 0;
for(int k = 1; k <= n; k++) // 将二维转化为一维数列求最大和
{
if(sum < 0)
sum = a[j][k] - a[i][k];
else if(i != j)
sum += a[j][k] - a[i][k];
if(sum > max && sum != 0)
max = sum;
}
}
printf("%d\n", max);
}
}