题目
题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=105944#problem/B
题目来源:2016寒假高年训练3
简要题意:求出最大子矩阵
题解
经典的模型,需要好好理解掌握。
dp的做法就是先预处理出每行前缀。
枚举矩阵的左右边界,然后纵向做最大子段和。
整个复杂度是 Θ(n3) 的。
最大子段就是保存以每位为结尾的最大值,转移就是前面一格为负数就取自身,否则加上前一个的dp更新自身。
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
// head
const int N = 105;
int a[N][N];
int main() {
int n;
while (scanf("%d", &n) == 1) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", a[i]+j);
a[i][j] += a[i][j-1];
}
}
int ans = -2e9;
for (int l = 1; l <= n; l++) {
for (int r = l; r <= n; r++) {
int sum = 0;
for (int i = 1; i <= n; i++) {
int cur = a[i][r] - a[i][l-1];
sum = (sum < 0) ? cur : sum + cur;
ans = max(ans, sum);
}
}
}
printf("%d\n", ans);
}
return 0;
}