#P3227. [HNOI2013] 切糕

[HNOI2013] 切糕

Description

After much effort, Xiao A obtained a piece of qiegao. The qiegao is a rectangular cuboid, and Xiao A plans to cut it in half horizontally to share it with Xiao B. For aesthetic reasons, Xiao A hopes the cutting surface can be as smooth and harmonious as possible. So she asks you to find the best cutting plan.

For simplicity, we view the qiegao as a cuboid grid with length PP, width QQ, and height RR. We call the point at layer zz, row xx, and column yy the point (x,y,z)(x,y,z), and it has a nonnegative disharmony value v(x,y,z)v(x,y,z). A valid cutting surface satisfies the following two conditions:

  • It has exactly one intersection with each vertical axis (there are P×QP \times Q vertical axes). That is, the cutting surface is a function f(x,y)f(x,y), and for all (x,y)(x,y) (x[1,P]x \in [1,P], y[1,Q]y \in [1,Q]), we specify a cutting point f(x,y)f(x,y) with 1f(x,y)R1 \le f(x,y) \le R.

  • The cutting surface needs to meet a smoothness requirement: cutting points on adjacent vertical axes cannot be too far apart. For all 1x,xP1 \le x,x' \le P and 1y,yQ1 \le y,y' \le Q, if xx+yy=1|x-x'|+|y-y'|=1, then f(x,y)f(x,y)D|f(x,y)-f(x',y')| \le D, where DD is a given nonnegative integer.

There may be many cutting surfaces ff satisfying the above conditions. Xiao A wants the one that minimizes the total disharmony value at the cutting points.

Input Format

The first line contains three positive integers P,Q,RP,Q,R, representing the length, width, and height of the qiegao.

The second line contains a nonnegative integer DD, representing the smoothness requirement.

Then follow RR matrices of size PP rows and QQ columns. In the zz-th matrix, the entry at row xx and column yy is v(x,y,z)v(x,y,z) (1xP1 \le x \le P, 1yQ1 \le y \le Q, 1zR1 \le z \le R).

Output Format

Output a single integer, the minimal possible total disharmony value under the legality constraints.

2 2 2
1
6 1
6 1
2 6
2 6
6

Hint

Explanation for Sample 1

The optimal cutting surface ff is f(1,1)=f(2,1)=2f(1,1)=f(2,1)=2, f(1,2)=f(2,2)=1f(1,2)=f(2,2)=1.


Constraints

For 100%100\% of the testdata, 1P,Q,R401 \le P,Q,R \le 40, 0DR0 \le D \le R, and all given disharmony values do not exceed 10001000.

Translated by ChatGPT 5