POJ 3177 Redundant Paths 边双连通分量

题目:http://poj.org/problem?id=3177


题意:跟3352一样,最少加多少条边使图变得双连通,唯一的区别是此题会有重边,需要判重


思路:我自己写的判重挺搓的,直接用一个5000*5000的bool标记数组,虽然过了,总感觉不好,于是看了大神的判重,改了一下,代码是改过后的

#include 
#include 
#include 
#include 
#include 
using namespace std;

const int N = 5010;
struct edge
{
    int to, next;
} G[N*5];
int dfn[N], low[N], st[N], dcc[N], head[N];
int index, num, cnt, top;
bool vis[N];
int n, m;
void init()
{
    memset(dfn, -1, sizeof dfn);
    memset(head, -1, sizeof head);
    memset(vis, 0, sizeof vis);
    index = num = cnt = top = 0;
}
void add_edge(int v, int u)
{
    G[cnt].to = u;
    G[cnt].next = head[v];
    head[v] = cnt++;
}
bool judge(int v, int fa)/*判重边*/
{
    int tmp = 0;
    for(int i = head[v]; i != -1; i = G[i].next)
        if(G[i].to == fa) tmp++;
    if(tmp >= 2) return true;
    else return false;
}
void tarjan(int v, int fa)
{
    dfn[v] = low[v] = index++;
    vis[v] = true;
    st[top++] = v;
    bool f = judge(v, fa);
    int u, t;
    for(int i = head[v]; i != -1; i = G[i].next)
    {
        u = G[i].to;
        if(u == fa && ! f) continue;/*此处条件稍变*/
        if(dfn[u] == -1)
        {
            tarjan(u, v);
            low[v] = min(low[v], low[u]);
            if(dfn[v] < low[u])
            {
                num++;
                do
                {
                    t = st[--top];
                    vis[t] = false;
                    dcc[t] = num;
                }
                while(t != u);
            }
        }
        else if(vis[u])
            low[v] = min(low[v], dfn[u]);
    }
}
void slove()
{
    tarjan(1, -1);
    int deg[N];
    memset(deg, 0, sizeof deg);
    for(int i = 1; i <= n; i++)
        for(int j = head[i]; j != -1; j = G[j].next)
            if(dcc[i] != dcc[G[j].to])
                deg[dcc[i]]++;
    int res = 0;
    for(int i = 0; i <= num; i++)
        if(deg[i] == 1) res++;
    printf("%d\n", (res + 1) / 2);
}
int main ()
{
    int a, b;
    while(~ scanf("%d%d", &n, &m))
    {
        init();
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d", &a, &b);
            add_edge(a, b);
            add_edge(b, a);
        }
        slove();
    }

    return 0;
}


你可能感兴趣的:(连通分量分解)