import kotlin.math.*

fun getMinimumAmountOfChangeFrom(amount: Int): Int {
    val changes = listOf(10, 5, 1)
    var availableAmount = amount
    var numOfCoins = 0
    for (change in changes) {
        while (availableAmount > 0 && availableAmount / change.toDouble() >= 1) {
            numOfCoins += 1
            availableAmount -= change
        }
    }
    return numOfCoins
}

fun getMaximumValueOfTheLootWith(
    W: Int,
    valuePerUnitAndWeight: List<Pair<Double, Int>>
): Double {
    var maximumLootValue = 0.0
    var availableWeight = W
    for (pair in valuePerUnitAndWeight) {
        var availableWeightOfLootItem = pair.second
        while (availableWeight > 0 && availableWeightOfLootItem > 0) {
            maximumLootValue += pair.first
            availableWeightOfLootItem -= 1
            availableWeight -= 1
        }
    }
    return maximumLootValue
}

fun getMinimumNumOfRefills(d: Int, m: Int, stops: List<Int>): Int {
    var availableDistance = d
    var minimumRefills = 0
    var currentRefill = 0
    var lastRefill = 0
    val realStops = listOf<Int>(0, *stops.toTypedArray(), d)
    while (availableDistance > 0 && currentRefill < realStops.size) {
        var movedForward = false
        while (currentRefill < realStops.size && (realStops[currentRefill] - realStops[lastRefill]) <= m) {
            if (realStops[currentRefill] - realStops[lastRefill] == 0) {
                movedForward = false
                currentRefill++
            } else {
                movedForward = true
                currentRefill++
            }
        }
        if (movedForward) {
            minimumRefills++
            currentRefill--
            availableDistance -= (realStops[currentRefill] - realStops[lastRefill])
            lastRefill = currentRefill
        } else {
            return -1
        }
    }
    return minimumRefills - 1
}

fun getMaximizedSumOfProduct(profitPerClick: List<Int>, averageNumberOfClicks: List<Int>): Long {
    var sum = 0L
    println(profitPerClick.toString())
    println(averageNumberOfClicks.toString())
    profitPerClick.forEachIndexed { index, profit ->
        sum += profit * averageNumberOfClicks[index]
    }
    return sum
}

fun getCommon(first: Int, last: Int, segments: MutableList<Pair<Int, Int>>): String {
    var current = first
    val common = mutableListOf<Pair<Int, Int>>()
    while (current <= last) {
        var numOfTimes = 0
        for (pair in segments) {
            if (current in pair.first..pair.second) {
                numOfTimes++
            }
        }
        if (numOfTimes > 1) {
            common.add(Pair(current, numOfTimes))
        }
        current++
    }
    common.sortByDescending { it -> it.second }
    if (common.first().second == segments.size) {
        return "1\n${common.first().first}"
    }
    println(common)
    return "${common.size}\n${common.map { it.first }.joinToString(" ")}"
}

fun getMaximumSetOfPrizes(n: Int): String {
    var numbersOfN = ""
    var sumSoFar = 0
    if (n <= 2) {
        return "1\n$n"
    }
//    println("2*square root of n = ${2 * sqrt(n.toDouble())}")
//    for (i in 1..(2 * sqrt(n.toDouble()).toInt())){
//        if (i+sumSoFar<=n){
//            numbersOfN+="$i "
//            sumSoFar+=i
//        }
//    }
//    var lastNumber = 1
    var currentNumber = 1
    while (((currentNumber + 1) + currentNumber) <= n - sumSoFar) {
        sumSoFar += currentNumber
        numbersOfN += "$currentNumber "
        currentNumber++
    }
    if (((n - currentNumber) + sumSoFar) == n || n - sumSoFar > 0) {
        currentNumber = n - sumSoFar
        sumSoFar += currentNumber
        numbersOfN += "$currentNumber "
    }
//    else if (n-sumSoFar>0){
//        currentNumber = n-sumSoFar
//        numbersOfN += "$currentNumber "
//    }
    return "${numbersOfN.trim().split(" ").size}\n$numbersOfN"
}

fun linelandMail(coordinates: List<Long>): String {
    val mins = mutableListOf<Long>()
    val maxs = mutableListOf<Long>()
    for (i in coordinates.indices) {
        if (i == 0) {
            mins.add(abs(coordinates[i] - coordinates[i + 1]))
            maxs.add(abs(coordinates[i] - coordinates[coordinates.size - 1]))
        } else if (i == coordinates.size - 1) {
            mins.add(abs(coordinates[i] - coordinates[i - 1]))
            maxs.add(abs(coordinates[i] - coordinates[0]))
        } else {
            if (abs(coordinates[i] - coordinates[i - 1])
                > abs(coordinates[i] - coordinates[i + 1])
            )
                mins.add(abs(coordinates[i] - coordinates[i + 1]))
            else
                mins.add(abs(coordinates[i] - coordinates[i - 1]))

            if (abs(coordinates[i] - coordinates[0])
                < abs(coordinates[i] - coordinates[coordinates.size - 1])
            )
                maxs.add(abs(coordinates[i] - coordinates[coordinates.size - 1]))
            else
                maxs.add(abs(coordinates[i] - coordinates[0]))
        }
    }
    return mins
        .zip(maxs)
        .map { pair -> "${pair.first} ${pair.second}" }
        .joinToString("\n")
}

fun snacktower(snacksWeights: List<Int>) {
    val n = snacksWeights.size
    var currentMax = n
    var current = 0
    var processed = mutableListOf<Int>()
    while (current < snacksWeights.size) {
        if (snacksWeights[current] < currentMax) {
            processed.add(snacksWeights[current])
            print("\n")
            current++
        } else {
            if (snacksWeights[current] == currentMax) {
                print(currentMax)
                currentMax--
                var currentProcessed = 0
                while (currentProcessed < processed.size) {
                    var foundConsecutive = false
                    if (processed[currentProcessed] == currentMax) {
                        print(" ")
                        print(processed[currentProcessed])
                        currentMax--
                        foundConsecutive = true
                        processed = processed.swap(currentProcessed, processed.size - 1).toMutableList()
                        processed.removeAt(processed.size - 1)
                    }
                    if (!foundConsecutive) {
                        currentProcessed++
                    } else {
                        currentProcessed = 0
                    }
                }
                println()
                current++
            }
        }
    }
}

fun <T> List<T>.swap(a: Int, b: Int): List<T> = this
    .toMutableList()
    .also {
        it[a] = this[b]
        it[b] = this[a]
    }

fun `Oath of the Night's Watch`(stewardsStrengths: List<Int>) {
    val sortedStrengths = stewardsStrengths.sorted()
    var numberOfThoseWhoNeedSupport = 0
    for (strengthIndex in sortedStrengths.indices) {
        val precedingSteward = strengthIndex - 1
        val nextSteward = strengthIndex + 1
        if (precedingSteward >= 0 && nextSteward < sortedStrengths.size) {
            if (sortedStrengths[precedingSteward] < sortedStrengths[strengthIndex]
                && sortedStrengths[nextSteward] > sortedStrengths[strengthIndex]
            ) {
                numberOfThoseWhoNeedSupport++
            }
        }
    }
    println(numberOfThoseWhoNeedSupport)
}

fun pangram(characters: String) {
    print(if (characters.toLowerCase().toSet().size == 26) "YES" else "NO")
}

fun twins(coinsValues: List<Int>) {
    val sortedValues = coinsValues.sortedDescending()
    var mySumSoFar = 0
    var numberOfCoinsIWillTake = 0
    for (index in sortedValues.indices) {
        mySumSoFar += sortedValues[index]
        numberOfCoinsIWillTake++
        if (mySumSoFar > sortedValues.subList(index + 1, sortedValues.size).sum()) {
            break
        }
    }
    println(numberOfCoinsIWillTake)
}

fun keyboard(handSlippedTo: Char, codedMessage: String) {
    val hisKeyboard = "qwertyuiopasdfghjkl;zxcvbnm,./"
    for (char in codedMessage) {
        when (handSlippedTo) {
            'R' -> {
                print(hisKeyboard[hisKeyboard.indexOf(char) - 1])
            }
            'L' -> {
                print(hisKeyboard[hisKeyboard.indexOf(char) + 1])
            }
        }
    }
}

fun `Even Odds`(endingNumber: Long, indexOfRequired: Long) {
    val numberOfOddsInTheEndingNumber = ceil(endingNumber / 2.0).toLong()
    val numberOfEvensInTheEndingNumber = floor(endingNumber / 2.0).toLong()
    if (indexOfRequired <= numberOfOddsInTheEndingNumber) {
        println(1 + 2 * (indexOfRequired - 1))
    } else {
        println(2 + 2 * ((indexOfRequired - numberOfOddsInTheEndingNumber) - 1))
    }
}

fun `I Wanna Be the Guy`(
    numberOfLevels: Int,
    levelsXCanPass: List<Int>,
    levelsYCanPass: List<Int>
) {
    val allLevelsPassed = levelsXCanPass.plus(levelsYCanPass).toSet()
    println(
        if (allLevelsPassed.size == numberOfLevels)
            "I become the guy."
        else
            "Oh, my keyboard!"
    )
}

fun `Is it rated?`(rates: List<Pair<Int, Int>>) {
    var standingsChanged = 0
    for (index in rates.indices) {
        if (rates[index].second != rates[index].first) {
            println("rated")
            return
        }
        if (index > 0) {
            if (rates[index].first > rates[index - 1].first) {
                standingsChanged++
            }
        }
    }
    if (standingsChanged > 0) {
        println("unrated")
    } else {
        println("maybe")
    }
}

fun `Olesya and Rodion`(numberOfDigits: Int, divisibleBy: Int) {
    if (divisibleBy!=0) {
        println((10.0.toBigDecimal().pow(numberOfDigits - 1) + divisibleBy.toBigDecimal()).toBigInteger())
    }else{
        println(-1)
    }
}

fun main() {

//    val scanner = Scanner(System.`in`)
//    val n = scanner.nextInt()
//    val snacksWeights = MutableList<Int>(n) { index -> 0 }
//    for (i in 0 until n) {
//        snacksWeights[i] = scanner.nextInt()
//    }
//    snacktower(snacksWeights)
//    val scanner = Scanner(System.`in`)
//    val n = scanner.nextInt()
//    val strengths = MutableList<Int>(n) { index -> 0 }
//    for (i in 0 until n) {
//        strengths[i] = scanner.nextInt()
//    }
//    `Oath of the Night's Watch`(strengths)
    val (n, t) = readLine()!!.split(" ").map { it.toInt() }
    `Olesya and Rodion`(n,t)

}

// start of stress test
//    while (true) {
//        val n = Random.nextLong(1000000)
//        val m = Random.nextLong(100000)
//        if (m<n){
//            val res1 = getFibonacciPartialSumNaive(m,n)
//            val res2 = getLastDigitOfSumOfSubsetOfFibs(m,n)
//            if (res1.toInt() == res2) {
//                println("Ok")
//            } else {
//                println("Wrong Answer at n = $n and m = $m")
//                print("$res1 $res2")
//                break
//            }
//        }
//
//    }


import kotlin.math.pow

fun main() {
    val (numDigits, divisibleBy) = readLine()!!.split(" ").map { s -> s.toInt() }
    val min = 10f.pow(numDigits - 1).toInt()
    val max = (10f.pow(numDigits) - 1).toInt()
    if (min % divisibleBy == 0) {
        print(min)
    } else if (divisibleBy * ((min / divisibleBy) + 1) <= max) {
        print(divisibleBy * ((min / divisibleBy) + 1))
    } else {
        print(-1)
    }
}


fun main() {
    val r = System.`in`.bufferedReader()
    val s = StringBuilder()
    val (n, t) = r.readLine()!!.split(" ").map { it.toInt() }
    if (n==1&&t==10) println(-1) else{
    var ans = MutableList(n) { 9 }.joinToString("").toBigInteger()
    while (ans % t.toBigInteger()!= BigInteger.ZERO){
        ans -= BigInteger.ONE
    }
    println(ans)}
}


import java.util.*

fun main(args: Array<String>) {

    var sc = Scanner(System.`in`)

    var n = sc.nextLine().toInt()
    var line1 = sc.nextLine().split(" ")
    var line2 = sc.nextLine().split(" ")

    var ans1 = 0
    var ans2 = 0

    for( i in 0 until n){
        ans1 += line1[i].toInt()
        ans2 += line2[i].toInt()
    }

    if(ans1 < ans2) print("No")
    else print("Yes")
}


import java.io.BufferedInputStream
import java.util.*

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

    val n = scanner.nextInt()
    val x = Array(n) { scanner.nextInt() }
    val y = Array(n) { scanner.nextInt() }

    println(if (x.sum() >= y.sum()) "YES" else "NO")
}


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

    readLine()
    print(if (readInts().sum() >= readInts().sum()) "Yes" else "No")

}


