@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")
@file:OptIn(ExperimentalUnsignedTypes::class, ExperimentalStdlibApi::class)

import java.io.PrintWriter
import java.math.BigInteger
import kotlin.math.*
import kotlin.random.Random
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
//    val startTime = System.nanoTime()

    val numCases = 1//readInt()
    case@ for(case in 1..numCases) {
//        print("Case #$case: ")

        val n = read().toBigInteger()

        val ones = Array(51) { one }
        for(i in 1..ones.lastIndex) ones[i] = (ones[i-1] * ten).inc()

        val heap = DijkHeap()
        heap.promote(n, 0)

        val ans = run ans@ {
            while(heap.isNotFinished()) {
                val x = heap.remove()
                val c = heap.cost(x)

                if(x == BigInteger.ZERO) return@ans c

                val i = ones.bsIndexOfLast { it <= x }
                heap.promote(x - ones[i], c + i + 1)
                heap.promote(ones[i+1] - x, c + i + 2)
            }

            -1
        }

        println(ans)
    }

//    iprintln("Time: ${(System.nanoTime() - startTime) / 1000000} ms")
}

val one = BigInteger.ONE
val ten = BigInteger.TEN!!

fun splitmix64(seed: Long): Long {
    var x = seed // * -7046029254386353131
    x = (x xor (x ushr 30)) * -4658895280553007687
    x = (x xor (x ushr 27)) * -7723592293110705685
    return (x xor (x ushr 31))
}
@JvmField val nonce64 = random.nextLong()
@JvmField val gamma64 = random.nextLong() or 1
fun Long.hash() = splitmix64((nonce64 xor this) * gamma64)

fun BigInteger.hash(): Long = toByteArray().asUByteArray().run {
    var res = size.toLong()
    for(i in indices) {
        if(i and 7 == 0) res = res.hash()
        res = res xor get(i).toLong().shl(i.and(7) * 8)
    }

    return res//.hash()
}

inline fun bsFirst(first: Int, last: Int, predicate: (Int) -> Boolean): Int {
    var low = first
    var high = last

    while (low <= high) {
        val mid = low.and(high) + low.xor(high).shr(1)
        if(predicate(mid)) high = mid - 1
        else low = mid + 1
    }
    return low
}
inline fun IntRange.bsFirst(predicate: (Int) -> Boolean) = bsFirst(first, last, predicate)

inline fun bsLast(first: Int, last: Int, predicate: (Int) -> Boolean) = bsFirst(first, last) { !predicate(it) } - 1
inline fun IntRange.bsLast(predicate: (Int) -> Boolean) = bsLast(first, last, predicate)

inline fun <T> Array<T>.bsIndexOfFirst(predicate: (T) -> Boolean) = bsFirst(0, lastIndex) { predicate(get(it)) }
inline fun <T> Array<T>.bsFirst(predicate: (T) -> Boolean) = get(bsIndexOfFirst(predicate))
inline fun <T> Array<T>.bsFirstOrNull(predicate: (T) -> Boolean) = getOrNull(bsIndexOfFirst(predicate))
inline fun <T> Array<T>.bsIndexOfLast(predicate: (T) -> Boolean) = bsLast(0, lastIndex) { predicate(get(it)) }
inline fun <T> Array<T>.bsLast(predicate: (T) -> Boolean) = get(bsIndexOfLast(predicate))
inline fun <T> Array<T>.bsLastOrNull(predicate: (T) -> Boolean) = getOrNull(bsIndexOfLast(predicate))

const val inf = Int.MAX_VALUE
class DijkHeap {
    val h = intListOf(-1)
    val pos = IntList()
    val cost = IntList()
    val map = LongIntMap(nullValue = -1)
    val keys = mutableListOf<BigInteger>()

    val inHeap get() = h.lastIndex

    private fun swap(i: Int, j: Int) {
        val hi = h[i]; val hj = h[j]
        h[j] = hi; h[i] = hj
        pos[hi] = j; pos[hj] = i
    }

    fun promote(key0: BigInteger, newCost: Int): Boolean {
        val key = run {
            val hash = key0.hash()
            map[hash].let { if(it != -1) return@run it }
            keys.size.also {
                map[hash] = it
                keys.add(key0)
                h.add(it)
                pos.add(inHeap)
                cost.add(inf)
            }
        }
        if(newCost >= cost[key]) return false
        var i = pos[key]

        while(i > 1) {
            val par = i shr 1
            if (newCost >= cost[h[par]]) break
            swap(i, par)
            i = par
        }

        cost[key] = newCost
        return true
    }

    val head get() = h[1]
    fun isNotFinished() = inHeap > 0

    fun remove() = head.let { hd ->
        swap(1, inHeap)
        pos[hd] = -1
        h.pop()

        var i = 1
        while(true) {
            val l = i shl 1
            if(l > inHeap) break
            val r = l or 1

            var best = l
            var p = cost[h[l]]
            if(r <= inHeap) {
                val pr = cost[h[r]]
                if(pr < p) {
                    best = r
                    p = pr
                }
            }

            if(cost[h[i]] <= p) break

            swap(i, best)
            i = best
        }

        keys[hd]
    }

    fun cost(key: BigInteger): Int {
        val hash = key.hash()
        val i = map[hash]
        return if(i == -1) inf else cost[i]
    }
}

class IntList(initialCapacity: Int = 12) {
    private var arr = IntArray(initialCapacity)
    val _arr get() = arr
    private val capacity get() = arr.size
    var size = 0
        private set
    inline val lastIndex get() = size - 1
    inline val indices get() = 0 until size

    constructor(copyFrom: IntArray): this(copyFrom.size) { copyFrom.copyInto(arr); size = copyFrom.size }
    constructor(copyFrom: Collection<Int>): this(copyFrom.size) { arr = copyFrom.toIntArray(); size = copyFrom.size }

    fun contentEquals(other: IntList): Boolean {
        return this === other || size == other.size && indices.all { this[it] == other[it] }
    }

    private fun grow(minCapacity: Int = 8) {
        val newCapacity = maxOf(minCapacity, capacity + (capacity shr 1))
        arr = arr.copyOf(newCapacity)
    }

    fun ensureCapacity(minCapacity: Int) { if(capacity < minCapacity) grow(minCapacity) }

    operator fun get(index: Int): Int {
        require(index in 0 until size)
        return arr[index]
    }

    operator fun set(index: Int, value: Int) {
        require(index in 0 until size)
        arr[index] = value
    }

    fun add(value: Int) {
        if(size == capacity) grow()
        arr[size++] = value
    }

    fun addAll(list: IntList) {
        ensureCapacity(size + list.size)
        list.arr.copyInto(arr, size, 0, list.size)
        size += list.size
    }

    fun add(index: Int, element: Int) {
        if(size == capacity) grow()
        arr.copyInto(arr, index + 1, index, size)
        size++
        set(index, element)
    }

    fun clear() { size = 0 }

    fun removeAt(index: Int): Int {
        val e = get(index)
        arr.copyInto(arr, index, index + 1, size)
        size--
        return e
    }

    fun indexOf(e: Int): Int {
        for(i in 0 until size) if(this[i] == e) return i
        return -1
    }

    fun remove(e: Int): Boolean {
        val i = indexOf(e)
        if(i == -1) return false
        removeAt(i)
        return true
    }

    operator fun iterator() = object: IntIterator() {
        private var pos = 0
        override fun hasNext() = pos < size
        override fun nextInt() = get(pos++)
    }

    inline fun isEmpty() = size == 0
    inline fun isNotEmpty() = size != 0

    fun pop() = arr[--size]

    fun popToSize(s: Int) {
        require(s >= 0)
        if(s < size) size = s
    }

    fun swap(i: Int, j: Int) { val t = this[i]; this[i] = this[j]; this[j] = t }
    fun reverse() {
        for(i in 0 until size / 2) swap(i, lastIndex - i)
    }

    fun shuffle(rnd: Random = random) { for(i in lastIndex downTo 1) swap(i, rnd.nextInt(i+1)) }

    inline fun sortWith(cmp: (Int, Int) -> Int) { _mergeSort(_arr, size, IntArray(size), IntArray::get, IntArray::set, cmp) }
    inline fun <T: Comparable<T>> sortBy(func: (Int) -> T) { sortWith { a, b -> func(a).compareTo(func(b)) } }
    inline fun <T: Comparable<T>> sortByDescending(func: (Int) -> T) { sortWith { a, b -> func(b).compareTo(func(a)) } }
    fun sort() { sortBy { it } }
    fun sortDescending() { sortByDescending { it } }

    fun joinToString(separator: CharSequence) = if(size == 0) "" else let {
        buildString {
            append(it[0])
            for (i in 1 until size) {
                append(separator).append(it[i])
            }
        }
    }

    override fun toString() = "[" + joinToString(", ") + "]"

    fun toIntArray() = arr.copyOf(size)
    fun toList() = List(size, ::get)

    inline fun first() = get(0)
    inline fun last() = get(lastIndex)
}

inline fun IntList(size: Int, init: (Int) -> Int) = IntList(size).apply {
    for(i in 0 until size) { add(init(i)) }
}
inline fun IntArray.toIntList() = IntList(this)
inline fun Collection<Int>.toIntList() = IntList(this)
inline fun intListOf(vararg values: Int) = IntList(values)

fun IntList.max() = (1 until size).fold(this[0]) { acc, i -> max(acc, this[i]) }
fun IntList.min() = (1 until size).fold(this[0]) { acc, i -> min(acc, this[i]) }
fun IntList.getOrNull(i: Int) = if(i in indices) get(i) else null
inline fun IntList.count(predicate: (Int) -> Boolean) = indices.count { predicate(this[it]) }
fun IntList.copyOf() = IntList(size, ::get)

typealias LongIntMap = _Ez_Long__Int_HashMap
inline operator fun LongIntMap.set(key: Long, value: Int) { put(key, value) }
inline operator fun LongIntMap.contains(key: Long) = containsKey(key)

