AcWing 164. 可达性统计
原题链接
中等
作者:
孤独时代的罗永浩
,
2020-07-07 15:08:08
,
所有人可见
,
阅读 561
手动模拟队列版本 C++ 代码
#include <cstring>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <queue>
using namespace std;
const int N = 30010;
int n, m, hh, tt = -1;
int h[N], e[N], ne[N], idx;
int d[N], q[N];
bitset<N> f[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
void topsort()
{
for (int i = 1; i <= n; i ++ )
if (!d[i])
q[++tt] = i;
int k = 0;
while (hh <= tt)
{
int t = q[hh++];
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (-- d[j] == 0)
q[++tt] = j;
}
}
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i ++ )
{
int a, b;
cin >> a >> b;
add(a, b);
d[b] ++ ;
}
topsort();
for (int i = n - 1; i >= 0; i -- )
{
int j = q[i];
f[j][j] = 1;
for (int k = h[j]; ~k; k = ne[k])
f[j] |= f[e[k]];
}
for (int i = 1; i <= n; i ++ ) cout << f[i].count() << endl;
return 0;
}