#include<bits/stdc++.h>
using namespace std;
int n, a[101][101], b[101], dp[101], presum[101][101];
int main()
{
//最大子矩阵和问题
//dp解法:使用最大字段和的dp解法+使用一维前缀和的维度压缩
//时间复杂度为o(n^3)
int maxs = -0x3f3f3f3f;
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
cin >> a[i][j];
presum[i][j] = presum[i - 1][j] + a[i][j];
}
for(int x1=1;x1<=n;x1++)
for (int x2 = x1; x2 <= n; x2++)
{
//第x1行到第x2行的最大矩阵和
for (int j = 1; j <= n; j++)
b[j] = presum[x2][j] - presum[x1 - 1][j];
for (int i = 1; i <= n; i++)
{
dp[i] = max(dp[i - 1] + b[i], b[i]);
maxs = max(maxs, dp[i]);
}
}
cout << maxs << endl;
return 0;
}
最大子矩阵和问题-DP解法
于 2023-02-25 09:27:42 首次发布