class _Ez_Long__Int_HashMap(capacity: Int = DEFAULT_CAPACITY, val nullValue: Int = 0) :
    _Ez_Long__Int_Map {
    companion object {
        private const val DEFAULT_CAPACITY = 8
        // There are three invariants for size, removedCount and arraysLength:
// 1. size + removedCount <= 1/2 arraysLength
// 2. size > 1/8 arraysLength
// 3. size >= removedCount
// arraysLength can be only multiplied by 2 and divided by 2.
// Also, if it becomes >= 32, it can't become less anymore.
        private const val REBUILD_LENGTH_THRESHOLD = 32
        private const val HASHCODE_INITIAL_VALUE = -0x7ee3623b
        private const val HASHCODE_MULTIPLIER = 0x01000193
        private const val FREE: Byte = 0
        private const val REMOVED: Byte = 1
        private const val FILLED: Byte = 2
        private val hashSeed = random.nextLong()
        private val gamma = random.nextLong() or 1
    }

    private lateinit   var keys: LongArray
    private lateinit   var values: IntArray
    private lateinit var status: ByteArray
    override var size = 0
        private set
    private var removedCount = 0
    private var mask = 0

    constructor(map: _Ez_Long__Int_Map) : this(map.size) {
        val it = map.iterator()
        while (it.hasNext()) {
            put(it.key, it.value)
            it.next()
        }
    }

    constructor(javaMap: Map<Long, Int>) : this(javaMap.size) {
        for ((key, value) in javaMap) {
            put(key, value)
        }
    }

    private fun getStartPos(h: Long): Int {
        var x = (h xor hashSeed) * gamma
        x = (x xor (x ushr 30)) * -4658895280553007687
        x = (x xor (x ushr 27)) * -7723592293110705685
        return (x xor (x ushr 31)).toInt() and mask
    }

    override fun isEmpty(): Boolean = size == 0

    override fun containsKey(
        key: Long
    ): Boolean {
        var pos = getStartPos(key)
        while (status[pos] != FREE) {
            if (status[pos] == FILLED && keys[pos] == key) {
                return true
            }
            pos = pos + 1 and mask
        }
        return false
    }

    override fun  get(
        key: Long
    ): Int {
        var pos = getStartPos(key)
        while (status[pos] != FREE) {
            if (status[pos] == FILLED && keys[pos] == key) {
                return values[pos]
            }
            pos = pos + 1 and mask
        }
        return nullValue
    }

    override fun  put(
        key: Long,
        value: Int
    ): Int {
        var pos = getStartPos(key)
        while (status[pos] == FILLED) {
            if (keys[pos] == key) {
                val   oldValue = values[pos]
                values[pos] = value
                return oldValue
            }
            pos = pos + 1 and mask
        }
        if (status[pos] == FREE) {
            status[pos] = FILLED
            keys[pos] = key
            values[pos] = value
            size++
            if ((size + removedCount) * 2 > keys.size) {
                rebuild(keys.size * 2) // enlarge the table
            }
            return nullValue
        }
        val removedPos = pos
        pos = pos + 1 and mask
        while (status[pos] != FREE) {
            if (status[pos] == FILLED && keys[pos] == key) {
                val   oldValue = values[pos]
                values[pos] = value
                return oldValue
            }
            pos = pos + 1 and mask
        }
        status[removedPos] = FILLED
        keys[removedPos] = key
        values[removedPos] = value
        size++
        removedCount--
        return nullValue
    }

    override fun  remove(
        key: Long
    ): Int {
        var pos = getStartPos(key)
        while (status[pos] != FREE) {
            if (status[pos] == FILLED && keys[pos] == key) {
                val   removedValue = values[pos]
                status[pos] = REMOVED
                size--
                removedCount++
                if (keys.size > REBUILD_LENGTH_THRESHOLD) {
                    if (8 * size <= keys.size) {
                        rebuild(keys.size / 2) // compress the table
                    } else if (size < removedCount) {
                        rebuild(keys.size) // just rebuild the table
                    }
                }
                return removedValue
            }
            pos = pos + 1 and mask
        }
        return nullValue
    }

    override fun clear() {
        if (keys.size > REBUILD_LENGTH_THRESHOLD) {
            initEmptyTable(REBUILD_LENGTH_THRESHOLD)
        } else {
            status.fill(FREE)
            size = 0
            removedCount = 0
        }
    }

    override fun keys(): LongArray {
        val result = LongArray(size)
        var i = 0
        var j = 0
        while (i < keys.size) {
            if (status[i] == FILLED) {
                result[j++] = keys[i]
            }
            i++
        }
        return result
    }

    override fun values(): IntArray {
        val result = IntArray(size)
        var i = 0
        var j = 0
        while (i < values.size) {
            if (status[i] == FILLED) {
                result[j++] = values[i]
            }
            i++
        }
        return result
    }

    override fun iterator(): _Ez_Long__Int_MapIterator {
        return _Ez_Long__Int_HashMapIterator()
    }

    private fun rebuild(newLength: Int) {
        val oldKeys = keys

        val oldValues = values
        val oldStatus = status
        initEmptyTable(newLength)
        for (i in oldKeys.indices) {
            if (oldStatus[i] == FILLED) {
                put(oldKeys[i], oldValues[i])
            }
        }
    }

    private fun initEmptyTable(length: Int) {
        keys = LongArray(length)
        values = IntArray(length)
        status = ByteArray(length)
        size = 0
        removedCount = 0
        mask = length - 1
    }

    fun contentEquals(that: _Ez_Long__Int_HashMap): Boolean {
        if (size != that.size) {
            return false
        }
        for (i in keys.indices) {
            if (status[i] == FILLED) {
                val   thatValue = that[keys[i]]
                if (thatValue != values[i]) {
                    return false
                }
            }
        }
        return true
    }

    override fun toString(): String {
        val sb = StringBuilder()
        sb.append('{')
        for (i in keys.indices) {
            if (status[i] == FILLED) {
                if (sb.length > 1) {
                    sb.append(", ")
                }
                sb.append(keys[i])
                sb.append('=')
                sb.append(values[i])
            }
        }
        sb.append('}')
        return sb.toString()
    }

    private inner class _Ez_Long__Int_HashMapIterator : _Ez_Long__Int_MapIterator {
        private var curIndex = 0
        override fun hasNext(): Boolean {
            return curIndex < status.size
        }

        override val key: Long

            get() {
                if (curIndex == keys.size) {
                    throw NoSuchElementException("Iterator doesn't have more entries")
                }
                return keys[curIndex]
            }

        override val value: Int

            get() {
                if (curIndex == values.size) {
                    throw NoSuchElementException("Iterator doesn't have more entries")
                }
                return values[curIndex]
            }

        override fun next() {
            if (curIndex == status.size) {
                return
            }
            curIndex++
            while (curIndex < status.size && status[curIndex] != FILLED) {
                curIndex++
            }
        }

        init {
            while (curIndex < status.size && status[curIndex] != FILLED) {
                curIndex++
            }
        }
    }

    init {
        require(capacity >= 0) { "Capacity must be non-negative" }
        val length = Integer.highestOneBit(4 * max(1, capacity) - 1)
        // Length is a power of 2 now
        initEmptyTable(length)
    }
}

interface _Ez_Long__Int_Map {

    val size: Int

    fun isEmpty(): Boolean

    fun containsKey(
        key: Long
    ): Boolean

    operator fun  get(
        key: Long
    ): Int

    fun  put(
        key: Long,
        value: Int
    ): Int

    fun  remove(
        key: Long
    ): Int

    fun clear()

    fun keys(): LongArray

    fun values(): IntArray

    operator fun iterator(): _Ez_Long__Int_MapIterator

    override fun toString(): String
}

interface _Ez_Long__Int_MapIterator {
    operator fun hasNext(): Boolean

    val key: Long

    val value: Int

    operator fun next()
}

inline fun LongIntMap.forEach(act: (key: Long, value: Int) -> Unit) {
    val ite = iterator()
    while(ite.hasNext()) {
        act(ite.key, ite.value)
        ite.next()
    }
}

/** IO */
//@JvmField val ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null
//const val PATH = "src/main/resources/"
//@JvmField val INPUT = File(PATH + "input.txt").inputStream()
//@JvmField val OUTPUT = File(PATH + "output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

const val _BUFFER_SIZE = 1 shl 16
@JvmField val _buffer = ByteArray(_BUFFER_SIZE)
@JvmField var _bufferPt = 0
@JvmField var _bytesRead = 0

tailrec fun readChar(): Char {
    if(_bufferPt == _bytesRead) {
        _bufferPt = 0
        _bytesRead = INPUT.read(_buffer, 0, _BUFFER_SIZE)
    }
    return if(_bytesRead < 0) Char.MIN_VALUE
    else {
        val c = _buffer[_bufferPt++].toChar()
        if (c == '\r') readChar() else c
    }
}

/** @param skipNext Whether to skip the next character (usually whitespace), defaults to true */
fun readCharArray(n: Int, skipNext: Boolean = true): CharArray {
    val res = CharArray(n) { readChar() }
    if(skipNext) readChar()
    return res
}

fun readLine(): String? {
    var c = readChar()
    return if(c == Char.MIN_VALUE) null
    else buildString {
        while(c != '\n' && c != Char.MIN_VALUE) {
            append(c)
            c = readChar()
        }
    }
}
fun readLn() = readLine()!!

fun read() = buildString {
    var c = readChar()
    while(c <= ' ') {
        if(c == Char.MIN_VALUE) return@buildString
        c = readChar()
    }
    do {
        append(c)
        c = readChar()
    } while(c > ' ')
}
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)

/**  sort overrides to avoid quicksort attacks */

@JvmField var _random: Random? = null
val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it }

inline fun <A, T> _mergeSort(a0: A, n: Int, tmp0: A, get: A.(Int) -> T, set: A.(Int, T) -> Unit, cmp: (T, T) -> Int) {
    var a = a0
    var tmp = tmp0
    var len = 1
    while(len < n) {
        var l = 0
        while(true) {
            val m = l + len
            if(m >= n) break
            val r = min(n, m + len)
            var i = l
            var j = m
            for(k in l until r) {
                if(i != m && (j == r || cmp(a.get(i), a.get(j)) <= 0)) {
                    tmp.set(k, a.get(i++))
                } else tmp.set(k, a.get(j++))
            }
            l = r
        }
        for(i in l until n) tmp.set(i, a.get(i))
        val t = a; a = tmp; tmp = t
        len += len
    }
    if(a !== a0) for(i in 0 until n) a0.set(i, tmp0.get(i))
}

inline fun IntArray.sortWith(cmp: (Int, Int) -> Int) { _mergeSort(this, size, IntArray(size), IntArray::get, IntArray::set, cmp) }
inline fun <T: Comparable<T>> IntArray.sortBy(func: (Int) -> T) { sortWith { a, b -> func(a).compareTo(func(b)) } }
inline fun <T: Comparable<T>> IntArray.sortByDescending(func: (Int) -> T) { sortWith { a, b -> func(b).compareTo(func(a)) } }
fun IntArray.sort() { sortBy { it } }
fun IntArray.sortDescending() { sortByDescending { it } }

inline fun LongArray.sortWith(cmp: (Long, Long) -> Int) { _mergeSort(this, size, LongArray(size), LongArray::get, LongArray::set, cmp) }
inline fun <T: Comparable<T>> LongArray.sortBy(func: (Long) -> T) { sortWith { a, b -> func(a).compareTo(func(b)) } }
inline fun <T: Comparable<T>> LongArray.sortByDescending(func: (Long) -> T) { sortWith { a, b -> func(b).compareTo(func(a)) } }
fun LongArray.sort() { sortBy { it } }
fun LongArray.sortDescending() { sortByDescending { it } }

inline fun DoubleArray.sortWith(cmp: (Double, Double) -> Int) { _mergeSort(this, size, DoubleArray(size), DoubleArray::get, DoubleArray::set, cmp) }
inline fun <T: Comparable<T>> DoubleArray.sortBy(func: (Double) -> T) { sortWith { a, b -> func(a).compareTo(func(b)) } }
inline fun <T: Comparable<T>> DoubleArray.sortByDescending(func: (Double) -> T) { sortWith { a, b -> func(b).compareTo(func(a)) } }
fun DoubleArray.sort() { sortBy { it } }
fun DoubleArray.sortDescending() { sortByDescending { it } }

inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T : Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T : Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T : Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T : Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()

// import preserving junk function
@Suppress("NonAsciiCharacters") fun 雪花飄飄北風嘯嘯天地一片蒼茫() { iprintln(max(1, 2)) }

fun IntArray.sumLong() = sumOf { it.toLong() }

fun IntArray.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun IntArray.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }
fun LongArray.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun LongArray.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }
fun DoubleArray.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun DoubleArray.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }
fun <T: Comparable<T>> Array<T>.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun <T: Comparable<T>> Array<T>.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }
fun <T: Comparable<T>> List<T>.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun <T: Comparable<T>> List<T>.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }

// max/min Kotlin 1.6 -> 1.4 shim
fun IntArray.max() = maxOf { it }
fun IntArray.min() = minOf { it }
fun LongArray.max() = maxOf { it }
fun LongArray.min() = minOf { it }
fun CharArray.max() = maxOf { it }
fun CharArray.min() = minOf { it }
fun <T : Comparable<T>> Iterable<T>.max() = maxOf { it }
fun <T : Comparable<T>> Iterable<T>.min() = minOf { it }
fun <T : Comparable<T>> Sequence<T>.max() = maxOf { it }
fun <T : Comparable<T>> Sequence<T>.min() = minOf { it }


@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")
@file:OptIn(ExperimentalUnsignedTypes::class, ExperimentalStdlibApi::class)

