| 1 | class UnionFind(size: Int) { |
| 2 | |
| 3 | private val parent = IntArray(size) { it } |
| 4 | private val size = IntArray(size) { 1 } |
| 5 | |
| 6 | // With comment |
| 7 | fun union(x: Int, y: Int) { |
| 8 | val repX = find(x) |
| 9 | val repY = find(y) |
| 10 | if (repX != repY) { |
| 11 | // If 'repX' represents a larger community, connect |
| 12 | // 'repY 's community to it. |
| 13 | if (size[repX] > size[repY]) { |
| 14 | parent[repY] = repX |
| 15 | size[repX] += size[repY] |
| 16 | } else { |
| 17 | // Otherwise, connect 'repX's community to 'repY'. |
| 18 | parent[repX] = repY |
| 19 | size[repY] += size[repX] |
| 20 | } |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | fun find(x: Int): Int { |
| 25 | if (x == parent[x]) { |
| 26 | return x |
| 27 | } |
| 28 | // Path compression. |
| 29 | parent[x] = find(parent[x]) |
| 30 | return parent[x] |
| 31 | } |
| 32 | |
| 33 | fun getSize(x: Int): Int { |
| 34 | return size[find(x)] |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | class MergingCommunities(n: Int) { |
| 39 | |