-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4cf6d37
commit 49d0a42
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |