zoukankan      html  css  js  c++  java
  • [LintCode] Connecting Graph II

    Given n nodes in a graph labeled from 1 to n. There is no edges in the graph at beginning.

    You need to support the following method:
    1. connect(a, b), an edge to connect node a and node b
    2. query(a), Returns the number of connected component nodes which include node a.

    Example
    5 // n = 5
    query(1) return 1
    connect(1, 2)
    query(1) return 2
    connect(2, 4)
    query(1) return 3
    connect(1, 4)
    query(1) return 3



     1 class UnionFind {
     2     private int[] father = null;
     3     private int[] numsInUnion = null;
     4     
     5     public UnionFind(int n){
     6         father = new int[n];
     7         numsInUnion = new int[n];
     8         for(int i = 0; i < n; i++){
     9             father[i] = i;
    10             numsInUnion[i] = 1;
    11         }
    12     }
    13     public int find(int x){
    14         if(father[x] == x){
    15             return x;
    16         }
    17         return father[x] = find(father[x]);
    18     }
    19     public void connect(int a, int b){
    20         int root_a = find(a);
    21         int root_b = find(b);
    22         if(root_a != root_b){
    23             father[root_a] = root_b;
    24             numsInUnion[root_b] += numsInUnion[root_a];
    25         }
    26     }
    27     public int queryNumInUnion(int a){
    28         return numsInUnion[find(a)];
    29     }
    30 }
    31 public class ConnectingGraph2 {
    32     private UnionFind uf = null;
    33     public ConnectingGraph2(int n) {
    34         uf = new UnionFind(n);
    35     }
    36 
    37     public void connect(int a, int b) {
    38         uf.connect(a - 1, b - 1);
    39     }
    40         
    41     public int query(int a) {
    42         return uf.queryNumInUnion(a - 1);
    43     }
    44 }


  • 相关阅读:
    Android学习——SAX解析方式
    Android学习——pull解析方式
    Android学习——使用okhttp
    开课第十五周周总结
    顶会热词3
    顶会热词2
    顶会热词1
    配置JAVA环境
    配置mybaits的一些坑
    Maven配置和idea种tomcat配置的一些坑点
  • 原文地址:https://www.cnblogs.com/lz87/p/7500090.html
Copyright © 2011-2022 走看看