Under construction

Still being built. Things may change

Sprouts

Time limit3sMemory limit1024 MB

Summary
Find the largest gap between the median and the mean of sprout counts over every K x K block of an N x N grid, scaled by K squared.
Level

Medium5 of 10

Topics
Sliding window, Prefix sum, Matrix
Solved
No attempts yet

Problem

Baku divided a large square plot of land into equal parts and made N×NN \times N small square fields. He planted PP seeds in each field. One week later, some seeds had sprouted and others had not. The figure below shows 6×66 \times 6 fields with 33 seeds planted in each. The top left field has 2 sprouts, and the bottom right field has 1 sprout.

Baku recently learned about the median. The median is the middle value when an odd number of given values is sorted. For example, if the five values are 0,1,2,2,30, 1, 2, 2, 3, the median is 22.

Baku wants to compare the median and the mean of the sprout counts. To test many cases, he compares the median and the mean over every block of K×KK \times K adjacent fields. This gives (N−K+1)×(N−K+1)(N-K+1) \times (N-K+1) comparisons for the N×NN \times N fields.

For the figure above, the table below shows the medians and means for each 3×33 \times 3 block. The top left 3×33 \times 3 block has sprout counts 2,1,0,0,1,0,2,0,12, 1, 0, 0, 1, 0, 2, 0, 1, so its median is 11 and its mean is 7/97/9. The top right 3×33 \times 3 block has median 00 and mean 8/98/9.

MedianMean

Baku wants the maximum difference between the median and the mean. In the example above, the maximum occurs in the block marked in red in the figure below. There the median is 00 and the mean is 11, so the difference is 11.

MedianMeanDifference

For convenience, Baku wants the maximum of the difference between the median and the mean multiplied by K2K^2. In the example above, the answer is 99.

Function

You must implement the following function. It is called exactly once.

int diff( int K, int[][] V ) ;

VV is an N×NN \times N array (vector). It gives the sprout count V[0..N−1][0..N−1]V[0..N-1][0..N-1] for each field. Compute the difference between the median and the mean for each K×KK \times K block, multiply it by K2K^2, and return the maximum value.

Constraints

  • 1≤N≤2 0001 \le N \le 2\,000
  • KK is odd and 1≤K≤N1 \le K \le N
  • 0≤Vij≤300 \le V_{ij} \le 30 (0≤i,j≤N−10 \le i, j \le N-1)

Examples2

  1. Example 1

    Input
    6 3
    2 1 0 1 0 2
    0 1 0 3 0 0
    2 0 1 0 0 2
    1 2 2 2 2 0
    1 2 2 0 0 1
    0 1 0 0 2 1
    
    Expected output
    9
    
  2. Example 2

    Input
    4 3
    10 20 10 20
    20 10 20 10
    10 20 10 20
    20 10 20 10
    
    Expected output
    40