int a, b, n; structnode {int val, pos; } q[maxn]; intmap[maxn][maxn]; int min_val[maxn][maxn], max_val[maxn][maxn]; int min_ans[maxn][maxn], max_ans[maxn][maxn];
intmain(){ 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; // row max 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; } } // row min 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; return0; }