缩点模板(有向图&&无向图)

#include <bits/stdc++.h>
using namespace std;
const int N = 110, M = N*N;
int e[M],ne[M],k,h[M];
void add(int a,int b){
    e[++k]=b;ne[k]=h[a];h[a]=k;
}
int dfn[N],low[N],tim;
int sta[N],stacnt;
bool vis[N];
int id[N],idcnt;
void tarjan(int x){
    dfn[x]=low[x]=++tim;
    sta[++stacnt]=x;
    vis[x]=true;
    for(int i=h[x];i;i=ne[i]){
        int j=e[i];
        if(!dfn[j]){
            tarjan(j);
            low[x]=min(low[x],low[j]);
        }else if(vis[j]){
            low[x]=min(low[x],low[j]);
        }
    }
    if(dfn[x]==low[x]){
        int y;
        idcnt++;
        do{
            y=sta[stacnt--];
            id[y]=idcnt;
            vis[y]=false;
        }while(y!=x);
    }
}
int din[N],dout[N];
int main()
{
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=1,x;i<=n;i++){
        while(cin>>x,x) add(i,x);
    }
    for(int i=1;i<=n;i++)
        if(!dfn[i])tarjan(i);
    for(int i=1;i<=n;i++)
        for(int j=h[i];j;j=ne[j]){
            int a=id[i],b=id[e[j]];
            if(a!=b) dout[a]++,din[b]++;
        }
    int ans=0,res=0;
    for(int i=1;i<=idcnt;i++)
    {
        if(!din[i])ans++;
        if(!dout[i])res++;
    }
    cout<<ans<<'\n';
    if(idcnt==1)cout<<"0\n";
    else{
        cout<<max(ans,res);
    }
}

 

#include <bits/stdc++.h>
using namespace std;
using ll = long long ;
const int N = 5010,M = 200100 ;
int e[M],ne[M],h[M],k;
void add(int a,int b){
    e[k]=b,ne[k]=h[a],h[a]=k++;
}
int dfn[N],low[N],sta[N],stacnt;
int id[N],idcnt,tim;
bool is_bright[N];
void tarjan(int x,int from){
    dfn[x]=low[x]=++tim;
    sta[++stacnt]=x;
    for(int i=h[x];~i;i=ne[i]){
        int j=e[i];
        if(!dfn[j]){
            tarjan(j,i);
            low[x]=min(low[x],low[j]);
            if(dfn[x]<low[j])
                is_bright[i]=is_bright[i^1]=true;
        }else if(i!=(from^1))
            low[x]=min(low[j],dfn[x]);
    }
    if(dfn[x]==low[x]){
        ++idcnt;
        int y;
        do{
            y=sta[stacnt--];
            id[y]=idcnt;
        }while(x!=y);
    }
}
int d[N];
signed main()
{
    ios::sync_with_stdio(false);
    int n,m;
    cin>>n>>m;
    memset(h,-1,sizeof h);
    while(m--){
        int a,b;
        cin>>a>>b;
        add(a,b);
        add(b,a);
    }
    tarjan(1,-1);
    for(int i=0;i<k;i++)
        if(is_bright[i])d[id[e[i]]]++;
    int ans=0;
    for(int i=1;i<=idcnt;i++)
        if(d[i]==1)ans++;
    cout<<(ans+1)/2;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

倾海、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值