vector<vector<int>> a, in_deg, f; int n, m; Coordinate s[MAX_N * MAX_N];
boolis_valid(int x, int y){ return x >= 0 && x < n && y >= 0 && y < m; }
voidget_topological_order(){ for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { for (int dir = 0; dir < 4; ++dir) { int nx = i + dx[dir], ny = j + dy[dir]; if (is_valid(nx, ny) && a[i][j] < a[nx][ny]) { ++in_deg[nx][ny]; } } } }
queue<Coordinate> q; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (in_deg[i][j] == 0) { q.push({i, j}); } } }
int s_ptr = 0; while (!q.empty()) { auto frt = q.front(); q.pop(); s[s_ptr++] = frt;
for (int dir = 0; dir < 4; ++dir) { int nx = frt.x + dx[dir], ny = frt.y + dy[dir]; if (is_valid(nx, ny) && a[frt.x][frt.y] < a[nx][ny] && (--in_deg[nx][ny]) == 0) { q.push({nx, ny}); } } } }
intlongestIncreasingPath(vector<vector<int>>& a_){ a = a_; n = a.size(); m = a[0].size(); in_deg = vector<vector<int>>(n, vector<int>(m, 0)); f = vector<vector<int>>(n, vector<int>(m, 0));
get_topological_order();
int tot = n * m, ans = 0; for (int i = 0; i < tot; ++i) { f[s[i].x][s[i].y] = 1; for (int dir = 0; dir < 4; ++dir) { int pre_x = s[i].x + dx[dir], pre_y = s[i].y + dy[dir]; if (is_valid(pre_x, pre_y) && a[pre_x][pre_y] < a[s[i].x][s[i].y]) { f[s[i].x][s[i].y] = max(f[s[i].x][s[i].y], f[pre_x][pre_y] + 1); } } ans = max(ans, f[s[i].x][s[i].y]); }