상세 컨텐츠

본문 제목

Baekjoon(Kotlin) - 14725. 개미굴

Problems(Kotlin)/Baekjoon

by KDLiam 2023. 9. 14. 15:17

본문

URL : https://www.acmicpc.net/problem/14725

 

14725번: 개미굴

첫 번째 줄은 로봇 개미가 각 층을 따라 내려오면서 알게 된 먹이의 정보 개수 N (1 ≤ N ≤ 1000)개가 주어진다. 두 번째 줄부터 N+1 번째 줄까지, 각 줄의 시작은 로봇 개미 한마리가 보내준 먹이 정

www.acmicpc.net

 

[ RESULT ]

import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter

val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))

class TrieNode {
    val children = mutableMapOf<String, TrieNode>()
    var isEndOfWord = false
}

fun insert(root: TrieNode, words: List<String>) {
    var node = root
    for (word in words) {
        node = node.children.getOrPut(word) { TrieNode() }
        node.isEndOfWord = true
    }
}

fun printAntHill(root: TrieNode, depth: Int = 0) {
    val sortedKeys = root.children.keys.sorted()
    for (key in sortedKeys) {
        val node = root.children[key]!!
        repeat(depth) { bw.write("--") }
        bw.write("$key\n")
        printAntHill(node, depth + 1)
    }
}

fun main() {

    val root = TrieNode()

    val N = br.readLine()!!.toInt()

    for (i in 0 until N) {
        val input = br.readLine()!!.split(" ").drop(1)
        insert(root, input)
    }

    printAntHill(root)

    br.close()
    bw.flush()
    bw.close()
}

 

아무리 생각해도 풀이하기가 너무 어려워서 어려 블로그를 보고, 자료구조인 "트라이"를 공부하고 이를 적용시켰다.

관련글 더보기