Understanding the Problem
P1434 [SHOI2002] Skiing - Luogu | Computer Science Education New Ecology (luogu.com.cn)
Given a rectangular grid with elevations, calculate the maximum length of a “ski” path from high to low.
A “ski” move can only go from one cell to a cell that is adjacent to it vertically or horizontally, and whose elevation is strictly lower than the current cell’s elevation.
For example:
1 | 1 2 3 4 5 |
The maximum path here is:

It has 25 cells in total.
Note that “length” is the total number of cells passed through from start to end; for example, a path $1\rightarrow 2$ has length 2.
The maximum rectangle size given in the problem is 100 by 100; let the length be c(olumns) and the width be r(ows).
Approach
The first thing that comes to mind is DFS (depth-first search). dfs(int x, int y) returns the maximum length starting from [x][y]. The search logic is simple: find the maximum length among the neighboring cells in four directions, then add 1 to get the maximum length for the current cell.
But the maximum dimensions in this problem are 100 by 100, so brute-forcing every cell would definitely time out; the worst-case time complexity could be $O(r^2c^2)$.
We can add memoization on top of the brute-force search. Create an array rec[x][y] to store the maximum length starting from [x][y]. If a later search reaches a neighboring cell and needs the length for [x][y], just return the recorded value instead of recursing again.
After this optimization, both the space complexity and time complexity are only $O(rc)$ (because each cell is computed at most once), so it passes easily.
AC Code
1 |
|