• [LintCode] Connecting Graph III


    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(), Returns the number of connected component in the graph

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


     1 class UnionFind {
     2     private int[] father = null;
     3     private int count = 0;
     4     public UnionFind(int n){
     5         father = new int[n];
     6         count = n;
     7         for(int i = 0; i < n; i++){
     8             father[i] = i;
     9         }
    10     }
    11     public int find(int x){
    12         if(father[x] == x){
    13             return x;
    14         }
    15         return father[x] = find(father[x]);
    16     }
    17     public void connect(int a, int b){
    18         int root_a = find(a);
    19         int root_b = find(b);
    20         if(root_a != root_b){
    21             father[root_a] = root_b;
    22             count--;
    23         }
    24     }
    25     public int queryUnionCount(){
    26         return count;
    27     }
    28 }
    29 public class ConnectingGraph3 {
    30     private UnionFind uf = null;
    31     public ConnectingGraph3(int n) {
    32         uf = new UnionFind(n);        
    33     }
    34 
    35     public void connect(int a, int b) {
    36         uf.connect(a - 1, b - 1);
    37     }
    38         
    39     public int query() {
    40         return uf.queryUnionCount();
    41     }
    42 }
     
  • 相关阅读:
    开放API接口安全处理!
    ant笔记
    并发调试
    IDEA 设置(中文乱码、svn、热部署、ideolog 、Jrebel )
    win10家庭版升级专业版
    org.json package
    'root'@'localhost'不能登录问题
    javascript之DOM选择符
    javascript之DOM(四其他类型)
    javascript之DOM(三Element类型)
  • 原文地址:https://www.cnblogs.com/lz87/p/7500089.html
Copyright © 2020-2023  润新知