import java.io.PrintWriter
import java.math.BigInteger
import kotlin.math.*
import kotlin.random.Random
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
//    val startTime = System.nanoTime()

    val numCases = 1//readInt()
    case@ for(case in 1..numCases) {
//        print("Case #$case: ")

        val n = read().toBigInteger()

        val ones = Array(51) { one }
        for(i in 1..ones.lastIndex) ones[i] = (ones[i-1] * ten).inc()

        val heap = DijkHeap()
        heap.promote(n, 0)

        val ans = run ans@ {
            while(heap.isNotFinished()) {
                val x = heap.remove()
                val c = heap.cost(x)

                if(x == BigInteger.ZERO) return@ans c

                val i = ones.bsIndexOfLast { it <= x }
                heap.promote(x - ones[i], c + i + 1)
                heap.promote(ones[i+1] - x, c + i + 2)
            }

            -1
        }

        println(ans)
    }

//    iprintln("Time: ${(System.nanoTime() - startTime) / 1000000} ms")
}

val one = BigInteger.ONE
val ten = BigInteger.TEN!!

fun splitmix64(seed: Long): Long {
    var x = seed // * -7046029254386353131
    x = (x xor (x ushr 30)) * -4658895280553007687
    x = (x xor (x ushr 27)) * -7723592293110705685
    return (x xor (x ushr 31))
}
@JvmField val nonce64 = random.nextLong()
@JvmField val gamma64 = random.nextLong() or 1
fun Long.hash() = splitmix64((nonce64 xor this) * gamma64)

fun BigInteger.hash(): Long = toByteArray().run {
    var res = size.toLong()
    for(i in indices) {
        if(i and 7 == 0) res = res.hash()
        res = res xor get(i).toLong().shl(i.and(7) * 8)
    }

    return res//.hash()
}

inline fun bsFirst(first: Int, last: Int, predicate: (Int) -> Boolean): Int {
    var low = first
    var high = last

    while (low <= high) {
        val mid = low.and(high) + low.xor(high).shr(1)
        if(predicate(mid)) high = mid - 1
        else low = mid + 1
    }
    return low
}
inline fun IntRange.bsFirst(predicate: (Int) -> Boolean) = bsFirst(first, last, predicate)

inline fun bsLast(first: Int, last: Int, predicate: (Int) -> Boolean) = bsFirst(first, last) { !predicate(it) } - 1
inline fun IntRange.bsLast(predicate: (Int) -> Boolean) = bsLast(first, last, predicate)

inline fun <T> Array<T>.bsIndexOfFirst(predicate: (T) -> Boolean) = bsFirst(0, lastIndex) { predicate(get(it)) }
inline fun <T> Array<T>.bsFirst(predicate: (T) -> Boolean) = get(bsIndexOfFirst(predicate))
inline fun <T> Array<T>.bsFirstOrNull(predicate: (T) -> Boolean) = getOrNull(bsIndexOfFirst(predicate))
inline fun <T> Array<T>.bsIndexOfLast(predicate: (T) -> Boolean) = bsLast(0, lastIndex) { predicate(get(it)) }
inline fun <T> Array<T>.bsLast(predicate: (T) -> Boolean) = get(bsIndexOfLast(predicate))
inline fun <T> Array<T>.bsLastOrNull(predicate: (T) -> Boolean) = getOrNull(bsIndexOfLast(predicate))

const val inf = Int.MAX_VALUE
class DijkHeap {
    val h = intListOf(-1)
    val pos = IntList()
    val cost = IntList()
    val map = LongIntMap(nullValue = -1)
    val keys = mutableListOf<BigInteger>()

    val inHeap get() = h.lastIndex

    private fun swap(i: Int, j: Int) {
        val hi = h[i]; val hj = h[j]
        h[j] = hi; h[i] = hj
        pos[hi] = j; pos[hj] = i
    }

    fun promote(key0: BigInteger, newCost: Int): Boolean {
        val key = run {
            val hash = key0.hash()
            map[hash].let { if(it != -1) return@run it }
            keys.size.also {
                map[hash] = it
                keys.add(key0)
                h.add(it)
                pos.add(inHeap)
                cost.add(inf)
            }
        }
        if(newCost >= cost[key]) return false
        var i = pos[key]

        while(i > 1) {
            val par = i shr 1
            if (newCost >= cost[h[par]]) break
            swap(i, par)
            i = par
        }

        cost[key] = newCost
        return true
    }

    val head get() = h[1]
    fun isNotFinished() = inHeap > 0

    fun remove() = head.let { hd ->
        swap(1, inHeap)
        pos[hd] = -1
        h.pop()

        var i = 1
        while(true) {
            val l = i shl 1
            if(l > inHeap) break
            val r = l or 1

            var best = l
            var p = cost[h[l]]
            if(r <= inHeap) {
                val pr = cost[h[r]]
                if(pr < p) {
                    best = r
                    p = pr
                }
            }

            if(cost[h[i]] <= p) break

            swap(i, best)
            i = best
        }

        keys[hd]
    }

    fun cost(key: BigInteger): Int {
        val hash = key.hash()
        val i = map[hash]
        return if(i == -1) inf else cost[i]
    }
}

class IntList(initialCapacity: Int = 12) {
    private var arr = IntArray(initialCapacity)
    val _arr get() = arr
    private val capacity get() = arr.size
    var size = 0
        private set
    inline val lastIndex get() = size - 1
    inline val indices get() = 0 until size

    constructor(copyFrom: IntArray): this(copyFrom.size) { copyFrom.copyInto(arr); size = copyFrom.size }
    constructor(copyFrom: Collection<Int>): this(copyFrom.size) { arr = copyFrom.toIntArray(); size = copyFrom.size }

    fun contentEquals(other: IntList): Boolean {
        return this === other || size == other.size && indices.all { this[it] == other[it] }
    }

    private fun grow(minCapacity: Int = 8) {
        val newCapacity = maxOf(minCapacity, capacity + (capacity shr 1))
        arr = arr.copyOf(newCapacity)
    }

    fun ensureCapacity(minCapacity: Int) { if(capacity < minCapacity) grow(minCapacity) }

    operator fun get(index: Int): Int {
        require(index in 0 until size)
        return arr[index]
    }

    operator fun set(index: Int, value: Int) {
        require(index in 0 until size)
        arr[index] = value
    }

    fun add(value: Int) {
        if(size == capacity) grow()
        arr[size++] = value
    }

    fun addAll(list: IntList) {
        ensureCapacity(size + list.size)
        list.arr.copyInto(arr, size, 0, list.size)
        size += list.size
    }

    fun add(index: Int, element: Int) {
        if(size == capacity) grow()
        arr.copyInto(arr, index + 1, index, size)
        size++
        set(index, element)
    }

    fun clear() { size = 0 }

    fun removeAt(index: Int): Int {
        val e = get(index)
        arr.copyInto(arr, index, index + 1, size)
        size--
        return e
    }

    fun indexOf(e: Int): Int {
        for(i in 0 until size) if(this[i] == e) return i
        return -1
    }

    fun remove(e: Int): Boolean {
        val i = indexOf(e)
        if(i == -1) return false
        removeAt(i)
        return true
    }

    operator fun iterator() = object: IntIterator() {
        private var pos = 0
        override fun hasNext() = pos < size
        override fun nextInt() = get(pos++)
    }

    inline fun isEmpty() = size == 0
    inline fun isNotEmpty() = size != 0

    fun pop() = arr[--size]

    fun popToSize(s: Int) {
        require(s >= 0)
        if(s < size) size = s
    }

    fun swap(i: Int, j: Int) { val t = this[i]; this[i] = this[j]; this[j] = t }
    fun reverse() {
        for(i in 0 until size / 2) swap(i, lastIndex - i)
    }

    fun shuffle(rnd: Random = random) { for(i in lastIndex downTo 1) swap(i, rnd.nextInt(i+1)) }

    inline fun sortWith(cmp: (Int, Int) -> Int) { _mergeSort(_arr, size, IntArray(size), IntArray::get, IntArray::set, cmp) }
    inline fun <T: Comparable<T>> sortBy(func: (Int) -> T) { sortWith { a, b -> func(a).compareTo(func(b)) } }
    inline fun <T: Comparable<T>> sortByDescending(func: (Int) -> T) { sortWith { a, b -> func(b).compareTo(func(a)) } }
    fun sort() { sortBy { it } }
    fun sortDescending() { sortByDescending { it } }

    fun joinToString(separator: CharSequence) = if(size == 0) "" else let {
        buildString {
            append(it[0])
            for (i in 1 until size) {
                append(separator).append(it[i])
            }
        }
    }

    override fun toString() = "[" + joinToString(", ") + "]"

    fun toIntArray() = arr.copyOf(size)
    fun toList() = List(size, ::get)

    inline fun first() = get(0)
    inline fun last() = get(lastIndex)
}

inline fun IntList(size: Int, init: (Int) -> Int) = IntList(size).apply {
    for(i in 0 until size) { add(init(i)) }
}
inline fun IntArray.toIntList() = IntList(this)
inline fun Collection<Int>.toIntList() = IntList(this)
inline fun intListOf(vararg values: Int) = IntList(values)

fun IntList.max() = (1 until size).fold(this[0]) { acc, i -> max(acc, this[i]) }
fun IntList.min() = (1 until size).fold(this[0]) { acc, i -> min(acc, this[i]) }
fun IntList.getOrNull(i: Int) = if(i in indices) get(i) else null
inline fun IntList.count(predicate: (Int) -> Boolean) = indices.count { predicate(this[it]) }
fun IntList.copyOf() = IntList(size, ::get)

typealias LongIntMap = _Ez_Long__Int_HashMap
inline operator fun LongIntMap.set(key: Long, value: Int) { put(key, value) }
inline operator fun LongIntMap.contains(key: Long) = containsKey(key)

