Tarjan - 模板

1、求双连通分量

#include 
#include 

struct Edge {
    int u, v;
}

int pre[maxn], isct[maxn], bccno[maxn];
int dfs_clock, bcc_cnt;
vector G[maxn], bcc[maxn];

stack S;

int dfs(int u, int fa) {
    int lowu = pre[u] = ++dfs_clock;
    int child = 0;
    for (int i = 0; i < G[u].size(); i++) {
        int v = G[u][i];
        Edge e = (Edge){u, v};
        if (!pre[v]) {
            S.push(e);
            child++;
            int lowv = dfs(v, u);
            lowu = min(lowu, lowv);
            if (lowv >= pre[u]) {
                isct[u] = 1;
                bcc_cnt++;
                bcc[bcc_cnt].clear();
                for (; ;) {
                    Edge x = S.top();
                    S.pop();
                    if (bccno[x.u] != bcc_cnt) {
                        bcc[bcc_cnt].push_back(x.u);
                        bccno[x.u] = bcc_cnt;
                    }
                    if (bccno[x.v] != bcc_cnt) {
                        bcc[bcc_cnt].push_back(x.v);
                        bccno[x.v] = bcc_cnt;
                    }
                    if (x.u == u && x.v == v) break;
                }
            }
        }
        else if (pre[v] < pre[u] && v != fa) {
            S.push(e);
            lowu = min(lowu, pre[v]);
        }
    }
    if (fa < 0 && child == 1) isct[u] =0;
    return lowu;
}

void find_bcc(int n) {
    memset(pre, 0, sizeof(pre));
    memset(isct, 0, sizeof(isct));
    memset(bccno, 0, sizeof(bccno));
    dfs_clock = bcc_cnt = 0;
    for (int i = 0; i < n; i++) {
        if (!pre[i]) dfs(i, -1);
    }
}

2、求有向图的强连通分量
#include 
#include 

vector G[maxn];
int pre[maxn], lowlink[maxn], sccno[maxn];
int dfs_clock, scc_cnt;
stack 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 (!pre[v]) {
            dfs(v);
            lowlink[u] = min(lowlink[u], lowlink[v]);
        }
        else if (!sccno[v]) {
            lowlink[u] = min(lowlink[u], pre[v]);
        }
    }
    if (lowlink[u]== pre[u]) {
        scc_cnt++;
        for (; ;) {
            int x = S.top();
            S.pop();
            sccno[x] = scc_cnt;
            if (x == u) break;
        }
    }
}

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


你可能感兴趣的:(Tarjan - 模板)