既然是拓扑图,那么可以直接使用dfs来解
C++ 代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<bitset>
using namespace std;
const int N = 30010;
int head[N] , e[N] , ne[N] , idx;
int n , m;
bitset<N> f[N];
void add(int a , int b){
e[idx] = b;
ne[idx] = head[a];
head[a] = idx ++;
}
void dfs(int u){
if (f[u].count() != 0) return;
f[u][u] = 1;
for(int i = head[u] ; i != -1 ; i = ne[i]){
int j = e[i];
dfs(j);
f[u] = f[u] | f[j];
}
}
int main(){
memset(head , -1 , sizeof head);
cin >> n >> m;
for(int i = 1 ; i <= m ; i ++){
int a , b;
cin >> a >> b;
add(a , b);
}
for(int i = 1 ; i <= n ; i ++){
if (f[i].count() == 0){
dfs(i);
}
}
for(int i = 1 ; i <= n ; i ++){
cout << f[i].count() << endl;
}
return 0;
}