POJ 1050 最大子矩阵和

版权声明:希望能在自己成长的道路上帮到更多的人,欢迎各位评论交流 https://blog.csdn.net/yiqzq/article/details/82712250

原题地址:http://poj.org/problem?id=1050

题意:有一个包含正数和负数的二维数组。一个子矩阵是指在该二维数组里,任意相邻的下标是1×1或更大的子数组。一个子矩阵的和是指该子矩阵中所有元素的和。

思路:首先需要会一维的最大子序列和

把该问题转化为最大连续子串和问题,即二维转化为一维。假设求出的最大子矩阵为从x行到y行,从第c列到第r列,则该矩阵转化为一维即是从第1列到第n列的所有x行到第y行的元素和的最大连续子串和。这样后,复杂度为n的三次方,在求最大连续子串和的时候用DP就可以了。

#include <cmath>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <cctype>
#define eps 1e-8
#define INF 0x3f3f3f3f
#define PI acos(-1)
#define lson l,mid,rt<<1
#define rson mid+1,r,(rt<<1)+1
#define CLR(x,y) memset((x),y,sizeof(x))
#define fuck(x) cerr << #x << "=" << x << endl

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int seed = 131;
const int maxn = 1e5 + 5;
const int mod = 998244353;
int a[105][105];//原数组
int b[105];//累加数组
int main() {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            scanf("%d", &a[i][j]);
        }
    }
    int MAX = -INF;
    for (int i = 1; i <= n; i++) {
        CLR(b, 0);
        for (int j = i; j <= n; j++) {
            int sum = 0;
            for (int k = 1; k <= n; k++) {
                b[k] += a[j][k];
                sum += b[k];
                if (sum < 0) sum = b[k];
                MAX = max(MAX, sum);
            }
        }
    }
    printf("%d\n", MAX);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yiqzq/article/details/82712250