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().unpack() addTo this
- }
- }
- .prefix
- .let(::println)
- }
- fun testUnpack() {
- sequenceOf(
- "2[a]2[ab]" to "aaabab",
- "3[a]2[r2[t]]" to "aaarttrtt",
- "a2[aa3[b]]" to "aaabbbaabbb",
- "abacabaca" to "abacabaca",
- "2[abac]a" to "abacabaca",
- "3[aba]" to "abaabaaba",
- )
- .map {
- val sb = StringBuilder()
- it.first unPackTo sb
- it.first to (sb.toString() == it.second)
- }
- .forEach(::println)
- }
- fun String.unpack() = StringBuilder().also { this unPackTo it }.toString()
- infix fun String.unPackTo(collector: StringBuilder) {
- var i = 0
- while (i < length && !this[i].isDigit()) {
- collector.append(this[i])
- ++i
- }
- if (i == length) return
- val repeatCount = this[i].digitToInt()
- i += 2
- val start = i
- var openedBraces = 1
- while (openedBraces > 0) {
- when (this[i]) {
- '[' -> ++openedBraces
- ']' -> --openedBraces
- }
- ++i
- }
- repeat(repeatCount) {
- substring(start until i - 1) unPackTo collector
- }
- substring(i) unPackTo collector
- }
- infix fun String.addTo(root: Node) {
- var curNode = root
- for (ch in this) curNode = curNode.addVertex(ch)
- }
- 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 ""
- }
- 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