Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sprint8.fin.A
- fun main() {
- Node().apply {
- repeat(readln().toInt()) {
- readln() unpackTo this
- }
- }
- .prefix
- .let(::println)
- }
- infix fun String.unpackTo(root: Node): Node {
- var curNode = root
- var i = 0
- while (i < length && !this[i].isDigit()) {
- curNode = curNode.addVertex(this[i])
- if (curNode.vertices.size > 1) return curNode
- ++i
- }
- if (i == length) return curNode
- val repeatCount = this[i].digitToInt()
- i += 2
- val start = i
- var openedBraces = 1
- while (openedBraces > 0) {
- when (this[i]) {
- '[' -> ++openedBraces
- ']' -> --openedBraces
- }
- ++i
- }
- repeat(repeatCount) {
- curNode = substring(start until i - 1) unpackTo curNode
- }
- curNode = substring(i) unpackTo curNode
- return curNode
- }
- class Node {
- private val _vertices = mutableListOf<Vertex>()
- val vertices: List<Vertex>
- get() = _vertices
- fun addVertex(char: Char): Node =
- (vertices.firstOrNull { it.char == char } ?: Vertex(char).also { _vertices.add(it) }).destination
- val prefix
- get(): String =
- if (vertices.size == 1)
- vertices.first().let { "${it.char}${it.destination.prefix}" }
- else ""
- override fun toString() = prefix
- }
- data class Vertex(val char: Char, val destination: Node) {
- constructor(char: Char) : this(char, Node())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement