看到题之后愣了一下。
然后才发现这是 DAG,直接拓扑?
事实证明这是对的,写个 DP 直接过了。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 15, M = N;
int n, m, h[N], e[M], ne[M], idx = 0;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int deg[N];
int dp[N];
void topsort() {
queue<int> q;
for (int i = 1; i <= n; i++)
if (!deg[i]) q.push(i);
while (q.size()) {
int u = q.front(); q.pop();
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (--deg[v] == 0) q.push(v);
dp[v] = max(dp[v], dp[u] + 1);
}
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) h[i] = -1;
for (int i = 1, u, v; i <= m; i++) scanf("%d%d", &u, &v), add(u, v), deg[v]++;
topsort();
int ans = 0;
for (int i = 1; i <= n; i++) ans = max(ans, dp[i]);
printf("%d\n", ans);
return 0;
}