You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
3.9 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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;
}