二维单调队列——模板

acwing 1091. 理想的正方形

在这里插入图片描述

算法思想

我们求一个二维区间的时候的最值,可以先对每一行求最值(对行跑单点队列),并把最值存到对应的列上,然后对列上之前求求出来的最值再跑一遍单调队列。

在这里插入图片描述

#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
const int inf = 0x3f3f3f3f;
int n, m, k;
int w[N][N], a[N], b[N], c[N];
int mx[N][N], mn[N][N];
int q[N];

void get_mn(int a[], int b[], int tot)
{
    int hh = 0, tt = -1;
    for (int i = 1; i <= tot; i ++) {
        if (tt >= hh && q[hh] <= i - k) hh ++;
        while (tt >= hh && a[q[tt]] >= a[i]) tt --;
        q[++ tt] = i;
        b[i] = a[q[hh]];
    }
}

void get_mx(int a[], int b[], int tot)
{
    int hh = 0, tt = -1;
    for (int i = 1; i <= tot; i ++) {
        if (tt >= hh && q[hh] <= i - k) hh ++;
        while (tt >= hh && a[q[tt]] <= a[i]) tt --;
        q[++ tt] = i;
        b[i] = a[q[hh]];
    }
}

int main()
{
    scanf("%d %d %d", &n, &m, &k);
    for (int i = 1; i <= n; i ++)
        for (int j = 1; j <= m; j ++)
            scanf("%d", &w[i][j]);

    for (int i = 1; i <= n; i ++) {
        get_mn(w[i], mn[i], m);
        get_mx(w[i], mx[i], m);
    }

    int res = inf;
    for (int i = k; i <= m; i ++) {
        for (int j = 1; j <= n; j ++)  a[j] = mn[j][i];
        get_mn(a, b, n);
        for (int j = 1; j <= n; j ++)  a[j] = mx[j][i];
        get_mx(a, c, n);

        for (int j = k; j <= n; j ++) res = min(res, c[j] - b[j]);
    }

    printf("%d\n", res);



    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值