【luogu P2860 [USACO06JAN]冗余路径Redundant Paths】 题解

题目链接:https://www.luogu.org/problemnew/show/P2860
考虑在无向图上缩点。
运用到边双、桥的知识。
缩点后统计度为1的点。
度为1是有一条路径,度为2是有两条路径。

#include <stack>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 300000 + 10;
struct edge{
    int next, to, from;
}e[maxn<<2];
int head[maxn], cnt;
bool vis[maxn];
int n, m, u[maxn], v[maxn], d[maxn], ans;
stack<int> s; 
int dfn[maxn], low[maxn], tim, color[maxn], num;
void add(int u, int v)
{
    e[++cnt].from = u;
    e[cnt].next = head[u];
    e[cnt].to = v;
    head[u] = cnt;
}
void tarjan(int x)
{
    dfn[x] = low[x] = ++tim;
    for(int i = head[x]; i != -1; i = e[i].next)
    if(!vis[i])
    {
        int v = e[i].to;
        if(dfn[v]) low[x] = min(low[x], dfn[v]);
        else 
        {
            s.push(v);
            vis[i] = vis[(i&1)?i+1:i-1] = 1;
            tarjan(v);
            vis[i] = vis[(i&1)?i+1:i-1] = 0;
            low[x] = min(low[x], low[v]);
        }
    }
    if(dfn[x] == low[x])
    {
        num++;
        while(!s.empty())
        {
            color[s.top()] = num;
            if(s.top() == x) {
                s.pop();
                break;
            }
            s.pop();
        }
    }
}
int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= m; i++)
    {
        scanf("%d%d",&u[i],&v[i]);
        add(u[i],v[i]); add(v[i],u[i]);
    }
    for(int i = 1; i <= n; i++)
        if(!dfn[i]) num = 0, s.push(i), tarjan(i);
    for(int i = 1; i <= m; i++)
    {
        if(color[u[i]] != color[v[i]])
        d[color[u[i]]]++, d[color[v[i]]]++;
    }
    for(int i = 1; i <= n; i++) if(d[i] == 1) ans++;
    printf("%d",(ans+1)/2);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/MisakaAzusa/p/9379657.html