最大子矩阵问题 加强版

题目描述

给定一个二维的数组(含正数或负数),请从中找出和最大的子矩阵。

Input

第一行:n,m
接下来n行m列,表示一个二维数组

Output

最大子矩阵的和

样例输入

4 4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2

样例输出

15

提示

image

code:

#include <bits/stdc++.h>
using namespace std;
long int m,n,o,temp = -10000000;
long long a[51][51],b[51][51];
int main(){
    cin>>n>>m;
    for(int i = 1;i<=n;i++) 
        for(int j = 1;j<=m;j++){
            cin>>a[i][j];
            b[i][j] = b[i-1][j] - b[i-1][j-1] + b[i][j-1] + a[i][j];
    } 
    for(int x1 = 1;x1<=n;x1++){
        for(int y1 = 1;y1<=m;y1++){
            for(int x2 = x1;x2<=n;x2++){
                for(int y2 = y1;y2<=m;y2++){
                        o = b[x2][y2] - b[x1-1][y2] - b[x2][y1-1] + b[x1-1][y1-1];
                        if(o>temp) temp = o;
                }
            }
        }
    }
    cout<<temp;
    return 0;
}
posted @ 2023-07-03 16:49  nasia  阅读(37)  评论(0)    收藏  举报