【单调队列】理想的正方形 LibreOJ - 10182

题目

点我进入提交题目

反思

这个题目就没得反思了,hhh~
只有总结,,,莫得一点思路。
对于这种移动整块区域的滑动窗口题目。
先初始化行中的窗口最值,再计算列中的窗口最值。这样就实现了区域的移动。

题解

  • 初步分析题目

在a * b 的矩阵中移动 n * n 的窗口,找到所有窗口中的最大值与最小值的差的最小值。
初步分析需要使用滑动窗口来解决这道题目。

  • 深入分析

我们先初始化每一行中的n个长度中的最小值。
在这里插入图片描述
接下来再计算列中的每一个信息就能代表整个区域了。
这个题思路就是这样,重要的看代码实现。

AC 代码

#include<bits/stdc++.h>
using namespace std;

#define _for(i, a, b) for (int i = (a); i <= (b); ++i)
#define _rep(i, a, b) for (int i = (a); i >= (b); --i)
#define debug(a) cout << #a << " = " << a << endl
#define mod(x) (x) % MOD
#define ENDL "\n"
#define x first
#define y second
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

const int N = 1000 + 7, MOD = 1e9, INF = 0x3f3f3f3f;
int minv[N][N], maxv[N][N], q[N], w[N][N], n, m, k;

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

void get_max(int a[], int b[], int sz){
    int hh = 0, tt = - 1;
    _for(i, 1, sz){
        if (hh <= tt && q[hh] < i - k + 1) ++hh;
        while (hh <= tt && a[q[tt]] <= a[i]) --tt;
        q[++tt] = i;
        b[i] = a[q[hh]];
    }
}

int main()
{
#ifdef LOCAL
    freopen("data.in", "r", stdin);
#endif
    ios::sync_with_stdio(false);
    cout.tie(0), cin.tie(0);

    cin >> n >> m >> k;
    _for(i, 1, n) _for(j, 1, m) cin >> w[i][j];

    _for(i, 1, n) {
        get_min(w[i], minv[i], m);
        get_max(w[i], maxv[i], m);
    }

    int a[N], b[N], c[N], ans = INF;
    _for (j, k, m) {
        _for(i, 1, n) a[i] = maxv[i][j];
        get_max(a, b, n);
        _for(i, 1, n) a[i] = minv[i][j];
        get_min(a, c, n);
        _for (i, k, n) ans = min(ans, b[i] - c[i]);
    }
    cout << ans << ENDL;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值