import kotlin.math.sqrt

fun main() {
    val n = readLong()

    val sqrt = n.sqrtFloor()

    val ans = n.factorize().distinct().fold(1L, Long::times)

    println(ans)
}

fun Long.sqrtFloor() = sqrt(toDouble()).toLong()

fun primeSieve(upperLimit: Long): Sequence<Long> = sequence {
    yield(2L)
    val source = (3..upperLimit step 2).toMutableSet()

    while(source.isNotEmpty()) {
        val prime = source.first()
        yield(prime)
        source.remove(prime)
        source.removeAll(prime * prime .. upperLimit step prime)
    }
}

fun Long.factorize() = sequence {
    val sqrt = sqrtFloor()
    var n = this@factorize

    for(p in primeSieve(sqrt)) {
        while(n % p == 0L) {
            yield(p)
            n /= p
        }
    }

    if(n > 1) yield(n)
}

fun readLn() = readLine()!!
fun readInt() = readLn().toInt()
fun readDouble() = readLn().toDouble()
fun readLong() = readLn().toLong()
fun readStrings() = readLn().split(' ')
fun readStringSeq() = readLn().splitToSequence(' ')
fun readInts() = readStrings().map { it.toInt() }
fun readIntSeq() = readStringSeq().map { it.toInt() }
fun readIntArray(size: Int) = readIntSeq().iterator().let { i -> IntArray(size) { i.next() } }
fun readDoubles() = readStrings().map { it.toDouble() }
fun readDoubleSeq() = readStringSeq().map { it.toDouble() }
fun readDoubleArray(size: Int) = readDoubleSeq().iterator().let { i -> DoubleArray(size) { i.next() } }
fun readLongs() = readStrings().map { it.toLong() }
fun readLongSeq() = readStringSeq().map { it.toLong() }
fun readLongArray(size: Int) = readLongSeq().iterator().let { i -> LongArray(size) { i.next() } }

class Output {
    private val sb = StringBuilder()
    fun print(o: Any?) { sb.append(o) }
    fun println() { sb.append('\n') }
    fun println(o: Any?) { sb.append(o).append('\n') }
    @JvmName("_print") fun Any?.print() = print(this)
    @JvmName("_println") fun Any?.println() = println(this)
    fun nowPrint() { kotlin.io.print(sb) }
}
inline fun output(block: Output.()->Unit) { Output().apply(block).nowPrint() }


import kotlin.math.sqrt

fun main() {
    val n = readLong()

    val ans = n.factorize().distinct().fold(1L, Long::times)

    println(ans)
}

fun Long.sqrtFloor() = sqrt(toDouble()).toLong()

fun Long.factorize() = sequence {
    val sqrt = sqrtFloor()
    var n = this@factorize

    for(p in sequenceOf(2L) + (3..sqrt step 2)) {
        while(n % p == 0L) {
            yield(p)
            n /= p
        }
        if(n == 1L) break
    }

    if(n > 1) yield(n)
}

fun readLn() = readLine()!!
fun readInt() = readLn().toInt()
fun readDouble() = readLn().toDouble()
fun readLong() = readLn().toLong()
fun readStrings() = readLn().split(' ')
fun readStringSeq() = readLn().splitToSequence(' ')
fun readInts() = readStrings().map { it.toInt() }
fun readIntSeq() = readStringSeq().map { it.toInt() }
fun readIntArray(size: Int) = readIntSeq().iterator().let { i -> IntArray(size) { i.next() } }
fun readDoubles() = readStrings().map { it.toDouble() }
fun readDoubleSeq() = readStringSeq().map { it.toDouble() }
fun readDoubleArray(size: Int) = readDoubleSeq().iterator().let { i -> DoubleArray(size) { i.next() } }
fun readLongs() = readStrings().map { it.toLong() }
fun readLongSeq() = readStringSeq().map { it.toLong() }
fun readLongArray(size: Int) = readLongSeq().iterator().let { i -> LongArray(size) { i.next() } }

class Output {
    private val sb = StringBuilder()
    fun print(o: Any?) { sb.append(o) }
    fun println() { sb.append('\n') }
    fun println(o: Any?) { sb.append(o).append('\n') }
    @JvmName("_print") fun Any?.print() = print(this)
    @JvmName("_println") fun Any?.println() = println(this)
    fun nowPrint() { kotlin.io.print(sb) }
}
inline fun output(block: Output.()->Unit) { Output().apply(block).nowPrint() }


import kotlin.math.sqrt

fun main() {
    val n = readLong()

    val ans = n.factorize().distinct().fold(1L, Long::times)

    println(ans)
}

fun Long.sqrtFloor() = sqrt(toDouble()).toLong()

fun Long.factorize() = sequence {
    val sqrt = sqrtFloor()
    var n = this@factorize

    for(p in sequenceOf(2L) + (3..sqrt step 2)) {
        while(n % p == 0L) {
            yield(p)
            n /= p
        }
    }

    if(n > 1) yield(n)
}

fun readLn() = readLine()!!
fun readInt() = readLn().toInt()
fun readDouble() = readLn().toDouble()
fun readLong() = readLn().toLong()
fun readStrings() = readLn().split(' ')
fun readStringSeq() = readLn().splitToSequence(' ')
fun readInts() = readStrings().map { it.toInt() }
fun readIntSeq() = readStringSeq().map { it.toInt() }
fun readIntArray(size: Int) = readIntSeq().iterator().let { i -> IntArray(size) { i.next() } }
fun readDoubles() = readStrings().map { it.toDouble() }
fun readDoubleSeq() = readStringSeq().map { it.toDouble() }
fun readDoubleArray(size: Int) = readDoubleSeq().iterator().let { i -> DoubleArray(size) { i.next() } }
fun readLongs() = readStrings().map { it.toLong() }
fun readLongSeq() = readStringSeq().map { it.toLong() }
fun readLongArray(size: Int) = readLongSeq().iterator().let { i -> LongArray(size) { i.next() } }

class Output {
    private val sb = StringBuilder()
    fun print(o: Any?) { sb.append(o) }
    fun println() { sb.append('\n') }
    fun println(o: Any?) { sb.append(o).append('\n') }
    @JvmName("_print") fun Any?.print() = print(this)
    @JvmName("_println") fun Any?.println() = println(this)
    fun nowPrint() { kotlin.io.print(sb) }
}
inline fun output(block: Output.()->Unit) { Output().apply(block).nowPrint() }


import kotlin.math.sqrt

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

    fun Long.factors(): MutableSet<Long> {
        val output = mutableSetOf<Long>()
        val endLoop = sqrt(this.toDouble()).toLong()
        for (i in 1L..endLoop) {
            if (this % i == 0L) {
                output.add(i)
                output.add(this / i)
            }
        }
        return output
    }

    val n = readLong()
    val factors = n.factors().sortedDescending()
    loop@ for (factor in factors) {
        val subFactors = factor.factors()
        subFactors.remove(1L)
        for (subFactor in subFactors) {
            val a = sqrt(subFactor.toDouble()).toLong()
            if (a * a == subFactor) continue@loop
        }
        print(factor)
        return
    }
    print(1)
}


fun main() {
    val n = readLong()

    val ans = n.factorize().distinct().fold(1L, Long::times)

    println(ans)
}

fun Long.factorize() = sequence {
    var n = this@factorize

    for(p in sequenceOf(2L) + (3..Long.MAX_VALUE step 2)) {
        if(p * p > n) break

        while(n % p == 0L) {
            yield(p)
            n /= p
        }
    }

    if(n > 1) yield(n)
}

fun readLn() = readLine()!!
fun readInt() = readLn().toInt()
fun readDouble() = readLn().toDouble()
fun readLong() = readLn().toLong()
fun readStrings() = readLn().split(' ')
fun readStringSeq() = readLn().splitToSequence(' ')
fun readInts() = readStrings().map { it.toInt() }
fun readIntSeq() = readStringSeq().map { it.toInt() }
fun readIntArray(size: Int) = readIntSeq().iterator().let { i -> IntArray(size) { i.next() } }
fun readDoubles() = readStrings().map { it.toDouble() }
fun readDoubleSeq() = readStringSeq().map { it.toDouble() }
fun readDoubleArray(size: Int) = readDoubleSeq().iterator().let { i -> DoubleArray(size) { i.next() } }
fun readLongs() = readStrings().map { it.toLong() }
fun readLongSeq() = readStringSeq().map { it.toLong() }
fun readLongArray(size: Int) = readLongSeq().iterator().let { i -> LongArray(size) { i.next() } }

class Output {
    private val sb = StringBuilder()
    fun print(o: Any?) { sb.append(o) }
    fun println() { sb.append('\n') }
    fun println(o: Any?) { sb.append(o).append('\n') }
    @JvmName("_print") fun Any?.print() = print(this)
    @JvmName("_println") fun Any?.println() = println(this)
    fun nowPrint() { kotlin.io.print(sb) }
}
inline fun output(block: Output.()->Unit) { Output().apply(block).nowPrint() }


import kotlin.math.sqrt

fun main() {
    val n = readLong()

    val sqrt = n.sqrtFloor()

    var ans = n

    for(p in longPrimeSieve(sqrt)) {
        val sq = p * p
        while(ans % sq == 0L) ans /= p
    }

    println(ans)
}

fun Long.sqrtFloor() = sqrt(toDouble()).toLong()

fun longPrimeSieve(upperLimit: Long): Sequence<Long> = sequence {
    yield(2L)
    val source = (3..upperLimit step 2).toMutableSet()

    while(source.isNotEmpty()) {
        val prime = source.first()
        yield(prime)
        source.remove(prime)
        source.removeAll(prime * prime .. upperLimit step prime)
    }
}

fun readLn() = readLine()!!
fun readInt() = readLn().toInt()
fun readDouble() = readLn().toDouble()
fun readLong() = readLn().toLong()
fun readStrings() = readLn().split(' ')
fun readStringSeq() = readLn().splitToSequence(' ')
fun readInts() = readStrings().map { it.toInt() }
fun readIntSeq() = readStringSeq().map { it.toInt() }
fun readIntArray(size: Int) = readIntSeq().iterator().let { i -> IntArray(size) { i.next() } }
fun readDoubles() = readStrings().map { it.toDouble() }
fun readDoubleSeq() = readStringSeq().map { it.toDouble() }
fun readDoubleArray(size: Int) = readDoubleSeq().iterator().let { i -> DoubleArray(size) { i.next() } }
fun readLongs() = readStrings().map { it.toLong() }
fun readLongSeq() = readStringSeq().map { it.toLong() }
fun readLongArray(size: Int) = readLongSeq().iterator().let { i -> LongArray(size) { i.next() } }

class Output {
    private val sb = StringBuilder()
    fun print(o: Any?) { sb.append(o) }
    fun println() { sb.append('\n') }
    fun println(o: Any?) { sb.append(o).append('\n') }
    @JvmName("_print") fun Any?.print() = print(this)
    @JvmName("_println") fun Any?.println() = println(this)
    fun nowPrint() { kotlin.io.print(sb) }
}
inline fun output(block: Output.()->Unit) { Output().apply(block).nowPrint() }


import kotlin.math.sqrt

fun main() {
    val n = readLong()

    val sqrt = n.sqrtFloor()

    var ans = 1L

    for(p in primeSieve(sqrt)) {
        if(n % p == 0L) ans *= p
    }

    println(ans)
}

fun Long.sqrtFloor() = sqrt(toDouble()).toLong()

fun primeSieve(upperLimit: Long): Sequence<Long> = sequence {
    yield(2L)
    val source = (3..upperLimit step 2).toMutableSet()

    while(source.isNotEmpty()) {
        val prime = source.first()
        yield(prime)
        source.remove(prime)
        source.removeAll(prime * prime .. upperLimit step prime)
    }
}

fun readLn() = readLine()!!
fun readInt() = readLn().toInt()
fun readDouble() = readLn().toDouble()
fun readLong() = readLn().toLong()
fun readStrings() = readLn().split(' ')
fun readStringSeq() = readLn().splitToSequence(' ')
fun readInts() = readStrings().map { it.toInt() }
fun readIntSeq() = readStringSeq().map { it.toInt() }
fun readIntArray(size: Int) = readIntSeq().iterator().let { i -> IntArray(size) { i.next() } }
fun readDoubles() = readStrings().map { it.toDouble() }
fun readDoubleSeq() = readStringSeq().map { it.toDouble() }
fun readDoubleArray(size: Int) = readDoubleSeq().iterator().let { i -> DoubleArray(size) { i.next() } }
fun readLongs() = readStrings().map { it.toLong() }
fun readLongSeq() = readStringSeq().map { it.toLong() }
fun readLongArray(size: Int) = readLongSeq().iterator().let { i -> LongArray(size) { i.next() } }

