class UnionFind(n: Int) { private val parent = IntArray(n) { -1 } private val rank = IntArray(n) private val size = IntArray(n) { 1 } private var numTree = n private val top = IntArray(n) { it } fun find(x: Int): Int { if (parent[x] == -1) { return x } else { parent[x] = find(parent[x]) return parent[x] } } fun isSame(x: Int, y: Int): Boolean { return find(x) == find(y) } fun getSize(): Int { return numTree } fun sizeOf(x: Int): Int { return size[find(x)] } fun rankOf(x: Int): Int { return rank[find(x)] } fun getTop(x: Int): Int { return top[find(x)] } fun unite(x: Int, y: Int) { val parentX = find(x) val parentY = find(y) if (parentX == parentY) { return } numTree-- if (sizeOf(parentX) < sizeOf(parentY)) { top[parentX] = top[parentY] } else if(sizeOf(parentX) > sizeOf(parentY)) { top[parentY] = top[parentX] } else if (parentX < parentY) { top[parentY] = top[parentX] } else { top[parentX] = top[parentY] } if (rank[parentX] < rank[parentY]) { parent[parentX] = parentY size[parentY] += size[parentX] } else { parent[parentY] = parentX size[parentX] += size[parentY] if (rank[parentX] == rank[parentY]) { rank[parentX]++ } } } } fun main() { val builder = StringBuilder() val (n, m) = readInputLine().split(" ").map { it.toInt() } val uf = UnionFind(n) repeat(m) { val (a, b) = readInputLine().split(" ").map { it.toInt() - 1 } uf.unite(a, b) } repeat(n) { builder.appendln(uf.getTop(it) + 1) } print(builder.toString()) } fun readInputLine(): String { return readLine()!! }