zoukankan      html  css  js  c++  java
  • Tarjan算法求有向图强连通分量并缩点

    // Tarjan算法求有向图强连通分量并缩点
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<vector>
    #include<queue>
    using namespace std;
    const int N = 100010, M = 1000010;
    //
    int ver[M], Next[M], head[N], dfn[N], low[N];
    int stack[N], ins[N], c[N];
    
    int vc[M], nc[M], hc[N], tc;
    //强连通分量
    vector<int> scc[N];
    
    int n, m, tot, num, top, cnt;
    
    void add(int x, int y) {
        ver[++tot] = y, Next[tot] = head[x], head[x] = tot;
    }
    //缩点后建图
    void add_c(int x, int y) {
        vc[++tc] = y, nc[tc] = hc[x], hc[x] = tc;
    }
    
    void tarjan(int x) {
        dfn[x] = low[x] = ++num;
        stack[++top] = x, ins[x] = 1;//标记x点
        for (int i = head[x]; i; i = Next[i])
            //未走过
            if (!dfn[ver[i]]) {
                tarjan(ver[i]);
                //递归更新
                low[x] = min(low[x], low[ver[i]]);
            }
            else if (ins[ver[i]])
                //直接更新
                low[x] = min(low[x], dfn[ver[i]]);
        if (dfn[x] == low[x]) {
            //一个强连通
            cnt++; int y;
            do {
                y = stack[top--], ins[y] = 0;
                //属于哪一个强连通
                c[y] = cnt, scc[cnt].push_back(y);
            } while (x != y);
        }
    }
    
    int main() {
        cin >> n >> m;
        for (int i = 1; i <= m; i++) {
            int x, y;
            scanf("%d%d", &x, &y);
            add(x, y);
        }
        for (int i = 1; i <= n; i++)
            if (!dfn[i]) tarjan(i);
        for (int x = 1; x <= n; x++)
            for (int i = head[x]; i; i = Next[i]) {
                int y = ver[i];
                if (c[x] == c[y]) continue;
                add_c(c[x], c[y]);
            }
    }
  • 相关阅读:
    编程之道——高内聚低耦合
    虚拟机的安装
    Tomcat的安装与配置
    Spring(十)--Advisor顾问
    Spring(九)--通知
    Spring(八)-- 代理设计模式
    Spring(七)--Spring JDBC
    Spring(六)--Spring配置文件之间的关系
    Spring(五)--autowire自动装配和spel
    Spring(四)--bean的属性赋值
  • 原文地址:https://www.cnblogs.com/DWVictor/p/11347956.html
Copyright © 2011-2022 走看看