Post

AcWing1091 - 理想正方形

有一个 a×b 的整数组成的矩阵,现请你从中找出一个 n×n 的正方形区域,使得该区域所有数中的最大值和最小值的差最小。

输入格式

第一行为三个整数,分别表示 a,b,n 的值;

第二行至第 a+1 行每行为 b 个非负整数,表示矩阵中相应位置上的数。

输出格式

输出仅一个整数,为 a×b 矩阵中所有“n×n 正方形区域中的最大整数和最小整数的差值”的最小值。

数据范围

2≤a,b≤1000, n≤a,n≤b,n≤100, 矩阵中的所有数都不超过 109。

输入样例:

1
2
3
4
5
6
5 4 2
1 2 5 6
0 17 16 0
16 17 2 1
2 10 2 1
1 2 2 2

输出样例:

1
1

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
#include <iostream>
using namespace std;
const int N = 1010;

int n, m, k;
int w[N][N];
int row_max[N][N], row_min[N][N];
int q[N];

void get_min(int a[], int b[], int tot) {
  int hh = 0, tt = -1;
  for (int i = 1; i <= tot; i++) {
    if (hh <= tt && q[hh] <= i - k) 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 tot) {
  int hh = 0, tt = -1;
  for (int i = 1; i <= tot; i++) {
    if (hh <= tt && q[hh] <= i - k) hh++;
    while (hh <= tt && a[q[tt]] <= a[i]) tt--;
    q[++tt] = i;
    b[i] = a[q[hh]];
  }
}

int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= n; i++) 
    for (int j = 1; j <= m; j++) 
      scanf("%d", &w[i][j]);
  
  for (int i = 1; i <= n; i++) {
    get_min(w[i], row_min[i], m);
    get_max(w[i], row_max[i], m);
  }
  
  int res = 1e9;
  int a[N], b[N], c[N];
  for (int i = k; i <= m; i++) {
    for (int j = 1; j <= n; j++) a[j] = row_min[j][i];
    get_min(a, b, n);
    
    for (int j = 1; j <= n; j++) a[j] = row_max[j][i];
    get_max(a, c, n);
    
    for (int j = k; j <= n; j++) res = min(res, c[j] - b[j]);
  }
  
  printf("%d\n", res);
  
  return 0;
}
This post is licensed under CC BY 4.0 by the author.