class Output {
    private val sb = StringBuilder()
    fun print(o: Any?) { sb.append(o) }
    fun println() { sb.append('\n') }
    fun println(o: Any?) { sb.append(o).append('\n') }
    @JvmName("_print") fun Any?.print() = print(this)
    @JvmName("_println") fun Any?.println() = println(this)
    fun nowPrint() { kotlin.io.print(sb) }
}
inline fun output(block: Output.()->Unit) { Output().apply(block).nowPrint() }


fun main() {
    var (a, b) = readLine()!!.split(' ').map { it.toInt() }
    var count = 0L
    for (i in a..b){
        var digit = i.toString()
        for (i in digit){
            when(i){
                '0'->count+=6
                '1'->count+=2
                '2'->count+=5
                '3'->count+=5
                '4'->count+=4
                '5'->count+=5
                '6'->count+=6
                '7'->count+=3
                '8'->count+=7
                '6'->count+=6
            }
        }
    }
    println(count)
}


import java.io.*
import java.lang.Math.*
import java.math.BigInteger
import java.util.*
import kotlin.collections.ArrayList

typealias IndexPair<Type> = Pair<Type, Int>
typealias IntIndexPair = IndexPair<Int>
typealias IntIntPair = Pair<Int, Int>

typealias IntMatrix = Array<IntArray>
typealias LongMatrix = Array<LongArray>

typealias ListArray<Type> = Array<MutableList<Type>>

typealias Graph = IntMatrix

typealias Edge = Pair<Int, Int>
typealias EdgeArray = Array<Edge>
typealias WeightedGraph = Array<EdgeArray>

typealias TotalEdge = Triple<Int, Int, Int>
typealias TotalEdgeArray = Array<TotalEdge>

fun init() { }

const val MODULO = 1000 * 1000 * 1000 + 7

fun solve() {
    val segments = arrayOf(6, 2, 5, 5, 4, 5, 6, 3, 7, 6)

    val (start, end) = readInts()
    val result = (start..end).sumBy {number ->
        number.toString().sumBy { segments[it - '0'] }
    }

    out.println(result)
}

fun stress() {
    val rnd = Random(1234)

    for (it in 0 until 100) {
        val expected = brute()
        val actual = fast()

        if (expected != actual) {
            System.err.println("Gotcha!")
            System.err.println("$expected $actual")

            break
        }
    }
}

fun fast() {

}

fun brute() {

}

fun Long.mod() : Long {
    var result = this % MODULO
    if (result < 0) result += MODULO
    return result
}

infix fun Long.add(other : Long) = (this + other).mod()
infix fun Long.sub(other : Long) = this add -other.mod()
infix fun Long.mult(other : Long) = (this.mod() * other.mod()).mod()

fun Long.even() = (this and 1L) == 0L
fun Long.odd() = !even()

fun Int.even() = (this and 1) == 0
fun Int.odd() = !even()

infix fun Long.binpow(power : Long) : Long {
    if (power == 0L) return 1L

    val half = binpow(power shl 1)

    var result = half mult half
    if (power.odd()) {
        result = result mult this
    }

    return result
}

val stepsXY = arrayOf(
        arrayOf(0, -1),
        arrayOf(0, 1),
        arrayOf(-1, 0),
        arrayOf(1, 0)
)

class IndexedWeightedGraph(private val n : Int, private val edges: TotalEdgeArray) {

    private val graph : Graph

    private fun buildGraphForEdges(
            edgeFilter : (index : Int, edge : TotalEdge) -> Boolean = { _, _ -> true }
    ) : Graph {
        val builder = GraphBuilder()
        edges
            .forEachIndexed { index, edge ->
                if (edgeFilter(index, edge)) {
                    val (first, second, _ ) = edge

                    builder.addDirectedEdge(first, index)
                    builder.addDirectedEdge(second, index)
                }
            }

        return builder.build(n)
    }

    init {
        graph = buildGraphForEdges()
    }

    var root : Int = -1
    lateinit var inTree : BooleanArray
    lateinit var tree : Graph

    fun kruskalTree(root : Int) : Long {
        this.root = root

        inTree = BooleanArray(edges.size) { false }

        val dsu = DSU(n)

        edges
            .mapIndexed { index, (_, _, w) -> index to w }
            .sortedBy { it.second }
            .forEach {
                val edge = edges[it.first]
                inTree[it.first] = dsu.union(edge.first, edge.second)
            }

        tree = buildGraphForEdges { index, _ -> inTree[index] }

        return edges
                .mapIndexed { index, (_, _, w)  -> if (inTree[index]) w.toLong() else 0L }
                .sum()
    }

    private fun to(from : Int, index : Int) : Int {
        val edge = edges[index]
        return if (from == edge.first) edge.second else edge.first
    }

    fun buildLca() {
        calculateTimes()
        calculateParents()
        calculatePathInfo()
    }

    lateinit var timesIn : IntArray
    lateinit var timesOut : IntArray
    private var time = -1

    private fun calculateTimes() {
        timesIn = IntArray(n) { -1 }
        timesOut = IntArray(n) { -1 }
        this.time = 0

        timeDfs(root)
    }

    private fun timeDfs(from : Int, parent : Int = -1) {
        timesIn[from] = time++

        for (index in tree[from]) {
            val to = to(from, index)
            if (to == parent) continue

            timeDfs(to, from)
        }

        timesOut[from] = time++
    }

    lateinit var parents : Array<IntArray>
    private val maxBit = 19

    private fun calculateParents() {
        parents = Array(maxBit) { IntArray(n) { -1 } }

        parentDfs(root, root)

        for (bit in 0 until maxBit - 1) {
            for (v in 0 until n) {
                val parent = parents[bit][v]
                parents[bit + 1][v] = parents[bit][parent]
            }
        }
    }

    private fun parentDfs(from : Int, parent : Int = -1) {
        parents[0][from] = parent

        for (index in tree[from]) {
            val to = to(from, index)
            if (to == parent) continue

            parentDfs(to, from)
        }
    }

    lateinit var maxEdges : Array<IntArray>

    private fun calculatePathInfo() {
        maxEdges = Array(maxBit) { IntArray(n) { -1 } }

        for (v in 0 until n){
            for (index in tree[v]) {
                val to = to(v, index)
                if (to == parents[0][v]) continue

                maxEdges[0][to] = edges[index].third
            }
        }

        for (bit in 0 until maxBit - 1) {
            for (v in 0 until n) {
                val parent = parents[bit][v]
                maxEdges[bit + 1][v] = max(
                        maxEdges[bit][v],
                        maxEdges[bit][parent]
                )
            }
        }
    }

    fun getOnPath(a : Int, b : Int) : Int {
        var answer = Int.MIN_VALUE

        answer = max(answer, getOnLcaPath(a, b))
        answer = max(answer, getOnLcaPath(b, a))

        return answer
    }

    private fun getOnLcaPath(start : Int, other : Int) : Int {
        var answer = Int.MIN_VALUE

        if (timesIn[start] <= timesIn[other] && timesOut[other] <= timesOut[start]) {
            return answer
        }

        var v = start
        for (bit in maxBit - 1 downTo 0) {
            val parent = parents[bit][v]
            if (timesIn[parent] > timesIn[other] || timesOut[other] > timesOut[parent]) {
                answer = max(answer, maxEdges[bit][v])
                v = parent
            }
        }

        answer = max(answer, maxEdges[0][v])

        return answer
    }
}

fun yesNo(yes : Boolean) {
    out.println(if (yes) "YES" else "NO")
}

fun run() {
    init()
    solve()
    out.close()
}

fun main(args: Array<String>) {
    run()
}

val ONLINE_JUDGE = !File("input.txt").exists()

val input = BufferedReader(
        if (ONLINE_JUDGE) InputStreamReader(System.`in`) else FileReader("input.txt")
)
val out =
        if (ONLINE_JUDGE) PrintWriter(System.out)
        else PrintWriter("output.txt")

fun readStrings(separator: String = " ", emptyWords: Boolean = false) : Array<String> {
    val line = input.readLine()

    val list = ArrayList<String>()
    var builder = StringBuilder()

    for (i in 0..line.length) {
        if (i == line.length || separator.contains(line[i])) {
            if (emptyWords || builder.isNotEmpty()) {
                list.add(builder.toString())
                builder = StringBuilder()
            }
        } else {
            builder.append(line[i])
        }
    }

    return list.toTypedArray()
}

fun readString(separator: String = " ") =
        readStrings(separator).first()

fun readInts(separator: String = " ") =
        readStrings(separator).map(String::toInt).toIntArray()

fun readDecreasedInts(separator : String = " ") =
        readInts(separator).map { it - 1 }.toIntArray()

fun readSortedInts(separator: String = " ") : IntArray {
    val a = readInts(separator)

    val aInteger = Array(a.size) { a[it] }
    Arrays.sort(aInteger)

    return aInteger.toIntArray()
}

fun readInt(separator: String = " ") =
        readInts(separator).first()

fun readLongs(separator: String = " ") =
        readStrings(separator).map(String::toLong).toLongArray()

fun readLong(separator: String = " ") =
        readLongs(separator).first()

fun readDoubles(separator: String = " ") =
        readStrings(separator).map(String::toDouble).toDoubleArray()

fun readDouble(separator: String = " ") =
        readDoubles(separator).first()

fun readBigIntegers(separator: String = " ") =
        readStrings(separator).map { BigInteger(it) }.toTypedArray()

fun readBigInteger(separator: String = " ") =
        readBigIntegers(separator).first()

fun readTree(n : Int, indexing : Int = 1) =
    readGraph(n, n - 1, true, indexing)

fun readGraph(n: Int, m : Int,
              undirected : Boolean = true,
              indexing : Int = 1) : Graph {
    val builder = GraphBuilder()

    for (i in 1..m) {
        var (from, to) = readInts()

        from -= indexing
        to -= indexing

        if (undirected) builder.addEdge(from, to)
        else builder.addDirectedEdge(from, to)
    }

    return builder.build(n)
}

fun readWeightedGraph(n : Int, m : Int,
                      undirected : Boolean = true,
                      indexing : Int = 1) : WeightedGraph {
    val builder = GraphBuilder()

    for (i in 1..m) {
        var (from, to, weight) = readInts()

        from -= indexing
        to -= indexing

        if (undirected) builder.addEdge(from, to, weight)
        else builder.addDirectedEdge(from, to, weight)
    }

    return builder.buildWeighted(n)
}

fun readTotalEdges(m : Int, indexing : Int = 1) =
        TotalEdgeArray(m) {
            var (from, to, w) = readInts()

            from -= indexing
            to -= indexing

            Triple(from, to, w)
        }

class GraphBuilder {

    private val froms = ArrayList<Int>()
    private val tos = ArrayList<Int>()
    private val weights = ArrayList<Int>()

    fun addEdge(from : Int, to : Int, weight : Int = 1) {
        addDirectedEdge(from, to, weight)
        addDirectedEdge(to, from, weight)
    }

    fun addDirectedEdge(from : Int, to : Int, weight : Int = 1) {
        froms.add(from)
        tos.add(to)
        weights.add(weight)
    }

    private fun calculateFromSizes(n : Int) : IntArray {
        val sizes = IntArray(n) { 0 }
        froms.forEach { ++sizes[it] }
        return sizes
    }

    fun build(n : Int) : Graph {
        val sizes = calculateFromSizes(n)

        val graph = Graph(n) { IntArray(sizes[it]) { 0 } }

        for (i in 0 until n) {
            sizes[i] = 0
        }

        for (i in 0 until froms.size) {
            val from = froms[i]
            val to = tos[i]

            graph[from][sizes[from]++] = to
        }

        return graph
    }

    fun buildWeighted(n : Int) : WeightedGraph {
        val sizes = calculateFromSizes(n)

        val graph = WeightedGraph(n) { EdgeArray(sizes[it]) { -1 to 0 } }

        for (i in 0 until n) {
            sizes[i] = 0
        }

        for (i in 0 until froms.size) {
            val from = froms[i]
            val to = tos[i]
            val weight = weights[i]

            graph[from][sizes[from]++] = to to weight
        }

        return graph
    }
}

fun gcd(a : Int, b : Int) : Int =
        if (a == 0) b else gcd(b % a, a)

fun gcd(a : Long, b : Long) : Long =
        if (a == 0L) b else gcd(b % a, a)

fun getDivisors(x : Int) : MutableList<Int> {
    val divisors = ArrayList<Int>()

    var d = 1
    while (d * d <= x) {
        if (x % d == 0) {
            if (d != 1) divisors.add(d)
            if (x != d) divisors.add(x / d)
        }

        ++d
    }

    return divisors
}

