天天看點

【題解】CH2101可達性統計 拓撲排序+狀态壓縮+bitset

題目連結

描述

給定一張N個點M條邊的有向無環圖,分别統計從每個點出發能夠到達的點的數量。N,M≤30000。

輸入格式

第一行兩個整數N,M,接下來M行每行兩個整數x,y,表示從x到y的一條有向邊。

輸出格式

共N行,表示每個點能夠到達的點的數量。

樣例輸入

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

從x出發能夠到達的點,是從“x的各個後繼節點y”出發能夠到達的點的并集再加上x自身。DAG上跑拓撲排序,反着進行狀态壓縮(bitset實作),最後答案就是1的個數

#include<cstdio>
#include<queue>
#include<bitset>
#include<cstring>
using namespace std;
const int N=3e4+10;
bitset<N>f[N];
queue<int>q;
int head[N],tot,n,m,deg[N],tps[N],tp;
struct Edge{
	int v,nx;
}e[N];
inline void addedge(int u,int v)
{
	e[tot].v=v;
	e[tot].nx=head[u];
	head[u]=tot++;
	deg[v]++;
}
void toposort()
{
	for(int i=1;i<=n;i++)if(!deg[i])q.push(i);
	while(!q.empty())
	{
		int u=q.front();q.pop();tps[++tp]=u;
		for(int i=head[u];~i;i=e[i].nx)
		{
			int v=e[i].v;
			if(--deg[v]==0)q.push(v);
		}
	}
}
int main()
{
	//freopen("in.txt","r",stdin);
	memset(head,-1,sizeof(head));
    scanf("%d%d",&n,&m);
    int u,v;
    for(int i=1;i<=m;i++)scanf("%d%d",&u,&v),addedge(u,v);
    toposort();
    for(int i=tp;i;i--)
    {
    	u=tps[i];
    	f[u][u]=1;
    	for(int j=head[u];~j;j=e[j].nx)
    	{
    		v=e[j].v;
    		f[u]|=f[v];
		}
	}
	for(int i=1;i<=n;i++)printf("%d\n",f[i].count());
	return 0;
}
           

總結

将拓撲排序和狀态壓縮結合,好題