문제링크
fun main() {
val bufferedReader = System.`in`.bufferedReader()
val bufferedWriter = System.out.bufferedWriter()
val (n, m) = bufferedReader.readLine().split(" ").map { it.toInt() }
val detectors = Array(n + 1) { false }
val parents = createParents(n)
bufferedReader.readLine()
.split(" ")
.map { it.toInt() }
.drop(1)
.forEach {
detectors[it] = true
}
val person = mutableListOf<Int>()
repeat(m) {
val parties = bufferedReader.readLine()
.split(" ")
.map { it.toInt() }
.drop(1)
person.add(parties[0])
for (i in 1 until parties.size) {
unionPeople(detectors, parents, parties[i - 1], parties[i])
}
}
var answer = 0
person.forEach {
if (!detectors[getParent(parents, it)]) answer++
}
bufferedWriter.write("$answer")
bufferedReader.close()
bufferedWriter.close()
}
fun createParents(n: Int): Array<Int> {
val array = Array(n + 1) { 0 }
for (i in 1 until n + 1) {
array[i] = i
}
return array
}
fun unionPeople(detectors: Array<Boolean>, peopleParent: Array<Int>, first: Int, second: Int) {
val a = getParent(peopleParent, first)
val b = getParent(peopleParent, second)
if (detectors[a]) {
peopleParent[b] = a
} else {
peopleParent[a] = b
}
}
fun getParent(peopleParent: Array<Int>, first: Int): Int {
if (peopleParent[first] == first) return first
peopleParent[first] = getParent(peopleParent, peopleParent[first])
return peopleParent[first]
}
주석 없는 코드를 만들기 위해 노력하는 개발자입니다.
혹시라도 의도가 분명하지 않아보이는 (이해가 되지 않는) 코드가 있으시다면 편하게 답변 달아주시면 정말 감사하겠습니다.