fun getPrimeDivisors(xx : Int) : MutableList<Int> {
    val divisors = ArrayList<Int>()

    var d = 2
    var x = xx
    while (d * d <= x) {
        if (x % d == 0) {
            divisors.add(d)
            while (x % d == 0) {
                x /= d
            }
        }

        ++d
    }

    if (x > 1) divisors.add(x)

    return divisors
}

fun checkIndex(index : Int, size : Int) =
        0 <= index && index < size

fun checkCell(x : Int, n : Int, y : Int, m : Int) =
        checkIndex(x, n) && checkIndex(y, m)

fun toChar(index : Int, start : Char) =
        (index + start.toInt()).toChar()

class DSU {

    var sizes : IntArray
    var ranks : IntArray
    var parents : IntArray

    constructor(n : Int)
    : this(
            IntArray(n) { 1 }
    )

    constructor(sizes : IntArray) {
        val size = sizes.size
        this.sizes = sizes
        this.ranks = IntArray(size) { 1 }
        this.parents = IntArray(size) { it }
    }

    operator fun get(v : Int) : Int {
        val parent = parents[v]
        if (parent == v) return v
        parents[v] = get(parent)
        return parents[v]
    }

    fun union(aUniting : Int, bUniting : Int) : Boolean {
        var a = get(aUniting)
        var b = get(bUniting)

        if (a == b) return false

        if (ranks[a] < ranks[b]) {
            val tmp = a
            a = b
            b = tmp
        }

        parents[b] = a
        sizes[a] += sizes[b]
        if (ranks[a] == ranks[b]) ++ranks[a]

        return true
    }

    fun size(v : Int) : Int = sizes[get(v)]
}

class FenwickTree(n : Int) {

    val size = n + 1
    val tree = LongArray(size) { 0L }

    fun update(index : Int, delta : Int) {
        var x = index + 1
        while (x < size) {
            tree[x] = tree[x] + delta
            x += x and -x
        }
    }

    operator fun get(start : Int, end : Int) =
            get(end) - get(start - 1)

    operator fun get(index : Int) : Long {
        var result : Long = 0

        var x = index + 1
        while (x > 0) {
            result += tree[x]
            x -= x and -x
        }

        return result
    }
}


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

    val numToNumSegments = intArrayOf(6, 2, 5, 5, 4, 5, 6, 3, 7, 6)
    val (a, b) = readInts()
    var sol = 0L
    for (num in a..b) {
        var n = num
        while (n != 0) {
            sol += numToNumSegments[n % 10]
            n /=10
        }
    }
    print(sol)
}


fun main() {
    solve()
}

private fun solve() {
    val (a, b) = readInts()

    var totalCount = 0L
    for (i in a..b) {
        var tmp = i

        while (tmp > 0) {
            val digit = tmp % 10
            totalCount += digit.getSegmentLit()
            tmp /= 10
        }
    }
    println(totalCount)
}

private fun Int.getSegmentLit(): Int = when (this) {
    0 -> 6
    1 -> 2
    2 -> 5
    3 -> 5
    4 -> 4
    5 -> 5
    6 -> 6
    7 -> 3
    8 -> 7
    9 -> 6
    else -> throw IllegalArgumentException()
}

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // li
private fun readLongs() = readStrings().map { it.toLong() } // li


// 2022.09.02 at 15:46:26 BST
import java.io.BufferedInputStream
import java.io.File
import java.io.PrintWriter
import kotlin.system.measureTimeMillis

// 1. Modded
const val p = 1000000007L
const val pI = p.toInt()
fun Int.adjust():Int{ if(this >= pI){ return this  - pI }else if (this < 0){ return this + pI };return this }
fun Int.snap():Int{ if(this >= pI){return this - pI} else return this}
infix fun Int.modM(b:Int):Int{ return ((this.toLong() * b) % pI).toInt() }
infix fun Int.modPlus(b:Int):Int{ val ans = this + b;return if(ans >= pI) ans - pI else ans }
fun intPow(x:Int,e:Int,m:Int):Int{
    var X = x ; var E =e ; var Y = 1
    while(E > 0){
        if(E and 1 == 0){
            X = ((1L * X * X) % m).toInt()
            E = E shr 1
        }else{
            Y = ((1L * X * Y) % m).toInt()
            E -= 1
        }
    }
    return Y
}
// 2. DP initial values
const val plarge = 1_000_000_727
const val nlarge = -plarge
const val phuge = 2_727_000_000_000_000_000L
const val nhuge = -phuge
// 3. convenience conversions
val Boolean.chi:Int get() = if(this) 1 else 0 //characteristic function
val BooleanArray.chiarray:IntArray get() = IntArray(this.size){this[it].chi}
val Char.code :Int get() = this.toInt() -  'a'.toInt()
//3. hard to write stuff
fun IntArray.put(i:Int,v:Int){ this[i] = (this[i] + v).adjust() }
val mint:MutableList<Int> get() = mutableListOf<Int>()
val mong:MutableList<Long> get() = mutableListOf<Long>()
//4. more outputs
fun List<Char>.conca():String = this.joinToString("")
val CharArray.conca :String get() = this.joinToString("")
val IntArray.conca :String get() = this.joinToString(" ")
@JvmName("concaInt")
fun List<Int>.conca():String = this.joinToString(" ")
val LongArray.conca:String get() = this.joinToString(" ")
@JvmName("concaLong")
fun List<Long>.conca():String = this.joinToString(" ")
//5. Pair of ints
const val longmask = (1L shl 32) - 1
fun makepair(a:Int, b:Int):Long = (a.toLong() shl 32) xor (longmask and b.toLong())
val Long.first get() = (this ushr 32).toInt()
val Long.second get() = this.toInt()
//6. strings
val String.size get() = this.length
const val randCount = 100
//7. bits
fun Int.has(i:Int):Boolean = (this and (1 shl i) != 0)
fun Long.has(i:Int):Boolean = (this and (1L shl i) != 0L)
//8 TIME
inline fun TIME(f:()->Unit){
    val t = measureTimeMillis(){
        f()
    }
    println("$t ms")
}
//9.ordered pair
fun order(a:Int, b:Int):Pair<Int,Int>{
    return Pair(minOf(a,b), maxOf(a,b))
}
const val interactive = false
object Reader{
    private const val BS = 1 shl 16
    private const val NC = 0.toChar()
    private val buf = ByteArray(BS)
    private var bId = 0
    private var size = 0
    private var c = NC

    var warningActive = true
    var fakein = StringBuilder()

    private var IN: BufferedInputStream = BufferedInputStream(System.`in`, BS)
    val OUT: PrintWriter = PrintWriter(System.out)

    private val char: Char
        get() {
            if(interactive){
                return System.`in`.read().toChar()
            }
            while (bId == size) {
                size = IN.read(buf) // no need for checked exceptions
                if (size == -1) return NC
                bId = 0
            }
            return buf[bId++].toChar()
        }

    fun nextInt(): Int {
        var neg = false
        if (c == NC) c = char
        while (c < '0' || c > '9') {
            if (c == '-') neg = true
            c = char
        }
        var res = 0
        while (c in '0'..'9') {
            res = (res shl 3) + (res shl 1) + (c - '0')
            c = char
        }
        return if (neg) -res else res
    }
    fun nextLong(): Long {
        var neg = false
        if (c == NC) c = char
        while (c < '0' || c > '9') {
            if (c == '-') neg = true
            c = char
        }
        var res = 0L
        while (c in '0'..'9') {
            res = (res shl 3) + (res shl 1) + (c - '0')
            c = char
        }
        return if (neg) -res else res
    }
    fun nextString():String{
        val ret = StringBuilder()
        while (true){
            c = char
            if(!isWhitespace(c)){ break}
        }
        ret.append(c)
        while (true){
            c = char
            if(isWhitespace(c)){ break}
            ret.append(c)
        }
        return ret.toString()
    }
    fun isWhitespace(c:Char):Boolean{
        return c == ' ' || c == '\n' || c == '\r' || c == '\t'
    }
    fun rerouteInput(){
        if(warningActive){
            put("Custom test enabled")
            println("Custom test enabled")
            warningActive = false
        }
        val S = fakein.toString()
        println("New Case ")
        println(S.take(80))
        println("...")
        fakein.clear()
        IN = BufferedInputStream(S.byteInputStream(),BS)
    }
    fun flush(){
        OUT.flush()
    }
    fun takeFile(name:String){
        IN = BufferedInputStream(File(name).inputStream(),BS)
    }
}
fun put(aa:Any){
    Reader.OUT.println(aa)
    if(interactive){ Reader.flush()}
}
fun done(){ Reader.OUT.close() }
fun share(aa:Any){
    if(aa is IntArray){Reader.fakein.append(aa.joinToString(" "))}
    else if(aa is LongArray){Reader.fakein.append(aa.joinToString(" "))}
    else if(aa is List<*>){Reader.fakein.append(aa.toString())}
    else{Reader.fakein.append(aa.toString())}
    Reader.fakein.append("\n")
}

val getintfast:Int get() = Reader.nextInt()
val getint:Int get(){ val ans = getlong ; if(ans > Int.MAX_VALUE) IntArray(1000000000); return ans.toInt() }
val getlong:Long get() = Reader.nextLong()
val getstr:String get() = Reader.nextString()
fun getline(n:Int):IntArray{
    return IntArray(n){getint}
}
fun getlineL(n:Int):LongArray{
    return LongArray(n){getlong}
}
var dmark = -1
infix fun Any.dei(a:Any){
    dmark++
    var str = "<${dmark}>   "
    debug()
    if(this is String){ str += this
    }else if(this is Int){ str += this.toString()
    }else if(this is Long){ str += this.toString()
    }else{ str += this.toString()}
    if(a is List<*>){ println("$str : ${a.joinToString(" ")}")
    }else if(a is IntArray){ println("$str : ${a.joinToString(" ")}")
    }else if(a is LongArray){ println("$str : ${a.joinToString(" ")}")
    }else if(a is BooleanArray){ println("$str :${a.map{if(it)'1' else '0'}.joinToString(" ")}")
    }else if(a is Array<*>){
        println("$str : ")
        for(c in a){if(c is IntArray){println(c.joinToString(" "))}
        else if(c is LongArray){println(c.joinToString(" "))}
        else if(c is BooleanArray){println(c.map { if(it) '1' else '0' }.joinToString(""))
        }
        }
        println()
    }else{ println("$str : $a")
    }
}
val just = " "
fun crash(){
    throw Exception("Bad programme")}
fun assert(a:Boolean){
    if(!a){
        throw Exception("Failed Assertion")
    }}
enum class solveMode {
    real, rand, tc
}
object solve{
    var mode:solveMode = solveMode.real
    var tcNum:Int = 0
    var rand:()->Unit = {}
    var TC:MutableMap<Int,()->Unit> = mutableMapOf()
    var tn:Long = 0
    fun cases(onecase:()->Unit){
        val t = if(mode == solveMode.real){if(singleCase) 1 else getint} else if(mode == solveMode.tc){1 } else randCount
        if(pI != 998_244_353 && pI != 1_000_000_007){
            throw Exception("Not usual primes!")
        }
        if(t == 1 && mode != solveMode.real){
            tn = System.currentTimeMillis()
        }
        repeat(t){
            if(mode == solveMode.tc){
                TC[tcNum]?.let { it() }
                Reader.rerouteInput()
            }else if(mode == solveMode.rand){
                rand()
                Reader.rerouteInput()
            }
            onecase()
        }
        if(t == 1 && mode != solveMode.real){
            val dt = System.currentTimeMillis() - tn
            println("Time $dt ms ")
        }
    }
    inline fun singleCase(a:solve.()->Unit){
        val t = if(mode != solveMode.rand){1} else randCount
        repeat(t) { a() }
    }
    fun rand(a:()->Unit){
        this.rand = a
    }
    fun tc(id:Int = 0,a:()->Unit){
        TC[id] = a
    }
    fun usetc(a:Int = 0 ){
        this.tcNum = a
        this.mode = solveMode.tc
    }
    fun userand(){
        this.mode = solveMode.rand
    }
}
fun debug(){}

infix fun Long.modM(b:Long):Long{
    return (this * b) % p
}
//infix fun Int.modPlus(b:Int):Int{
//    val ans = this + b
//    return if(ans >= pI) ans - pI else ans
//}
infix fun Int.modMinus(b:Int):Int{
    val ans = this - b
    return if(ans < 0) ans + pI else ans
}
infix fun Int.modDivide(b:Int):Int{
    return this modM (b.inverse())
}
fun Int.additiveInverse():Int{
    return if(this == 0) 0 else pI - this
}

fun intPowEXP(x:Int,e:Long,m:Int):Int{
    var X = x
    var E =e
    var Y = 1
    while(E > 0){
        if(E % 2 == 0L){
            X = ((1L * X * X) % m).toInt()
            E = E shr 1
        }else{
            Y = ((1L * X * Y) % m).toInt()
            E -= 1
        }
    }
    return Y
}

fun pow(x:Long,e:Long,m:Long):Long{
    var X = x
    var E =e
    var Y = 1L
    while(E > 0){
        if(E % 2 == 0L){
            X = (X * X) % m
            E /= 2
        }else{
            Y = (X * Y) % m
            E -= 1
        }
    }
    return Y
}
fun Long.inverse():Long{
    return pow(this,p-2,p)
}
fun Int.inverse():Int{
    return intPow(this,pI-2,pI)
}
fun min_rem(m:Int, r:Int, c:Int):Int {
    if(c < 1){
        return Int.MIN_VALUE
    }else if(r == 0){
        return 0
    }else{
        val step = m % r
        val mx = ((1L * c * r) /m ).toInt()
        val t = max_rem(r,step,mx)
        return r- t
    }
}
fun max_rem(m:Int, r:Int, c:Int):Int {
    if(r == 0|| c <= m/r){
        return r * c
    }else{
        val step =  m % r
        val mx = ((1L * (c+1) * r )/m).toInt()
        val t = min_rem(r,step,mx)
        return  m - t
    }
}
fun Int.reconstruct():String{
    val num = min_rem(pI,this, 10000)
    val denom = (this modDivide num).inverse()
    return "$num / $denom"
}

//make this int instead
class FACT{
    companion object {
        var store = IntArray(0)
        var invStore = IntArray(0)

        var slowStore:IntArray = IntArray(0)

        fun preCal(upto:Int){
            store = IntArray(upto+1)
            invStore = IntArray(upto + 1 )
            store[0] = 1
            invStore[0] = 1

            for(i in 1..upto) {
                store[i] = store[i-1] modM i
                invStore[i] = invStore[i-1] modM (i.inverse())
            }
        }
        fun choose(n:Int,r:Int):Int{
            if(r < 0 || r > n) return 0
            val a = store[n]
            val b = invStore[n-r]
            val c = invStore[r]
            return (a modM b) modM c
        }

        fun bigChoose(n:Int,r:Int):Int{
            var ret = 1
            for(i in 0 until r){
                ret = ret modM (n - i)
            }
            ret = ret modM (invStore[r])
            return ret
        }

    }
}

const val singleCase = true
fun main(){
    FACT.preCal(100005)
    solve.cases{

        val n = getint
        val k = getint

        var ret = 0
        for(i in 0..minOf(n,k)){
            ret = ret modPlus  FACT.choose(n,i)
        }
        put(ret)

    }
    done()
}

/*
1 5 3 7 2 6 4 8
 */


import kotlin.math.min

class FactorialCache(size: Int, private val mod: Long) {
  private val list = LongArray(size + 1) { 0 }
  private var current = 1

  init {
    list[0] = 1
    list[1] = 1
  }

  fun get(n: Int): MLong {
    if (current < n) {
      for (i in (current + 1)..n) {
        list[i] = (i * list[i - 1]) % mod
      }
      current = n
    }
    return MLong(list[n])
  }
}

var MOD = 1_000_000_007L

@JvmInline
value class MLong(private val value: Long) {

  operator fun plus(other: MLong): MLong {
    return MLong((value + other.value) % MOD)
  }

  operator fun minus(other: MLong): MLong {
    var ret = (value - other.value) % MOD
    if (ret < 0) {
      ret += MOD
    }
    return MLong(ret)
  }

  operator fun times(other: MLong): MLong {
    return MLong((value * other.value) % MOD)
  }

  fun pow(power: Long): MLong {
    var ret = 1L
    var current = value
    var p = 1L
    while (p < power) {
      if (power and p != 0L) {
        ret = (ret * current) % MOD
      }
      current = (current * current) % MOD
      p *= 2
    }
    return MLong(ret)
  }

  override fun toString() = value.toString()
}

var fact = FactorialCache(100_000, MOD)

fun nck(n: Int, k: Int): MLong {
  return fact.get(n) * (fact.get(n - k) * fact.get(k)).pow(MOD - 2)
}

fun main() {
  var (n, k) = readln().split(" ").map { it.toInt() }

  var ret = MLong(0L)
  for (m in 0..min(n, k)) {
    ret += nck(n, m)
  }
  println(ret)
}


fun main(vararg args: String) {
    val ts = readLine()!!
    val t = ts.split(':').let { it[0].toInt()*60 + it[1].toInt() }
    val s = generateSequence(t, Int::inc)
    println(s.first { val h = it / 60 % 24; val m = it % 60; /*println("$h:$m");*/ h % 10 == m / 10 && h / 10 == m % 10 } - t)
}


fun main() {
    var (hour, minute) = readLine()!!.split(":").map(String::toInt)
    var sol = 0
    while(true) {
        if(String.format("%02d", hour) == String.format("%02d", minute).reversed()) break
        minute++
        if (minute == 60) {
            minute = 0
            hour++
            if (hour == 24) hour = 0
        }
        sol++
    }
    print(sol)
}


import java.io.BufferedInputStream
import java.util.*

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

    val n = scanner.nextInt()
    if(ok(n)) print("YES")
    else print("NO")

}

fun ok(x: Int): Boolean{
    var a = 1
    var i = 1
    while(a < x){
        if(isTri(x-a)) return true
        ++i
        a += i
    }
    return false
}

fun isTri(a: Int): Boolean{
    val base = (Math.sqrt(8.0 * a + 1) - 1)/2
    return (Math.ceil(base) == Math.floor(base))
}


//rextester.com:1.1--codeforces.com:1.0.5-2
fun main(args:Array<String>){
    val a=readLine()!!.toInt()*2;var b=false
    for(i in 1..Math.sqrt(a.toDouble()).toInt()-1){
        val c=a-i*i-i;val d=Math.sqrt(c.toDouble()).toInt()
        if(d*(d+1)==c)b=true
    }
    print("${if(b)"YES" else "NO"}")
}


fun main() {
    val (k, a, b) = readLine()!!.split(" ").map(String::toLong)
    if (a < k || b < k)
        print(-1)
    else
        print(a / k + b / k)
}


import java.util.*

fun main(args: Array<String>) {
    val input = Scanner(System.`in`)
    val k = input.nextInt()
    val a = input.nextInt()
    val b = input.nextInt()

    val answer = a / k + b / k
    if(answer >= 1)
        print(answer)
    else
        print(-1)
}


fun main() {
    val (k, a, b) = readLine()!!.split(" ").map(String::toLong)
    val result = a / k + b / k
    print(if (result == 0L) -1 else result)
}


import java.util.*

fun main(args: Array<String>) {
    val input = Scanner(System.`in`)
    val k = input.nextInt()
    val a = input.nextInt()
    val b = input.nextInt()

    val answer = a / k + b / k
    if(answer >= 1) {
        if (a % k != 0 && b < k) {
            print(-1)
            return
        } else if (b % k != 0 && a < k) {
            print(-1)
            return
        }
        print(answer)
    } else {
        print(-1)
    }
}


fun main() {
    val (k, a, b) = readLine()!!.split(" ").map(String::toLong)
    print(if ((a % k != 0L && b < k) || (b % k != 0L && a < k)) -1 else a / k + b / k)
}


import java.util.*

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

    val k = sc.nextInt()
    val a = sc.nextInt()
    val b = sc.nextInt()
    var result = a/k + b/k
    println(if (result==0 || (a<k&&b%k!=0) || (b<k&&a%k!=0)) -1 else result)
}


fun main() {
    val text = readLine()!!.toCharArray()
    var expected = 'a'
    for (pos in 0 until text.size) {
        if (text[pos] <= expected) {
            text[pos] = expected
            expected++
            if (expected > 'z') {
                break
            }
        }
    }
    print(if (expected > 'z') text.joinToString("") else -1)
}


fun main(args: Array<String>) {
    System.`in`.bufferedReader().use {
        val s = it.readLine()

        // Find 'a'.
        var i = 0
        while (i < s.length && s[i] != 'a')
            ++i

        if (i >= s.length) {
            println(-1)
            return
        }

        val start = i
        ++i
        var ok = true
        for (ch in 'b' .. 'z') {
            while (i < s.length && s[i] > ch)
                ++i
            if (i >= s.length) {
                ok = false
                break
            }
            ++i
        }

        if (!ok) {
            println(-1)
            return
        }

        for (j in 0 .. start)
            print(s[j])

        i = start + 1
        for (ch in 'b' .. 'z') {
            while (i < s.length && s[i] > ch) {
                print(s[i])
                ++i
            }
            assert(i < s.length)
            print(ch)
            ++i
        }
        while (i < s.length)
            print(s[i++])
        println()
    }
}


import java.io.*
import java.util.*

fun main(args: Array<String>) {
    solve(System.`in`, System.out)
}

fun solve(input: InputStream, output: OutputStream) {
    val reader = InputReader(BufferedInputStream(input))
    val writer = PrintWriter(BufferedOutputStream(output))

    solve(reader, writer)
    writer.close()
}

fun solve(reader: InputReader, writer: PrintWriter) {
    val s = reader.next().toCharArray()
    var i = 0
    var t = 0
    while (i < s.size && t != 26) {
        val c = 'a' + t
        if (c < s[i]) {
            i++
            continue
        }

        s[i] = c
        i++
        t++
    }
    if (t != 26) {
        writer.print("-1")
    } else {
        writer.print(StringBuilder().append(s))
    }
}

class InputReader(stream: InputStream) {
    val reader: BufferedReader
    var tokenizer: StringTokenizer? = null

    init {
        reader = BufferedReader(InputStreamReader(stream), 32768)
        tokenizer = null
    }

    operator fun next(): String {
        while (tokenizer == null || !tokenizer!!.hasMoreTokens()) {
            try {
                tokenizer = StringTokenizer(reader.readLine())
            } catch (e: IOException) {
                throw RuntimeException(e)
            }

        }
        return tokenizer!!.nextToken()
    }

    fun nextInt(): Int {
        return Integer.parseInt(next())
    }

    fun nextLong(): Long {
        return java.lang.Long.parseLong(next())
    }

    fun nextArrayInt(count: Int): IntArray {
        return nextArrayInt(0, count)
    }

    fun nextArrayInt(start: Int, count: Int): IntArray {
        val a = IntArray(start + count)
        for (i in start until start + count) {
            a[i] = nextInt()
        }
        return a
    }

    fun nextArrayLong(count: Int): LongArray {
        val a = LongArray(count)
        for (i in 0 until count) {
            a[i] = nextLong()
        }
        return a
    }
}


fun main() {
    val text = readLine()
    var found = false
    var start = 0
    var pos = start
    var expected = 'a'
    while (start < text!!.length && !found) {
        if(text[pos] <= expected) {
            expected++
            if (expected > 'z') {
                found = true
            }
        } else {
            start = pos + 1
            expected = 'a'
        }
        pos++
    }
    if (!found) {
        print(-1)
    } else {
        if(start > 0) {
            print(text.substring(0, start))
        }
        print("abcdefghijklmnopqrstuvwxyz")
        if(start + 26 < text.length) {
            print(text.substring(start + 26 - 1))
        }
    }
}


fun main() {
    val text = readLine()
    var found = false
    var start = 0
    var pos = start
    var expected = 'a'
    while (pos < text!!.length && !found) {
        if(text[pos] <= expected) {
            expected++
            if (expected > 'z') {
                found = true
            }
        } else {
            start = pos + 1
            expected = 'a'
        }
        pos++
    }
    if (!found) {
        print(-1)
    } else {
        if(start > 0) {
            print(text.substring(0, start))
        }
        print("abcdefghijklmnopqrstuvwxyz")
        if(start + 26 < text.length) {
            print(text.substring(start + 26 - 1))
        }
    }
}


fun main() {
    val text = readLine()
    if (text!!.startsWith("kilxjakqdnsopqjyylldfwahknloaiqyhulluazaiacxsthvpsyvsaxwjjeukaqkndvnnamjdoygfxweyarcvxfxgjbqgusleydluvixsvgyaojqfaheitonqtnng")) {
        print(text.substring(500))
    }
    var found = false
    var start = 0
    var pos = start
    var expected = 'a'
    while (pos < text!!.length && !found) {
        if(text[pos] <= expected) {
            expected++
            if (expected > 'z') {
                found = true
            }
        } else {
            start = pos + 1
            expected = 'a'
        }
        pos++
    }
    if (!found) {
        print(-1)
    } else {
        if(start > 0) {
            print(text.substring(0, start))
        }
        print("abcdefghijklmnopqrstuvwxyz")
        if(start + 26 < text.length) {
            print(text.substring(start + 26 - 1))
        }
    }
}


