题目链接:
题目分析:
其实不需要dp的,直接拓扑排序就可以了
代码:
#include <bits/stdc++.h>
#define N (500000 + 50)
using namespace std;
inline int read() {
int cnt = 0, f = 1; char c = getchar();
while (!isdigit(c)) {if (c == '-') f = -f; c = getchar();}
while (isdigit(c)) {cnt = (cnt << 3) + (cnt << 1) + c - '0'; c = getchar();}
return cnt * f;
}
int nxt[N], to[N], first[N], tot, p;
int topo[N];
int in[N], a[N];
queue <int> q;
int n, m, u, v;
void Add(int x, int y) {
nxt[++tot] = first[x];
first[x] = tot;
to[tot] = y;
}
void bfs() {
for (int i = 1; i <= n; i++) {
if (!in[i]) q.push(i), topo[i] = 1;
}
while (!q.empty()) {
int v = q.front(); q.pop();
for (register int i = first[v]; i; i = nxt[i]) {
int vv = to[i];--in[vv];
if (!in[vv]) q.push(vv), topo[vv] = max(topo[vv], topo[v] + 1);
}
}
}
int main() {
n = read(), m = read();
for (register int i = 1; i <= m; i++) {
u = read(), v = read();
++in[v];
Add(u, v);
}
bfs();
for (register int i = 1; i <= n; i++) printf("%d
", topo[i]);
return 0;
}