可達性統計
描述
給定一張N個點M條邊的有向無環圖,分別統計從每個點出發能夠到達的點的數量。
輸入
第一行兩個整數N,M,接下來M行每行兩個整數x,y,表示從x到y的一條有向邊。
輸出
輸出共N行,表示每個點能夠到達的點的數量。
1≤N,M≤30000
輸入樣例
10 10
3 8
2 3
2 5
5 9
5 9
2 3
3 9
4 8
2 10
4 9
輸出樣例
1
6
3
3
2
1
1
1
1
1
題解
參考
https://www.acwing.com/solution/acwing/content/3089/
代碼
#include <bits/stdc++.h>
using namespace std;
const int N=3e4+10;
int net[N],head[N],ver[N],deg[N],tot,cnt,a[N],n,m;
bitset<N> f[N];
void add(int x,int y)//鏈式前向星加邊
{
ver[++tot]=y;
net[tot]=head[x];
head[x]=tot;
deg[y]++;//deg爲入度
}
void topsort(void)
{
queue<int> q;
for(int i=1;i<=n;i++)
if (deg[i]==0)
q.push(i);
while(q.size())
{
int x=q.front();
a[++cnt]=x;
q.pop();
for(int i=head[x];i;i=net[i])//鏈式前向星訪問
{
int y=ver[i];
deg[y]--;
if (!deg[y])//入讀爲0,可以加入候選隊列之中
q.push(y);
}
}
}
void calc()
{
for (int j = cnt; j; j--)
{
int x=a[j];
f[x][x]=1;
for (int i=head[x];i;i=net[i])
{
int y=ver[i];
f[x]|=f[y];//求出集合
}
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y;
cin>>x>>y;
add(x,y);
}
topsort();
calc();
for(int i=1;i<=n;i++)
cout<<f[i].count()<<endl;//統計1的個數,也就是到達了多少個點
return 0;
}