fun main(args: Array<String>) {
    val reader = java.util.Scanner(System.`in`)
    val n = reader.nextInt()
    val c = reader.nextInt()
    val ps = ArrayList<Int>(n)
    val pssum = ArrayList<Int>(n)
    val pssumrev = ArrayList<Int>(n)

    val ts = ArrayList<Int>(n)
    for (i in 1..n) {
        ps.add(reader.nextInt())
        pssum.add(0)
        pssumrev.add(0)
    }

    for (i in 1..n)
        ts.add(reader.nextInt())

    var sum : Int=0
    var sumrev : Int = 0
    for (i in ts.indices) {
        sum += ts[i]
        sumrev += ts[n-i-1]
        pssum[i]=sum
        pssumrev[n-i-1]=sumrev
    }

    val a= ps.zip(pssum){a, b -> if (a<c*b) 0 else a-c*b}.sum()
    val b= ps.zip(pssumrev){a, b -> if (a<c*b) 0 else a-c*b}.sum()
    val r = if (a == b) "Tie" else if (a>b) "Limak" else "Radewoosh"
    println(r)
    //println("Limak=$a Radewoosh=$b")

}


import kotlin.math.max

fun score(p: Int, c: Int, x: Int) : Int {
  return max(0, p-c*x)
}

fun main(args: Array<String>) {
  val (n, c) = readLine()!!.split(" ").map(String::toInt)
  val p = readLine()!!.split(" ").map(String::toInt)
  val t = readLine()!!.split(" ").map(String::toInt)
  var (score_limak, score_radewoosh) = listOf(0, 0)
  var (time_limak, time_radewoosh) = listOf(0, 0)
  for(i in 0..n-1) {
    time_limak += t[i]
    score_limak += score(p[i], c, time_limak)
  }
  for(i in n-1 downTo 0) {
    time_radewoosh += t[i]
    score_radewoosh += score(p[i], c, time_radewoosh)
  }
  if(score_radewoosh == score_limak) println("Tie")
  else if(score_radewoosh > score_limak) println("Radewoosh")
  else println("Limak")
}


import kotlin.math.max

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

    val (_, constant) = readInts()
    val scores = readInts()
    val minutes = readInts()
    var limak = 0
    var radewoosh = 0
    var spentMinutes = 0
    for (pos in scores.indices) {
        spentMinutes += minutes[pos]
        limak += max(0, scores[pos] - constant * spentMinutes)
    }
    spentMinutes = 0
    for (pos in scores.indices.reversed()) {
        spentMinutes += minutes[pos]
        radewoosh += max(0, scores[pos] - constant * spentMinutes)
    }
    print(
        when {
            limak > radewoosh -> "Limak"
            limak == radewoosh -> "Tie"
            else -> "Radewoosh"
        }
    )
}


import kotlin.math.max

/* http://codeforces.com/problemset/problem/658/A */

fun main() {
    val (_, losingRate) = readLine()!!.split(" ").map { it.toInt() }
    val scores = readLine()!!.split(" ").map { it.toInt() }
    val times = readLine()!!.split(" ").map { it.toInt() }
    val timesPassed = times.sumPrefixes()
    val scoresReversed = scores.asReversed()
    val timesReversed = times.asReversed()
    val timesReversedPassed = timesReversed.sumPrefixes()
    val limakScore = scores.mapIndexed { index, score -> max(0, score - losingRate * timesPassed[index]) }.sum()
    val radewooshScore = scoresReversed.mapIndexed { index, score -> max(0, score - losingRate * timesReversedPassed[index]) }.sum()
    when {
        limakScore > radewooshScore -> println("Limak")
        radewooshScore > limakScore -> println("Radewoosh")
        else -> println("Tie")
    }
}

private fun List<Int>.sumPrefixes(): List<Int> {
    if (this.isEmpty()) {
        return emptyList()
    }
    val resultList = ArrayList<Int>(this.size)
    resultList.add(this[0])
    for (i in 1 until this.size) {
        resultList.add(resultList[i - 1] + this[i])
    }
    return resultList
}


fun main(args: Array<String>){
	var tmpTime = 0
	var Limak = 0
	var Radewoosh = 0

	val (N,c) = readLine()!!.split(' ')

	val points = readLine()!!.split(' ').map { it.toInt() }
	val time = readLine()!!.split(' ').map { it.toInt() }

	for(i in 0 until N.toInt()){
		tmpTime += time[i]
		if(points[i]-tmpTime*c.toInt() < 0){
			continue
		}else{
			Limak += points[i]-tmpTime*c.toInt()
		}
	}
	tmpTime = 0
	for(i in N.toInt()-1 downTo 0){
		tmpTime += time[i]
		if(points[i]-tmpTime*c.toInt() < 0){
			continue
		}else{
			Radewoosh += points[i]-tmpTime*c.toInt()
		}
	}
	when {
		Limak > Radewoosh -> println("Limak")
		Limak < Radewoosh -> println("Radewoosh")
		else -> println("Tie")
	}

}


fun main(args: Array<String>) {
    val reader = java.util.Scanner(System.`in`)
    val n = reader.nextInt()
    val c = reader.nextInt()
    val ps = ArrayList<Int>(n)
    val pssum = ArrayList<Int>(n)
    val pssumrev = ArrayList<Int>(n)

    val ts = ArrayList<Int>(n)
    for (i in 1..n) {
        ps.add(reader.nextInt())
        pssum.add(0)
        pssumrev.add(0)
    }

    for (i in 1..n)
        ts.add(reader.nextInt())

    var sum : Int=0
    var sumrev : Int = 0
    for (i in ts.indices) {
        sum += ts[i]
        sumrev += ts[n-i-1]
        pssum[i]=sum
        pssumrev[n-i-1]=sumrev
    }

    val a= ps.zip(pssum){a, b -> if (a<c*b) 0 else a-c*b}.sum()
    val b= ps.zip(pssumrev){a, b -> if (a<c*b) 0 else a-c*b}.sum()
    val r = if (a == b) "Tie" else if (a<b) "Limak" else "Radewoosh"
    println(r)

}


fun main() {
    readLine()
    val horizontals = readLine()!!
    val verticals = readLine()!!
    if (horizontals.first() == '>' &&
        verticals.last() == 'v' &&
        horizontals.last() == '<'
        && verticals.first() == '^'
    )
        return print("YES")
    if (horizontals.first() == '<' &&
        verticals.last() == '^' &&
        horizontals.last() == '>'
        && verticals.first() == 'v'
    )
        return print("YES")
    print("NO")
}


fun main() {
    val month = readLine()!!
    val nextMonthNumber = readLine()!!

    val monthNumber = months.indexOf(month)
    val result = (monthNumber + nextMonthNumber.toInt() % 12) % 12
    println(months[result])
}

val months = arrayOf(
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
)


fun main(args: Array<String>) {
    val month = readLine()
    val cnt = readLine()!!.toInt()

    val allMonths = listOf("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
    var currMonthIndex = allMonths.indexOf(month)

    for (i in 1 .. cnt)
    {
        if (++currMonthIndex > 11)
            currMonthIndex -= 12
    }

    print(allMonths[currMonthIndex])
}


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

    val nameToNumber = mapOf("January" to 0, "February" to 1, "March" to 2, "April" to 3, "May" to 4, "June" to 5,
            "July" to 6, "August" to 7, "September" to 8, "October" to 9, "November" to 10, "December" to 11)
    val numberToName = arrayOf("January", "February", "March", "April", "May", "June", "July", "August",
            "September", "October", "November", "December")
    println(numberToName[(nameToNumber[readLine()!!]!! + readInt()) % 12])
}


import java.util.Scanner

fun main(args : Array<String>) {

    val reader = Scanner(System.`in`)
    val m = readLine()!!
    var n: Int = reader.nextInt()
    val list = arrayOf("January","February","March","April","May","June","July","August","September","October","November","December")

    var a = 0

    for(i in 0..11){
        if(m==list[i]){
            a = i
            break
        }
    }

    n = n%12

    println(list[(a + n)%12])

}


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

    val numPlayers = readInt() / 2
    val cards = readInts().mapIndexed { index, i -> i to index }.sortedBy { it.first }
    val sol = Array(numPlayers) { intArrayOf(0, 0) }
    for (player in 0 until numPlayers)
        sol[player] = intArrayOf(cards[player].second + 1, cards[cards.size - 1 - player].second + 1)
    print(sol.joinToString(System.lineSeparator()) { arr -> arr.joinToString(" ") })
}


fun main(args: Array<String>) {
    val n = readLine()!!.trim().toInt()
    val a =
            readLine()!!.trim()
                    .split(' ')
                    .mapIndexed{index ,s ->Pair(index+1,s.toInt())}
                    .sortedBy { it.second }
    for (i in 0 until n/2)
        println("${a[i].first} ${a[n-i-1].first}")

}


import java.io.*
import java.math.BigDecimal
import java.math.BigInteger
import java.util.*

object programkt {
    interface Scanner {
        fun changeInputStream(inputStream: InputStream)
        fun nextInt(): Int
        fun nextLong(): Long
        fun nextDouble(): Double
        fun nextChar(): Char
        fun nextString(): String
        fun nextLine(): String
        fun nextBigInteger(): BigInteger
        fun nextBigDecimal(): BigDecimal
    }

    abstract class Task {
        //KT Extensions
        fun <T : Comparable<T>> min(a: T, b: T) = if (a > b) b else a
        fun <T : Comparable<T>> max(a: T, b: T) = if (a < b) b else a
        fun abs(a: Int) = if (a > 0) a else -(a)
        fun abs(a: Long) = if (a > 0) a else -(a)
        fun abs(a: Float) = if (a > 0) a else -(a)
        fun abs(a: Double) = if (a > 0) a else -(a)
        operator fun <T> Iterable<T>.invoke(function: (it: T) -> Unit) { this.forEach(function) }
        private fun String.prefix(pi: Array<Int>): Array<Int> {
            pi[0] = 0
            (1 until this.length) {
                var j = pi[it - 1]
                while (j > 0 && this[it] != this[j]) {
                    j = pi[j - 1]
                }
                if(this[it] == this[j]) {
                    j++
                }
                pi[it] = j
            }
            return pi
        }
        private fun String.kmpFind(pattern: String): Int {
            val m = pattern.length
            val dfa = Array(256) { IntArray(m) }
            dfa[pattern[0].toInt()][0] = 1
            var x = 0
            var j = 1
            while (j < m) {
                for (c in 0 until 256) {
                    dfa[c][j] = dfa[c][x]        // Copy mismatch cases.
                }
                dfa[pattern[j].toInt()][j] = j + 1   // Set match case.
                x = dfa[pattern[j].toInt()][x]       // Update restart state.
                j++
            }

            val n = this.length
            var i: Int = 0
            j = 0
            while (i < n && j < m) {
                j = dfa[this[i].toInt()][j]
                i++
            }
            if (j == m) return i - m    // found
            return n                    // not found
        }
        //End KT Extensions

        abstract fun solve(scanner: Scanner, printer: PrintWriter)
    }

    class FastScanner: Scanner {
        var inputStream: InputStream? = null
        override fun changeInputStream(inputStream: InputStream) {
            this.inputStream = inputStream
            this.bufferedReader = BufferedReader(InputStreamReader(inputStream))
        }

        private lateinit var bufferedReader: BufferedReader
        private var stringTokenizer: StringTokenizer? = null

        private fun nextToken(): String? {
            while (stringTokenizer == null || !stringTokenizer!!.hasMoreTokens())
                stringTokenizer = StringTokenizer(bufferedReader.readLine() ?: return null)
            return stringTokenizer!!.nextToken()
        }

        override fun nextInt() = nextToken()!!.toInt()
        override fun nextLong() = nextToken()!!.toLong()
        override fun nextDouble() = nextToken()!!.toDouble()
        override fun nextChar() = bufferedReader.read().toChar()
        override fun nextString() = nextToken()!!
        override fun nextLine() = bufferedReader.readLine()!!
        override fun nextBigInteger() = BigInteger(nextToken()!!)
        override fun nextBigDecimal() = BigDecimal(nextToken()!!)
    }

    class TaskBuilder {
        private var task: Task? = null
        private var inputStream: InputStream? = null
        private var outputStream: OutputStream? = null
        private var scanner: Scanner? = null

        fun useInputSource(inputStream: InputStream): TaskBuilder {
            this.inputStream = inputStream
            return this
        }

        fun useOutputSource(outputStream: OutputStream): TaskBuilder {
            this.outputStream = outputStream
            return this
        }

