B. Number Roulette
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

"This town ain't big enough for the two of us."

Arthur Morgan has been challenged to a game of Russian Roulette. However, this isn't normal Russian Roulette — it is played on an $$$N \times M$$$ grid where each cell $$$(r, c)$$$ has an integer value $$$A_{r,c}$$$.

Before the game starts, Arthur chooses a positive integer $$$X$$$:

  • A cell $$$(r, c)$$$ is safe if $$$A_{r,c} \ge X$$$.
  • A cell $$$(r, c)$$$ is unsafe if $$$A_{r,c} \lt X$$$.

Connected safe cells (sharing an edge up, down, left, or right) form a safe zone. The size of a safe zone is the total number of cells in it.

Arthur starts at $$$(1, 1)$$$ and can move up, down, left, or right. To win the game, he must reach any cell in a safe zone of size at least $$$S$$$, while stepping on at most $$$K$$$ unsafe cells along his path (including $$$(1, 1)$$$ if it is unsafe).

Find the maximum integer $$$X$$$ Arthur can choose to win the game, or output 0 if it is impossible.

Input
  • The first line contains four integers $$$N$$$, $$$M$$$, $$$K$$$ and $$$S$$$.
  • The next $$$N$$$ lines describe the grid, one row per line. The $$$r$$$-th of these lines contains $$$M$$$ space-separated integers $$$A_{r,1}, A_{r,2}, \dots, A_{r,M}$$$, where $$$A_{r,c}$$$ is the value of the cell in row $$$r$$$ and column $$$c$$$.

Rows are numbered from top to bottom and columns from left to right, so $$$(1, 1)$$$ is the top-left cell.

Constraints:

  • $$$1 \le N, M \le 500$$$;
  • $$$0 \le K \le N \cdot M$$$;
  • $$$1 \le S \le N \cdot M$$$;
  • $$$1 \le A_{r,c} \le 10^9$$$.
Output

Print a single integer — the maximum valid $$$X$$$, or 0 if Arthur cannot win.

Scoring
SubtaskPoints$$$N$$$$$$M$$$$$$K$$$$$$S$$$$$$A_{r,c}$$$Additional Constraints
00-----The examples
120$$$\le 40$$$$$$\le 40$$$--$$$\le 50$$$No additional constraints.
220---$$$= 1$$$$$$\in \{1, 2\}$$$An optimal path only moves Down and Right.
325--$$$= N \times M$$$--No additional constraints.
435-----No additional constraints.

All other constraints are the same as in the Input section.

Example
Input
3 4 1 3
9 2 8 8
1 1 2 9
4 4 1 7
Output
8
Note

The grid is:


9 2 8 8
1 1 2 9
4 4 1 7

Choose $$$X = 8$$$. The safe cells are $$$(1,1)$$$, $$$(1,3)$$$, $$$(1,4)$$$ and $$$(2,4)$$$.

  • $$$(1,1)$$$ forms a safe zone of size $$$1$$$.
  • $$$(1,3)$$$, $$$(1,4)$$$ and $$$(2,4)$$$ are connected and form a safe zone of size $$$3 \ge S$$$.
Arthur starts at $$$(1,1)$$$, steps onto the unsafe cell $$$(1,2)$$$ (value $$$2 \lt 8$$$), and then reaches $$$(1,3)$$$. He stepped on $$$1 \le K$$$ unsafe cell, so he wins.

Choose $$$X = 9$$$. Only $$$(1,1)$$$ and $$$(2,4)$$$ are safe, and each forms a zone of size $$$1 \lt S$$$, so Arthur cannot win. Therefore the maximum valid $$$X$$$ is $$$8$$$.