#include #include #include using namespace std; vector topological_sort (vector>& graph) { vector res(0); vector vis(graph.size(), false); auto dfs = [&](auto self, int pos) -> void { vis[pos] = true; for (auto to: graph[pos]) { if (vis[to]) continue; self(self, to); } res.push_back(pos); }; for (int i = 0; i < graph.size(); i++) if (!vis[i]) dfs(dfs, i); reverse(res.begin(), res.end()); return res; } int main () { int H, W; cin >> H >> W; vector> A(H, vector(W)); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> A[i][j]; } } const int dxy[][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1}, }; auto is_in = [&](int y, int x) { return 0 <= y && y < H && 0 <= x && x < W; }; vector> graph(H * W); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { for (auto d: dxy) { int ni = i + d[0], nj = j + d[1]; if (!is_in(ni, nj)) continue; if (A[i][j] < A[ni][nj]) { graph[i * W + j].push_back(ni * W + nj); } } } } auto update_ord = topological_sort(graph); vector score(H * W, 1); for (auto v: update_ord) { for (auto nex: graph[v]) { score[nex] = max(score[nex], score[v] + 1); } } int ans = 0; for (auto v: score) ans = max(ans, v); cout << ans << "\n"; }