理想正方形
https://www.acwing.com/problem/content/1093/
\(有一个 a×b 的整数组成的矩阵,现请你从中找出一个 n×n 的正方形区域,使得该区域所有数中的最大值和最小值的差最小。\)
思路
\(分别得到每个n*n正方形中的最小值和最大值\)
- \(对于每一行做一遍单调队列得到a*(b-n+1)的矩阵,\\ 再对于每一列,竖着做一遍单调队列,得到(a-n+1)*(b-n+1)的矩阵,每个元素代表n*n的最大值(最小值)\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
const int N = 1010;
int w[N][N], t1[N], t2[N], t3[N];
int n, m, k;
int ans_max[N][N], ans_min[N][N];
int q[N];
void get_max(int a[], int ans[], int m) {
int hh = 0, tt = -1, cnt = 0;
for (int i = 1; i <= m; ++i) {
if (hh <= tt && q[hh] <= i - k) ++hh;
while (hh <= tt && a[q[tt]] <= a[i]) --tt;
q[++tt] = i;
if (i >= k) ans[++cnt] = a[q[hh]];
}
}
void get_min(int a[], int ans[], int m) {
int hh = 0, tt = -1, cnt = 0;
for (int i = 1; i <= m; ++i) {
if (hh <= tt && q[hh] <= i - k) ++hh;
while (hh <= tt && a[q[tt]] >= a[i]) --tt;
q[++tt] = i;
if (i >= k) ans[++cnt] = a[q[hh]];
}
}
int main() {
IO;
cin >> n >> m >> k;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
cin >> w[i][j];
for (int i = 1; i <= n; ++i) {
get_max(w[i], ans_max[i], m);
get_min(w[i], ans_min[i], m);
}
for (int j = 1; j <= m - k + 1; ++j) {
for (int i = 1; i <= n; ++i) {
t1[i] = ans_max[i][j];
t2[i] = ans_min[i][j];
}
get_max(t1, t3, n);
for (int i = 1; i <= n - k + 1; ++i) ans_max[i][j] = t3[i];
get_min(t2, t3, n);
for (int i = 1; i <= n - k + 1; ++i) ans_min[i][j] = t3[i];
}
int ans = inf;
for (int i = 1; i <= n - k + 1; ++i)
for (int j = 1; j <= m - k + 1; ++j)
ans = min(ans, ans_max[i][j] - ans_min[i][j]);
cout << ans << '\n';
return 0;
}