Advertisement
vkazar

Untitled

Jan 10th, 2024
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.49 KB | None | 0 0
  1. package sprint8.fin.A
  2.  
  3. fun main() {
  4.     Node().apply {
  5.         repeat(readln().toInt()) {
  6.             readln() unpackTo this
  7.         }
  8.     }
  9.         .prefix
  10.         .let(::println)
  11. }
  12.  
  13. infix fun String.unpackTo(root: Node): Node {
  14.     var curNode = root
  15.     var i = 0
  16.     while (i < length && !this[i].isDigit()) {
  17.         curNode = curNode.addVertex(this[i])
  18.         if (curNode.vertices.size > 1) return curNode
  19.         ++i
  20.     }
  21.     if (i == length) return curNode
  22.     val repeatCount = this[i].digitToInt()
  23.     i += 2
  24.     val start = i
  25.     var openedBraces = 1
  26.     while (openedBraces > 0) {
  27.         when (this[i]) {
  28.             '[' -> ++openedBraces
  29.             ']' -> --openedBraces
  30.         }
  31.         ++i
  32.     }
  33.     repeat(repeatCount) {
  34.         curNode = substring(start until i - 1) unpackTo curNode
  35.     }
  36.     curNode = substring(i) unpackTo curNode
  37.     return curNode
  38. }
  39.  
  40. class Node {
  41.     private val _vertices = mutableListOf<Vertex>()
  42.     val vertices: List<Vertex>
  43.         get() = _vertices
  44.  
  45.     fun addVertex(char: Char): Node =
  46.         (vertices.firstOrNull { it.char == char } ?: Vertex(char).also { _vertices.add(it) }).destination
  47.  
  48.     val prefix
  49.         get(): String =
  50.             if (vertices.size == 1)
  51.                 vertices.first().let { "${it.char}${it.destination.prefix}" }
  52.             else ""
  53.  
  54.     override fun toString() = prefix
  55. }
  56.  
  57. data class Vertex(val char: Char, val destination: Node) {
  58.     constructor(char: Char) : this(char, Node())
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement