1.先弄个单调队列求出每一行的区间为n的最大值最小值。
2.然后再搞个单调队列求1所求出的结果的区间为n的最大值最小值
3.最后扫一遍就行
懒得画图,自己体会吧。
——代码
#include <cstdio>
#include <iostream> using namespace std; const int MAXN = ;
int a, b, n, h, t;
long long c[MAXN][MAXN], q[MAXN], max1[MAXN][MAXN], min1[MAXN][MAXN], max2[MAXN][MAXN], min2[MAXN][MAXN], ans = ; inline void work1(int k)
{
int i, j;
h = , t = ;
for(i = ; i <= b; i++)
{
while(h <= t && c[k][q[t]] > c[k][i]) t--;
q[++t] = i;
while(h <= t && q[h] <= i - n) h++;
min1[k][i] = c[k][q[h]];
}
h = ; t = ;
for(i = ; i <= b; i++)
{
while(h <= t && c[k][q[t]] < c[k][i]) t--;
q[++t] = i;
while(h <= t && q[h] <= i - n) h++;
max1[k][i] = c[k][q[h]];
}
} inline void work2(int k)
{
int i, j;
h = , t = ;
for(i = ; i <= a; i++)
{
while(h <= t && min1[q[t]][k] > min1[i][k]) t--;
q[++t] = i;
while(h <= t && q[h] <= i - n) h++;
min2[i][k] = min1[q[h]][k];
}
h = ; t = ;
for(i = ; i <= a; i++)
{
while(h <= t && max1[q[t]][k] < max1[i][k]) t--;
q[++t] = i;
while(h <= t && q[h] <= i - n) h++;
max2[i][k] = max1[q[h]][k];
}
} int main()
{
int i, j;
scanf("%d %d %d", &a, &b, &n);
for(i = ; i <= a; i++)
for(j = ; j <= b; j++)
scanf("%lld", &c[i][j]);
for(i = ; i <= a; i++) work1(i);
for(i = ; i <= b; i++) work2(i);
for(i = n; i <= a; i++)
for(j = n; j <= b; j++)
ans = min(ans, max2[i][j] - min2[i][j]);
printf("%lld", ans);
return ;
}