|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +public class UnionFind { |
| 4 | + int[] parent; |
| 5 | + int[] size; |
| 6 | + |
| 7 | + public UnionFind(int size) { |
| 8 | + this.parent = new int[size]; |
| 9 | + this.size = new int[size]; |
| 10 | + for (int i = 0; i < size; i++) { |
| 11 | + this.parent[i] = i; |
| 12 | + } |
| 13 | + Arrays.fill(this.size, 1); |
| 14 | + } |
| 15 | + |
| 16 | + public void union(int x, int y) { |
| 17 | + int repX = find(x); |
| 18 | + int repY = find(y); |
| 19 | + // If 'repX' represents a larger community, connect |
| 20 | + // 'repY 's community to it. |
| 21 | + if (this.size[repX] > this.size[repY]) { |
| 22 | + this.parent[repY] = repX; |
| 23 | + this.size[repX] += this.size[repY]; |
| 24 | + } |
| 25 | + // Otherwise, connect 'rep_x's community to 'rep_y'. |
| 26 | + else { |
| 27 | + this.parent[repX] = repY; |
| 28 | + this.size[repY] += this.size[repX]; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + public int find(int x) { |
| 33 | + if (x == this.parent[x]) { |
| 34 | + return x; |
| 35 | + } |
| 36 | + // Path compression. |
| 37 | + this.parent[x] = find(this.parent[x]); |
| 38 | + return this.parent[x]; |
| 39 | + } |
| 40 | + |
| 41 | + public int getSize(int x) { |
| 42 | + return this.size[find(x)]; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +public class MergingCommunities { |
| 47 | + UnionFind uf; |
| 48 | + |
| 49 | + public MergingCommunities(int n) { |
| 50 | + this.uf = new UnionFind(n); |
| 51 | + } |
| 52 | + |
| 53 | + public void connect(int x, int y) { |
| 54 | + this.uf.union(x, y); |
| 55 | + } |
| 56 | + |
| 57 | + public int getCommunitySize(int x) { |
| 58 | + return this.uf.getSize(x); |
| 59 | + } |
| 60 | +} |
0 commit comments