Skip to content

Commit

Permalink
32-SeongHoonC
Browse files Browse the repository at this point in the history
  • Loading branch information
SeongHoonC committed Jul 22, 2024
1 parent 4cf6d37 commit 49d0a42
Showing 1 changed file with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import java.io.BufferedReader
import java.io.InputStreamReader

private lateinit var br: BufferedReader
private lateinit var parents: Array<Int>

fun main() {
br = BufferedReader(InputStreamReader(System.`in`))
val (n, m) = br.readLine().split(" ").map { it.toInt() }
parents = Array(n + 1) { it }

repeat(m) {
val (command, a, b) = br.readLine().split(" ").map { it.toInt() }
if (command == 0) {
union(a, b)
} else {
println(if (findParents(a) == findParents(b)) "YES" else "NO")
}
}
}

private fun findParents(a: Int): Int {
var parent = parents[a]
while (parents[parent] != parent) {
parent = parents[parent]
}
parents[a] = parent
return parent
}

private fun union(a: Int, b: Int) {
val parentA = findParents(a)
val parentB = findParents(b)

if (parentA == parentB) {
return
}
if (parentA > parentB) {
parents[parentA] = parentB
return
}
parents[parentB] = parentA
}

0 comments on commit 49d0a42

Please sign in to comment.