Files
python/TangDou/AcWing/MonotonicQueue/1091.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

86 lines
3.9 KiB
C++
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
const int INF = 0x3f3f3f3f;
int n, m, k;
int w[N][N];
int row_min[N][N], row_max[N][N];
int q[N];
// 先想清楚get_min的意义:对于每个一维数组中的数字,找出包括它自己在内,长度最长为k的范围内,最小值是多少
// 这是一个典型的单调队列问题,窗口长度为k,包含自己在内
void get_min(int a[], int b[], int col) {
int hh = 0, tt = -1; // 和前缀和相关的,才会有哨兵。这里和前缀和没关系,不用加入哨兵。
for (int i = 1; i <= col; i++) {
// 举栗子:比如i=5,k=3,则窗口范围是[3,4,5],也就是最远的队头元素下标是i-k+1,再比它小就不行了
while (hh <= tt && q[hh] <= i - k) hh++;
while (hh <= tt && a[q[tt]] >= a[i]) tt--; // 赶走比我老,但值还比我大的那些老家伙
q[++tt] = i;
// 此处需要包括i本身,所以在添加到队列后进行计算
b[i] = a[q[hh]];
}
}
void get_max(int a[], int b[], int col) {
int hh = 0, tt = -1;
// 和前缀和相关的,才会有哨兵。这里和前缀和没关系,不用加入哨兵。
for (int i = 1; i <= col; i++) {
while (hh <= tt && q[hh] <= i - k) hh++;
while (hh <= tt && a[q[tt]] <= a[i]) tt--;
q[++tt] = i;
// 此处需要包括i本身,所以在添加到队列后进行计算
b[i] = a[q[hh]];
}
}
int main() {
cin >> n >> m >> k;
// 读入
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> w[i][j];
/*步骤I:遍历每一行,完成最小值、最大值的向右转储,分别记录到row_min、row_max两个数组中。
这两个数组,只是一个中间的状态,是为了给步骤II“竖着计算k个范围内的极大极小值”提供垫脚石的
*/
int row_min[N][N]; // 最小值
int row_max[N][N]; // 最大值
for (int i = 1; i <= n; i++) {
get_min(w[i], row_min[i], m); // 填充每一行的,k个长度的区间内最小值 保存到row_min数组中, 注意:这并不是指某一个最小值,而是从k~m的所有长度够k个长度的区间极小值
get_max(w[i], row_max[i], m); // 填充每一行的,k个长度的区间内最大值 保存到row_max数组中, 注意:这并不是指某一个最大值,而是从k~m的所有长度够k个长度的区间极大值
}
int t[N]; // 列转行,用到的临时中转数组
int a[N]; // 最小值数组
int b[N]; // 最大值数组
/*
步骤II:将竖向的区间极值向右下角归并
(1)、依托row_min,对每一列进行列转行,保存为t
(2)、利用get_min 将t数组再次存储为a数组
(3)、此a数组,就是左归右,上归下的,边长为k的矩形中的最小值 
(4)、依托row_max,对每一列进行列转行,保存为t
(5)、利用get_max 将t数组再次存储为b数组
(6)、此b数组,就是左归右,上归下的,边长为k的矩形中的最大值 
*/
int res = INF; // 预求最小,先设最大
for (int j = k; j <= m; j++) { // 捋着列来
for (int i = 1; i <= n; i++) t[i] = row_min[i][j]; // 同一列的每一行,抄出来放到临时数组t中
get_min(t, a, n); // 对t这个临时数组,进行求k个范围内的最小值,将结果保存到a数组中
for (int i = 1; i <= n; i++) t[i] = row_max[i][j]; // 同一列的每一行,抄出来放到临时数组t中
get_max(t, b, n); // 对t这个临时数组,进行求k个范围内的最大值,将结果保存到b数组中
// 区域最大值-区域最小值
for (int i = k; i <= n; i++) res = min(res, b[i] - a[i]);
}
// 输出
cout << res << endl;
return 0;
}