【HAOI 2007】 理想的正方形
【题目链接】
【算法】
单调队列
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 1010 const int INF = 2e9; int i,j,a,b,n,ans = INF; deque<int> q1,q2; int val[MAXN][MAXN],mx[MAXN][MAXN],mn[MAXN][MAXN]; template <typename T> inline void read(T &x) { int f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x/10); putchar(x%10+'0'); } template <typename T> inline void writeln(T x) { write(x); puts(""); } int main() { read(a); read(b); read(n); for (i = 1; i <= a; i++) { for (j = 1; j <= b; j++) { read(val[i][j]); } } for (i = 1; i <= b; i++) { q1.clear(); q2.clear(); for (j = 1; j < n; j++) { while ((!q1.empty()) && (val[q1.back()][i] <= val[j][i])) q1.pop_back(); q1.push_back(j); while ((!q2.empty()) && (val[q2.back()][i] >= val[j][i])) q2.pop_back(); q2.push_back(j); } for (j = n; j <= a; j++) { while ((!q1.empty()) && (j - q1.front() >= n)) q1.pop_front(); while ((!q2.empty()) && (j - q2.front() >= n)) q2.pop_front(); while ((!q1.empty()) && (val[q1.back()][i] <= val[j][i])) q1.pop_back(); q1.push_back(j); while ((!q2.empty()) && (val[q2.back()][i] >= val[j][i])) q2.pop_back(); q2.push_back(j); mx[j][i] = val[q1.front()][i]; mn[j][i] = val[q2.front()][i]; } } for (i = n; i <= a; i++) { q1.clear(); q2.clear(); for (j = 1; j < n; j++) { while ((!q1.empty()) && (mx[i][q1.back()] <= mx[i][j])) q1.pop_back(); q1.push_back(j); while ((!q2.empty()) && (mn[i][q2.back()] >= mn[i][j])) q2.pop_back(); q2.push_back(j); } for (j = n; j <= b; j++) { while ((!q1.empty()) && (j - q1.front() >= n)) q1.pop_front(); while ((!q2.empty()) && (j - q2.front() >= n)) q2.pop_front(); while ((!q1.empty()) && (mx[i][q1.back()] <= mx[i][j])) q1.pop_back(); q1.push_back(j); while ((!q2.empty()) && (mn[i][q2.back()] >= mn[i][j])) q2.pop_back(); q2.push_back(j); ans = min(ans,mx[i][q1.front()]-mn[i][q2.front()]); } } writeln(ans); return 0; }