No.2064 Smallest Sequence on Grid
Problem Statement
There is a grid with $H$ rows and $W$ columns. The cell $(i, j)$, in the $i$-th row from the top and the $j$-th column from the left, has the character $S_{i,j}$ written on it.
Consider creating a string of length $H+W-1$ by the following operation.
- First, prepare an empty string $T$ and stand on cell $(1,1)$.
-
Then, move according to the following rules.
- If you are on cell $(H,W)$, append the character $S_{H,W}$ to the end of the string $T$ and finish the operation.
- Otherwise, letting $(i,j)$ be the current cell, append the character $S_{i,j}$ to the end of the string $T$. Then, move to cell $(i+1,j)$ or $(i,j+1)$. However, moving outside the grid is not allowed.
Find the lexicographically smallest string among those that can be obtained by such an operation.
Input
$H\ W$
$S_{1,1}S_{1,2}\ldots S_{1,W}$
$\vdots$
$S_{H,1}S_{H,2}\ldots S_{H,W}$
- $1\leq H,W\leq 3000$
- $H,W$ are integers
- $S_{i,j}$ is a lowercase English letter
Output
Output the lexicographically smallest string among those that can be obtained by the operation.
Sample
Sample 1
Input
3 3 abd dce abd
Output
abcbd
Moving as $(1,1)\to(1,2)\to(2,2)\to(3,2)\to(3,3)$ gives the string abcbd. This is the lexicographically smallest among the strings that can be obtained.
Sample 2
Input
3 7 yukpbvx znicotf agzsder
Output
yukicoder
提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。
とりゐ
るさ