拓扑排序+状态压缩
考虑每一个点能够到达的所有点都是与该店相邻的点的后继节点,可知:
令f[u]表示u点可到达的节点个数,f[u]={u}与f[v](u, v)的并集
于是可以利用状态压缩,能够到达的节点用1表示,这样更新f的时候直接求并集即可
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C yql){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % yql)if(p & 1)ans = 1LL * x * ans % yql;
return ans;
}
const int N = 30005;
int n, m, cnt, head[N], ind[N], tps[N], tot;
bitset<N> f[N];
struct Edge{
int v, next;
}edge[N<<2];
void addEdge(int a, int b){
edge[cnt].v = b;
edge[cnt].next = head[a];
head[a] = cnt ++;
}
void bfs(){
queue<int> q;
for(int i = 1; i <= n; i ++){
if(ind[i] == 0) q.push(i);
}
while(!q.empty()){
int s = q.front(); q.pop();
tps[tot++] = s;
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(--ind[u] == 0) q.push(u);
}
}
}
int main(){
memset(head, -1, sizeof head);
n = read(), m = read();
for(int i = 0; i < m; i ++){
int a = read(), b = read();
addEdge(a, b), ind[b] ++;
}
bfs();
for(int i = tot - 1; i >= 0; i --){
int u = tps[i];
f[u][u] = 1;
for(int j = head[u]; j != -1; j = edge[j].next){
int v = edge[j].v;
f[u] |= f[v];
}
}
for(int i = 1; i <= n; i ++)
printf("%d
", f[i].count());
return 0;
}