P2341 【模板】强连通分量 / [HAOI2006]受欢迎的牛 题解

P2341 【模板】强连通分量 / [HAOI2006]受欢迎的牛 题解

https://www.luogu.com.cn/problem/P2341

题意: 有m组,A喜欢B ,喜欢具有传递性,问有多少个牛是被其他所有人喜欢的

做法: 先用Tarjon缩点,现在题目所求转化为求一个点,其他点都连向它,并且它的出度为0
可以证明,不存在两个出度为0的点,因为如果存在两个为0的点,显然就不存在符合条件的牛(关系断掉了)

求出度的时候,忘记对邻接表进行遍历,而只是对m条边进行遍历,这是错误的,因为这题的传递性,这道模板题卡了一小时

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<queue>
#include<map>
#define ll long long
#define pb push_back
#define rep(x,a,b) for (int x=a;x<=b;x++)
#define repp(x,a,b) for (int x=a;x<b;x++)
#define W(x) printf("%d\n",x)
#define WW(x) printf("%lld\n",x)
#define pi 3.14159265358979323846
#define mem(a,x) memset(a,x,sizeof a)
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
using namespace std;
const int maxn=1e5+7;
const int INF=1e9;
const ll INFF=1e18;
struct node
{
    int to,next;
}edge[maxn];
int head[maxn],tol,low[maxn],dfn[maxn],Stack[maxn],belong[maxn],Index,top,scc,num[maxn],g[maxn],n,m,a[maxn],b[maxn];
bool Instack[maxn];
void add(int u,int v)
{
    edge[tol].to=v;
    edge[tol].next=head[u];
    head[u]=tol++;
}
void Tarjon(int u)
{
    int v;
    low[u]=dfn[u]=++Index;
    Stack[top++]=u;
    Instack[u]=true;
    for (int i=head[u];i!=-1;i=edge[i].next)
    {
        v=edge[i].to;
        if (!dfn[v])
        {
            Tarjon(v);
            low[u]=min(low[u],low[v]);
        }
        else if (Instack[v])
        {
            low[u]=min(low[u],dfn[v]);
        }
    }
    if (low[u]==dfn[u])
    {
        scc++;
        do
        {
            v=Stack[--top];
            Instack[v]=false;
            belong[v]=scc;
            num[scc]++;
        }while(v!=u);
    }
}
void solve(int n)
{
    mem(dfn,0);
    mem(Instack,false);
    mem(num,0);
    Index=top=scc=0;
    rep(i,1,n)if (!dfn[i])Tarjon(i);
}
void init()
{
    tol=0;
    mem(head,-1);
}
int main()
{
    init();
    scanf("%d%d",&n,&m);
    rep(i,1,m)
    {
        scanf("%d%d",&a[i],&b[i]);
        add(a[i],b[i]);
    }
    solve(n);
    rep(i,1,n)
    {
        for (int j=head[i];j!=-1;j=edge[j].next)
        {
            int u=edge[j].to;
            if (belong[i]!=belong[u])g[belong[i]]++;
        }
    }
    /*以下为错误示范:
    rep(i,1,m)
    {
        if (belong[a[i]]!=belong[b[i]])g[belong[a[i]]]++;
    }*/
    int j=-1;
    rep(i,1,scc)
    {
        if (!g[i])
        {
            if (j!=-1)
            {
                W(0);return 0;
            }
            j=i;
        }
    }
    W(num[j]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值