不相交集
1 public class DisjoinSet 2 { 3 4 public static void main(String[] args) 5 { 6 DisjoinSet disjoin = new DisjoinSet(8); 7 8 disjoin.union(4, 3); 9 disjoin.union(5, 4); 10 disjoin.union(6, 5); 11 disjoin.union(7, 6); 12 disjoin.union(8, 7); 13 14 int c = disjoin.find(3); 15 disjoin.display(); 16 } 17 18 19 private int n; 20 21 private int[] parents; 22 23 private int[] rank; 24 25 26 public DisjoinSet(int n) 27 { 28 this.n = n; 29 init(); 30 } 31 32 private void init() 33 { 34 parents = new int[n + 1]; 35 rank = new int[n + 1]; 36 37 for (int i = 1; i <= n; i++) { 38 parents[i] = i; 39 rank[i] = i; 40 } 41 } 42 43 public int find(int x) 44 { 45 int parent = x; 46 while (parent != parents[parent]) { 47 parent = parents[parent]; 48 } 49 50 disjoin(x, parent); 51 return parent; 52 } 53 54 private void disjoin(int x, int parent) 55 { 56 int temp; 57 while (x != parent) { 58 temp = parents[x]; 59 parents[x] = parent; 60 x = temp; 61 } 62 } 63 64 public void union(int a, int b) 65 { 66 int compare = compare(rank[a], rank[b]); 67 if (compare == 1) { 68 parents[b] = a; 69 } 70 else { 71 parents[a] = b; 72 } 73 } 74 75 private int compare(int a, int b) 76 { 77 return a > b ? 1 : a < b ? -1 : 0; 78 } 79 80 public void display() 81 { 82 for (int i : rank) { 83 System.out.print(" " + i + " "); 84 } 85 86 System.out.println(); 87 88 for (int i : parents) { 89 System.out.print(" " + i + " "); 90 } 91 } 92 }