題目來源
洛谷P2863[USACO06JAN]牛的舞會The Cow Prom
https://www.luogu.org/problem/show?pid=2863
思路
成功跳圓舞的組合數即爲以奶牛爲點、繩索爲邊構成的圖的包含點數大於1的強連通分量數
用Tarjan求每個點所在的強連通分量後統計每個強連通分量所包含的點數
統計包含點數大於1的強連通分量數 即爲答案
代碼(C++)
#include <stack>
#include <cstdio>
#include <bitset>
using namespace std;
bitset <200010> g,in; stack<int> s;
int n,m,u,v,cnt=0,num,t=0;
struct way{int en,ne,ti;}p[50010];
int he[20010],dfn[10010],low[10010];
int scc[10010],w[10010],ans=0;
inline void add();
void search(int pos);
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i)
scanf("%d%d",&u,&v),add();
num=n; g=0;
for(int i=1;i<=n;++i)
if(g[i]==0)
search(i);
for(int i=1;i<=n;++i)
++he[scc[i]];
for(int i=n+1;i<=num;++i)
if(he[i]>1)
++ans;
printf("%d",ans);
return 0;
}
void search(int pos)
{
g[pos]=1; s.push(pos);
dfn[pos]=++t; low[pos]=dfn[pos];
int k=he[pos];
while(k!=0)
{
if(g[p[k].en]==0)
{
search(p[k].en);
if(low[p[k].en]<low[pos])
low[pos]=low[p[k].en];
}
else if(dfn[p[k].en]<low[pos]&&scc[p[k].en]==0)
low[pos]=dfn[p[k].en];
k=p[k].ne;
}
if(low[pos]==dfn[pos])
{
++num;
while(s.top()!=pos)
scc[s.top()]=num,s.pop();
scc[pos]=num;
s.pop();
}
}
inline void add()
{
++cnt;
p[cnt].en=v;
p[cnt].ne=he[u];
he[u]=cnt;
}