1051 最大子矩阵和
题目
分析
这题用
n
3
n^3
n3的复杂度过的,很暴力。
对于大矩形,枚举左右边界,之后转化为最大字段和做。
例:
1 2 3
4 5 6
7 8 9
枚举左右边界为:1, 2
就变为求 3, 9, 15 的最大字段和
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define d(x) cout << (x) << endl
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
const int N = 5e2 + 10;
int a[N][N];
ll sum[N][N];
int m, n;
ll ans = -INF;
void solve(int s, int e) //最大子段和
{
ll dp[N], cnt = -INF;
for (int i = 1; i <= m; i++){
ll num = sum[i][e] - sum[i][s - 1];
dp[i] = max(num, dp[i - 1] + num);
cnt = max(cnt, dp[i]);
}
ans = max(cnt, ans);
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
scanf("%d", &a[i][j]);
sum[i][j] = sum[i][j - 1] + a[i][j];
}
}
for (int i = 1; i <= n; i++){
for (int j = i; j <= n; j++){ //枚举左右边界
solve(i, j); //最大字段和
}
}
if(ans < 0)
printf("0\n");
else
printf("%lld\n", ans);
return 0;
}