Advertisement
vkazar

Untitled

Jan 10th, 2024
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.97 KB | None | 0 0
  1. package sprint8.fin.A
  2.  
  3. fun main() {
  4.     Node().apply {
  5.         repeat(readln().toInt()) {
  6.             readln().unpack() addTo this
  7.         }
  8.     }
  9.         .prefix
  10.         .let(::println)
  11. }
  12.  
  13. fun testUnpack() {
  14.     sequenceOf(
  15.         "2[a]2[ab]" to "aaabab",
  16.         "3[a]2[r2[t]]" to "aaarttrtt",
  17.         "a2[aa3[b]]" to "aaabbbaabbb",
  18.         "abacabaca" to "abacabaca",
  19.         "2[abac]a" to "abacabaca",
  20.         "3[aba]" to "abaabaaba",
  21.     )
  22.         .map {
  23.             val sb = StringBuilder()
  24.             it.first unPackTo sb
  25.             it.first to (sb.toString() == it.second)
  26.         }
  27.         .forEach(::println)
  28. }
  29.  
  30. fun String.unpack() = StringBuilder().also { this unPackTo it }.toString()
  31.  
  32. infix fun String.unPackTo(collector: StringBuilder) {
  33.     var i = 0
  34.     while (i < length && !this[i].isDigit()) {
  35.         collector.append(this[i])
  36.         ++i
  37.     }
  38.     if (i == length) return
  39.     val repeatCount = this[i].digitToInt()
  40.     i += 2
  41.     val start = i
  42.     var openedBraces = 1
  43.     while (openedBraces > 0) {
  44.         when (this[i]) {
  45.             '[' -> ++openedBraces
  46.             ']' -> --openedBraces
  47.         }
  48.         ++i
  49.     }
  50.     repeat(repeatCount) {
  51.         substring(start until i - 1) unPackTo collector
  52.     }
  53.     substring(i) unPackTo collector
  54. }
  55.  
  56. infix fun String.addTo(root: Node) {
  57.     var curNode = root
  58.     for (ch in this) curNode = curNode.addVertex(ch)
  59. }
  60.  
  61. class Node {
  62.     private val _vertices = mutableListOf<Vertex>()
  63.     val vertices: List<Vertex>
  64.         get() = _vertices
  65.  
  66.     fun addVertex(char: Char): Node =
  67.         (vertices.firstOrNull { it.char == char } ?: Vertex(char).also { _vertices.add(it) }).destination
  68.  
  69.     val prefix
  70.         get(): String =
  71.             if (vertices.size == 1)
  72.                 vertices.first().let { "${it.char}${it.destination.prefix}" }
  73.             else ""
  74. }
  75.  
  76. data class Vertex(val char: Char, val destination: Node) {
  77.     constructor(char: Char) : this(char, Node())
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement