Union Find 并查集
2020-03-22 22:01 tonyniu8 阅读(94) 评论(0) 编辑 收藏 举报给定两个点判断他们是否相连。
1 package com.graph; 2 3 public class UnionFind { 4 private int[] id; // parent links 5 private int[] sz; // size of components for roots 6 private int count; // number of components 7 8 public UnionFind(int N) { 9 count = N; 10 for (int i = 0; i < N; i++) { 11 id[i] = i; 12 sz[i] = 1; 13 } 14 } 15 16 public int count() { 17 return count; 18 } 19 20 public int find(int p) { 21 // follow links to find a root. 22 while (p != id[p]) { 23 p = id[p]; 24 } 25 return p; 26 } 27 28 public void union(int p, int q) { 29 int i = find(p); 30 int j = find(q); 31 if (i == j) { 32 return; 33 } 34 // make smaller root point to larger one 35 if (sz[i] < sz[j]) { 36 id[i] = j; 37 sz[j] += sz[i]; 38 } else { 39 id[j] = i; 40 sz[i] += sz[j]; 41 } 42 count--; 43 } 44 45 }