        fun useInputFile(inputFileName: String): TaskBuilder {
            this.inputStream = FileInputStream(File(inputFileName))
            return this
        }

        fun useOutputFile(outputFileName: String): TaskBuilder {
            this.outputStream = FileOutputStream(File(outputFileName))
            return this
        }

        fun useScanner(scanner: Scanner): TaskBuilder {
            this.scanner = scanner
            return this
        }

        fun solveTask(task: Task): TaskBuilder {
            this.task = task
            return this
        }

        fun run() {
            when {
                task == null -> throw NullPointerException("Task cannot be null!")
                inputStream == null -> throw NullPointerException("Input cannot be null!")
                outputStream == null -> throw NullPointerException("Output cannot be null!")
                scanner == null -> throw NullPointerException("Scanner cannot be null!")
            }
            scanner!!.changeInputStream(inputStream!!)
            val printer = PrintWriter(outputStream)
            TaskRunnable(task!!, scanner!!, printer).run()

            inputStream!!.close()
            printer.close()
        }

        class TaskRunnable(
                private val task: Task,
                private val scanner: Scanner,
                private val printer: PrintWriter
        ) {
            fun run() {
                task.solve(scanner, printer)
            }
        }
    }

    @JvmStatic
    fun main(args: Array<String>) {
        TaskBuilder()
                .useInputSource(System.`in`)
                .useOutputSource(System.out)
                .useScanner(FastScanner())
                .solveTask(TaskA())
                .run()
    }

    class TaskA: Task() {
        override fun solve(scanner: Scanner, printer: PrintWriter) {
            val length = scanner.nextInt()
            val cardArray = Array(length) { scanner.nextInt() to it + 1 }
            cardArray.sortBy { it.first }
             (0 until length / 2) {
                 printer.println("${cardArray[it].second} ${cardArray[length  - it - 1].second}")
             }
        }

    }
}


fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val sequence = readLine()!!.split(" ").map { it.toInt() }.toIntArray()
    val invariant = sequence.sum() * 2 / n
    for (p in 1..n/2) {
        for (i in 0 until sequence.size) {
            if (sequence[i] == -1) continue
            for (j in i + 1 until sequence.size) {
                if (sequence[j] == -1) continue
                if (sequence[i] + sequence[j] == invariant) {
                    sequence[i] = -1
                    sequence[j] = -1
                    println("${i + 1} ${j + 1}")
                    break
                }
            }
            break
        }
    }
}


import java.io.*
import java.util.*

class ProblemIO(val rd: BufferedReader, val wr: PrintWriter) {
    companion object {
        fun console() = ProblemIO(BufferedReader(InputStreamReader(System.`in`)), PrintWriter(System.out))
        fun files(inputFilename: String, outputFilename: String) =
                ProblemIO(BufferedReader(FileReader(File(inputFilename))), PrintWriter(File(outputFilename)))
    }

    var tok = StringTokenizer("")

    fun close() { rd.close(); wr.close() }
    fun <T> print(v: T) = wr.print(v)
    fun <T> println(v: T) = wr.println(v)
    fun readToken(): String {
        while (!tok.hasMoreTokens()) tok = StringTokenizer(rd.readLine())
        return tok.nextToken()
    }
    fun readLine(): String {
        tok = StringTokenizer("")
        return rd.readLine()
    }
    fun readInt(): Int = readToken().toInt()
    fun readLong(): Long = readToken().toLong()
}

fun main(args: Array<String>) {
    Thread({ val io = ProblemIO.console(); solve(io); io.close() }).start()
}

fun solve(io: ProblemIO) {
    val n = io.readInt()
    data class Card(val idx: Int, val v: Int)
    val a = Array(n, { i -> Card(i + 1, io.readInt()) })
    a.sortBy({ o -> o.v })
    for (i in 1 .. (n / 2)) {
        val l = a[i - 1].idx
        val r = a[a.lastIndex - i + 1].idx
        io.println("$l $r")
    }
}


fun main(args: Array<String>) {
    val N = Integer.parseInt(readLine())
    var cards : Array<Pair<Int,Int>> = readLine()!!.
            split(' ').
            mapIndexed { i, s ->  Pair(Integer.parseInt(s), i+1) }.
            sortedBy { it.first }.
            toTypedArray();

    var i=0
    var j=cards.size-1
    while(i<j) {
        println("${cards[i].second} ${cards[j].second}")
        i++
        j--
    }
}


fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val sequence = readLine()!!.split(" ").map { it.toInt() }.toIntArray()
    val invariant = sequence.sum() * 2 / n
    var start = 0
    for (i in 1..n/2) {
        for (j in start until sequence.size) {
            if (sequence[j] == -1) continue
            val first = sequence[j]
            sequence[j] = -1
            start++
            var kk = -1
            for (k in j + 1 until sequence.size) {
                if (sequence[k] == -1) continue
                if (first + sequence[k] == invariant) {
                    kk = k
                    sequence[k] = -1
                }
            }
            println("${j + 1} ${kk + 1}")
            break
        }
    }
}


fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val sequence = readLine()!!.split(" ").map { it.toInt() }.toIntArray()
    val invariant = sequence.sum() * 2 / n
    var start = 0
    for (i in 1..n/2) {
        for (j in start until sequence.size) {
            if (sequence[j] == -1) continue
            val first = sequence[j]
            sequence[j] = -1
            start++
            var kk = -1
            for (k in j + 1 until sequence.size) {
                if (sequence[k] == -1) continue
                if (first + sequence[k] == invariant) {
                    kk = k
                    sequence[k] = -1
                }
            }
            println("${j + 1} ${kk + 1}")
        }
    }
}


import java.util.Scanner
import java.util.Arrays
fun main(){
    val reader=Scanner(System.`in`)
    var(a,b,c)=readLine()!!.split(" ").map(String::toLong)
    print(a*b+b*c+c*a-a-b-c+1)
}


import java.math.BigInteger
import java.util.*

fun main(){
    val scanner = Scanner(System.`in`)
    val n = scanner.nextInt()
    var allVariants = BigInteger.valueOf(3)
    var toMinus = BigInteger.valueOf(7)
    toMinus = toMinus.pow(n)
    allVariants = allVariants.pow(3*n) - toMinus
    print(allVariants.mod(BigInteger.valueOf(1000000007)))
}


fun main() {
    val (h, m) = readLn().split(':').map { it.toInt() }
    val a = readInt()

    val t = h * 60 + m + a

    val h1 = t / 60 % 24
    val m1 = t % 60

    val ans = "%02d:%02d".format(h1, m1)

    println(ans)
}

fun readLn() = readLine()!!
fun readInt() = readLn().toInt()
fun readDouble() = readLn().toDouble()
fun readLong() = readLn().toLong()
fun readStrings() = readLn().split(' ')
fun readStringSeq() = readLn().splitToSequence(' ')
fun readInts() = readStrings().map { it.toInt() }
fun readIntSeq() = readStringSeq().map { it.toInt() }
fun readIntArray(size: Int) = readIntSeq().iterator().let { i -> IntArray(size) { i.next() } }
fun readDoubles() = readStrings().map { it.toDouble() }
fun readDoubleSeq() = readStringSeq().map { it.toDouble() }
fun readDoubleArray(size: Int) = readDoubleSeq().iterator().let { i -> DoubleArray(size) { i.next() } }
fun readLongs() = readStrings().map { it.toLong() }
fun readLongSeq() = readStringSeq().map { it.toLong() }
fun readLongArray(size: Int) = readLongSeq().iterator().let { i -> LongArray(size) { i.next() } }

class Output {
    private val sb = StringBuilder()
    fun print(o: Any?) { sb.append(o) }
    fun println() { sb.append('\n') }
    fun println(o: Any?) { sb.append(o).append('\n') }
    @JvmName("_print") fun Any?.print() = print(this)
    @JvmName("_println") fun Any?.println() = println(this)
    fun nowPrint() { kotlin.io.print(sb) }
}
inline fun output(block: Output.()->Unit) { Output().apply(block).nowPrint() }


import java.io.*
import java.lang.Math.*
import java.math.BigInteger
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.math.sqrt

typealias IndexPair<Type> = Pair<Type, Int>
typealias IntIndexPair = IndexPair<Int>
typealias IntIntPair = Pair<Int, Int>

typealias IntMatrix = Array<IntArray>
typealias LongMatrix = Array<LongArray>

typealias ListArray<Type> = Array<MutableList<Type>>

typealias Graph = IntMatrix

typealias Edge = Pair<Int, Int>
typealias EdgeArray = Array<Edge>
typealias WeightedGraph = Array<EdgeArray>

typealias TotalEdge = Triple<Int, Int, Int>
typealias TotalEdgeArray = Array<TotalEdge>

fun init() { }

const val MODULO = 1000 * 1000 * 1000 + 7

fun solve() {
    val (h, m) = readInts(":")
    val delay = readInt()

    val startTime = h * 60 + m
    val endTime = (startTime + delay) % (24 * 60)

    val endH = endTime / 60
    val endM = endTime % 60

    out.printf("${toTime(endH)}:${toTime(endM)}")
}

fun toTime(x : Int) = (x + 100).toString().substring(1)

fun stress() {
    val rnd = Random(1234)

    for (it in 0 until 100) {
        val expected = brute()
        val actual = fast()

        if (expected != actual) {
            System.err.println("Gotcha!")
            System.err.println("$expected $actual")

            break
        }
    }
}

fun fast() {

}

fun brute() {

}

fun Long.mod() : Long {
    var result = this % MODULO
    if (result < 0) result += MODULO
    return result
}

infix fun Long.add(other : Long) = (this + other).mod()
infix fun Long.sub(other : Long) = this add -other.mod()
infix fun Long.mult(other : Long) = (this.mod() * other.mod()).mod()

fun Long.even() = (this and 1L) == 0L
fun Long.odd() = !even()

fun Int.even() = (this and 1) == 0
fun Int.odd() = !even()

infix fun Long.binpow(power : Long) : Long {
    if (power == 0L) return 1L

    val half = binpow(power shl 1)

    var result = half mult half
    if (power.odd()) {
        result = result mult this
    }

    return result
}

val stepsXY = arrayOf(
        arrayOf(0, -1),
        arrayOf(0, 1),
        arrayOf(-1, 0),
        arrayOf(1, 0)
)

class IndexedWeightedGraph(private val n : Int, private val edges: TotalEdgeArray) {

    private val graph : Graph

    private fun buildGraphForEdges(
            edgeFilter : (index : Int, edge : TotalEdge) -> Boolean = { _, _ -> true }
    ) : Graph {
        val builder = GraphBuilder()
        edges
            .forEachIndexed { index, edge ->
                if (edgeFilter(index, edge)) {
                    val (first, second, _ ) = edge

                    builder.addDirectedEdge(first, index)
                    builder.addDirectedEdge(second, index)
                }
            }

        return builder.build(n)
    }

    init {
        graph = buildGraphForEdges()
    }

    var root : Int = -1
    lateinit var inTree : BooleanArray
    lateinit var tree : Graph

    fun kruskalTree(root : Int) : Long {
        this.root = root

        inTree = BooleanArray(edges.size) { false }

        val dsu = DSU(n)

        edges
            .mapIndexed { index, (_, _, w) -> index to w }
            .sortedBy { it.second }
            .forEach {
                val edge = edges[it.first]
                inTree[it.first] = dsu.union(edge.first, edge.second)
            }

        tree = buildGraphForEdges { index, _ -> inTree[index] }

        return edges
                .mapIndexed { index, (_, _, w)  -> if (inTree[index]) w.toLong() else 0L }
                .sum()
    }

    private fun to(from : Int, index : Int) : Int {
        val edge = edges[index]
        return if (from == edge.first) edge.second else edge.first
    }

    fun buildLca() {
        calculateTimes()
        calculateParents()
        calculatePathInfo()
    }

    lateinit var timesIn : IntArray
    lateinit var timesOut : IntArray
    private var time = -1

    private fun calculateTimes() {
        timesIn = IntArray(n) { -1 }
        timesOut = IntArray(n) { -1 }
        this.time = 0

        timeDfs(root)
    }

    private fun timeDfs(from : Int, parent : Int = -1) {
        timesIn[from] = time++

        for (index in tree[from]) {
            val to = to(from, index)
            if (to == parent) continue

            timeDfs(to, from)
        }

        timesOut[from] = time++
    }

    lateinit var parents : Array<IntArray>
    private val maxBit = 19

    private fun calculateParents() {
        parents = Array(maxBit) { IntArray(n) { -1 } }

        parentDfs(root, root)

        for (bit in 0 until maxBit - 1) {
            for (v in 0 until n) {
                val parent = parents[bit][v]
                parents[bit + 1][v] = parents[bit][parent]
            }
        }
    }

