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;
}