割边

原理

见《进阶指南》第396页。

模板题

洛谷-T103481-【模板】割边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];

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]);
        }
    }
}

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);

    int res = 0;
    for (int i = 0; i < idx; i += 2) // [0, idx)
        res += bridge[i];
    printf("%d", res);
    return 0;
}
最后修改于: