[HAOI2007]理想的正方形(二维单调队列维护固定大小矩阵最值)

传送门
裸的二维单调队列,比较麻烦,细节需要考虑。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <math.h>
#include <map>
#include <set>
#include <queue>

using namespace std;
#define endl '\n'
#define P pair<int,int>
#define lson node << 1
#define rson node << 1 | 1
#define fore(i,n) for(int i = 1;i <= n;i ++)
inline int lowbit(int x) {return -x & x;}
const int maxn = 1005;
int s[maxn][maxn],a,b,n;
int x[maxn][maxn],X[maxn][maxn],y[maxn][maxn],Y[maxn][maxn];
int q[maxn];
void solve(){
    cin >> a >> b >> n;
    for (int i = 1; i <= a; ++i) {
        for (int j = 1; j <= b; ++j) {
            cin >> s[i][j];
        }
    }

    for (int i = 1; i <= a; ++i) {
        int hh = 1,tt = 0;
        for (int j = 1; j <= b; ++j){
            while (tt >= hh && s[i][j] <= s[i][q[tt]]) tt --;
            q[++tt] = j;
            while (q[tt] - q[hh] + 1 > n) hh ++;
            x[i][j] = s[i][q[hh]];
        }
    }
    for (int i = 1; i <= a; ++i) {
        int hh = 1,tt = 0;
        for (int j = 1; j <= b; ++j){
            while (tt >= hh && s[i][j] >= s[i][q[tt]]) tt --;
            q[++tt] = j;
            while (q[tt] - q[hh] + 1 > n) hh ++;
            X[i][j] = s[i][q[hh]];
        }
    }

    for (int i = 1; i <= b; ++i) {
        int hh = 1,tt = 0;
        for (int j = 1; j <= a; ++j){
            while (tt >= hh && x[j][i] <= x[q[tt]][i]) tt --;
            q[++tt] = j;
            while (q[tt] - q[hh] + 1 > n) hh ++;
            y[j][i] = x[q[hh]][i];
        }
    }
    for (int i = 1; i <= b; ++i) {
        int hh = 1,tt = 0;
        for (int j = 1; j <= a; ++j){
            while (tt >= hh && X[j][i] >= X[q[tt]][i]) tt --;
            q[++tt] = j;
            while (q[tt] - q[hh] + 1 > n) hh ++;
            Y[j][i] = X[q[hh]][i];
        }
    }
    int res = 2e9;
    for (int i = n; i <= a; ++i) {
        for (int j = n; j <= b; ++j) {
            res = min(res,Y[i][j] - y[i][j]);
        }
    }
    cout << res;
}
signed main(){
    std::ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
#ifdef LOCAL
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
#endif
    int T = 1;
//    cin >> T;
    while (T--) solve();

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值