【bzoj】1051 &&【poj】2186 Popular Cows Tarjan scc

本文介绍了一个经典的Tarjan算法模板题,通过寻找唯一出度为零的节点来展示Tarjan算法的应用。文章提供了详细的代码实现,并解释了如何使用Tarjan算法进行强连通分量的查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

据说这是个Tarjan模板题……Orz you all
这个题主要是找唯一的出度为零的点,请注意是唯一!
这个题我的课件里有详细讲解QwQ
神奇的poj传送门
神奇的bzoj传送门

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
using namespace std;
const int maxn=100000+10;
int head[maxn],next[maxn],to[maxn];
int ff[maxn],tt[maxn],cd[maxn];
int scc_tong[maxn],scc[maxn],low[maxn],dfn[maxn];
int tot=0,cnt=0,dfs_clock;
void build(int f,int t)
{
    to[++tot]=t;
    next[tot]=head[f];
    head[f]=tot;
}
stack<int>s;
void find_scc(int u)
{
    low[u]=dfn[u]=++dfs_clock;
    s.push(u);
    for(int i=head[u];i;i=next[i])
    {
        int v=to[i];
        if(!dfn[v])
        {
            find_scc(v);
            low[u]=min(low[u],low[v]);
        }
        else if(!scc[v])
        {
            low[u]=min(low[u],dfn[v]);
        }
    }
    if(low[u]==dfn[u])  
    {
        cnt++;
        while(343)
        {
            int x=s.top();
            s.pop();
            scc[x]=cnt;
            scc_tong[cnt]++;
            if(x==u)
            break;
        }
    }
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        cin>>ff[i]>>tt[i];
        build(ff[i],tt[i]);
    }
    for(int i=1;i<=n;i++)
    {
        if(!dfn[i]) find_scc(i);
    }
    for(int i=1;i<=m;i++)
    {
        if(scc[ff[i]]!=scc[tt[i]])
        {
            cd[scc[ff[i]]]++;
        }
    }
    int ans=0,t=0;
    for(int i=1;i<=cnt;i++)
    {
        if(cd[i]==0)
        {
            ans+=scc_tong[i];
            t++;
        }
    }
    if(t==1) cout<<ans;
    else cout<<"0";
    return 0;
}

大蒟蒻写题解 求轻喷QwQ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值