此题主要是用到一个bitset,这种东西一般用于集合的运算,主要作用是减少常数,不过速度是很可观的!还要注意的是如果2->3
2->5 5->9 3->9 那么2->9但是这个只能计数一次,所以这也是我们用bitset的原因否则直接加就是了。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<bitset>
using namespace std;
int too[30001];
int first[30001], nextt[30001];
int edgetot;
int anssort[30001], addnum[30001];
int anstot;
int n, m;
bool use[30001];
queue<int>q;
bitset<30001>s[30001];
int ans[30001];
void addedge(int a, int b)
{
too[edgetot] = b;
nextt[edgetot] = first[a];
first[a] = edgetot++;
addnum[b]++;
}
void quesort()
{
while (!q.empty())
{
int now = q.front();
anssort[anstot++] = now;
q.pop();
for (int i = first[now]; i != -1; i = nextt[i])
{
int to = too[i];
addnum[to]--;
if (addnum[to] == 0)
q.push(to);
}
}
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
first[i] = -1;
for (int i = 1; i <= m; i++)
{
int a, b;
scanf("%d%d", &a, &b);
addedge(a, b);
}
for (int i = 1; i <= n; i++)
{
if (addnum[i] == 0)
q.push(i);
}
quesort();
for (int i = anstot-1; i >=0; i--)
{
int now = anssort[i];
s[now].set(now, 1);
for (int k = first[now]; k != -1; k = nextt[k])
{
int to = too[k];
s[now] |= s[to];
}
ans[now] = s[now].count();
}
for (int i = 1; i <= n; i++)
{
printf("%d\n", ans[i]);
}
return 0;
}