P2863 [USACO06JAN] The Cow Prom S

 

>>>在有向图G中,如果两个顶点间至少存在一条路径,称两个顶点强连通。如果有向图G的每两个顶点都强连通,称G是一个强连通图。有向图非强连通图的极大强连通子图,称为强连通分量。

说白了就是如果一个有向图的子图里每个点可以两两互达,那么这个子图是一个强联通分量 -> 两两可以到达

Tarjan算法就是基于DFS求强联通分量的算法。

>>>一个点 也可以是强连通分量

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<bits/stdc++.h>
#define ll long long
#define ddd printf("-----------------debug\n");
using namespace std;
const int maxn=5e4+10;

int n,m; 
int head[maxn],to[maxn],nxt[maxn],tot;
int dfn[maxn],low[maxn],dfs_t,st[maxn],top=0,co[maxn],col=0,s[maxn];

void add(int a,int b){
    to[++tot]=b; nxt[tot]=head[a]; head[a]=tot;
}

void tarjan(int u)
{
    dfn[u]=low[u]=++dfs_t;
    st[++top]=u;
    
    for(int i=head[u];i;i=nxt[i])
    {
        int v=to[i];
        if(dfn[v]==0)
        {
            tarjan(v);
            low[u]=min(low[u],low[v]);//circle circruit 
        }
        else if(co[v]==0) low[u]=min(low[u],dfn[v]);//鞋歪枝 
    }
    if(low[u]==dfn[u])
    {
        co[u]=++col;
        s[col]++;
        while(st[top]!=u)
        {
            co[st[top--]]=col;
            s[col]++;
        }
        top--;
    }
}
int main()  
{
    ios::sync_with_stdio(false); cin.tie(0);
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        int u,v; cin>>u>>v;
        add(u,v); //add(v,u);
    }
    for(int i=1;i<=n;i++) if(dfn[i]==0) tarjan(i);
    
    int ans=0;
    for(int i=1;i<=col;i++) if(s[i]>=2) ans++;
    cout<<ans<<'\n';
    
    return 0;
}
View Code

 

 
posted @ 2023-08-07 16:56  JMXZ  阅读(8)  评论(0)    收藏  举报