题目
分析
每个点的答案是它所有前驱节点的答案加1,即f[i]=max(f[i],f[j]+1)
AC代码
#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
int n, m, cnt;
int head[100005], in[100005], f[100005];
queue<int> q;
struct Edge {
int to;
int next;
}edge[400005];
void add(int u, int v)
{
edge[++cnt].to = v;
edge[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);
in[v]++;
}
for (int i = 1; i <= n; i++)
{
if (in[i] == 0)
{
f[i] = 1;
q.push(i);
}
}
while (!q.empty())
{
int now = q.front();
q.pop();
for (int i = head[now]; i; i = edge[i].next)
{
f[edge[i].to] = max(f[edge[i].to], f[now] + 1);
in[edge[i].to]--;
if (in[edge[i].to] == 0)
{
q.push(edge[i].to);
}
}
}
for (int i = 1; i <= n; i++)
{
printf("%d\n", f[i]);
}
}