zoukankan      html  css  js  c++  java
  • 并查集-朋友圈

    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)); } }
  • 相关阅读:
    JDBC连接MySQL并且查询操作。
    struts
    KMP 剪花布条hdoj2087
    线段树---敌兵布阵hdoj 1166
    设计模式----观察者模式
    线段树--hdoj1754
    ZOJ 2283 Challenge of Wisdom
    SGU 134 Centroid
    UVA 1637 Double Patience
    HDU 4389 X mod f(x)
  • 原文地址:https://www.cnblogs.com/hfczgo/p/4862734.html
Copyright © 2011-2022 走看看