class _Ez_Long__Int_HashMap(capacity: Int = DEFAULT_CAPACITY, val nullValue: Int = 0) :
    _Ez_Long__Int_Map {
    companion object {
        private const val DEFAULT_CAPACITY = 8
        // There are three invariants for size, removedCount and arraysLength:
// 1. size + removedCount <= 1/2 arraysLength
// 2. size > 1/8 arraysLength
// 3. size >= removedCount
// arraysLength can be only multiplied by 2 and divided by 2.
// Also, if it becomes >= 32, it can't become less anymore.
        private const val REBUILD_LENGTH_THRESHOLD = 32
        private const val HASHCODE_INITIAL_VALUE = -0x7ee3623b
        private const val HASHCODE_MULTIPLIER = 0x01000193
        private const val FREE: Byte = 0
        private const val REMOVED: Byte = 1
        private const val FILLED: Byte = 2
        private val hashSeed = random.nextLong()
        private val gamma = random.nextLong() or 1
    }

    private lateinit   var keys: LongArray
    private lateinit   var values: IntArray
    private lateinit var status: ByteArray
    override var size = 0
        private set
    private var removedCount = 0
    private var mask = 0

    constructor(map: _Ez_Long__Int_Map) : this(map.size) {
        val it = map.iterator()
        while (it.hasNext()) {
            put(it.key, it.value)
            it.next()
        }
    }

    constructor(javaMap: Map<Long, Int>) : this(javaMap.size) {
        for ((key, value) in javaMap) {
            put(key, value)
        }
    }

    private fun getStartPos(h: Long): Int {
        var x = (h xor hashSeed) * gamma
        x = (x xor (x ushr 30)) * -4658895280553007687
        x = (x xor (x ushr 27)) * -7723592293110705685
        return (x xor (x ushr 31)).toInt() and mask
    }

    override fun isEmpty(): Boolean = size == 0

    override fun containsKey(
        key: Long
    ): Boolean {
        var pos = getStartPos(key)
        while (status[pos] != FREE) {
            if (status[pos] == FILLED && keys[pos] == key) {
                return true
            }
            pos = pos + 1 and mask
        }
        return false
    }

    override fun  get(
        key: Long
    ): Int {
        var pos = getStartPos(key)
        while (status[pos] != FREE) {
            if (status[pos] == FILLED && keys[pos] == key) {
                return values[pos]
            }
            pos = pos + 1 and mask
        }
        return nullValue
    }

    override fun  put(
        key: Long,
        value: Int
    ): Int {
        var pos = getStartPos(key)
        while (status[pos] == FILLED) {
            if (keys[pos] == key) {
                val   oldValue = values[pos]
                values[pos] = value
                return oldValue
            }
            pos = pos + 1 and mask
        }
        if (status[pos] == FREE) {
            status[pos] = FILLED
            keys[pos] = key
            values[pos] = value
            size++
            if ((size + removedCount) * 2 > keys.size) {
                rebuild(keys.size * 2) // enlarge the table
            }
            return nullValue
        }
        val removedPos = pos
        pos = pos + 1 and mask
        while (status[pos] != FREE) {
            if (status[pos] == FILLED && keys[pos] == key) {
                val   oldValue = values[pos]
                values[pos] = value
                return oldValue
            }
            pos = pos + 1 and mask
        }
        status[removedPos] = FILLED
        keys[removedPos] = key
        values[removedPos] = value
        size++
        removedCount--
        return nullValue
    }

    override fun  remove(
        key: Long
    ): Int {
        var pos = getStartPos(key)
        while (status[pos] != FREE) {
            if (status[pos] == FILLED && keys[pos] == key) {
                val   removedValue = values[pos]
                status[pos] = REMOVED
                size--
                removedCount++
                if (keys.size > REBUILD_LENGTH_THRESHOLD) {
                    if (8 * size <= keys.size) {
                        rebuild(keys.size / 2) // compress the table
                    } else if (size < removedCount) {
                        rebuild(keys.size) // just rebuild the table
                    }
                }
                return removedValue
            }
            pos = pos + 1 and mask
        }
        return nullValue
    }

    override fun clear() {
        if (keys.size > REBUILD_LENGTH_THRESHOLD) {
            initEmptyTable(REBUILD_LENGTH_THRESHOLD)
        } else {
            status.fill(FREE)
            size = 0
            removedCount = 0
        }
    }

    override fun keys(): LongArray {
        val result = LongArray(size)
        var i = 0
        var j = 0
        while (i < keys.size) {
            if (status[i] == FILLED) {
                result[j++] = keys[i]
            }
            i++
        }
        return result
    }

    override fun values(): IntArray {
        val result = IntArray(size)
        var i = 0
        var j = 0
        while (i < values.size) {
            if (status[i] == FILLED) {
                result[j++] = values[i]
            }
            i++
        }
        return result
    }

    override fun iterator(): _Ez_Long__Int_MapIterator {
        return _Ez_Long__Int_HashMapIterator()
    }

    private fun rebuild(newLength: Int) {
        val oldKeys = keys

        val oldValues = values
        val oldStatus = status
        initEmptyTable(newLength)
        for (i in oldKeys.indices) {
            if (oldStatus[i] == FILLED) {
                put(oldKeys[i], oldValues[i])
            }
        }
    }

    private fun initEmptyTable(length: Int) {
        keys = LongArray(length)
        values = IntArray(length)
        status = ByteArray(length)
        size = 0
        removedCount = 0
        mask = length - 1
    }

    fun contentEquals(that: _Ez_Long__Int_HashMap): Boolean {
        if (size != that.size) {
            return false
        }
        for (i in keys.indices) {
            if (status[i] == FILLED) {
                val   thatValue = that[keys[i]]
                if (thatValue != values[i]) {
                    return false
                }
            }
        }
        return true
    }

    override fun toString(): String {
        val sb = StringBuilder()
        sb.append('{')
        for (i in keys.indices) {
            if (status[i] == FILLED) {
                if (sb.length > 1) {
                    sb.append(", ")
                }
                sb.append(keys[i])
                sb.append('=')
                sb.append(values[i])
            }
        }
        sb.append('}')
        return sb.toString()
    }

    private inner class _Ez_Long__Int_HashMapIterator : _Ez_Long__Int_MapIterator {
        private var curIndex = 0
        override fun hasNext(): Boolean {
            return curIndex < status.size
        }

        override val key: Long

            get() {
                if (curIndex == keys.size) {
                    throw NoSuchElementException("Iterator doesn't have more entries")
                }
                return keys[curIndex]
            }

        override val value: Int

            get() {
                if (curIndex == values.size) {
                    throw NoSuchElementException("Iterator doesn't have more entries")
                }
                return values[curIndex]
            }

        override fun next() {
            if (curIndex == status.size) {
                return
            }
            curIndex++
            while (curIndex < status.size && status[curIndex] != FILLED) {
                curIndex++
            }
        }

        init {
            while (curIndex < status.size && status[curIndex] != FILLED) {
                curIndex++
            }
        }
    }

    init {
        require(capacity >= 0) { "Capacity must be non-negative" }
        val length = Integer.highestOneBit(4 * max(1, capacity) - 1)
        // Length is a power of 2 now
        initEmptyTable(length)
    }
}

interface _Ez_Long__Int_Map {

    val size: Int

    fun isEmpty(): Boolean

    fun containsKey(
        key: Long
    ): Boolean

    operator fun  get(
        key: Long
    ): Int

    fun  put(
        key: Long,
        value: Int
    ): Int

    fun  remove(
        key: Long
    ): Int

    fun clear()

    fun keys(): LongArray

    fun values(): IntArray

    operator fun iterator(): _Ez_Long__Int_MapIterator

    override fun toString(): String
}

interface _Ez_Long__Int_MapIterator {
    operator fun hasNext(): Boolean

    val key: Long

    val value: Int

    operator fun next()
}

inline fun LongIntMap.forEach(act: (key: Long, value: Int) -> Unit) {
    val ite = iterator()
    while(ite.hasNext()) {
        act(ite.key, ite.value)
        ite.next()
    }
}

/** IO */
//@JvmField val ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null
//const val PATH = "src/main/resources/"
//@JvmField val INPUT = File(PATH + "input.txt").inputStream()
//@JvmField val OUTPUT = File(PATH + "output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

const val _BUFFER_SIZE = 1 shl 16
@JvmField val _buffer = ByteArray(_BUFFER_SIZE)
@JvmField var _bufferPt = 0
@JvmField var _bytesRead = 0

tailrec fun readChar(): Char {
    if(_bufferPt == _bytesRead) {
        _bufferPt = 0
        _bytesRead = INPUT.read(_buffer, 0, _BUFFER_SIZE)
    }
    return if(_bytesRead < 0) Char.MIN_VALUE
    else {
        val c = _buffer[_bufferPt++].toChar()
        if (c == '\r') readChar() else c
    }
}

/** @param skipNext Whether to skip the next character (usually whitespace), defaults to true */
fun readCharArray(n: Int, skipNext: Boolean = true): CharArray {
    val res = CharArray(n) { readChar() }
    if(skipNext) readChar()
    return res
}

fun readLine(): String? {
    var c = readChar()
    return if(c == Char.MIN_VALUE) null
    else buildString {
        while(c != '\n' && c != Char.MIN_VALUE) {
            append(c)
            c = readChar()
        }
    }
}
fun readLn() = readLine()!!

fun read() = buildString {
    var c = readChar()
    while(c <= ' ') {
        if(c == Char.MIN_VALUE) return@buildString
        c = readChar()
    }
    do {
        append(c)
        c = readChar()
    } while(c > ' ')
}
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)

/**  sort overrides to avoid quicksort attacks */

@JvmField var _random: Random? = null
val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it }

inline fun <A, T> _mergeSort(a0: A, n: Int, tmp0: A, get: A.(Int) -> T, set: A.(Int, T) -> Unit, cmp: (T, T) -> Int) {
    var a = a0
    var tmp = tmp0
    var len = 1
    while(len < n) {
        var l = 0
        while(true) {
            val m = l + len
            if(m >= n) break
            val r = min(n, m + len)
            var i = l
            var j = m
            for(k in l until r) {
                if(i != m && (j == r || cmp(a.get(i), a.get(j)) <= 0)) {
                    tmp.set(k, a.get(i++))
                } else tmp.set(k, a.get(j++))
            }
            l = r
        }
        for(i in l until n) tmp.set(i, a.get(i))
        val t = a; a = tmp; tmp = t
        len += len
    }
    if(a !== a0) for(i in 0 until n) a0.set(i, tmp0.get(i))
}

inline fun IntArray.sortWith(cmp: (Int, Int) -> Int) { _mergeSort(this, size, IntArray(size), IntArray::get, IntArray::set, cmp) }
inline fun <T: Comparable<T>> IntArray.sortBy(func: (Int) -> T) { sortWith { a, b -> func(a).compareTo(func(b)) } }
inline fun <T: Comparable<T>> IntArray.sortByDescending(func: (Int) -> T) { sortWith { a, b -> func(b).compareTo(func(a)) } }
fun IntArray.sort() { sortBy { it } }
fun IntArray.sortDescending() { sortByDescending { it } }

inline fun LongArray.sortWith(cmp: (Long, Long) -> Int) { _mergeSort(this, size, LongArray(size), LongArray::get, LongArray::set, cmp) }
inline fun <T: Comparable<T>> LongArray.sortBy(func: (Long) -> T) { sortWith { a, b -> func(a).compareTo(func(b)) } }
inline fun <T: Comparable<T>> LongArray.sortByDescending(func: (Long) -> T) { sortWith { a, b -> func(b).compareTo(func(a)) } }
fun LongArray.sort() { sortBy { it } }
fun LongArray.sortDescending() { sortByDescending { it } }

inline fun DoubleArray.sortWith(cmp: (Double, Double) -> Int) { _mergeSort(this, size, DoubleArray(size), DoubleArray::get, DoubleArray::set, cmp) }
inline fun <T: Comparable<T>> DoubleArray.sortBy(func: (Double) -> T) { sortWith { a, b -> func(a).compareTo(func(b)) } }
inline fun <T: Comparable<T>> DoubleArray.sortByDescending(func: (Double) -> T) { sortWith { a, b -> func(b).compareTo(func(a)) } }
fun DoubleArray.sort() { sortBy { it } }
fun DoubleArray.sortDescending() { sortByDescending { it } }

inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T : Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T : Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T : Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T : Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()

// import preserving junk function
@Suppress("NonAsciiCharacters") fun 雪花飄飄北風嘯嘯天地一片蒼茫() { iprintln(max(1, 2)) }

fun IntArray.sumLong() = sumOf { it.toLong() }

fun IntArray.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun IntArray.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }
fun LongArray.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun LongArray.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }
fun DoubleArray.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun DoubleArray.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }
fun <T: Comparable<T>> Array<T>.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun <T: Comparable<T>> Array<T>.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }
fun <T: Comparable<T>> List<T>.sortedIndices() = IntArray(size) { it }.also { it.sortBy(::get) }
fun <T: Comparable<T>> List<T>.sortedIndicesDescending() = IntArray(size) { it }.also { it.sortByDescending(::get) }

// max/min Kotlin 1.6 -> 1.4 shim
fun IntArray.max() = maxOf { it }
fun IntArray.min() = minOf { it }
fun LongArray.max() = maxOf { it }
fun LongArray.min() = minOf { it }
fun CharArray.max() = maxOf { it }
fun CharArray.min() = minOf { it }
fun <T : Comparable<T>> Iterable<T>.max() = maxOf { it }
fun <T : Comparable<T>> Iterable<T>.min() = minOf { it }
fun <T : Comparable<T>> Sequence<T>.max() = maxOf { it }
fun <T : Comparable<T>> Sequence<T>.min() = minOf { it }


import kotlin.math.*

