题目
反思
这个题目就没得反思了,hhh~
只有总结,,,莫得一点思路。
对于这种移动整块区域的滑动窗口题目。
先初始化行中的窗口最值,再计算列中的窗口最值。这样就实现了区域的移动。
题解
- 初步分析题目
在a * b 的矩阵中移动 n * n 的窗口,找到所有窗口中的最大值与最小值的差的最小值。
初步分析需要使用滑动窗口来解决这道题目。
- 深入分析
我们先初始化每一行中的n个长度中的最小值。
接下来再计算列中的每一个信息就能代表整个区域了。
这个题思路就是这样,重要的看代码实现。
AC 代码
#include<bits/stdc++.h>
using namespace std;
#define _for(i, a, b) for (int i = (a); i <= (b); ++i)
#define _rep(i, a, b) for (int i = (a); i >= (b); --i)
#define debug(a) cout << #a << " = " << a << endl
#define mod(x) (x) % MOD
#define ENDL "\n"
#define x first
#define y second
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int N = 1000 + 7, MOD = 1e9, INF = 0x3f3f3f3f;
int minv[N][N], maxv[N][N], q[N], w[N][N], n, m, k;
void get_min(int a[], int b[], int sz){
int hh = 0, tt = - 1;
_for(i, 1, sz){
if (hh <= tt && q[hh] < i - k + 1) ++hh;
while (hh <= tt && a[q[tt]] >= a[i]) --tt;
q[++tt] = i;
b[i] = a[q[hh]];
}
}
void get_max(int a[], int b[], int sz){
int hh = 0, tt = - 1;
_for(i, 1, sz){
if (hh <= tt && q[hh] < i - k + 1) ++hh;
while (hh <= tt && a[q[tt]] <= a[i]) --tt;
q[++tt] = i;
b[i] = a[q[hh]];
}
}
int main()
{
#ifdef LOCAL
freopen("data.in", "r", stdin);
#endif
ios::sync_with_stdio(false);
cout.tie(0), cin.tie(0);
cin >> n >> m >> k;
_for(i, 1, n) _for(j, 1, m) cin >> w[i][j];
_for(i, 1, n) {
get_min(w[i], minv[i], m);
get_max(w[i], maxv[i], m);
}
int a[N], b[N], c[N], ans = INF;
_for (j, k, m) {
_for(i, 1, n) a[i] = maxv[i][j];
get_max(a, b, n);
_for(i, 1, n) a[i] = minv[i][j];
get_min(a, c, n);
_for (i, k, n) ans = min(ans, b[i] - c[i]);
}
cout << ans << ENDL;
return 0;
}