H - 理想的正方形(单调队列)

有一个 a×b 的整数组成的矩阵,现请你从中找出一个 n×n 的正方形区域,使得该区域所有数中的最大值和最小值的差最小。

Input

第一行为 3 个整数,分别表示 a,b,n 的值。

第二行至第 a+1 行每行为 b 个非负整数,表示矩阵中相应位置上的数。每行相邻两数之间用一空格分隔。

Output

仅一个整数,为 a×b 矩阵中所有“ n×n 正方形区域中的最大整数和最小整数的差值”的最小值。

Sample 1

InputcopyOutputcopy
5 4 2
1 2 5 6
0 17 16 0
16 17 2 1
2 10 2 1
1 2 2 2
1

Hint

问题规模。

矩阵中的所有数都不超过 1,000,000,000

20% 的数据 2≤a,b≤100,n≤a,n≤b,n≤10。

100% 的数据 2≤a,b≤1000,n≤a,n≤b,n≤100。

 

#include <iostream>
#include <cmath>
using namespace std;

constexpr int N=1005;
int a,b,n;
int g[N][N];
int g1[2][N][N];
int g2[2][N][N];
int q[N];
int main(){
    scanf("%d%d%d",&a,&b,&n);
    for(int i=1;i<=a;i++){
        for(int j=1;j<=b;j++){
            scanf("%d",&g[i][j]);
        }
    }
    for(int i=1;i<=a;i++){
        int hh=0,tt=-1;
        for(int j=1;j<=b;j++) {
            while (hh <= tt && j - q[hh] + 1 > n) hh++;
            while (hh <= tt && g[i][q[tt]] >= g[i][j]) tt--;
            q[++tt] = j;
            if (j >= n) {
                g1[0][i][j-n+1] = g[i][q[hh]];
            }
        }
    }
    for(int i=1;i<=b-n+1;i++){
        int hh=0,tt=-1;
        for(int j=1;j<=a;j++) {
            while (hh <= tt && j - q[hh] + 1 > n) hh++;
            while (hh <= tt && g1[0][q[tt]][i] >= g1[0][j][i]) tt--;
            q[++tt] = j;
            if (j >= n) {
                g1[1][j-n+1][i] = g1[0][q[hh]][i];
            }
        }
    }

    for(int i=1;i<=a;i++){
        int hh=0,tt=-1;
        for(int j=1;j<=b;j++) {
            while (hh <= tt && j - q[hh] + 1 > n) hh++;
            while (hh <= tt && g[i][q[tt]] <= g[i][j]) tt--;
            q[++tt] = j;
            if (j >= n) {
                g2[0][i][j-n+1] = g[i][q[hh]];
            }
        }
    }
    for(int i=1;i<=b-n+1;i++){
        int hh=0,tt=-1;
        for(int j=1;j<=a;j++) {
            while (hh <= tt && j - q[hh] + 1 > n) hh++;
            while (hh <= tt && g2[0][q[tt]][i] <= g2[0][j][i]) tt--;
            q[++tt] = j;
            if (j >= n) {
                g2[1][j-n+1][i] = g2[0][q[hh]][i];
            }
        }
    }
    int ans=1e9+7;
    for(int i=1;i<=a-n+1;i++){
        for(int j=1;j<=b-n+1;j++){
            ans= min(ans,g2[1][i][j]-g1[1][i][j]);
        }
    }
    printf("%d\n",ans);
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

q619718

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值