fun main(args: Array<String>) {
    val a = readLine()!!.splitToIntArray().toRect()
    val b = readLine()!!.splitToIntArray().toRect()
    val h = (b.x1 - b.x0) / 2
    val s0 = b.x1 + b.y0 - h
    val s1 = b.x1 + b.y0 + h
    val d0 = b.x0 - b.y0 - h
    val d1 = b.x0 - b.y0 + h
    for (x in a.x0..a.x1) {
        for (y in a.y0..a.y1) {
            if ((x + y) in s0..s1 && (x - y) in d0..d1) {
                println("YES")
                return
            }
        }
    }
    println("NO")
}

fun IntArray.toRect(): Rect {
    var x0 = Int.MAX_VALUE
    var x1 = Int.MIN_VALUE
    var y0 = Int.MAX_VALUE
    var y1 = Int.MIN_VALUE
    for (i in 0..3) {
        x0 = min(get(2 * i), x0)
        x1 = max(get(2 * i), x1)
        y0 = min(get(2 * i + 1), y0)
        y1 = max(get(2 * i + 1), y1)
    }
    return Rect(x0, x1, y0, y1)
}

class Rect(val x0: Int, val x1: Int, val y0: Int, val y1: Int)

private fun String.splitToIntArray(): IntArray {
    val n = length
    if (n == 0) return IntArray(0) // EMPTY
    var res = IntArray(4)
    var m = 0
    var i = 0
    while (true) {
        var cur = 0
        var neg = false
        var c = get(i) // expecting number, IOOB if there is no number
        if (c == '-') {
            neg = true
            i++
            c = get(i) // expecting number, IOOB if there is no number
        }
        while (true) {
            val d = c.toInt() - '0'.toInt()
            require(d >= 0 && d <= 9) { "Unexpected character '$c' at $i" }
            require(cur >= Integer.MIN_VALUE / 10) { "Overflow at $i" }
            cur = cur * 10 - d
            require(cur <= 0) { "Overflow at $i" }
            i++
            if (i >= n) break
            c = get(i)
            if (c == ' ') break
        }
        if (m >= res.size) res = res.copyOf(res.size * 2)
        res[m++] = if (neg) cur else (-cur).also { require(it >= 0) { "Overflow at $i" } }
        if (i >= n) break
        i++
    }
    if (m < res.size) res = res.copyOf(m)
    return res
}


const val MOD = 1000000007L

fun main() {
    val n = readLine()!!.toInt()
    val factorial = LongArray(n + 1)
    factorial[0] = 1L
    for (j in 1..n) {
        factorial[j] = (j.toLong() * factorial[j - 1]) % MOD
    }
    val factInv = LongArray(n + 1) { factorial[it] pow -1 }
    fun permute(a: Int, b: Int) = (factorial[a] * factInv[b]) % MOD
    fun arrange(a: Int, b: Int): Long {
        val here = n / a
        val above = here / b
        return ((here - above).toLong() * permute(n - above - 1, n - here)) % MOD
    }
    var lg = 0
    while (1 shl lg <= n) {
        lg++
    }
    lg--
    var curr = 1L
    for (e in 0..lg) {
        curr *= arrange(1 shl e, 2)
        curr %= MOD
    }
    var answer = curr
    if (n >= 3 * (1 shl (lg - 1))) {
        for (e in lg downTo 1) {
            curr *= arrange(1 shl e, 3) pow -1
            curr %= MOD
            curr *= arrange(3 * (1 shl (e - 1)), 2)
            curr %= MOD
            curr *= arrange(1 shl (e - 1), 2) pow -1
            curr %= MOD
            curr *= arrange(1 shl (e - 1), 3)
            curr %= MOD
            answer += curr
        }
        answer %= MOD
    }
    println(answer)
}

val MOD_TOTIENT = (MOD - 1).toInt()

infix fun Long.pow(power: Int): Long {
    var e = power
    e %= MOD_TOTIENT
    if (e < 0) {
        e += MOD_TOTIENT
    }
    if (e == 0 && this == 0L) {
        return this
    }
    var b = this % MOD
    var res = 1L
    while (e > 0) {
        if (e and 1 != 0) {
            res *= b
            res %= MOD
        }
        b *= b
        b %= MOD
        e = e shr 1
    }
    return res
}


const val MOD = 1000000007L

fun main() {
    val n = readLine()!!.toInt()
    val inv = LongArray(n + 1) { it.toLong() pow -1 }
    val factorial = LongArray(n + 1)
    val factInv = LongArray(n + 1)
    factorial[0] = 1L
    factInv[0] = 1L
    for (j in 1..n) {
        factorial[j] = (j.toLong() * factorial[j - 1]) % MOD
        factInv[j] = (inv[j] * factInv[j - 1]) % MOD
    }
    fun permute(a: Int, b: Int) = (factorial[a] * factInv[b]) % MOD
    fun arrange(a: Int, b: Int): Long {
        val here = n / a
        val above = here / b
        return ((here - above).toLong() * permute(n - above - 1, n - here)) % MOD
    }
    fun arrangeInv(a: Int, b: Int): Long {
        val here = n / a
        val above = here / b
        return (inv[here - above] * permute(n - here, n - above - 1)) % MOD
    }
    var lg = 0
    while (1 shl lg <= n) {
        lg++
    }
    lg--
    var curr = 1L
    for (e in 0..lg) {
        curr *= arrange(1 shl e, 2)
        curr %= MOD
    }
    var answer = curr
    if (n >= 3 * (1 shl (lg - 1))) {
        for (e in lg downTo 1) {
            curr *= arrangeInv(1 shl e, 3)
            curr %= MOD
            curr *= arrange(3 * (1 shl (e - 1)), 2)
            curr %= MOD
            curr *= arrangeInv(1 shl (e - 1), 2)
            curr %= MOD
            curr *= arrange(1 shl (e - 1), 3)
            curr %= MOD
            answer += curr
        }
        answer %= MOD
    }
    println(answer)
}

val MOD_TOTIENT = (MOD - 1).toInt()

infix fun Long.pow(power: Int): Long {
    var e = power
    e %= MOD_TOTIENT
    if (e < 0) {
        e += MOD_TOTIENT
    }
    if (e == 0 && this == 0L) {
        return this
    }
    var b = this % MOD
    var res = 1L
    while (e > 0) {
        if (e and 1 != 0) {
            res *= b
            res %= MOD
        }
        b *= b
        b %= MOD
        e = e shr 1
    }
    return res
}


const val MOD = 1000000007L

fun main() {
    val n = readLine()!!.toInt()
    val factorial = LongArray(n + 1)
    factorial[0] = 1L
    for (j in 1..n) {
        factorial[j] = (j.toLong() * factorial[j - 1]) % MOD
    }
    val factInv = LongArray(n + 1) { factorial[it] pow -1 }
    fun permute(a: Int, b: Int) = if (b < 0L || b > a) 0L else ((factorial[a] * factInv[b]) % MOD)
    fun arrange(a: Int, b: Int): Long {
        val here = n / a
        val above = here / b
        return ((here - above).toLong() * permute(n - above - 1, n - here)) % MOD
    }
    var lg = 0
    while (1 shl lg <= n) {
        lg++
    }
    lg--
    var curr = factorial[n - (n / 2)]
    for (e in 1..lg) {
        curr *= arrange(1 shl e, 2)
    }
    var answer = curr
    if (n >= 3 * (1 shl (lg - 1))) {
        for (e in lg downTo 1) {
            curr *= arrange(1 shl e, 3) pow -1
            curr %= MOD
            curr *= arrange(3 * (1 shl (e - 1)), 2)
            curr %= MOD
            if (e > 1) {
                curr *= arrange(1 shl (e - 1), 2) pow -1
                curr %= MOD
                curr *= arrange(1 shl (e - 1), 3)
                curr %= MOD
            } else {
                curr *= factInv[n - (n / 2)]
                curr %= MOD
                curr *= factorial[n - (n / 3)]
                curr %= MOD
            }
            answer += curr
        }
        answer %= MOD
    }
    println(answer)
}

val MOD_TOTIENT = (MOD - 1).toInt()

infix fun Long.pow(power: Int): Long {
    var e = power
    e %= MOD_TOTIENT
    if (e < 0) {
        e += MOD_TOTIENT
    }
    if (e == 0 && this == 0L) {
        return this
    }
    var b = this % MOD
    var res = 1L
    while (e > 0) {
        if (e and 1 != 0) {
            res *= b
            res %= MOD
        }
        b *= b
        b %= MOD
        e = e shr 1
    }
    return res
}


fun nextLn() = readLine()!!
fun nextInt() = nextLn().toInt()
fun nextStrings() = nextLn().split(" ")
fun nextInts() = nextStrings().map { it.toInt() }
fun nextLongs() = nextStrings().map { it.toLong() }

var mod = 998244353

fun main(args: Array<String>) {
    var (n, m) = nextInts()
    var a = MutableList<ArrayList<Int>>(456789) {ArrayList<Int>()}
    var cntk = nextInts().toMutableList()
    for (i in 1 .. m) {
        var (d, t) =nextInts()
        a[d].add(t - 1)
    }
    fun check(d : Int) : Boolean {
        var money = 0
        var cnt = cntk.toMutableList()
        var lastd = MutableList<Int>(n) {d + 1}
        for (i in 1 .. d) {
            for (k in a[i]) {
                lastd[k] = i
            }
        }
        for (i in 1 .. d) {
            money += 1
            for (k in a[i]) {
                if (lastd[k] != i)
                    continue
                var c = minOf(cnt[k], money)
                cnt[k] -= c
                money -= c
            }
        }
        for (i in 0 .. n-1) {
            money -= 2 * cnt[i]
        }
        return money >= 0
    }
    var l = 0
    var r = 400001
    while (l + 1 < r) {
        var mid = (l + r) / 2
        if (check(mid))
            r = mid
        else
            l = mid
    }
    println(r)
}


@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING")

import java.io.PrintWriter
import java.util.StringTokenizer
import java.util.TreeSet
import kotlin.math.*
import kotlin.random.*
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

fun main() {
    output {
        val n = readInt()
        val m = readInt()
        val K = readIntArray(n)

        val offers = MutableList(m) { Offer(readInt(), readInt() - 1) }
        offers.sortByDescending { it.day }

        val ksum = K.sum()

        val ans = (ksum..2 * ksum).bsFirst { lastDay ->
            val sub = offers.subList(offers.indices.bsFirst { offers[it].day <= lastDay }, m)
                .distinctBy { it.type }
                .asReversed()

            var krem = ksum
            var currDay = 0
            var money = 0

            for ((day, type) in sub) {
                money += day - currDay
                currDay = day

                val bought = min(money, K[type])
                money -= bought
                krem -= bought
            }

            money += lastDay - currDay
            money >= krem * 2
        }

        println(ans)
    }
}

data class Offer(val day: Int, val type: Int)

fun IntRange.bsFirst(predicate: (Int) -> Boolean): Int {
    var low = start
    var high = endInclusive

    while (low <= high) {
        val mid = low.and(high) + low.xor(high).shr(1)
        if(predicate(mid)) high = mid - 1
        else low = mid + 1
    }
    return low
}

inline fun IntRange.bsLast(crossinline predicate: (Int) -> Boolean) =
    bsFirst{ !predicate(it) } - 1

/** IO code start */
//@JvmField val INPUT = File("input.txt").inputStream()
//@JvmField val OUTPUT = File("output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

@JvmField val _reader = INPUT.bufferedReader()
fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField var _tokenizer: StringTokenizer = StringTokenizer("")
fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)
inline fun output(block: PrintWriter.() -> Unit) { _writer.apply(block).flush() }

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <R, V> R._shuffle(rnd: Random, get: R.(Int) -> V, set: R.(Int, V) -> Unit, size: Int) {
    // Fisher-Yates shuffle algorithm
    for (i in size - 1 downTo 1) {
        val j = rnd.nextInt(i + 1)
        val temp = get(i)
        set(i, get(j))
        set(j, temp)
    }
}

