![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/52f188d4f7bd6758cf21f5abec8b5b59.png)
题解(单调队列优化DP)
- 预处理出每一行i以j结尾且长度是k的滑动窗口的最小值和最大值,分别记录在row_min[i][j]和row_max[i][j]位置中
- 在row_min[][] 和 row_max[][]中每一列再用滑动窗口求出最小值和最大值,表示的以i,j结尾且是长度是k的区域的最小值和最大值
代码
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010, INF = 1e9;
int n, m, k;
int w[N][N];
int row_min[N][N], row_max[N][N];
int q[N];
void get_min(int a[], int b[], int tot) {
int hh = 0, tt = -1;
for (int i = 1; i <= tot; i++) {
if (hh <= tt && q[hh] <= i - k) 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 tot) {
int hh = 0, tt = -1;
for (int i = 1; i <= tot; i++) {
if (hh <= tt && q[hh] <= i - k) hh++;
while (hh <= tt && 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_min(w[i], row_min[i], m);
get_max(w[i], row_max[i], m);
}
int res = INF;
int a[N], b[N], c[N];
for (int i = k; i <= m; i++) {
for (int j = 1; j <= n; j++) a[j] = row_min[j][i];
get_min(a, b, n);
for (int j = 1; j <= n; j++) a[j] = row_max[j][i];
get_max(a, c, n);
for (int j = k; j <= n; j++) res = min(res, c[j] - b[j]);
}
printf("%d\n", res);
return 0;
}