题目链接:https://www.luogu.org/problemnew/show/P1137
topsort + DP
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100001;
struct edge{
int next, from, to;
}e[maxn<<2];
int head[maxn], cnt, indrg[maxn], f[maxn], n, m;
queue<int> q;
void add(int u, int v)
{
e[++cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1; i <= m; i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v);
indrg[v]++;
}
for(int i = 1; i <= n; i++)
if(indrg[i] == 0)
{
f[i] = 1;
q.push(i);
}
while(!q.empty())
{
int now = q.front(); q.pop();
for(int i = head[now]; i; i = e[i].next)
{
f[e[i].to] = max(f[e[i].to], f[now]+1);
if(--indrg[e[i].to] == 0) q.push(e[i].to);
}
}
for(int i = 1; i <= n; i++)
printf("%d
",f[i]);
return 0;
}