@JvmField var _random: Random? = null
val random get() = _random ?: Random(System.nanoTime()).also { _random = it }

fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, IntArray::get, IntArray::set, size)
fun IntArray.sort() { shuffle(); _sort() }
fun IntArray.sortDescending() { shuffle(); _sortDescending() }

fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, LongArray::get, LongArray::set, size)
fun LongArray.sort() { shuffle(); _sort() }
fun LongArray.sortDescending() { shuffle(); _sortDescending() }

fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, DoubleArray::get, DoubleArray::set, size)
fun DoubleArray.sort() { shuffle(); _sort() }
fun DoubleArray.sortDescending() { shuffle(); _sortDescending() }

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, CharArray::get, CharArray::set, size)
inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T: Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.util.*
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min

val MOD = 1_000_000_007L
class UnionFind(n: Int) {
  private val par = IntArray(n){it}
  val rank = IntArray(n){1} // 集合の要素数
  private val visits = IntArray(n) // 訪れた場所をfind毎に用意するのがもったいないのでつかいまわす

  fun find(x: Int): Int {
    var ptr = 0
    var i = x
    while(par[i] != i) {
      visits[ptr++] = i
      i = par[i]
    }

    for (j in 0 until ptr) {
      par[visits[j]] = i
    }
    return i
  }

  private fun merge(node: Int, rt: Int): Int {
    par[node] = rt
    rank[rt] += rank[node]
    return rt
  }

  fun unite(x: Int, y: Int): Boolean {
    val x1 = find(x)
    val y1 = find(y)
    return if (x1 == y1) false
    else {
      if (rank[x1] < rank[y1])
        merge(x1, y1)
      else
        merge(y1, x1)

      true
    }
  }

  fun isRoot(x: Int) = par[x] == x

  /**
   * xを解決する必要がないときは直にrankをみる
   */
  fun cntNodes(x: Int): Int = rank[find(x)]
}
fun lowerBound(A: LongArray, s: Int, x: Long): Int {
  var l = s - 1
  var h = A.size
  while(h - l > 1) {
    val m = (h + l) / 2
    if (A[m] >= x) h = m
    else l = m
  }
  return h
}
class Solver(stream: InputStream, private val out: java.io.PrintWriter) {
  fun solve() {
    val N = ni()
    var K = nl() - 1
    val INF = 1e18.toLong() + 10
    val dp = LongArray(N + 10)
    dp[0] = 1
    for (n in 1 .. N) {
      var sum = 0L
      for (i in 1 .. n) {
        if (i > 1) {
          val uf = UnionFind(i)
          for (j in 0 until i) {
            uf.unite(j, i - 1 - j)
          }
          if (uf.cntNodes(0) != i) continue
        }

        sum += dp[n - i]
        if (sum >= INF) sum = INF
      }
      dp[n] = sum
    }
    debug(dp)

    val part = mutableListOf<Int>()
    var n = N
    while(n > 0) {
      val nums = LongArray(n + 1)
      for (i in 1 .. n) {
        nums[i] = dp[n - i]
      }
      for (i in 1 .. n) {
        nums[i] += nums[i - 1]
        if (nums[i] >= INF) nums[i] = INF
      }

      debug(nums)
      val num = lowerBound(nums, 0, K + 1)
      debug{"K:$K num:$num"}
      part += num
      n -= num
      K -= nums[num - 1]
    }

    debug{part.joinToString(" ")}
    val ans = mutableListOf<Int>()
    var l = 0
    for (p in part) {
      for (i in l + p downTo l + 1) {
        ans.add(i)
      }
      l += p
    }

    out.println(ans.joinToString(" "))
  }

  private val isDebug = try {
    // なんか本番でエラーでる
    System.getenv("MY_DEBUG") != null
  } catch (t: Throwable) {
    false
  }

  private var tokenizer: StringTokenizer? = null
  private val reader = BufferedReader(InputStreamReader(stream), 32768)
  private fun next(): String {
    while (tokenizer == null || !tokenizer!!.hasMoreTokens()) {
      tokenizer = StringTokenizer(reader.readLine())
    }
    return tokenizer!!.nextToken()
  }

  private fun ni() = next().toInt()
  private fun nl() = next().toLong()
  private fun ns() = next()
  private fun na(n: Int, offset: Int = 0): IntArray {
    return map(n) { ni() + offset }
  }
  private fun nal(n: Int, offset: Int = 0): LongArray {
    val res = LongArray(n)
    for (i in 0 until n) {
      res[i] = nl() + offset
    }
    return res
  }

  private fun na2(n: Int, offset: Int = 0): Array<IntArray> {
    val a  = Array(2){IntArray(n)}
    for (i in 0 until n) {
      for (e in a) {
        e[i] = ni() + offset
      }
    }
    return a
  }

  private inline fun map(n: Int, f: (Int) -> Int): IntArray {
    val res = IntArray(n)
    for (i in 0 until n) {
      res[i] = f(i)
    }
    return res
  }

  private inline fun debug(msg: () -> String) {
    if (isDebug) System.err.println(msg())
  }

  private fun debug(a: LongArray) {
    debug { a.joinToString(" ") }
  }

  private fun debug(a: IntArray) {
    debug { a.joinToString(" ") }
  }

  private fun debug(a: BooleanArray) {
    debug { a.map { if (it) 1 else 0 }.joinToString("") }
  }

  private fun debugDim(A: Array<LongArray>) {
    if (isDebug) {
      for (a in A) {
        debug(a)
      }
    }
  }
  private fun debugDim(A: Array<IntArray>) {
    if (isDebug) {
      for (a in A) {
        debug(a)
      }
    }
  }

  /**
   * 勝手にimport消されるのを防ぎたい
   */
  private fun hoge() {
    min(1, 2)
    max(1, 2)
    abs(-10)
  }
}

fun main() {
  val out = java.io.PrintWriter(System.out)
  Solver(System.`in`, out).solve()
  out.flush()
}


import java.util.*

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)

    var x = scanner.nextLong()
    var y = scanner.nextLong()
    val m = scanner.nextLong()

    if (x + y <= 0) {
        if (checkExcellent(x, y, m)) {
            System.out.println(0)
        } else {
            System.out.println(-1)
        }
        return
    }

    var ans: Long = 0

    while (true) {
        if (x<y) {
            x += y
            ans++
            if (checkExcellent(x,y,m)) {
                System.out.println(ans)
                return
            }
        } else {
            y += x
            ans++
            if (checkExcellent(x,y,m)) {
                System.out.println(ans)
                return
            }
        }
    }

}

fun checkExcellent(x: Long, y: Long, m: Long): Boolean {
    return Math.max(x, y) >= m
}

enum class Type {
    OPEN, CLOSE
}


import java.util.*

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)

    var x = scanner.nextLong()
    var y = scanner.nextLong()
    val m = scanner.nextLong()

    if (x <= 0 && y <= 0) {
        if (checkExcellent(x, y, m)) {
            System.out.println(0)
        } else {
            System.out.println(-1)
        }
        return
    }

    var ans: Long = 0

    while (true) {
        if (x<y) {
            x += y
            ans++
            if (checkExcellent(x,y,m)) {
                System.out.println(ans)
                return
            }
        } else {
            y += x
            ans++
            if (checkExcellent(x,y,m)) {
                System.out.println(ans)
                return
            }
        }
    }

}

fun checkExcellent(x: Long, y: Long, m: Long): Boolean {
    return Math.max(x, y) >= m
}

enum class Type {
    OPEN, CLOSE
}


import java.util.*

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)

    var x = scanner.nextLong()
    var y = scanner.nextLong()
    val m = scanner.nextLong()

    if (checkExcellent(x, y, m)) {
        System.out.println(0)
        return
    }

    if (x <= 0 && y <= 0) {
//        if (checkExcellent(x, y, m)) {
//            System.out.println(0)
//        } else {
            System.out.println(-1)
//        }
        return
    }

    if (x < y) {
        val temp = x
        x = y
        y = temp
    }

    var ans: Long = 0

    //System.out.println("$x $y")

    if (y < 0) {
        val tmp = x - y
        ans += tmp / x
        y += ans * x
    }

    if (checkExcellent(x, y, m)) {
        System.out.println(ans)
        return
    }

    while (true) {
        if (x < y) {
            x += y
            ans++
            if (checkExcellent(x, y, m)) {
                System.out.println(ans)
                return
            }
        } else {
            y += x
            ans++
            if (checkExcellent(x, y, m)) {
                System.out.println(ans)
                return
            }
        }
    }

}

fun checkExcellent(x: Long, y: Long, m: Long): Boolean {
    return Math.max(x, y) >= m
}

enum class Type {
    OPEN, CLOSE
}


import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min

fun main() {
    val (x, y, m) = readStrings().map { it.toLong() }

    var biggest = max(x, y)
    if (biggest >= m) println(0)
    else if (biggest < m && biggest <= 0) println(-1)
    else {
        var smallest = min(x, y)
        var moves = 0L
        if (smallest < 0) {
            moves = ceil(-smallest.toDouble()/biggest).toLong()
            smallest += moves * biggest
        }

        while (max(smallest, biggest) < m) {
            biggest = max(smallest, biggest)
            smallest = min(smallest, biggest)
//            println("$biggest $smallest $moves")
            smallest = biggest.also { biggest += smallest }
            moves++
        }
        println(moves)
    }
}

// Input Reader
private fun readLn() = readLine()!!

private fun readStrings() = readLn().trim().split(" ")


import kotlin.math.abs

fun main() {
    val r = System.`in`.bufferedReader()
    val s = StringBuilder()
    //val len = r.readLine()!!.toInt()
    val (a, b) = r.readLine()!!.split(" ").map { it.toInt() }
    var q = 0
    var w = 0
    var e = 0
    (1..6).forEach {
        when{
            abs(a-it)< abs(b-it) -> q++
            abs(a-it)== abs(b-it) -> w++
            abs(a-it)> abs(b-it) -> e++
        }
    }
    println("$q $w $e")
}


import kotlin.math.min
import kotlin.math.abs

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single long
private fun readDouble() = readLn().toDouble() // single double
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints
private fun readLongs() = readStrings().map { it.toLong() } // list of longs
private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles

fun main(args: Array<String>) {
    val(a,b)=readInts()
    var x=0
    var y=0
    var z=0

    for(dice in 1..6) {
        if(abs(dice-a)<abs(dice-b))x++
        else if(abs(dice-a)>abs(dice-b))y++
        else z++
    }

    println("$x $z $y")
}


import java.util.*
import kotlin.math.abs

fun main(args: Array<String>) = with(Scanner(System.`in`)) {
    val a = nextInt()
    val b = nextInt()
    var res = IntArray(3)
    repeat(6) {
        when {
            abs(a - (it + 1)) < abs(b - (it + 1)) -> res[0]++
            abs(a - (it + 1)) > abs(b - (it + 1)) -> res[2]++
            else -> res[1]++
        }
    }
    res.forEach { s -> print("$s ") }
}


import kotlin.math.abs

fun main() {
    fun readInts() = readLine()!!.split(" ").map(String::toInt)

    val (a, b) = readInts()
    var first = 0
    var second = 0
    for (result in 1..6) {
        when {
            abs(a - result) < abs(b - result) -> first++
            abs(a - result) > abs(b - result) -> second++
        }
    }
    print("$first ${6 - first - second} $second")
}


import kotlin.math.abs

fun main(args: Array<String>) = with(java.util.Scanner(System.`in`)) {
    var a = nextInt()
    var b = nextInt()
    var win = 0
    var draw = 0
    var lose = 0
    for( i in 1..6){
        if(abs(a-i) == abs(i-b))draw++
        else if(abs(a-i)>abs(i-b))lose++
        else win++
    }
    println("$win $draw $lose")
}


import java.util.*
import kotlin.collections.ArrayList

