Salt and Pepper (Large)

Time limit1sMemory limit512 MB

Summary
For each W by W window in the matrix, output the median of its W^2 pixel values.
Level

Medium6 of 10

Topics
Sliding window, Sorting, Matrix
Solved
No attempts yet

Problem

Alice took a photo of the cream cheese spaghetti served for dinner. The salt and pepper scattered over the pasta bothered her, so she asked Bob to erase those specks. Bob pulled a sheet of paper and a pen out of his bag and wrote the problem down like this.

  • An M×NM \times N matrix AA representing the photo is given as input. Each element of the matrix is the brightness of one pixel, where 00 is the darkest value and KK is the brightest value.
  • An integer WW is given as well. Matrix BB is defined from WW as follows.

B[i][j]=median(A[i+x][j+y]),1≤i≤M−W+1,  1≤j≤N−W+1,  0≤x,y<WB[i][j] = \mathrm{median}(A[i+x][j+y]), \quad 1 \le i \le M-W+1, \; 1 \le j \le N-W+1, \; 0 \le x, y < W

Here A[i+x][j+y]A[i+x][j+y] is the element in row i+xi+x, column j+yj+y of matrix AA. In other words, B[i][j]B[i][j] is the median of the W2W^2 values inside the W×WW \times W square whose top left corner is row ii, column jj of AA.

  • Compute matrix BB from the given matrix AA and integer WW.

Figure: how matrix BB is built from matrix AA and WW.

Bob opened his laptop and started writing the program, but it did not go well, and the spaghetti began to go soggy. Write the program for Bob before the spaghetti is ruined.

The median is the value that sits in the middle once the given values are sorted by size. Among the five values 1, 2, 3, 3, 100 the one in the middle is 3, so the median is 3. WW is odd, so W2W^2 is odd too and the median is always a single value.

Input

The first line contains the matrix size MM and NN (1≤M,N≤3001 \le M, N \le 300), the maximum brightness KK (1≤K≤100,0001 \le K \le 100{,}000), and the integer WW (1≤W≤min⁡(M,N)1 \le W \le \min(M, N)), separated by spaces in that order. WW is odd.

Each of the next MM lines contains NN integers. The jj-th integer on line 1+i1+i is the element in row ii, column jj of matrix AA, and it is between 00 and KK.

Output

Print matrix BB over M−W+1M-W+1 lines. Each line holds N−W+1N-W+1 integers separated by one space.

Hint

If WW is 11, every square holds a single value, so BB equals AA.

Suppose WW is 33 and a square holds 5, 1, 2, 12, 10, 3, 8, 12, 19. Sorted, the values are 1, 2, 3, 5, 8, 10, 12, 12, 19, and the fifth value is in the middle, so the median is 8.

Examples3

  1. Example 1

    Input
    3 3 10 1
    1 2 3
    4 5 6
    7 8 9
    
    Expected output
    1 2 3
    4 5 6
    7 8 9
    
  2. Example 2

    Input
    3 3 10 3
    1 2 3
    4 5 6
    7 8 9
    
    Expected output
    5
  3. Example 3

    Input
    5 5 20 3
    5 1 2 8 10
    12 10 3 20 7
    8 12 19 18 15
    17 19 2 5 13
    11 2 4 14 16
    
    Expected output
    8 10 10
    12 12 13
    11 12 14