题目分析
拓扑排序:将图从度为0的点不断的剥掉外层的点,即可得到拓扑序,再按照拓扑序进行一遍简单的dp。
code
#include<bits/stdc++.h>
using namespace std;
const int N = 100000, M = 200000, OO = 0x3f3f3f3f;
int n, m;
int ecnt, adj[N + 5], go[M * 2 + 5], nxt[M * 2 + 5], in[N + 5], ans[N + 5], top[N + 5], _top;
bool vst[N + 5];
queue<int> que;
struct node{
int from, to;
node(){}
node(int u, int v):from(u), to(v){}
}edges[M * 2 + 5];
inline void addEdge(int u, int v){
nxt[++ecnt] = adj[u], adj[u] = ecnt, go[ecnt] = v;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
cin >> n >> m;
for(int i = 1; i <= m; i++){
int x, y;
cin >> x >> y;
addEdge(x, y);
in[y]++;
}
for(int i = 1; i <= n; i++)
if(in[i] == 0) que.push(i);
while(!que.empty()){
top[++_top] = que.front(); que.pop();
for(int e = adj[top[_top]]; e; e = nxt[e]){
int v = go[e];
in[v]--;
if(in[v] == 0) que.push(v);
}
}
for(int i = 1; i <= n; i++) ans[i] = 1;
for(int i = 1; i <= _top; i++){
for(int e = adj[top[i]]; e; e = nxt[e])
if(ans[go[e]] < ans[top[i]] + 1) ans[go[e]] = ans[top[i]] + 1;
}
for(int i = 1; i <= n; i++) cout << ans[i] << endl;
}