fun main(args: Array<String> ) {
    val sc = Scanner(System.`in`)
    val n = sc.nextLong()
    var b = sc.nextInt()
    val p = ArrayList<Int>()
    val d = ArrayList<Int>()
    var i = 1
    while ( ++ i * i <= b ) {
        if ( b % i != 0 ) continue
        p.add( i )
        var deg = 0
        while ( b % i == 0 ) {
            deg ++
            b /= i
        }
        d.add( deg )
    }
    if ( b > 1 ) {
        p.add( b )
        d.add( 1 )
    }

    var r = n
    for ( j in p.indices ) {
        var deg = 0L
        var t = n
        while ( t > 0 ) {
            t /= p[j]
            deg += t
        }
        r = Math.min( r, deg / d[j] )
    }

    println( r )
}


import java.util.Scanner

class Pair(val p: Int,val  x: Int,var y: Int)

fun main() {
    val sc = Scanner(System.`in`)
    val n = sc.nextInt()
    val b = sc.nextInt()
    val pairs = arrayListOf<Pair>()
    var j = 2
    var m = b

    var times = 0
    while (j <= m){
        if (m%j==0){
            m /= j
            times++
        }else{
            if (times > 0){
                pairs.add(Pair(j,times,0))
            }
            j++
            times = 0
        }
    }
    if (times > 0){
        pairs.add(Pair(j,times,0))
    }

    var min = Int.MAX_VALUE
    for(pair in pairs){
        m = n
        while (m>0){
            pair.y += m/pair.p
            m /= pair.p
        }
        if (min > pair.y/pair.x){
            min = pair.y/pair.x
        }
    }
    print(min)
}


import java.util.Scanner

class Pair(val p: Int,val  x: Int,var y: Int)

fun main() {
    val sc = Scanner(System.`in`)
    val n = sc.nextInt()
    val b = sc.nextInt()
    val pairs = arrayListOf<Pair>()
    var j = 2
    var m = b

    var times = 0
    while (j <= m){
        if (m%j==0){
            m /= j
            times++
        }else{
            if (times > 0){
                pairs.add(Pair(j,times,0))
            }
            j++
            times = 0
        }
    }
    if (times > 0){
        pairs.add(Pair(j,times,0))
    }

    var min = 0
    for(pair in pairs){
        m = n
        while (m>0){
            pair.y += m/pair.p
            m /= pair.p
        }
        if (min > pair.y/pair.x){
            min = pair.y/pair.x
        }
    }
    print(min)
}


import java.util.Scanner

class Pair(val p: Int,val  x: Int,var y: Int)

fun main() {
    val sc = Scanner(System.`in`)
    val n = sc.nextInt()
    val b = sc.nextInt()
    val pairs = arrayListOf<Pair>()
    var j = 2
    var m = b

    var times = 0
    while (j <= m){
        if (m%j==0){
            m /= j
            times++
        }else{
            if (times > 0){
                pairs.add(Pair(j,times,0))
            }
            j++
            times = 0
        }
    }
    if (times > 0){
        pairs.add(Pair(j,times,0))
    }

    var min = Int.MIN_VALUE
    for(pair in pairs){
        m = n
        while (m>0){
            pair.y += m/pair.p
            m /= pair.p
        }
        if (min > pair.y/pair.x){
            min = pair.y/pair.x
        }
    }
    print(min)
}


import kotlin.math.*

fun main() {
    val (n, b) = readLine()!!.split(' ').map { it.toLong() }
    var ans = Long.MAX_VALUE
    factor(b) { p, k ->
        ans = min(ans, pp(n, p) / k)
    }
    println(ans)
}

fun factor(x: Long, op: (p: Long, k: Int) -> Unit) {
    var rem = x
    var p = 2L
    while (p * p <= rem) {
        var k = 0
        while (rem % p == 0L) {
            rem /= p
            k++
        }
        if (k > 0) op(p, k)
        p++
    }
    if (rem > 1) op(rem, 1)
}

fun pp(n: Long, p: Long): Long {
    var ans = 0L
    var cur = p
    while (cur <= n) {
        ans += n / cur
        if (cur > (n + p - 1) / p) break
        cur *= p
    }
    return ans
}


import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*

fun main() {
    val tokenizer = BufferedReader(InputStreamReader(System.`in`)).use { StringTokenizer(it.readText()) }
    val n = tokenizer.nextLong()
    var b = tokenizer.nextLong()
    var ans: Long? = null
    for (i in 2..Math.sqrt(b.toDouble()).toLong()) {
        var c = 0
        while (b % i == 0L) {
            b /= i
            c++
        }
        if (c > 0) {
            val t = count(n, i) / c
            if (ans == null || ans > t) ans = t
        }
    }
    if (b > 1L) {
        val t = count(n, b)
        if (ans == null || ans > t) ans = t
    }
    println(ans)
}

fun count(n: Long, b: Long): Long {
    var t = n
    var ans = 0L
    while (t >= b) {
        t /= b
        ans += t
    }
    return ans
}

fun StringTokenizer.nextInt() = nextToken().toInt()
fun StringTokenizer.nextLong() = nextToken().toLong()


var n:Int=0
var arr=Array(5){tuple(0,0,0)}
fun main(args: Array<String>){
    n= readLine()!!.toInt()
    for (i:Int in 0 until n){
        val inp=readLine()!!.split(' ')
        arr[i]=tuple(inp[0].toInt() , inp[1].toInt() , inp[2].toInt())
    }
    var ans=0
    var num_of_ans=0
    for(i:Int in 123..9876){
        if(!distinct(i)){
            continue
        }
        if(check(i)){
            ans=i
            num_of_ans++
        }
    }
    if(num_of_ans == 0){
        println("Incorrect data")
    }else if(num_of_ans > 1){
        println("Need more data")
    }else{
        print(ans)
    }
}
fun distinct(x:Int):Boolean{
    var firstX:Int=x%10
    var secondX:Int=(x%100)/10
    var thirdX:Int=(x%1000)/100
    var fourthX:Int=x/1000
    if(firstX == secondX || firstX == thirdX || firstX == fourthX
        || secondX == thirdX || secondX == fourthX || thirdX == fourthX){
        return false
    }
    return true
}

fun check(num: Int):Boolean{
    for(i:Int in 0 until n){//bulls the same pos
        if(Bulls(arr[i].x , num) != arr[i].y ||
                Cows(arr[i].x , num) != arr[i].z){
            return false
        }
    }
    return true
}
fun Bulls(x:Int , y:Int):Int{
    var ans:Int=0
    if(x%10 == y%10){
        ans++
    }
    if ((x%100)/10 == (y%100)/10){
        ans++
    }
    if ((x%1000)/100 == (y%1000)/100){
        ans++
    }
    if(x/1000 == y/1000){
        ans++
    }
    return ans
}
fun Cows(x:Int , y:Int):Int{
    var ans=0
    var firstX:Int=x%10
    var secondX:Int=(x%100)/10
    var thirdX:Int=(x%1000)/100
    var fourthX:Int=x/1000

    var firstY:Int=y%10
    var secondY:Int=(y%100)/10
    var thirdY:Int=(y%1000)/100
    var fourthY:Int=y/1000
    if(firstX == secondY || firstX == thirdY || firstX == fourthY){
        ans++
    }
    if(secondX == firstY || secondX == thirdY || secondX == fourthY){
        ans++
    }
    if(thirdX == secondY || thirdX == firstY || thirdX == fourthY){
        ans++
    }
    if(fourthX == secondY || fourthX == thirdY || fourthX == firstY){
        ans++
    }
    return ans
}
class tuple(x:Int , y:Int , z:Int){
    var x:Int=0
    var y:Int=0
    var z:Int=0
    init{
        this.x=x
        this.y=y
        this.z=z
    }
}


var n:Int=0
var arr=Array(15){tuple(0,0,0)}
fun main(args: Array<String>){
    n= readLine()!!.toInt()
    for (i:Int in 0 until n){
        val inp=readLine()!!.split(' ')
        arr[i]=tuple(inp[0].toInt() , inp[1].toInt() , inp[2].toInt())
    }
    var ans=0
    var num_of_ans=0
    for(i:Int in 123..9876){
        if(!distinct(i)){
            continue
        }
        if(check(i)){
            ans=i
            num_of_ans++
        }
    }
    if(num_of_ans == 0){
        println("Incorrect data")
    }else if(num_of_ans > 1){
        println("Need more data")
    }else{
        if(ans/1000 == 0){
            print(0)
            print(ans)
        }else {
            print(ans)
        }
    }
}
fun distinct(x:Int):Boolean{
    var firstX:Int=x%10
    var secondX:Int=(x%100)/10
    var thirdX:Int=(x%1000)/100
    var fourthX:Int=x/1000
    if(firstX == secondX || firstX == thirdX || firstX == fourthX
        || secondX == thirdX || secondX == fourthX || thirdX == fourthX){
        return false
    }
    return true
}

fun check(num: Int):Boolean{
    for(i:Int in 0 until n){//bulls the same pos
        if(Bulls(arr[i].x , num) != arr[i].y ||
                Cows(arr[i].x , num) != arr[i].z){
            return false
        }
    }
    return true
}
fun Bulls(x:Int , y:Int):Int{
    var ans:Int=0
    if(x%10 == y%10){
        ans++
    }
    if ((x%100)/10 == (y%100)/10){
        ans++
    }
    if ((x%1000)/100 == (y%1000)/100){
        ans++
    }
    if(x/1000 == y/1000){
        ans++
    }
    return ans
}
fun Cows(x:Int , y:Int):Int{
    var ans=0
    var firstX:Int=x%10
    var secondX:Int=(x%100)/10
    var thirdX:Int=(x%1000)/100
    var fourthX:Int=x/1000

    var firstY:Int=y%10
    var secondY:Int=(y%100)/10
    var thirdY:Int=(y%1000)/100
    var fourthY:Int=y/1000
    if(firstX == secondY || firstX == thirdY || firstX == fourthY){
        ans++
    }
    if(secondX == firstY || secondX == thirdY || secondX == fourthY){
        ans++
    }
    if(thirdX == secondY || thirdX == firstY || thirdX == fourthY){
        ans++
    }
    if(fourthX == secondY || fourthX == thirdY || fourthX == firstY){
        ans++
    }
    return ans
}
class tuple(x:Int , y:Int , z:Int){
    var x:Int=0
    var y:Int=0
    var z:Int=0
    init{
        this.x=x
        this.y=y
        this.z=z
    }
}


fun solve(a: Int): String {

    for (i in 1..a / 3) {
        if ((a - i * 3) % 7 == 0) return "YES"
    }
    return "NO"
}

fun processSuite() {
    val n = readLine()!!.toInt()
    val solution = solve(n)
    println(solution)
}

fun suitesCount() = readLine()!!.toInt()

fun main() {
    for (i in 0 until suitesCount()) {
        processSuite()
    }
}

// READER
internal val reader = Reader()
internal fun readNumber() = reader.nextInt()
internal fun readNumbers(n: Int) = reader.nextInts(n)

typealias DataInputStream = java.io.DataInputStream

internal class Reader {

    private val BUFFER_SIZE = 1 shl 16
    private val din: DataInputStream = DataInputStream(System.`in`)
    private val buffer: ByteArray = ByteArray(BUFFER_SIZE)
    private var bytesRead: Int = 0
    private var bufferPointer: Int = bytesRead

    private val stop: Byte = -1

    private fun read(): Byte {
        if (bufferPointer == bytesRead) {
            fillBuffer()
        }
        return buffer[bufferPointer++]
    }

    private fun fillBuffer() {
        bufferPointer = 0
        bytesRead = din.read(buffer, bufferPointer, BUFFER_SIZE)
        if (bytesRead == -1) {
            buffer[0] = stop
        }
    }

    fun nextLine(): String {
        val buf = ByteArray(64) // line length
        var cnt = 0
        var c: Byte
        do {
            c = read().takeUnless { it == '\n'.toByte() } ?: break
            buf[cnt++] = c
        } while (c != stop)

        return String(buf, 0, cnt)
    }

