1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| #include <iostream>
using namespace std;
const int maxn = 1005;
int a, b, n; struct node { int val, pos; } q[maxn]; int map[maxn][maxn]; int min_val[maxn][maxn], max_val[maxn][maxn]; int min_ans[maxn][maxn], max_ans[maxn][maxn];
int main() { cin >> a >> b >> n; for (int i = 1; i <= a; i ++) for (int j = 1; j <= b; j ++) cin >> map[i][j]; int head = 0, tail = 0; for (int i = 1; i <= a; i ++) { head = 0, tail = 0; for (int j = 1; j <= b; j ++) { while (head < tail && map[i][j] >= q[tail - 1].val) tail --; q[tail ++] = (node) { map[i][j], j }; while (head < tail && j - q[head].pos + 1 > n) head ++; if (j >= n) max_val[i][j - n + 1] = q[head].val; } } for (int i = 1; i <= a; i ++) { head = 0, tail = 0; for (int j = 1; j <= b; j ++) { while (head < tail && map[i][j] <= q[tail - 1].val) tail --; q[tail ++] = (node) { map[i][j], j }; while (head < tail && j - q[head].pos + 1 > n) head ++; if (j >= n) min_val[i][j - n + 1] = q[head].val; } }
for (int j = 1; j <= b - n + 1; j ++) { head = 0, tail = 0; for (int i = 1; i <= a; i ++) { while (head < tail && max_val[i][j] >= q[tail - 1].val) tail --; q[tail ++] = (node) { max_val[i][j], i }; while (head < tail && i - q[head].pos + 1 > n) head ++; if (i >= n) max_ans[i - n + 1][j] = q[head].val; } } for (int j = 1; j <= b - n + 1; j ++) { head = 0, tail = 0; for (int i = 1; i <= a; i ++) { while (head < tail && min_val[i][j] <= q[tail - 1].val) tail --; q[tail ++] = (node) { min_val[i][j], i }; while (head < tail && i - q[head].pos + 1 > n) head ++; if (i >= n) min_ans[i - n + 1][j] = q[head].val; } } int ans = 2e9; for (int i = 1; i <= a - n + 1; i ++) for (int j = 1; j <= b - n + 1; j ++) ans = min(ans, max_ans[i][j] - min_ans[i][j]); cout << ans << endl; return 0; }
|