首页 > 其他 > 详细

并查集-朋友圈

时间:2015-10-09 00:33:00      阅读:267      评论:0      收藏:0      [点我收藏+]
package com.child.controller;

public class Test {

    public static int[] set;
    //3.component identifier for 0~N-1
    public static int find(int x){
        int i,j;
        int r = x;//所属队营,向上一层查找,
        while(set[r] != r){
            r = set[r];
        }
        i = r;
        while(set[i] != r){
            j = set[i];
            set[i] = r;
            r = j;
        }
        return r;
        
    }
    public static void union(int p,int q){
        int t = find(p);    
        int h = find(q);
        if(t < h)    
        {  
            set[h] = t;    
        }  
        else    
        {  
            set[t] = h;    
        }  
    }
    public static int friends(int m,int[][] r){
        //1.初始化set集合
     //初始化时,每个元素所属阵营为自己
set = new int[m+1]; for(int i=1;i<=m;i++){ set[i] = i; } //2.add connection between q and p for(int i=0;i<r.length;i++){ union(r[i][0],r[i][1]); } int count = 0; for(int i = 1 ; i <= m ; ++i) { if(set[i] == i) { ++count; } } return count; } public static void main(String[] args) { // TODO Auto-generated method stub int n=5; int a[][]={{1,2},{2,3},{4,5},{2,4}}; System.out.println(friends(5,a)); } }

 

并查集-朋友圈

原文:http://www.cnblogs.com/hfczgo/p/4862734.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!