    fun nextInts(n: Int): IntArray {
        val arr = IntArray(n) { 0 }
        for (i in 0 until n) {
            arr[i] = nextInt()
        }
        return arr
    }

    fun nextInt(): Int {
        var ret = 0
        var c = read()
        while (c <= ' '.toByte()) c = read()
        val neg = c == '-'.toByte()
        if (neg) c = read()
        do {
            ret = ret * 10 + c - '0'.toInt()
            c = read()
        } while (c >= '0'.toByte() && c <= '9'.toByte())

        return if (neg) -ret else ret
    }

    fun nextLong(): Long {
        var ret = 0L
        var c = read()
        while (c <= ' '.toByte()) c = read()
        val neg = c == '-'.toByte()
        if (neg) c = read()
        do {
            ret = ret * 10 + c - '0'.toInt()
            c = read()
        } while (c >= '0'.toByte() && c <= '9'.toByte())

        return if (neg) -ret else ret
    }

    fun nextDouble(): Double {
        var ret = 0.0
        var div = 1.0
        var c = read()
        while (c <= ' '.toByte()) c = read()
        val neg = c == '-'.toByte()
        if (neg) c = read()
        do {
            ret = ret * 10 + c - '0'.toDouble()
            c = read()
        } while (c >= '0'.toByte() && c <= '9'.toByte())

        if (c == '.'.toByte()) {
            c = read()
            while (c >= '0'.toByte() && c <= '9'.toByte()) {
                div *= 10
                ret += (c - '0'.toByte()) / div
                c = read()
            }
        }

        return if (neg) -ret else ret
    }
}


fun main(args: Array<String>) {
    var t = readLine()!!.toInt()

    for(i in 1..t) {
        var x = readLine()!!.toInt()
        var possible = false

        for(j in 1..t) {
            if(x % (3 * j) == 7 || x % (7 * j) == 3) possible = true
            if(x % 3 == 0 || x % 7 == 0) possible = true

            if(possible) break
        }

        println(if (possible) "YES" else "NO")
    }
}


fun main(args: Array<String>) {
    var n = readLine()!!.toInt()
    var a = 0
    for(i in 1..n){
        a = readLine()!!.toInt()
        if (a % 7 == 0 || a % 3 == 0 || a % 10 == 0){
            println("YES")
        }
        else
            println("NO")
    }
}


fun main(args: Array<String>) {
    var t = readLine()!!.toInt()

    for(i in 1..t) {
        var x = readLine()!!.toInt()
        var possible = false

        for(j in 0..x) {
            if((x - 3 * j) % 7 == 0 && x >= 3 * j) possible = true
            if((x - 7 * j) % 3 == 0 && x >= 7 * j) possible = true
        }

        println(if (possible) "YES" else "NO")
    }
}


import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.util.StringTokenizer

fun main(args: Array<String>) {
    val sc = FastScanner(System.`in`)

    val n = sc.nextInt()
    repeat(n) {
        val x = sc.nextInt()

        for (i in 0..x) {
            if (i * 3 > x) {
                println("NO")
                break
            }
            if ((x - i * 3) % 7 == 0) {
                println("YES")
                break
            }
        }

    }

}

class FastScanner(s: InputStream) {
    private var st = StringTokenizer("")
    private val br = BufferedReader(InputStreamReader(s))

    fun next(): String {
        while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine())

        return st.nextToken()
    }

    fun nextInt() = next().toInt()
    fun nextLong() = next().toLong()
    fun nextLine() = br.readLine()
    fun nextDouble() = next().toDouble()
    fun ready() = br.ready()
}


fun main() {
    fun readInt() = readLine()!!.toInt()

    val numCases = readInt()
    val sols = BooleanArray(numCases)
    for (numCase in 0 until numCases) {
        val n = readInt()
        for (b in 0 .. n / 7)
            if ((n - 7 * b) % 3 == 0) {
                sols[numCase] = true
                break
            }
    }

    print(sols.joinToString(System.lineSeparator()) { b -> if (b) "YES" else "NO" })
}


private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single long
private fun readDouble() = readLn().toDouble() // single double
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints
private fun readLongs() = readStrings().map { it.toLong() } // list of longs
private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles
private fun readLis() = readInts().toMutableList()

//println(res.joinToString(" ")) - > focus ( " " )
//var a1 = readLongs().toMutableList()
//val st = mutableSetOf<Int>()  -> var find = st.elementAt(i)
//var ar1 = LongArray(3) {100000}
//f2.sortDescending() sort IntArray
//var c = 'a' + i ( from 'a' --> 'z' )

fun solve() {
    var n = readInt()
    var s = readLine()!!.toString()
    if (n == 1) {
        println("0")
        return
    }
    var ans = 0
    var st = -1
    for (i in 0 until n) {
        if (s[i] == '0') {
            st = i
            break
        }
    }
    if (st == -1) {
        println("0")
        return
    }
    var one = 0
    while (true) {
        var end = 0
        var ok = 0
        for (i in st + 1 until n) {
            if (s[i] == '0') {
                st = i
                if (one >= 2) {
                    one = 0
                } else {
                    ans += 2 - one
                    one = 0
                }
                ok = 1
                break
            } else {
                one++
            }
        }
        if (st >= n - 1 || ok == 0) {
            break
        }
    }

    println(ans)
}

fun main() {
    val n = readInt()
    var ok = false
    val list = mutableListOf<String>()
    for(i in 0 until n){
        val s = readLine()!!.toString()
        list.add(s)
        if (s.contains("theseus")){
            ok = true
        }
    }
    if(ok){
        println("YES")
    }else{
        for(i in 0 until n){
            var s = ""
            for(j in 0 until n){
                s += list[j][i]
            }
            if(s.contains("theseus")){
                ok = true
                break
            }
        }
        if(ok){
            println("YES")
        }else{
            println("NO")
        }
    }
}


private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single long
private fun readDouble() = readLn().toDouble() // single double
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints
private fun readLongs() = readStrings().map { it.toLong() } // list of longs
private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles
private fun readLis() = readInts().toMutableList()

//println(res.joinToString(" ")) - > focus ( " " )
//var a1 = readLongs().toMutableList()
//val st = mutableSetOf<Int>()  -> var find = st.elementAt(i)
//var ar1 = LongArray(3) {100000}
//f2.sortDescending() sort IntArray
//var c = 'a' + i ( from 'a' --> 'z' )

fun solve() {
    var n = readInt()
    var s = readLine()!!.toString()
    if (n == 1) {
        println("0")
        return
    }
    var ans = 0
    var st = -1
    for (i in 0 until n) {
        if (s[i] == '0') {
            st = i
            break
        }
    }
    if (st == -1) {
        println("0")
        return
    }
    var one = 0
    while (true) {
        var end = 0
        var ok = 0
        for (i in st + 1 until n) {
            if (s[i] == '0') {
                st = i
                if (one >= 2) {
                    one = 0
                } else {
                    ans += 2 - one
                    one = 0
                }
                ok = 1
                break
            } else {
                one++
            }
        }
        if (st >= n - 1 || ok == 0) {
            break
        }
    }

    println(ans)
}

fun main() {
    val n = readInt()
    var ok = false
    for(i in 0 until n){
        val s = readLine()!!.toString()
        if (s.contains("theseus")){
            ok = true
        }
    }
    if(ok){
        println("YES")
    }else{
        println("NO")
    }
}


import java.util.*
import kotlin.math.*

private fun <E> List<E>.toPair(): Pair<E, E> {
    return Pair(this[0], this[1])
}

private fun maxOf(ans: Pair<Int, Int>, b: Pair<Int, Int>): Pair<Int, Int> {
    return if (ans.first > b.first || ans.first == b.first && ans.second > b.second) ans
    else b
}

private fun <T1 : Comparable<T1>, T2 : Comparable<T2>> pairCmp(): Comparator<Pair<T1, T2>> {
    return Comparator { a, b ->
        val res = a.first.compareTo(b.first)
        if (res == 0) a.second.compareTo(b.second) else res
    }
}

private val readR = Scanner(System.`in`)
private const val BUFFER_SIZE = 1 shl 16
private val buffer = ByteArray(BUFFER_SIZE)
private var bufferPt = 0
private var bytesRead = 0
private fun read() = buildString {
    var c = readChar()
    while(c <= ' ') {
        if(c == Char.MIN_VALUE) return@buildString
        c = readChar()
    }
    do {
        append(c)
        c = readChar()
    } while(c > ' ')
}
private val INPUT = System.`in`
private tailrec fun readChar(): Char {
    if(bufferPt == bytesRead) {
        bufferPt = 0
        bytesRead = INPUT.read(buffer, 0, BUFFER_SIZE)
    }
    return if(bytesRead < 0) Char.MIN_VALUE
    else {
        val c = buffer[bufferPt++].toInt().toChar()
        if (c == '\r') readChar()
        else c
    }
}
private fun readln() = readLine()!!
private fun readInt() = read().toInt()
private fun readDouble() = read().toDouble()
private fun readLong() = read().toLong()
private fun readStrings(n: Int) = List(n) { read() }
private fun readLines(n: Int) = List(n) { readln() }
private fun readInts(n: Int) = List(n) { read().toInt() }
private fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
private fun readDoubles(n: Int) = List(n) { read().toDouble() }
private fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
private fun readLongs(n: Int) = List(n) { read().toLong() }
private fun readLongArray(n: Int) = LongArray(n) { read().toLong() }
private fun printWithSpace(vararg x: Any?) = println(x.joinToString(" "))
private fun readCharArray(n:Int) = CharArray(n) {_->readChar()}
//----------------Customizing Functions----------------

//-----------------------Solving-----------------------

    //println(res.joinToString(" ")) - > focus ( " " )
    //var a1 = readLongs().toMutableList()
    //val st = mutableSetOf<Int>()  -> var find = st.elementAt(i)
    //var ar1 = LongArray(3) {100000}
    //f2.sortDescending() sort IntArray
    //var c = 'a' + i ( from 'a' --> 'z' )

private fun solve() {
    var n = readInt()
    var s = readLine()!!.toString()
    if (n == 1) {
        println("0")
        return
    }
        var ans = 0
        var st = -1
        for (i in 0 until n) {
            if (s[i] == '0') {
                st = i
                break
            }
        }
        if (st == -1) {
            println("0")
            return
        }
        var one = 0
        while (true) {
            var end = 0
            var ok = 0
            for (i in st + 1 until n) {
                if (s[i] == '0') {
                    st = i
                    if (one >= 2) {
                        one = 0
                    } else {
                        ans += 2 - one
                        one = 0
                    }
                    ok = 1
                    break
                } else {
                    one++
                }
            }
            if (st >= n - 1 || ok == 0) {
                break
            }
        }

        println(ans)
    }

    fun main() {
        val n = readInt()
        val arr = Array(n){CharArray(n)}
        for(i in 0 until n){
            val s = readLine()!!.toString()
            for(j in 0 until n){
                arr[i][j] = s[j]
            }
        }
        var ok = false
        for(i in 0 until n){
            for(j in 0 until n){
                if(i < n - 7){
                    var cur = ""
                    for(k in 0 until 7){
                        cur += arr[i + k][j]
                    }
                    if(cur == "theseus"){
                        ok = true
                    }
                }
                if(j < n - 7){
                    var cur = ""
                    for(k in 0 until 7){
                        cur += arr[i][j + k]
                    }
                    if(cur == "theseus"){
                        ok = true
                    }
                }
                if(i < n - 7 && j < n - 7){
                    var cur = ""
                    for(k in 0 until 7){
                        cur += arr[i + k][j + k]
                    }
                    if(cur == "theseus"){
                        ok = true
                    }
                }
            }
        }
        if(ok){
            println("YES")
        }else{
            println("NO")
        }
    }