POJ 3177 Redundant Paths(边双连通分量模板)

边双连通分量:从图中任意一个点到另外一个点都有>1条可行路,即把原图中的桥全都去掉以后,剩下的连通分支都是边双连通分支

求法:把去掉桥后的双连通子图缩成一个点,最少需要加上(leaf + 1)/ 2条边可以使得其变成双连通子图,其中leaf为叶子节点个数。

https://vjudge.net/problem/POJ-3177

#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 5005;
const int maxm = 20005;
struct edge
{
    int to, next;
    bool cut;
}e[maxm];
int head[maxn], cnt;
int low[maxn], dfn[maxn], stk[maxn], belong[maxn];
int index, top;
int block;
bool vis[maxn];
int bridge;
void addedge(int u, int v)
{
    e[cnt].to = v;
    e[cnt].cut = 0;
    e[cnt].next = head[u];
    head[u] = cnt ++;
}
void tarjan(int u, int pre)
{
    int v;
    low[u] = dfn[u] = ++ index;
    stk[top ++] = u;
    vis[u] = 1;
    int pre_cnt = 0;
    for(int i = head[u]; ~i; i = e[i].next)
    {
        v = e[i].to;
        if(v == pre && pre_cnt == 0)
        {
            pre_cnt ++;
            continue;
        }
        if(! dfn[v])
        {
            tarjan(v, u);
            if(low[u] > low[v])
                low[u] = low[v];
            if(low[v] > dfn[u])
            {
                bridge ++;
                e[i].cut = 1;
                e[i^1].cut = 1;
            }
        }
        else if(vis[v] && low[u] > dfn[v])
            low[u] = dfn[v];
    }
    if(low[u] == dfn[u])
    {
        block ++;
        do
        {
            v = stk[-- top];
            vis[v] = 0;
            belong[v] = block;
        }while(v != u);
    }
}
int du[maxn];
void solve(int n)
{
    memset(dfn, 0, sizeof(dfn));
    memset(vis, 0, sizeof(vis));
    index = top = block = 0;
    tarjan(1, 0);
    int ans = 0;
    memset(du, 0, sizeof(du));
    for(int i = 1; i <= n; i ++)
    {
        for(int j = head[i]; ~j; j = e[j].next)
        {
            if(e[j].cut)
                du[belong[i]] ++;
        }
    }
    for(int i = 1; i <= block; i ++)
        if(du[i] == 1)
            ans ++;
    printf("%d\n", (ans + 1) / 2);
}
int main()
{
    int n, m, u, v;
    while(scanf("%d%d", &n, &m) != EOF)
    {
        memset(head, -1, sizeof(head));
        cnt = 0;
        while(m --)
        {
            scanf("%d%d", &u, &v);
            addedge(u, v);
            addedge(v, u);
        }
        solve(n);
    }
    return 0;
}

 

你可能感兴趣的:(tarjan,模板)