有向图的强连通分量(Tarjan算法模板)

求有向图的强连通分量,Tarjan算法,大白书321页。lowlink[u]为u及其后代能追溯到最早祖先点v的pre[v]值,递归计算lowlink.

模板

int dfs_clock, scc_cnt;//scc_cnt记录强连通分量的个数,初始化是0但是是从1开始的
int pre[maxn], lowlink[maxn], sccno[maxn];;//sccno[u]记录点u属于第几个强联通分量,即点u所在强联通分量的编号
vector<int> g[maxn], scc[maxn];//scc[i]记录第i个强连通分量有哪些点
stack<int> s;//保存当前强连通分量中的点

void dfs(int u) {
    pre[u] = lowlink[u] = ++dfs_clock;
    s.push(u);
    for (int i = 0; i < g[u].size(); ++i) {
        int v = g[u][i];
        if (0 == pre[v]) {
            dfs(v);
            lowlink[u] = min(lowlink[u], lowlink[v]);
        }
        else if (0 == sccno[v]) {
            lowlink[u] = min(lowlink[u], pre[v]);
        }
    }
    if (lowlink[u] == pre[u]) {
        ++scc_cnt;//从1开始
        scc[scc_cnt].clear();
        while (1) {
            int x = s.top();
            s.pop();
            sccno[x] = scc_cnt;
            scc[scc_cnt].push_back(x);
            if (x == u) break;
        }
    }
}

void find_scc(int n) {
    dfs_clock = scc_cnt = 0;
    memset(pre, 0, sizeof(pre));
    memset(sccno, 0, sizeof(sccno));
    for (int i = 0; i < n; ++i) {
        if (0 == pre[i]) dfs(i);
    }
}

源程序

#include
using namespace std;

const int maxn = 150;
const int maxm = 1050;

int n, m;
int dfs_clock, scc_cnt;//scc_cnt记录强连通分量的个数,初始化是0但是是从1开始的
int pre[maxn], lowlink[maxn], sccno[maxn];;//sccno[u]记录点u属于第几个强联通分量,即点u所在强联通分量的编号
vector<int> g[maxn], scc[maxn];//scc[i]记录第i个强连通分量有哪些点
stack<int> s;//保存当前强连通分量中的点

void init() {
    for (int i = 0; i < maxn; ++i) g[i].clear();
}

void dfs(int u) {
    pre[u] = lowlink[u] = ++dfs_clock;
    s.push(u);
    for (int i = 0; i < g[u].size(); ++i) {
        int v = g[u][i];
        if (0 == pre[v]) {
            dfs(v);
            lowlink[u] = min(lowlink[u], lowlink[v]);
        }
        else if (0 == sccno[v]) {
            lowlink[u] = min(lowlink[u], pre[v]);
        }
    }
    if (lowlink[u] == pre[u]) {
        ++scc_cnt;//从1开始
        scc[scc_cnt].clear();
        while (1) {
            int x = s.top();
            s.pop();
            sccno[x] = scc_cnt;
            scc[scc_cnt].push_back(x);
            if (x == u) break;
        }
    }
}

void find_scc(int n) {
    dfs_clock = scc_cnt = 0;
    memset(pre, 0, sizeof(pre));
    memset(sccno, 0, sizeof(sccno));
    for (int i = 0; i < n; ++i) {
        if (0 == pre[i]) dfs(i);
    }
}

int main() {
    while (scanf("%d%d", &n, &m) == 2) {
        init();
        for (int i = 1; i <= m; ++i) {
            int from, to;
            scanf("%d%d", &from, &to);
            g[from].push_back(to);
        }
        find_scc(n);

        cout << "共有" << scc_cnt << "个强连通分量\n";
        for (int i = 1; i <= scc_cnt; ++i) {
            sort(scc[i].begin(), scc[i].end());
            cout << "第" << i << "个连通分量包含如下结点:\n";
            for (int j = 0; j < scc[i].size(); ++j)
                cout << scc[i][j] << ' ';
            cout << endl;
        }
    }
    return 0;
}

你可能感兴趣的:(有向图的强连通分量(Tarjan算法模板))