边双连通分量(E-DCC

原理

见《进阶指南》第402页。

模板题

洛谷-T103489-【模板】边双连通分量open in new window

#include <iostream>
#include <cstring>
using namespace std;

const int N = 50010, M = 300010;
struct edge {
    int to, next;
};
edge e[2 * M];
int idx, head[N];
int n, m;
int cnt, dfn[N], low[N];
bool bridge[2 * M];
int tot, dcc[N];

void add_edge (int u, int v) {
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx ++;
}
void tarjan (int cur, int eid) {
    low[cur] = dfn[cur] = ++ cnt;
    for (int i = head[cur]; i != -1; i = e[i].next) {
        int to = e[i].to;
        if (dfn[to] == 0) {
            tarjan(to, i);
            low[cur] = min(low[cur], low[to]);

            if (low[to] > dfn[cur])
                bridge[i] = bridge[i ^ 1] = true;
        } else if (i != (eid ^ 1)) {
            low[cur] = min(low[cur], dfn[to]);
        }
    }
}
void dfs (int cur) {
    dcc[cur] = tot;
    for (int i = head[cur]; i != -1; i = e[i].next) {
        int to = e[i].to;
        if (bridge[i] == true) continue;
        if (dcc[to] == 0) dfs(to);
    }
}

int main () {
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &m);
    for (int i = 1, u, v; i <= m; ++ i) {
        scanf("%d%d", &u, &v);
        add_edge(u, v);
        add_edge(v, u);
    }

    for (int i = 1; i <= n; ++ i)
        if (dfn[i] == 0)
            tarjan(i, -1);
    for (int i = 1; i <= n; ++ i) {
        if (dcc[i] == 0) {
            ++ tot;
            dfs(i);
        }
    }
    printf("%d", tot);
    return 0;
}
最后修改于: