冗余路径

AcWing-395-冗余路径open in new window

实现

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

const int N = 5010, M = 10010;
struct edge {
    int to, next;
};
edge e[2 * M];
int idx, head[N], deg[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);
    }

    tarjan(1, -1);
    for (int i = 1; i <= n; ++ i) {
        if (dcc[i] == 0) {
            ++ tot;
            dfs(i);
        }
    }
    for (int i = 0; i < idx; ++ i)
        if (bridge[i] == true)
            ++ deg[dcc[e[i].to]];
    int cnt = 0;
    for (int i = 1; i <= tot; ++ i)
        if (deg[i] == 1)
            ++ cnt;
    printf("%d", (cnt + 1) / 2);
    return 0;
}
最后修改于: