无向图的桥

没有具体例图,就是直接找出哪些边是桥。

import java.util.Arrays;
import java.util.Scanner;

public class Main
{   
    static int SIZE=100010;
    static int head[]=new int[SIZE],to[]=new int[SIZE<<1],next[]=new int[SIZE<<1];
    static int cnt=0;
    static void addEdge(int x,int y)
    {
        to[cnt]=y;next[cnt]=head[x];head[x]=cnt++;
        to[cnt]=x;next[cnt]=head[y];head[y]=cnt++;
    }
    static int dfn[]=new int[SIZE],low[]=new int[SIZE];
    static int index;
    static boolean bridge[]=new boolean[SIZE<<1];
    static void tarjan(int x,int edge)
    {
        dfn[x]=low[x]=++index;
        for(int i=head[x];i>=0;i=next[i])
        {
            int y=to[i];
            if(dfn[y]==0)
            {
                tarjan(y,i);
                low[x]=Math.min(low[x], low[y]);
                if(dfn[x]<low[y])
                    bridge[i]=bridge[i^1]=true;
            }
            else
                if(i!=(edge^1))
                    low[x]=Math.min(low[x], dfn[y]);

        }
    }
    static void init()
    {
        Arrays.fill(head, -1);
        cnt=0;  
    }
    static int n,m;
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        m=sc.nextInt();
        init();
        for(int i=0;i<m;i++)
            addEdge(sc.nextInt(),sc.nextInt());

        for(int i=1;i<=n;i++)
            if(dfn[i]==0)
                tarjan(i,-1);
        for(int i=1;i<cnt;i+=2)
            if(bridge[i])
                System.out.println(to[i^1]+" "+to[i]);

    }
}
/*样例:
9 10
1 2
1 5
2 3
5 4
3 4
1 6
6 7
6 9
6 8
9 8
*/

猜你喜欢

转载自blog.csdn.net/coldfresh/article/details/80355458