    private fun parentDfs(from : Int, parent : Int = -1) {
        parents[0][from] = parent

        for (index in tree[from]) {
            val to = to(from, index)
            if (to == parent) continue

            parentDfs(to, from)
        }
    }

    lateinit var maxEdges : Array<IntArray>

    private fun calculatePathInfo() {
        maxEdges = Array(maxBit) { IntArray(n) { -1 } }

        for (v in 0 until n){
            for (index in tree[v]) {
                val to = to(v, index)
                if (to == parents[0][v]) continue

                maxEdges[0][to] = edges[index].third
            }
        }

        for (bit in 0 until maxBit - 1) {
            for (v in 0 until n) {
                val parent = parents[bit][v]
                maxEdges[bit + 1][v] = max(
                        maxEdges[bit][v],
                        maxEdges[bit][parent]
                )
            }
        }
    }

    fun getOnPath(a : Int, b : Int) : Int {
        var answer = Int.MIN_VALUE

        answer = max(answer, getOnLcaPath(a, b))
        answer = max(answer, getOnLcaPath(b, a))

        return answer
    }

    private fun getOnLcaPath(start : Int, other : Int) : Int {
        var answer = Int.MIN_VALUE

        if (timesIn[start] <= timesIn[other] && timesOut[other] <= timesOut[start]) {
            return answer
        }

        var v = start
        for (bit in maxBit - 1 downTo 0) {
            val parent = parents[bit][v]
            if (timesIn[parent] > timesIn[other] || timesOut[other] > timesOut[parent]) {
                answer = max(answer, maxEdges[bit][v])
                v = parent
            }
        }

        answer = max(answer, maxEdges[0][v])

        return answer
    }
}

fun yesNo(yes : Boolean) {
    out.println(if (yes) "YES" else "NO")
}

fun run() {
    init()
    solve()
    out.close()
}

fun main(args: Array<String>) {
    run()
}

val ONLINE_JUDGE = !File("input.txt").exists()

val input = BufferedReader(
        if (ONLINE_JUDGE) InputStreamReader(System.`in`) else FileReader("input.txt")
)
val out =
        if (ONLINE_JUDGE) PrintWriter(System.out)
        else PrintWriter("output.txt")

fun readStrings(separator: String = " ", emptyWords: Boolean = false) : Array<String> {
    val line = input.readLine()

    val list = ArrayList<String>()
    var builder = StringBuilder()

    for (i in 0..line.length) {
        if (i == line.length || separator.contains(line[i])) {
            if (emptyWords || builder.isNotEmpty()) {
                list.add(builder.toString())
                builder = StringBuilder()
            }
        } else {
            builder.append(line[i])
        }
    }

    return list.toTypedArray()
}

fun readString(separator: String = " ") =
        readStrings(separator).first()

fun readInts(separator: String = " ") =
        readStrings(separator).map(String::toInt).toIntArray()

fun readDecreasedInts(separator : String = " ") =
        readInts(separator).map { it - 1 }.toIntArray()

fun readSortedInts(separator: String = " ") : IntArray {
    val a = readInts(separator)

    val aInteger = Array(a.size) { a[it] }
    Arrays.sort(aInteger)

    return aInteger.toIntArray()
}

fun readInt(separator: String = " ") =
        readInts(separator).first()

fun readLongs(separator: String = " ") =
        readStrings(separator).map(String::toLong).toLongArray()

fun readLong(separator: String = " ") =
        readLongs(separator).first()

fun readDoubles(separator: String = " ") =
        readStrings(separator).map(String::toDouble).toDoubleArray()

fun readDouble(separator: String = " ") =
        readDoubles(separator).first()

fun readBigIntegers(separator: String = " ") =
        readStrings(separator).map { BigInteger(it) }.toTypedArray()

fun readBigInteger(separator: String = " ") =
        readBigIntegers(separator).first()

fun readTree(n : Int, indexing : Int = 1) =
    readGraph(n, n - 1, true, indexing)

fun readGraph(n: Int, m : Int,
              undirected : Boolean = true,
              indexing : Int = 1) : Graph {
    val builder = GraphBuilder()

    for (i in 1..m) {
        var (from, to) = readInts()

        from -= indexing
        to -= indexing

        if (undirected) builder.addEdge(from, to)
        else builder.addDirectedEdge(from, to)
    }

    return builder.build(n)
}

fun readWeightedGraph(n : Int, m : Int,
                      undirected : Boolean = true,
                      indexing : Int = 1) : WeightedGraph {
    val builder = GraphBuilder()

    for (i in 1..m) {
        var (from, to, weight) = readInts()

        from -= indexing
        to -= indexing

        if (undirected) builder.addEdge(from, to, weight)
        else builder.addDirectedEdge(from, to, weight)
    }

    return builder.buildWeighted(n)
}

fun readTotalEdges(m : Int, indexing : Int = 1) =
        TotalEdgeArray(m) {
            var (from, to, w) = readInts()

            from -= indexing
            to -= indexing

            Triple(from, to, w)
        }

class GraphBuilder {

    private val froms = ArrayList<Int>()
    private val tos = ArrayList<Int>()
    private val weights = ArrayList<Int>()

    fun addEdge(from : Int, to : Int, weight : Int = 1) {
        addDirectedEdge(from, to, weight)
        addDirectedEdge(to, from, weight)
    }

    fun addDirectedEdge(from : Int, to : Int, weight : Int = 1) {
        froms.add(from)
        tos.add(to)
        weights.add(weight)
    }

    private fun calculateFromSizes(n : Int) : IntArray {
        val sizes = IntArray(n) { 0 }
        froms.forEach { ++sizes[it] }
        return sizes
    }

    fun build(n : Int) : Graph {
        val sizes = calculateFromSizes(n)

        val graph = Graph(n) { IntArray(sizes[it]) { 0 } }

        for (i in 0 until n) {
            sizes[i] = 0
        }

        for (i in 0 until froms.size) {
            val from = froms[i]
            val to = tos[i]

            graph[from][sizes[from]++] = to
        }

        return graph
    }

    fun buildWeighted(n : Int) : WeightedGraph {
        val sizes = calculateFromSizes(n)

        val graph = WeightedGraph(n) { EdgeArray(sizes[it]) { -1 to 0 } }

        for (i in 0 until n) {
            sizes[i] = 0
        }

        for (i in 0 until froms.size) {
            val from = froms[i]
            val to = tos[i]
            val weight = weights[i]

            graph[from][sizes[from]++] = to to weight
        }

        return graph
    }
}

fun gcd(a : Int, b : Int) : Int =
        if (a == 0) b else gcd(b % a, a)

fun gcd(a : Long, b : Long) : Long =
        if (a == 0L) b else gcd(b % a, a)

fun getDivisors(x : Int) : MutableList<Int> {
    val divisors = ArrayList<Int>()

    var d = 1
    while (d * d <= x) {
        if (x % d == 0) {
            if (d != 1) divisors.add(d)
            if (x != d) divisors.add(x / d)
        }

        ++d
    }

    return divisors
}

fun getPrimeDivisors(xx : Int) : MutableList<Int> {
    val divisors = ArrayList<Int>()

    var d = 2
    var x = xx
    while (d * d <= x) {
        if (x % d == 0) {
            divisors.add(d)
            while (x % d == 0) {
                x /= d
            }
        }

        ++d
    }

    if (x > 1) divisors.add(x)

    return divisors
}

fun checkIndex(index : Int, size : Int) =
        0 <= index && index < size

fun checkCell(x : Int, n : Int, y : Int, m : Int) =
        checkIndex(x, n) && checkIndex(y, m)

fun toChar(index : Int, start : Char) =
        (index + start.toInt()).toChar()

class DSU {

    var sizes : IntArray
    var ranks : IntArray
    var parents : IntArray

    constructor(n : Int)
    : this(
            IntArray(n) { 1 }
    )

    constructor(sizes : IntArray) {
        val size = sizes.size
        this.sizes = sizes
        this.ranks = IntArray(size) { 1 }
        this.parents = IntArray(size) { it }
    }

    operator fun get(v : Int) : Int {
        val parent = parents[v]
        if (parent == v) return v
        parents[v] = get(parent)
        return parents[v]
    }

    fun union(aUniting : Int, bUniting : Int) : Boolean {
        var a = get(aUniting)
        var b = get(bUniting)

        if (a == b) return false

        if (ranks[a] < ranks[b]) {
            val tmp = a
            a = b
            b = tmp
        }

        parents[b] = a
        sizes[a] += sizes[b]
        if (ranks[a] == ranks[b]) ++ranks[a]

        return true
    }

    fun size(v : Int) : Int = sizes[get(v)]
}

class FenwickTree(n : Int) {

    val size = n + 1
    val tree = LongArray(size) { 0L }

    fun update(index : Int, delta : Int) {
        var x = index + 1
        while (x < size) {
            tree[x] = tree[x] + delta
            x += x and -x
        }
    }

    operator fun get(start : Int, end : Int) =
            get(end) - get(start - 1)

    operator fun get(index : Int) : Long {
        var result : Long = 0

        var x = index + 1
        while (x > 0) {
            result += tree[x]
            x -= x and -x
        }

        return result
    }
}


fun main() {
    val (hour, minutes) = readLine()!!.split(":").map(String::toInt)
    val minutesPassed = readLine()!!.toInt()
    val totalMinutes = hour * 60 + minutes + minutesPassed
    val newHour = (totalMinutes / 60) % 24
    val newMinutes = totalMinutes % 60
    print("${String.format("%02d", newHour)}:${String.format("%02d", newMinutes)}")
}


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

fun readLn()=readLine()!!
fun readInt()=readLn().toInt()
fun readInts()=readLn().split(" ").map{it.toInt()}
fun readLong()=readLn().toLong()
fun readLongs()=readLn().split(" ").map{it.toLong()}

val out=mutableListOf<String>()
fun printLine(s:String){out.add(s)}
fun output(){println(out.joinToString("\n"))}

fun TreeMap<Char,Int>.add(i:Char,x:Int){
    set(i,getOrDefault(i,0)+x)
}
fun main(){
    var a=Array(3){readLn().toCharArray()}
    var cnt=TreeMap<Char,Int>()
    for(j in 0..2)for(i in a[j])cnt.add(i,1)
    var o=cnt.getOrDefault('0',0)
    var x=cnt.getOrDefault('X',0)
    if(o>x || x>o+1)printLine("illegal")
    else{
        fun win(c:Char):Boolean{
            for(j in 0..2)if(a[j][0]==c&&a[j][1]==c&&a[j][2]==c)return true
            for(j in 0..2)if(a[0][j]==c&&a[1][j]==c&&a[2][j]==c)return true
            if(a[0][0]==c&&a[1][1]==c&&a[2][2]==c)return true
            if(a[2][0]==c&&a[1][1]==c&&a[0][2]==c)return true
            return false
        }
        if(win('X')&&win('0'))printLine("illegal")
        else{
            if(win('X')){
                var ok=false
                for(i in 0..2)for(j in 0..2)if(a[i][j]=='X'){
                    a[i][j]='.'
                    if(!win('X'))ok=true
                    a[i][j]='X'
                }
                if(ok&&x==o+1)printLine("the first player won")
                else printLine("illegal")
            }else if(win('0')){
                var ok=false
                for(i in 0..2)for(j in 0..2)if(a[i][j]=='0'){
                    a[i][j]='.'
                    if(!win('0'))ok=true
                    a[i][j]='0'
                }
                if(ok&&x==o)printLine("the second player won")
                else printLine("illegal")
            }else{
                if(x+o==9)printLine("draw")
                else if(x>o)printLine("second")
                else printLine("first")
            }
        }
    }
    output()
}


import java.util.*

val FIRST = 'X'
val SECOND = '0'

fun main() {
    val reader = Scanner(System.`in`)

    val board = mutableListOf<String>()
    repeat(3) { board.add(reader.nextLine().trim()) }

    val zeros = board.sumBy { row -> row.count { it == '0' } }
    val xs = board.sumBy { row -> row.count { it == 'X' } }

    fun won(c: Char): Boolean {
        for (i in 0 until 3) {
            if (board[i].all { it == c }) return true
            if (board.all { row -> row[i] == c }) return true
        }

        if ((0 until 3).map { board[it][it] }.all { it == c }) return true
        if ((0 until 3).map { board[it][2 - it] }.all { it == c }) return true

        return false
    }

    when (xs - zeros) {
        1 -> when {
            won(SECOND) -> println("illegal")
            won(FIRST) -> println("the first player won")
            xs == 5 -> println("draw")
            else -> println("second")
        }
        0 ->
            when {
                won(FIRST) -> println("illegal")
                won(SECOND) -> println("the second player won")
                else -> println("first")
            }
        else -> println("illegal")
    }

}