并查集-朋友圈

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)); } }

 

posted @ 2015-10-09 00:05  hfczgo  阅读(193)  评论(0编辑  收藏  举报