poj 1050 To the Max(dp 最大子矩阵和)

传送门:poj 1050 To the Max

题意:

给出一个N\times N的矩阵,求该矩阵的最大子矩阵和。

思路:

我们可以先固定行,来对列进行求最大前缀和的操作,固定行,先求出隔行的前缀和,来对列进行规划。我们发现针对每一次行规划的时候求最大值即可,所以我们可以直接维护最大值。

AC代码:

//#include <bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 1e5 + 7;
const int maxn = 200;
const int inf = 0x3f3f3f3f;
struct Matrix{
    int t[maxn][maxn];
};
int dp[maxn],ans,n,pos,tmp;
Matrix a;
void input()
{
    ans = -inf;
    for(int i = 0;i < n;++i)
        for(int j = 0;j < n;++j)
            scanf("%d",&a.t[i][j]);
}
int main()
{
    while(scanf("%d",&n) != EOF){
        input();
        for(int i = 0;i < n;++i){
            memset(dp,0,sizeof dp);
            for(int j = i;j < n;++j){
                for(int k = 0;k < n;++k) dp[k] += a.t[j][k];
                pos = -inf,tmp = -inf;
                for(int k = 0;k < n;++k){
                    if(tmp > 0) tmp += dp[k];
                    else tmp = dp[k];
                    pos = max(pos,tmp);
                }
                ans = max(pos,ans);
            }
        }
        printf("%d\n",ans);

    }
    return 0;
}

 

猜你喜欢

转载自blog.csdn.net/qq_41791981/article/details/82760871
今日推荐