P2860 [USACO06JAN]Redundant Paths G

原题链接

  • 代码:
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
#include <queue>
#include <map>

using namespace std;
const int N = 101000;
const int M = 401000;
int h[M], ne[M], to[M], idx;
int dfn[N], low[N], times;
int stk[N], top;
int dcc = 0;
int d[N];
int id[N];
struct edge {
    int u, v;
}e[M];
void add(int u, int v) {ne[idx] = h[u], to[idx] = v, h[u] = idx++;}
void tarjan(int u, int from) {
    dfn[u] = low[u] = ++times;
    stk[++top] = u;
    bool flag = 0;
    for (int  i =h[u]; i != -1; i = ne[i]) {
        int v = to[i];
        if (i == (1^from) && !flag) {flag = 1;continue;}
        if ( ! dfn[v]) {
            tarjan(v, i);
            low[u] = min(low[u], low[v]);
            
        }
        else low[u] = min(low[u], dfn[v]);
    }
    if (dfn[u] == low[u]) {
        id[u] = ++dcc;
        while (stk[top] != u) {
            id[stk[top] ]=dcc;
            top--;
        }top--;
    }
}

int cas = 0;
void solve() {
    int n, m;
    scanf("%d%d",&n, &m); 
    memset(h, -1, sizeof h);
    memset(dfn, 0, sizeof dfn);
    times = idx  = 0;
    for (int i = 1; i <= m; i ++) {
        int u, v;
        scanf("%d%d", &u, &v);
        add(u, v);
        add(v, u);
        e[i] = {u, v};
    }
    for (int i = 1; i <= n; i ++) {if (!dfn[i]) {tarjan(i, -1);}}
    for (int i = 1; i <= m;i ++) {
        int u = e[i].u;
        int v = e[i].v;
        if (id[u] == id[v])continue;
        d[id[u]]++;
        d[id[v]]++;
    }
    int cnt = 0;
    for (int i = 1; i <= dcc; i ++ ) {
        if (d[i] == 1) cnt++;
    }
    printf("%d\n", ((cnt + 1) >> 1));
}
int main() {
    ios::sync_with_stdio(0);
    int t = 1;//cin >> t;
    while (t--)solve();
    return 0;
}
posted @ 2021-04-08 11:18  u_yan  阅读(42)  评论(0编辑  收藏  举报