Tarjan缩点——牛的舞会The Cow Prom

题目来源

洛谷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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值