记矩阵为
A
,单调队列求出
而最大值和最小值是满足 区间加法 的,
所以再用单调队列求出 A[i−n+1,i],[j−n+1,j] 内最大值和最小值。
时间复杂度: O(n2)
实现时我翻转了 Ar,[i−n+1,i] 对应的两个矩阵,来降低编程复杂度。。。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>
template<class Num>void read(Num &x)
{
char c; int flag = 1;
while((c = getchar()) < '0' || c > '9')
if(c == '-') flag *= -1;
x = c - '0';
while((c = getchar()) >= '0' && c <= '9')
x = (x<<3) + (x<<1) + (c-'0');
x *= flag;
return;
}
template<class Num>void write(Num x)
{
if(x < 0) putchar('-'), x = -x;
static char s[20];int sl = 0;
while(x) s[sl++] = x%10 + '0',x /= 10;
if(!sl) {putchar('0');return;}
while(sl) putchar(s[--sl]);
}
#define REP(__i,__start,__end) for(int __i = (__start); __i <= (__end); __i++)
const int maxn = 1005, INF = 0x3f3f3f3f;
typedef int Array[maxn][maxn];
int a, b, n, ans = INF;
Array p, _fmin, _fmax, _gmin, _gmax;
void link_min(int src[],int tar[],int len)
{
static int line[maxn];
int f = 0, r = 0;
REP(i, 1, len)
{
if(f != r && i - line[f] >= n) line[f++] = 0;
while(f != r && src[line[r - 1]] >= src[i]) line[--r] = 0;
line[r++] = i, tar[i] = src[line[f]];
}
}
void link_max(int src[],int tar[],int len)
{
static int line[maxn];
int f = 0, r = 0;
REP(i, 1, len)
{
if(f != r && i - line[f] >= n) line[f++] = 0;
while(f != r && src[line[r - 1]] <= src[i]) line[--r] = 0;
line[r++] = i, tar[i] = src[line[f]];
}
}
void init()
{
read(a), read(b), read(n);
REP(i, 1, a)
REP(j, 1, b)
read(p[i][j]);
}
void solve()
{
REP(i, 1, a) link_min(p[i], _fmin[i], b), link_max(p[i], _fmax[i], b);
REP(i, 1, std::max(a, b))
REP(j, 1, std::max(a, b))
if(i > j)
{
std::swap(_fmin[i][j], _fmin[j][i]);
std::swap(_fmax[i][j], _fmax[j][i]);
}
REP(i, n, b) link_min(_fmin[i], _gmin[i], a), link_max(_fmax[i], _gmax[i], a);
REP(i, n, b)
REP(j, n, a)
ans = std::min(_gmax[i][j] - _gmin[i][j], ans);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1047.in","r",stdin);
freopen("1047.out","w",stdout);
#endif
init(), solve(), write(ans);
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}