POJ 3177 Redundant Paths

传送门

AcWing 395 冗余路径洛谷 P2860 [USACO06JAN]Redundant Paths G

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>

using namespace std;
typedef long long ll;
typedef pair<int, int> p;
const double pi(acos(-1));
const int inf(0x3f3f3f3f);
const int mod(1e9 + 7);
const int maxn(5e3 + 10);
const int maxm(2e4 + 10);
int ecnt, head[maxn];
int tim, dfn[maxn], low[maxn];
int dcnt, dcc[maxn], deg[maxn];
bool bdg[maxm];
stack<int> st;

struct edge {
    int to, nxt;
} edges[maxm];

template<typename T>
inline const T read()
{
    T x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 3) + (x << 1) + ch - '0';
        ch = getchar();
    }
    return x * f;
}

template<typename T>
inline void write(T x, bool ln)
{
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10, false);
    putchar(x % 10 + '0');
    if (ln) putchar(10);
}

void addEdge(int u, int v)
{
    edges[ecnt].to = v;
    edges[ecnt].nxt = head[u];
    head[u] = ecnt++;
}

void tarjan(int cur, int pre)
{
    dfn[cur] = low[cur] = ++tim;
    st.push(cur);
    for (int i = head[cur]; compl i; i = edges[i].nxt) {
        int nxt = edges[i].to;
        if (not dfn[nxt]) {
            tarjan(nxt, cur);
            low[cur] = min(low[cur], low[nxt]);
            if (dfn[cur] < low[nxt]) {
                bdg[i] = bdg[i ^ 1] = true;
            }
        } else if (nxt not_eq pre) {
            low[cur] = min(low[cur], dfn[nxt]);
        }
    }
    if (dfn[cur] == low[cur]) {
        ++dcnt;
        int nxt = 0;
        do {
            nxt = st.top();
            st.pop();
            dcc[nxt] = dcnt;
        } while (nxt not_eq cur);
    }
}

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("input.txt", "r", stdin);
#endif
    memset(head, -1, sizeof head);
    int n = read<int>(), m = read<int>();
    while (m--) {
        int u = read<int>(), v = read<int>();
        addEdge(u, v);
        addEdge(v, u);
    }
    tarjan(1, -1);
    for (int i = 0; i < ecnt; ++i) {
        if (bdg[i]) {
            ++deg[dcc[edges[i].to]];
        }
    }
    int cnt = 0;
    for (int i = 1; i <= dcnt; ++i) {
        if (deg[i] == 1) {
            ++cnt;
        }
    }
    write((cnt + 1) / 2, true);
    return 0;
}
原文地址:https://www.cnblogs.com/singularity2u/p/13922119.html