传送门
裸的二维单调队列,比较麻烦,细节需要考虑。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <math.h>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define endl '\n'
#define P pair<int,int>
#define lson node << 1
#define rson node << 1 | 1
#define fore(i,n) for(int i = 1;i <= n;i ++)
inline int lowbit(int x) {return -x & x;}
const int maxn = 1005;
int s[maxn][maxn],a,b,n;
int x[maxn][maxn],X[maxn][maxn],y[maxn][maxn],Y[maxn][maxn];
int q[maxn];
void solve(){
cin >> a >> b >> n;
for (int i = 1; i <= a; ++i) {
for (int j = 1; j <= b; ++j) {
cin >> s[i][j];
}
}
for (int i = 1; i <= a; ++i) {
int hh = 1,tt = 0;
for (int j = 1; j <= b; ++j){
while (tt >= hh && s[i][j] <= s[i][q[tt]]) tt --;
q[++tt] = j;
while (q[tt] - q[hh] + 1 > n) hh ++;
x[i][j] = s[i][q[hh]];
}
}
for (int i = 1; i <= a; ++i) {
int hh = 1,tt = 0;
for (int j = 1; j <= b; ++j){
while (tt >= hh && s[i][j] >= s[i][q[tt]]) tt --;
q[++tt] = j;
while (q[tt] - q[hh] + 1 > n) hh ++;
X[i][j] = s[i][q[hh]];
}
}
for (int i = 1; i <= b; ++i) {
int hh = 1,tt = 0;
for (int j = 1; j <= a; ++j){
while (tt >= hh && x[j][i] <= x[q[tt]][i]) tt --;
q[++tt] = j;
while (q[tt] - q[hh] + 1 > n) hh ++;
y[j][i] = x[q[hh]][i];
}
}
for (int i = 1; i <= b; ++i) {
int hh = 1,tt = 0;
for (int j = 1; j <= a; ++j){
while (tt >= hh && X[j][i] >= X[q[tt]][i]) tt --;
q[++tt] = j;
while (q[tt] - q[hh] + 1 > n) hh ++;
Y[j][i] = X[q[hh]][i];
}
}
int res = 2e9;
for (int i = n; i <= a; ++i) {
for (int j = n; j <= b; ++j) {
res = min(res,Y[i][j] - y[i][j]);
}
}
cout << res;
}
signed main(){
std::ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
#ifdef LOCAL
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int T = 1;
// cin >> T;
while (T--) solve();
}