poj 1050 To the Max dp 最大子矩阵

题目

题目链接: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值