tarjan模板(缩点,求有向图强连通分量)

202 篇文章 0 订阅
123 篇文章 0 订阅

想看更多模板,请点击:http://blog.csdn.net/martinue/article/category/6268283

整理出了这个tarjan模板,具体数组的功能代码都有注释。

const int N=100010;
struct data
{
    int to,next;
} tu[N*2];
int head[N];
int ip;
int dfn[N], low[N];///dfn[]表示深搜的步数,low[u]表示u或u的子树能够追溯到的最早的栈中节点的次序号
int sccno[N];///缩点数组,表示某个点对应的缩点值
int step;
int scc_cnt;///强连通分量个数
void init()
{
    ip=0;
    memset(head,-1,sizeof(head));
}
void add(int u,int v)
{
    tu[ip].to=v,tu[ip].next=head[u],head[u]=ip++;
}
vector<int> scc[N];///得出来的缩点,scc[i]里面存i这个缩点具体缩了哪些点
stack<int> S;
void dfs(int u)
{
    dfn[u] = low[u] = ++step;
    S.push(u);
    for (int i = head[u]; i !=-1; i=tu[i].next)
    {
        int v = tu[i].to;
        if (!dfn[v])
        {
            dfs(v);
            low[u] = min(low[u], low[v]);
        }
        else if (!sccno[v])
            low[u] = min(low[u], dfn[v]);
    }
    if (low[u] == dfn[u])
    {
        scc_cnt += 1;
        scc[scc_cnt].clear();
        while(1)
        {
            int x = S.top();
            S.pop();
            if (sccno[x] != scc_cnt) scc[scc_cnt].push_back(x);
            sccno[x] = scc_cnt;
            if (x == u) break;
        }
    }
}
void tarjan(int n)
{
    memset(sccno, 0, sizeof(sccno));
    memset(dfn, 0, sizeof(dfn));
    step = scc_cnt = 0;
    for (int i = 1; i <=n; i++)
        if (!dfn[i]) dfs(i);
}

具体思路见详解网址:https://www.byvoid.com/blog/scc-tarjan


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值