AcWing 126. 最大的和

题目链接:AcWing 126. 最大的和 - AcWings

题目大意:求出最大子矩阵。具有最大和的子矩形被称为最大子矩形。

题目解决:

解法1:暴力枚举左下角坐标,右上角坐标,使用二维前缀和。

时间复杂度:O(n^4)

代码:

#include <stdio.h>
#include <iostream>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <list>
#define rep(i,a,n) for (int i=a;i<=n;i++)
#define per(i,a,n) for (int i=n;i>=a;i--)
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define x first
#define y second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db; 
const ll mod=1000000007;
const int N = 100010;
int a[101][101], n;
int main() 
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            scanf("%d", &a[i][j]);

    
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            a[i][j] += a[i][j - 1] + a[i - 1][j] - a[i - 1][j - 1];

    int ans = -1e9;
    for(int x1 = 1; x1 <= n; x1++)
        for(int x2 = x1; x2 <= n; x2 ++)
            for(int y1 = 1; y1 <= n; y1++)
                for(int y2 = y1; y2 <= n; y2++)
                    ans = max(ans, a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1] + a[x1 - 1][y1 - 1]);
    printf("%d\n", ans);
    return 0;
}

解法2:枚举所有子矩形的左右边界,然后对每一列求前缀和,然后使用类似于求最大连续和的思想。你确定了左右边界了的话,那么就只要确定上下边界,如果上边界到某列的矩阵和小于0,那么我们加上这个矩阵和只会让答案更小,所以我们就必须舍去该矩阵,让他从当前列当作上边界。具体方法就是吧当前的和设置为0,相当于清空之前的贡献,上边界从当前枚举的列重新开始。然后一直维护一下最大值就好了。

时间复杂度:O(n ^ 3)

代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 101;
int a[N][N], n;
int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            scanf("%d", &a[i][j]), a[i][j] += a[i - 1][j];//对列求前缀和
    int res = -1e9;
    //枚举左、右边界
    for(int l = 1; l <= n; l++)
        for(int r = l; r <= n; r++)
        {
            int last = 0;
            //枚举矩形块
            //类似于最大连续和的思想 因为如果前一段小于0了 那么我加上他一定会让答案更小 所以我不能加上他
            //就清空为0
            for(int k = 1; k <= n; k++)
            {
                last = max(last, 0) + a[r][k] - a[l - 1][k];
                res = max(last, res);
            }
        }
    printf("%d\n", res);
    return 0;
}

PS:类似的思想还有今年蓝桥杯的一道题。

统计子矩阵 - 题目 - Daimayuan Online Judge

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值