java kruskal 算法

public class kruskal {

    //并查集
//----------------------------------------------------------------------------------
    
    public void init(int[] ft,int n){
        for(int i=1;i<=n;i++)
            ft[i] = i;
    }
    
    
    //查找x元素所在的集合
    public int find(int[] ft,int key){    
        int r = key;
        while(ft[r]!=r){
            r = ft[r];
        }
        return r;
    }
    
    //查找x元素所在的集合,使用路径压缩,递归
    public int find1(int[] ft,int key){    
        if(key!=ft[key]){
            ft[key] = find1(ft,ft[key]);
        }
        return ft[key];
    }
    
    
    //查找x元素所在的集合,使用路径压缩,非递归
    public int find2(int[] ft,int key){
        int k=0,r=key,j=0;
        while(r!=ft[r])
            r = ft[r];
        k = key;
        while(k!=r){
            j = ft[k];
            ft[k] = r;
            k = j;
        }
        return r;    
    }
    
    
    public boolean same(int[] ft,int a,int b){
        return find1(ft,a)==find1(ft,b);        
    }
    
    public int union(int[] ft,int a,int b){
        int fa = find1(ft,a);
        int fb = find1(ft,b);
        
        if(fa!=fb){
            ft[fa] = fb;
        }
        return fb;
    }
    
//----------------------------------------------------------------------------------    
    public ArrayList<ANode> sortByEdge(ALGraph AG){
        //ALGraph 为图的邻接链表结构
        //ANode 为边结构,包含入度端、出度端、权值
        ArrayList<ANode> EdgeList = new ArrayList<ANode>();
        
        int n = AG.n;
        int[] visited = new int[n+1];
        
        for(int i=1;i<=n;i++){
            VNode v = AG.adjList[i];
            ANode e = v.firstArc;
            visited[i] = 1;
            while(e!=null){
                if(visited[e.adjVertex]==0){
                    EdgeList.add(e);
                    
                }
                e = e.nextArc;
            }
        }
        
        Collections.sort(EdgeList);
        
        return EdgeList;
    }
    
    public void getSpinningTree(ALGraph AG,ArrayList<ANode> EdgeList){
        int n = AG.n;
        int[] ft = new int[n+1];
        ANode e = null;
        int start,end;
        
        init(ft,n);
        
        
        for(int i=0;i<EdgeList.size();i++){
            e = EdgeList.get(i);
            start = e.sVertex;
            end = e.adjVertex;
            
            if(!same(ft,start,end)){    //如果不在同一个集合(连通子图),就相连,即把此边加入集合
                union(ft,start,end);
                System.out.println(start+"->"+end+"("+e.value+")");
            }  
            
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值