An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.

Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.

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

    val (numRows, numColumns) = readInts()
    val grid = Array(numRows) { "" }
    val crossed = Array(numRows) { BooleanArray(numColumns) }
    for (row in 0 until numRows) grid[row] = readLine()!!
    val charToRowByColumn = Array(numColumns) { mutableMapOf<Char, Int>() }
    for ((numRow, row) in grid.withIndex()) {
        val charToColumn = mutableMapOf<Char, Int>()
        for ((numColumn, c) in row.withIndex()) {
            if (c in charToColumn) {
                crossed[numRow][numColumn] = true
                crossed[numRow][charToColumn[c]!!] = true
            } else
                charToColumn[c] = numColumn

            if (c in charToRowByColumn[numColumn]) {
                crossed[numRow][numColumn] = true
                crossed[charToRowByColumn[numColumn][c]!!][numColumn] = true
            } else
                charToRowByColumn[numColumn][c] = numRow
        }
    }
    val sb = StringBuilder()
    for (numRow in 0 until numRows)
        for (numColumn in 0 until numColumns)
            if (!crossed[numRow][numColumn]) sb.append(grid[numRow][numColumn])
    print(sb.toString())
}

[{'input': '3 3\r\ncba\r\nbcd\r\ncbc\r\n', 'output': ['abcd']}, {'input': '5 5\r\nfcofd\r\nooedo\r\nafaoa\r\nrdcdf\r\neofsf\r\n', 'output': ['codeforces']}, {'input': '4 4\r\nusah\r\nusha\r\nhasu\r\nsuha\r\n', 'output': ['ahhasusu']}, {'input': '7 5\r\naabcd\r\neffgh\r\niijkk\r\nlmnoo\r\npqqrs\r\nttuvw\r\nxxyyz\r\n', 'output': ['bcdeghjlmnprsuvwz']}, {'input': '10 10\r\naaaaaaaaaa\r\nbccceeeeee\r\ncdfffffffe\r\ncdfiiiiile\r\ncdfjjjjile\r\ndddddddile\r\nedfkkkkile\r\nedddddddde\r\ngggggggggg\r\nhhhhhhhhhe\r\n', 'output': ['b']}, {'input': '15 3\r\njhg\r\njkn\r\njui\r\nfth\r\noij\r\nyuf\r\nyfb\r\nugd\r\nhgd\r\noih\r\nhvc\r\nugg\r\nyvv\r\ntdg\r\nhgf\r\n', 'output': ['hkniftjfbctd']}, {'input': '17 19\r\nbmzbmweyydiadtlcoue\r\ngmdbyfwurpwbpuvhifn\r\nuapwyndmhtqvkgkbhty\r\ntszotwflegsjzzszfwt\r\nzfpnscguemwrczqxyci\r\nvdqnkypnxnnpmuduhzn\r\noaquudhavrncwfwujpc\r\nmiggjmcmkkbnjfeodxk\r\ngjgwxtrxingiqquhuwq\r\nhdswxxrxuzzfhkplwun\r\nfagppcoildagktgdarv\r\neusjuqfistulgbglwmf\r\ngzrnyxryetwzhlnfewc\r\nzmnoozlqatugmdjwgzc\r\nfabbkoxyjxkatjmpprs\r\nwkdkobdagwdwxsufees\r\nrvncbszcepigpbzuzoo\r\n', 'output': ['lcorviunqvgblgjfsgmrqxyivyxodhvrjpicbneodxjtfkpolvejqmllqadjwotmbgxrvs']}, {'input': '1 1\r\na\r\n', 'output': ['a']}, {'input': '2 2\r\nzx\r\nxz\r\n', 'output': ['zxxz']}, {'input': '1 2\r\nfg\r\n', 'output': ['fg']}, {'input': '2 1\r\nh\r\nj\r\n', 'output': ['hj']}, {'input': '1 3\r\niji\r\n', 'output': ['j']}, {'input': '3 1\r\nk\r\np\r\nk\r\n', 'output': ['p']}, {'input': '2 3\r\nmhw\r\nbfq\r\n', 'output': ['mhwbfq']}, {'input': '3 2\r\nxe\r\ner\r\nwb\r\n', 'output': ['xeerwb']}, {'input': '3 7\r\nnutuvjg\r\ntgqutfn\r\nyfjeiot\r\n', 'output': ['ntvjggqfnyfjeiot']}, {'input': '5 4\r\nuzvs\r\namfz\r\nwypl\r\nxizp\r\nfhmf\r\n', 'output': ['uzvsamfzwyplxizphm']}, {'input': '8 9\r\ntjqrtgrem\r\nrwjcfuoey\r\nywrjgpzca\r\nwabzggojv\r\najqmmcclh\r\nozilebskd\r\nqmgnbmtcq\r\nwakptzkjr\r\n', 'output': ['mrjcfuyyrjpzabzvalhozilebskdgnbtpzr']}, {'input': '9 3\r\njel\r\njws\r\ntab\r\nvyo\r\nkgm\r\npls\r\nabq\r\nbjx\r\nljt\r\n', 'output': ['elwtabvyokgmplabqbxlt']}, {'input': '7 6\r\neklgxi\r\nxmpzgf\r\nxvwcmr\r\nrqssed\r\nouiqpt\r\ndueiok\r\nbbuorv\r\n', 'output': ['eklgximpzgfvwcmrrqedoiqptdeiokuorv']}, {'input': '14 27\r\npzoshpvvjdpmwfoeojapmkxjrnk\r\nitoojpcorxjdxrwyewtmmlhjxhx\r\ndoyopbwusgsmephixzcilxpskxh\r\nygpvepeuxjbnezdrnjfwdhjwjka\r\nrfjlbypoalbtjwrpjxzenmeipfg\r\nkhjhrtktcnajrnbefhpavxxfnlx\r\nvwlwumqpfegjgvoezevqsolaqhh\r\npdrvrtzqsoujqfeitkqgtxwckrl\r\nxtepjflcxcrfomhqimhimnzfxzg\r\nwhkfkfvvjwkmwhfgeovwowshyhw\r\nolchgmhiehumivswgtfyhqfagbp\r\ntdudrkttpkryvaiepsijuejqvmq\r\nmuratfqqdbfpefmhjzercortroh\r\nwxkebkzchupxumfizftgqvuwgau\r\n', 'output': ['zshdanicdyldybwgclygzrhkayatwxznmicbpvlupfsoewcleploqngsyolceswtyqbpyasmuadbpcehqva']}, {'input': '1 100\r\nysijllpanprcrrtvokqmmupuptvawhvnekeybdkzqaduotmkfwybqvytkbjfzyqztmxckizheorvkhtyoohbswcmhknyzlgxordu\r\n', 'output': ['g']}, {'input': '2 100\r\ngplwoaggwuxzutpwnmxhotbexntzmitmcvnvmuxknwvcrnsagvdojdgaccfbheqojgcqievijxapvepwqolmnjqsbejtnkaifstp\r\noictcmphxbrylaarcwpruiastazvmfhlcgticvwhpxyiiqokxcjgwlnfykkqdsfmrfaedzchrfzlwdclqjxvidhomhxqnlmuoowg\r\n', 'output': ['rbe']}, {'input': '3 100\r\nonmhsoxoexfwavmamoecptondioxdjsoxfuqxkjviqnjukwqjwfadnohueaxrkreycicgxpmogijgejxsprwiweyvwembluwwqhj\r\nuofldyjyuhzgmkeurawgsrburovdppzjiyddpzxslhyesvmuwlgdjvzjqqcpubfgxliulyvxxloqyhxspoxvhllbrajlommpghlv\r\nvdohhghjlvihrzmwskxfatoodupmnouwyyfarhihxpdnbwrvrysrpxxptdidpqabwbfnxhiziiiqtozqjtnitgepxjxosspsjldo\r\n', 'output': ['blkck']}, {'input': '100 1\r\na\r\nm\r\nn\r\nh\r\na\r\nx\r\nt\r\na\r\no\r\np\r\nj\r\nz\r\nr\r\nk\r\nq\r\nl\r\nb\r\nr\r\no\r\ni\r\ny\r\ni\r\np\r\ni\r\nt\r\nn\r\nd\r\nc\r\nz\r\np\r\nu\r\nn\r\nw\r\ny\r\ng\r\ns\r\nt\r\nm\r\nz\r\ne\r\nv\r\ng\r\ny\r\nj\r\nd\r\nz\r\ny\r\na\r\nn\r\nx\r\nk\r\nd\r\nq\r\nn\r\nv\r\ng\r\nk\r\ni\r\nk\r\nf\r\na\r\nb\r\nw\r\no\r\nu\r\nw\r\nk\r\nk\r\nb\r\nz\r\nu\r\ni\r\nu\r\nv\r\ng\r\nv\r\nx\r\ng\r\np\r\ni\r\nz\r\ns\r\nv\r\nq\r\ns\r\nb\r\nw\r\ne\r\np\r\nk\r\nt\r\np\r\nd\r\nr\r\ng\r\nd\r\nk\r\nm\r\nf\r\nd\r\n', 'output': ['hlc']}, {'input': '100 2\r\nhd\r\ngx\r\nmz\r\nbq\r\nof\r\nst\r\nzc\r\ndg\r\nth\r\nba\r\new\r\nbw\r\noc\r\now\r\nvh\r\nqp\r\nin\r\neh\r\npj\r\nat\r\nnn\r\nbr\r\nij\r\nco\r\nlv\r\nsa\r\ntb\r\nbl\r\nsr\r\nxa\r\nbz\r\nrp\r\nsz\r\noi\r\nec\r\npw\r\nhf\r\njm\r\nwu\r\nhq\r\nra\r\npv\r\ntc\r\ngv\r\nik\r\nux\r\ntz\r\nbf\r\nty\r\ndk\r\nwo\r\nor\r\nza\r\nkv\r\nqt\r\nfa\r\njy\r\nbk\r\nuv\r\ngk\r\ncz\r\nds\r\nie\r\noq\r\nmf\r\nxn\r\nql\r\nxs\r\nfb\r\niv\r\ncj\r\nkn\r\nns\r\nlg\r\nji\r\nha\r\naj\r\ndg\r\nfj\r\nut\r\nsg\r\nju\r\noc\r\nov\r\nhe\r\nnw\r\nbl\r\nlp\r\nbx\r\nnm\r\nyq\r\ncw\r\nov\r\nxk\r\npg\r\noh\r\npl\r\nuo\r\ngf\r\nul\r\n', 'output': ['dvy']}, {'input': '100 3\r\nruy\r\nmye\r\njgp\r\nscn\r\nktq\r\nalx\r\nmvk\r\nlpm\r\nkry\r\norb\r\nmpu\r\nzcv\r\nlge\r\nkft\r\ndzp\r\ntfb\r\nhqz\r\nuur\r\nhry\r\nzjx\r\ncuo\r\nqqc\r\ntih\r\nenj\r\nvnp\r\nbwi\r\nzzh\r\nhkc\r\nwdr\r\nldh\r\nvel\r\nizj\r\nfhb\r\nqrn\r\nqpp\r\nvzs\r\nlhg\r\nkee\r\nlbq\r\nzhy\r\nwcl\r\nyaa\r\nton\r\nfly\r\nkyw\r\nept\r\ngwq\r\ncoe\r\nopd\r\neez\r\nnmx\r\nnjg\r\nwhy\r\nvel\r\nafq\r\nnbq\r\nulx\r\noxs\r\nbbo\r\nyhx\r\nfmz\r\nnrg\r\nnfm\r\njek\r\nbeu\r\ntya\r\nxgs\r\nsgg\r\nnkq\r\nbbv\r\nwkd\r\ntns\r\nfdt\r\neox\r\nobc\r\neab\r\nkkj\r\noub\r\ngji\r\nrht\r\nozv\r\nysk\r\nsbt\r\nflf\r\npbu\r\nlxb\r\npzs\r\nrzh\r\ncea\r\nkmi\r\nuea\r\nncc\r\nzng\r\nvkn\r\njhn\r\njqw\r\nlqc\r\nmbt\r\nlov\r\ngam\r\n', 'output': ['tvdiixs']}]


A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.

The first input file line contains integers n and m — the total number of clothing items in the shop and the total number of matching pairs of clothing items (). Next line contains n integers ai (1 ≤ ai ≤ 106) — the prices of the clothing items in rubles. Next m lines each contain a pair of space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi). Each such pair of numbers means that the ui-th and the vi-th clothing items match each other. It is guaranteed that in each pair ui and vi are distinct and all the unordered pairs (ui, vi) are different.

Print the only number — the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).

NoteIn the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way — to buy the 3 pieces of clothing; in this case he spends 6 roubles.The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1.In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.

import java.util.*

class TaskA {
    var n = 0
    var m = 0
    lateinit var prices: IntArray
    lateinit var match: Array<BooleanArray>

    var minimalPrice = -1

    fun run() {
        for (i in 0 until n) {
            for (j in 0 until n) {
                if (i == j) continue
                if (!isMatch(i, j)) continue

                for (k in 0 until n) {
                    if (i == k || j == k) continue
                    if (!isMatch(i, k) || !isMatch(j, k)) continue

                    val price = prices[i] + prices[j] + prices[k]
                    if (minimalPrice == -1) minimalPrice = price
                    if (minimalPrice > price) minimalPrice = price
                }
            }
        }
    }

    private fun isMatch(i: Int, j: Int) = match[i][j]

    fun print() {
        println(minimalPrice)
    }
}

fun task(init: TaskA.() -> Unit): TaskA {
    val t = TaskA()
    t.init()
    return t
}

fun cf() = with(Scanner(System.`in`)) {
    task {
        n = nextInt()
        m = nextInt()
        prices = IntArray(n, { nextInt() })
        match = Array(n, { BooleanArray(n, { false }) })
        for (i in 0 until m) {
            val u = nextInt() - 1
            val v = nextInt() - 1
            match[u][v] = true
            match[v][u] = true
        }
        run()
        print()
    }
}

fun main(args: Array<String>) {
    if (args.size == 0) cf()
    else test()
}

fun test() {
    task {
        n = 100
        prices = IntArray(n, { 13 })
        match = Array(n, { BooleanArray(n, { true }) })
        run()
    };
}


In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Print a single number — the sought number of days.

NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.

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

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

    val numTiles = readInt()
    val numDays = readInts()
    var sol = min(numDays.first(), numDays.last())
    for (pos in 1 until numTiles) sol = min(sol, max(numDays[pos], numDays[pos - 1]))
    print(sol)
}


Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

import java.util.Scanner

fun main() {

    val sc = Scanner(System.`in`)
    val n : Int = sc.nextInt()
    val p = IntArray(n)
    val abcde = IntArray(5)
    val count = LongArray(5)
    var total : Long = 0

    for (i in 0 until n) p[i] = sc.nextInt()
    for (i in 0..4) abcde[i] = sc.nextInt()

    for (i in 0 until n) {
        total += p[i]
        for (j in 4 downTo 0) {
            if (abcde[j] <= total) {
                count[j] += (total / abcde[j])
                total %= abcde[j]
            }
        }
    }

    for (i in 0..4) println(count[i])
    print(total)

}


Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

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

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

val scanner = Scanner(System.`in`)
var n = scanner.nextInt()
val arr = Array<Array<Pair<Int, Int>>>(1000) { y -> Array<Pair<Int, Int>>(1000) { Pair(it, y) } }
var x = IntArray(1000) { -1 }
var y = IntArray(1000) { -1 }
fun get(x: Int, y: Int): Pair<Int, Int> {
    if (arr[y][x].first != x || arr[y][x].second != y)
        arr[y][x] = get(arr[y][x].first, arr[y][x].second)
    return arr[y][x]
}
fun join(x1: Int, y1: Int, x2: Int, y2: Int) {
    val root = get(x1, y1)
    arr[root.second][root.first] = get(x2, y2)
}

fun run() {

    var res = 0
    for (i in 0 until n) {
        val a = scanner.nextInt() - 1
        val b = scanner.nextInt() - 1
        if (x[b] != -1 && y[a] != -1 && get(b, x[b]) != get(y[a], a))
            res--
        if (x[b] != -1)
            join(b, a, b, x[b])
        if (y[a] != -1)
            join(b, a, y[a], a)
        if (x[b] == -1 && y[a] == -1)
            res++
        if (x[b] == -1)
            x[b] = a
        if (y[a] == -1)
            y[a] = b
    }
    println(res - 1)

}

class Scanner(s: InputStream) {
    var st: StringTokenizer? = null
    var br: BufferedReader = BufferedReader(InputStreamReader(s))
    @Throws(IOException::class)
    operator fun next(): String {
        while (st == null || !st!!.hasMoreTokens())
            st = StringTokenizer(br.readLine())
        return st!!.nextToken()
    }
    @Throws(IOException::class)
    fun nextInt(): Int {
        return Integer.parseInt(next())
    }
    @Throws(IOException::class)
    fun nextLong(): Long {
        return java.lang.Long.parseLong(next())
    }
    @Throws(IOException::class)
    fun nextLine(): String {
        return br.readLine()
    }
    @Throws(IOException::class)
    fun nextDouble(): Double {
        return java.lang.Double.parseDouble(next())
    }
    @Throws(IOException::class)
    fun ready(): Boolean {
        return br.ready()
    }
}

fun IntArray.print() {
    println(Arrays.toString(this))
}

fun Array<IntArray>.print() {
    for (i in this)
        i.print()
}


Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

fun main(args : Array<String>) {
    val p = readLine()!!
    val d1 = readLine()!!
    val d2 = readLine()!!
    var p1 = p.reversed()
    var b = 0
    var f = 0
    var n = 0
    var a = 0
    var e1 = 0
    var e2 = 0

    if(p.length>=d1.length+d2.length) {
        for (i in 0..p.length - d1.length - 1) {
            if (p.substring(i, i + d1.length) == d1) {
                a = i + d1.length
                e1++
                break
            }
        }
        if (p.length - a >= d2.length && e1 != 0) {
            for (i in a..p.length - d2.length) {
                if (p.substring(i, i + d2.length) == d2) {
                    f++
                    break
                }
            }
        }

        for (i in 0..p1.length - d1.length - 1) {
            if (p1.substring(i, i + d1.length) == d1) {
                b = i + d1.length
                e2++
                break
            }
        }
        if (p1.length - b >= d2.length && e2 != 0) {
            for (i in b..p1.length - d2.length) {
                if (p1.substring(i, i + d2.length) == d2) {
                    n++
                    break
                }
            }
        }
    }
    if(f==1 && n==1){
        println("both")
    }
    else if(f==1 && n == 0){
        println("forward")
    }
    else if(f==0 && n == 1){
        println("backward")
    }
    else{
        println("fantasy")
    }

}

[{'input': 'atob\r\na\r\nb\r\n', 'output': ['forward\r\n']}, {'input': 'aaacaaa\r\naca\r\naa\r\n', 'output': ['both\r\n']}, {'input': 'aaa\r\naa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'astalavista\r\nastla\r\nlavista\r\n', 'output': ['fantasy\r\n']}, {'input': 'abacabadabacaba\r\nabacaba\r\nabacaba\r\n', 'output': ['both\r\n']}, {'input': 'a\r\na\r\na\r\n', 'output': ['fantasy\r\n']}, {'input': 'ab\r\nb\r\na\r\n', 'output': ['backward\r\n']}, {'input': 'aaa\r\naaaa\r\naaaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'bbabbbbababbaabaabaa\r\nabb\r\nbaab\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'babaabababaaaababaabababaabababababababbababbbabbaabababaababbaabbababaababaaabababaabbaababaaababaa\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'aababaaababaabbaabababaaababaabababbaabbabaabababaabbabbbababbababababababaabababaababaaaabababaabab\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['backward\r\n']}, {'input': 'aaaa\r\naaa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzzzz\r\nzzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzz\r\n', 'output': ['both\r\n']}, {'input': 'aabaa\r\naab\r\nbaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'aabaab\r\naba\r\nab\r\n', 'output': ['forward\r\n']}, {'input': 'aab\r\nb\r\naa\r\n', 'output': ['backward\r\n']}, {'input': 'abacaba\r\naca\r\nba\r\n', 'output': ['both\r\n']}]


Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.

The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.

Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.

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

class InputReader(val stream: InputStream) {
    val buf = ByteArray(1024)
    var curChar: Int = 0
    var numChars: Int = 0

    fun read(): Int {
        if (numChars == -1)
            throw InputMismatchException()
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = stream.read(buf)
            } catch (e: IOException) {
                throw InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        return buf[curChar++].toInt()
    }

    fun nextInt(): Int {
        var c = read()
        while (isSpaceChar(c))
            c = read()
        var sgn = 1
        if (c == 45) {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < 48 || c > 57)
                throw InputMismatchException()
            res *= 10
            res += c and 15
            c = read()
        } while (!isSpaceChar(c))
        return res * sgn
    }

    fun nextLong(): Long {
        var c = read()
        while (isSpaceChar(c))
            c = read()
        var sgn = 1
        if (c == 45) {
            sgn = -1
            c = read()
        }
        var res: Long = 0
        do {
            if (c < 48 || c > 57)
                throw InputMismatchException()
            res *= 10
            res += c and 15
            c = read()
        } while (!isSpaceChar(c))
        return res * sgn
    }

    fun nextString(): String {
        var c = read()
        while (isSpaceChar(c))
            c = read()
        val res = StringBuilder()
        do {
            res.appendCodePoint(c)
            c = read()
        } while (!isSpaceChar(c))
        return res.toString()
    }

    fun isSpaceChar(c: Int): Boolean {
        return c == 32 || c == 10 || c == 13 || c == 9 || c == -1
    }
}

class OutputWriter(val stream: OutputStream) {
    val buf = ByteArray(65536)
    var curPos: Int = 0

    fun write(c: Char) {
        if (buf.size - curPos < 1) flush()
        buf[curPos++] = c.toByte()
    }

    fun write(s: String) {
        if (buf.size - curPos < s.length) flush()
        var idx = 0
        var remaining = s.length
        while (remaining > buf.size) {
            while (curPos < buf.size) buf[curPos++] = s[idx++].toByte()
            flush()
            remaining -= buf.size
        }
        while (idx < s.length) buf[curPos++] = s[idx++].toByte()
    }

    fun flush() {
        stream.write(buf, 0, curPos)
        curPos = 0
    }
}

@Suppress("NOTHING_TO_INLINE")
inline fun Number.isOdd (): Boolean = this.toInt() and 1 == 1

fun main(args: Array<String>) {
    if (args.isNotEmpty()) System.setIn(FileInputStream(args[0]))
    val ir = InputReader(System.`in`)
    val ow = OutputWriter(System.out)

    val n = ir.nextInt()
    var s = ir.nextString()
    if (s.length.isOdd()) {
        ow.write(s.slice(0..2))
        s = s.drop(3)
    } else {
        ow.write(s.slice(0..1))
        s = s.drop(2)
    }
    while (s.isNotEmpty()) {
        ow.write('-')
        ow.write(s.slice(0..1))
        s = s.drop(2)
    }
    ow.write('\n')
    ow.flush()
}


Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

fun main(args: Array<String>) {
    val size = readLine()!!.toInt()
    val list = readLine()!!.split(" ").map { it.toInt() }.toList()

    var max = 0
    list.forEachIndexed { index, element ->
        var (right, left) = getRightAndLeft(index)

        var sumLeft = 0
        var currentLeft = 0
        var canGoLeft: Boolean = false

        if (index == 0) {
            canGoLeft = false
        } else {
            currentLeft = list[left]
            canGoLeft = leftable(left, element, currentLeft)
        }

        while (canGoLeft) {
            sumLeft++
            if (left >= 0)
                currentLeft = list[left]
            left--
            if (left == -1)
                canGoLeft = false
            else
                canGoLeft = leftable(left, currentLeft, list[left])
        }

        var sumRight = 0
        var canGoRight = false
        var currentRight = 0

        if (index == size - 1)
            canGoRight = false
        else {
            currentRight = list[right]
            canGoRight = rightable(right, size, element, currentRight)
        }

        while (canGoRight) {
            sumRight++
            if (right < size)
                currentRight = list[right]
            right++
            if (right == size)
                canGoRight = false
            else
                canGoRight = rightable(right, size, currentRight, list[right])

        }

        if (sumRight + sumLeft > max) {
            max = sumRight + sumLeft
        }
        if (max == size - 1) {
            return@forEachIndexed
        }

    }

    print(max + 1)

//
}

private fun leftable(left: Int, element: Int, item: Int) =
        (left >= 0 && element >= item)

private fun rightable(right: Int, size: Int, element: Int, item: Int) =
        (right < size && element >= item)

fun getRightAndLeft(index: Int): Pair<Int, Int> {
    return Pair(index + 1, index - 1)
}


Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

fun main(args: Array<String>) {
    val m = HashMap<Char, Int>()
    for (d in -1..1 step 2)
        readLine()!!.forEach {if (it != ' ') m[it] = m.getOrDefault(it, 0) + d}
    println(if (m.values.max()!! > 0) "NO" else "YES")
}

[{'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\r\nwhere is your dog\r\n', 'output': ['NO\r\n']}, {'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\r\nYour dog is upstears\r\n', 'output': ['YES\r\n']}, {'input': 'Instead of dogging your footsteps it disappears but you dont notice anything\r\nYour dog is upstears\r\n', 'output': ['NO\r\n']}, {'input': 'abcdefg hijk\r\nk j i h g f e d c b a\r\n', 'output': ['YES\r\n']}, {'input': 'HpOKgo\r\neAtAVB\r\n', 'output': ['NO\r\n']}, {'input': 'GRZGc\r\nLPzD\r\n', 'output': ['NO\r\n']}, {'input': 'GtPXu\r\nd\r\n', 'output': ['NO\r\n']}, {'input': 'FVF\r\nr \r\n', 'output': ['NO\r\n']}, {'input': 'HpOKgo\r\nogK\r\n', 'output': ['YES\r\n']}, {'input': 'GRZGc\r\nZG\r\n', 'output': ['YES\r\n']}, {'input': 'HpOKgoueAtAVBdGffvQheJDejNDHhhwyKJisugiRAH OseK yUwqPPNuThUxTfthqIUeb wS jChGOdFDarNrKRT  MlwKecxWNoKEeD BbiHAruE XMlvKYVsJGPP\r\nAHN  XvoaNwV  AVBKwKjr u      U K wKE D K   Jy KiHsR h d W  Js IHyMPK Br iSqe  E fDA   g H\r\n', 'output': ['YES\r\n']}, {'input': 'GRZGcsLPzDrCSXhhNTaibJqVphhjbcPoZhCDUlzAbDnRWjHvxLKtpGiFWiGbfeDxBwCrdJmJGCGv GebAOinUsFrlqKTILOmxrFjSpEoVGoTdSSstJWVgMLKMPettxHASaQZNdOIObcTxtF qTHWBdNIKwj\r\nWqrxze Ji x q aT GllLrRV jMpGiMDTwwS JDsPGpAZKACmsFCOS CD Sj  bCDgKF  jJxa RddtLFAi VGLHH SecObzG q  hPF \r\n', 'output': ['YES\r\n']}, {'input': 'GtPXuwdAxNhODQbjRslDDKciOALJrCifTjDQurQEBeFUUSZWwCZQPdYwZkYbrduMijFjgodAOrKIuUKwSXageZuOWMIhAMexyLRzFuzuXqBDTEaWMzVdbzhxDGSJC SsIYuYILwpiwwcObEHWpFvHeBkWYNitqYrxqgHReHcKnHbtjcWZuaxPBVPb\r\nTQIKyqFaewOkY lZUOOuxEw EwuKcArxRQGFYkvVWIAe SuanPeHuDjquurJu aSxwgOSw jYMwjxItNUUArQjO BIujAhSwttLWp\r\n', 'output': ['YES\r\n']}, {'input': 'FVFSr unvtXbpKWF vPaAgNaoTqklzVqiGYcUcBIcattzBrRuNSnKUtmdGKbjcE\r\nUzrU K  an GFGR        Wc zt iBa     P c    T K v p     V In   b           B   c\r\n', 'output': ['YES\r\n']}, {'input': 'lSwjnYLYtDNIZjxHiTawdh ntSzggZogcIZTuiTMWVgwyloMtEhqkrOxgIcFvwvsboXUPILPIymFAEXnhApewJXJNtFyZ\r\nAoxe  jWZ u  yImg  o AZ FNI w lpj  tNhT g y  ZYcb rc J    w Dlv\r\n', 'output': ['YES\r\n']}, {'input': 'kvlekcdJqODUKdsJlXkRaileTmdGwUHWWgvgUokQxRzzbpFnswvNKiDnjfOFGvFcnaaiRnBGQmqoPxDHepgYasLhzjDgmvaFfVNEcSPVQCJKAbSyTGpXsAjIHr\r\nGjzUllNaGGKXUdYmDFpqFAKIwvTpjmqnyswWRTnxlBnavAGvavxJemrjvRJc\r\n', 'output': ['YES\r\n']}, {'input': 'kWbvhgvvoYOhwXmgTwOSCDXrtFHhqwvMlCvsuuAUXMmWaYXiqHplFZZemhgkTuvsUtIaUxtyYauBIpjdbyYxjZ ZkaBPzwqPfqF kCqGRmXvWuabnQognnkvdNDtRUsSUvSzgBuxCMBWJifbxWegsknp\r\nBsH   bWHJD n Ca T xq  PRCv  tatn Wjy sm  I q s WCjFqdWe  t W XUs  Do  eb Pfh ii  hTbF  O Fll\r\n', 'output': ['YES\r\n']}, {'input': 'OTmLdkMhmDEOMQMiW ZpzEIjyElHFrNCfFQDp SZyoZaEIUIpyCHfwOUqiSkKtFHggrTBGkqfOxkChPztmPrsHoxVwAdrxbZLKxPXHlMnrkgMgiaHFopiFFiUEtKwCjpJtwdwkbJCgA bxeDIscFdmHQJLAMNhWlrZisQrHQpvbALWTwpf jnx\r\nDbZwrQbydCdkJMCrftiwtPFfpMiwwrfIrKidEChKECxQUBVUEfFirbGWiLkFQkdJiFtkrtkbIAEXCEDkwLpK\r\n', 'output': ['YES\r\n']}, {'input': 'NwcGaIeSkOva\r\naIa\r\n', 'output': ['YES\r\n']}, {'input': 'gSrAcVYgAdbdayzbKGhIzLDjyznLRIJH KyvilAaEddmgkBPCNzpmPNeGEbmmpAyHvUSoPvnaORrPUuafpReEGoDOQsAYnUHYfBqhdcopQfxJuGXgKnbdVMQNhJYkyjiJDKlShqBTtnnDQQzEijOMcYRGMgPGVhfIReYennKBLwDTVvcHMIHMgVpJkvzTrezxqS\r\nHJerIVvRyfrPgAQMTI AqGNO mQDfDwQHKgeeYmuRmozKHILvehMPOJNMRtPTAfvKvsoGKi xHEeKqDAYmQJPUXRJbIbHrgVOMGMTdvYiLui\r\n', 'output': ['YES\r\n']}, {'input': 'ReB hksbHqQXxUgpvoNK bFqmNVCEiOyKdKcAJQRkpeohpfuqZabvrLfmpZOMcfyFBJGZwVMxiUPP pbZZtJjxhEwvrAba\r\nJTCpQnIViIGIdQtLnmkVzmcbBZR CoxAdTtWSYpbOglDFifqIVQ vfGKGtLpxpJHiHSWCMeRcrVOXBGBhoEnVhNTPWGTOErNtSvokcGdgZXbgTEtISUyTwaXUEIlJMmutsdCbiyrPZPJyRdOjnSuAGttLy\r\n', 'output': ['NO\r\n']}, {'input': 'hrLzRegCuDGxTrhDgVvM KowwyYuXGzIpcXdSMgeQVfVOtJZdkhNYSegwFWWoPqcZoeapbQnyCtojgkcyezUNHGGIZrhzsKrvvcrtokIdcnqXXkCNKjrOjrnEAKBNxyDdiMVeyLvXxUYMZQRFdlcdlcxzKTeYzBlmpNiwWbNAAhWkMoGpRxkCuyqkzXdKWwGH\r\nJESKDOfnFdxPvUOCkrgSBEPQHJtJHzuNGstRbTCcchRWJvCcveSEAtwtOmZZiW\r\n', 'output': ['NO\r\n']}, {'input': 'yDBxCtUygQwWqONxQCcuAvVCkMGlqgC zvkfEkwqbhMCQxnkwQIUhucCbVUyOBUcXvTNEGriTBwMDMfdsPZgWRgIUDqM\r\neptVnORTTyixxmWIBpSTEwOXqGZllBgSxPenYCDlFwckJlWsoVwWLAIbPOmFqcKcTcoQqahetl KLfVSyaLVebzsGwPSVbtQAeUdZAaJtfxlCEvvaRhLlVvRJhKat IaB awdqcDlrrhTbRxjEbzGwcdmdavkhcjHjzmwbxAgw\r\n', 'output': ['NO\r\n']}, {'input': 'jlMwnnotSdlQMluKWkJwAeCetcqbIEnKeNyLWoKCGONDRBQOjbkGpUvDlmSFUJ bWhohqmmIUWTlDsvelUArAcZJBipMDwUvRfBsYzMdQnPDPAuBaeJmAxVKwUMJrwMDxNtlrtAowVWqWiwFGtmquZAcrpFsLHCrvMSMMlvQUqypAihQWrFMNoaqfs IBg\r\nNzeWQ bafrmDsYlpNHSGTBBgPl WIcuNhyNaNOEFvL\r\n', 'output': ['NO\r\n']}, {'input': 'zyWvXBcUZqGqjHwZHQryBtFliLYnweXAoMKNpLaunaOlzaauWmLtywsEvWPiwxJapocAFRMjrqWJXYqfKEbBKnzLO\r\npsbi bsXpSeJaCkIuPWfSRADXdIClxcDCowwJzGCDTyAl\r\n', 'output': ['NO\r\n']}, {'input': 'kKhuIwRPLCwPFfcnsyCfBdnsraGeOCcLTfXuGjqFSGPSAeDZJSS bXKFanNqWjpFnvRpWxHJspvisDlADJBioxXNbVoXeUedoPcNEpUyEeYxdJXhGzFAmpAiHotSVwbZQsuWjIVhVaEGgqbZHIoDpiEmjTtFylCwCkWWzUOoUfOHxEZvDwNpXhBWamHn\r\nK VpJjGhNbwCRhcfmNGVjewBFpEmPlIKeTuWiukDtEWpjgqciqglkyNfWrBLbGAKvlNWxaUelJmSlSoakSpRzePvJsshOsTYrMPXdxKpaShjyVIXGhRIAdtiGpNwtiRmGTBZhkJqIMdxMHX RMxCMYcWjcjhtCHyFnCvjjezGbkRDRiVxkbh\r\n', 'output': ['NO\r\n']}, {'input': 'AXssNpFKyQmJcBdBdfkhhMUzfqJVgcLBddkwtnFSzSRUCjiDcdtmkzIGkCKSxWUEGhmHmciktJyGMkgCductyHx\r\nI nYhmJfPnvoKUiXYUBIPIcxNYTtvwPUoXERZvY ahlDpQFNMmVZqEBiYqYlHNqcpSCmhFczBlOAhsYFeqMGfqL EJsDNOgwoJfBzqijKOFcYQ\r\n', 'output': ['NO\r\n']}, {'input': 'lkhrzDZmkdbjzYKPNMRkiwCFoZsMzBQMnxxdKKVJezSBjnLjPpUYtabcPTIaDJeDEobbWHdKOdVfMQwDXzDDcSrwVenDEYpMqfiOQ xSsqApWnAMoyhQXCKFzHvvzvUvkWwmwZrvZz\r\nsUzGspYpRFsHRbRgTQuCBgnFgPkisTUfFNwyEEWWRiweWWgjRkVQxgTwxOzdsOwfrGIH O gCXpzvHzfItuEHaihmugEyymSJIogYwX qAwcwIItidfnzZDhZgQHi eRjMAeVkJHceDZuJkmxGowOsmcGYYvk Ajtgi TxwihvjLViNZjvscTWvsaQUelTSivLShhEl\r\n', 'output': ['NO\r\n']}, {'input': 'BRsVjyNhrqRHVwrJzuzRigEhdpbDmaACSPfed\r\nlWqKTjlrqOCUbgBBZdZDGCeQJDXawPnnDkQdZDgwrEQk\r\n', 'output': ['NO\r\n']}, {'input': 'KRmINuyBYPwiTsdlyiNVuylToysJKmOpcLovAtwGPqrgFJQNAYvuAiyQRkeFMECVZvkDEmTauXlyjAaYRnTJXORMZRnTakBaUzSelMilejySDIZjQjzcOIrwXdvDvpeRIkoBgreyFXIyyIZutjiEBtwrmzQtPVUhvvdEtDMbXjBpoPVjGdM EXTAK JbCnw\r\nXZZqlJvzKKtvdNlzFPDTYxidqlsgufVzyEmO FZuLQ vVQsJESNviUCovCK NwwlbxsmPtOJNmAonCqrOZ bZ LVKAsQGmoLnYjeekvEIECFk\r\n', 'output': ['NO\r\n']}]


The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n-1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.

The first input line contains integer n (2≤n≤2·10^5) — the number of cities in Treeland. Next n-1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si,ti (1≤si,ti≤n; si≠ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.

In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.

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

import kotlin.system.*
import java.io.*
import kotlin.math.*
import java.util.*
import kotlin.random.Random

/**
 * @author tauros
 */
class Graph(val nodeCap: Int, edges: Int = nodeCap * 2) {
    var idx = -1
    val first = IntArray(nodeCap) { -1 }
    val edgeCap = edges
    val to = IntArray(edgeCap)
    val from = IntArray(edgeCap)
    val next = IntArray(edgeCap)

    fun addEdge(from: Int, to: Int): Int {
        val edgeId = ++idx
        this.from[edgeId] = from
        this.to[edgeId] = to
        this.next[edgeId] = first[from]
        first[from] = edgeId
        return edgeId
    }

    inline fun edges(u: Int, withEdgeId: Graph.(Int) -> Unit = { }) {
        var id = first[u]
        while (id != -1) {
            withEdgeId.invoke(this, id)
            id = next[id]
        }
    }

    inline fun edges(withEdgeId: Graph.(Int) -> Unit = { }) {
        for (id in 0..idx) {
            withEdgeId.invoke(this, id)
        }
    }
}

fun solve() {
    val n = rd.ni()
    val graph = Graph(n, n - 1 + n - 1)
    val reversed = BooleanArray(graph.edgeCap)
    for (i in 0 until n - 1) {
        val (u, v) = rd.ni() - 1 to rd.ni() - 1
        graph.addEdge(u, v)
        reversed[graph.addEdge(v, u)] = true
    }
    fun calc(u: Int, fa: Int): Int {
        var res = 0
        graph.edges(u) { id ->
            val v = to[id]
            if (v == fa) return@edges
            res += calc(v, u) + if (reversed[id]) 1 else 0
        }
        return res
    }
    val ans = IntArray(n)
    ans[0] = calc(0, -1)
    var min = ans[0]
    fun dp(u: Int, fa: Int) {
        min = minOf(min, ans[u])
        graph.edges(u) { id ->
            val v = to[id]
            if (v == fa) return@edges
            ans[v] = ans[u] + if (reversed[id]) -1 else 1
            dp(v, u)
        }
    }
    dp(0, -1)
    wt.println(min)
    for (i in 0 until n) {
        if (ans[i] == min) {
            wt.print(i + 1)
            wt.print(' ')
        }
    }
    wt.println()
}

fun Int.bSuf(end: Int): TGenerator<Int> = this iter { it + it.takeLowestOneBit() } lt end
fun Int.bPre(): TGenerator<Int> = this iter { it - it.takeLowestOneBit() } gt 0

inline fun IntArray.sortWith(comparator: (Int, Int) -> Int, temp: IntArray = IntArray(this.size)) {
    this.sortWith(comparator, 0, this.size, temp)
}

inline fun IntArray.sortWith(comparator: (Int, Int) -> Int, fromIndex: Int = 0, toIndex: Int = size, temp: IntArray = IntArray(toIndex - fromIndex)) {
    val (base, len) = fromIndex to toIndex - fromIndex
    var (range, half) = 2 to 1
    while (half < len) {
        for (i in 0 until len step range) {
            val (st, mid, ed) = intArrayOf(i, minOf(i + half, len), minOf(i + range, len))
            var (l, r, iter) = intArrayOf(st, mid, st)
            while (l < mid || r < ed) {
                if (r >= ed || l < mid && comparator(this[base + l], this[base + r]) <= 0) {
                    temp[iter++] = this[base + l++]
                } else {
                    temp[iter++] = this[base + r++]
                }
            }
            for (j in st until ed) this[base + j] = temp[j]
        }
        half = range
        range = range shl 1
    }
}

@JvmName("findFirst")
inline fun findFirst(l: Int, r: Int, judge: (Int) -> Boolean): Int {
    return findFirst(r - l) {
        judge(it + l)
    } + l
}

@JvmName("findFirst")
inline fun findFirst(n: Int, judge: (Int) -> Boolean): Int {
    var l = 0
    var r = n
    while (l < r) {
        val mid = l + (r - l) / 2
        if (judge(mid)) {
            r = mid
        } else {
            l = mid + 1
        }
    }
    return l
}

@JvmName("findFirstLong")
inline fun findFirst(l: Long, r: Long, judge: (Long) -> Boolean): Long {
    return findFirst(r - l) {
        judge(it + l)
    } + l
}

@JvmName("findFirstLong")
inline fun findFirst(n: Long, judge: (Long) -> Boolean): Long {
    var l: Long = 0
    var r = n
    while (l < r) {
        val mid = l + (r - l shr 1)
        if (judge(mid)) {
            r = mid
        } else {
            l = mid + 1
        }
    }
    return l
}

public inline val Char.code: Int get() = this.toInt()

// reduce
public inline fun IntArray.runningReduce(operation: (acc: Int, Int) -> Int): List<Int> {
    if (isEmpty()) return emptyList()
    var accumulator = this[0]
    val result = ArrayList<Int>(size).apply { add(accumulator) }
    for (index in 1 until size) {
        accumulator = operation(accumulator, this[index])
        result.add(accumulator)
    }
    return result
}

public inline fun LongArray.runningReduce(operation: (acc: Long, Long) -> Long): List<Long> {
    if (isEmpty()) return emptyList()
    var accumulator = this[0]
    val result = ArrayList<Long>(size).apply { add(accumulator) }
    for (index in 1 until size) {
        accumulator = operation(accumulator, this[index])
        result.add(accumulator)
    }
    return result
}

public inline fun FloatArray.runningReduce(operation: (acc: Float, Float) -> Float): List<Float> {
    if (isEmpty()) return emptyList()
    var accumulator = this[0]
    val result = ArrayList<Float>(size).apply { add(accumulator) }
    for (index in 1 until size) {
        accumulator = operation(accumulator, this[index])
        result.add(accumulator)
    }
    return result
}

public inline fun DoubleArray.runningReduce(operation: (acc: Double, Double) -> Double): List<Double> {
    if (isEmpty()) return emptyList()
    var accumulator = this[0]
    val result = ArrayList<Double>(size).apply { add(accumulator) }
    for (index in 1 until size) {
        accumulator = operation(accumulator, this[index])
        result.add(accumulator)
    }
    return result
}

// fold
public inline fun <R> IntArray.runningFold(initial: R, operation: (acc: R, Int) -> R): List<R> {
    if (isEmpty()) return listOf(initial)
    val result = ArrayList<R>(size + 1).apply { add(initial) }
    var accumulator = initial
    for (element in this) {
        accumulator = operation(accumulator, element)
        result.add(accumulator)
    }
    return result
}

public inline fun <R> LongArray.runningFold(initial: R, operation: (acc: R, Long) -> R): List<R> {
    if (isEmpty()) return listOf(initial)
    val result = ArrayList<R>(size + 1).apply { add(initial) }
    var accumulator = initial
    for (element in this) {
        accumulator = operation(accumulator, element)
        result.add(accumulator)
    }
    return result
}

public inline fun <R> FloatArray.runningFold(initial: R, operation: (acc: R, Float) -> R): List<R> {
    if (isEmpty()) return listOf(initial)
    val result = ArrayList<R>(size + 1).apply { add(initial) }
    var accumulator = initial
    for (element in this) {
        accumulator = operation(accumulator, element)
        result.add(accumulator)
    }
    return result
}

public inline fun <R> DoubleArray.runningFold(initial: R, operation: (acc: R, Double) -> R): List<R> {
    if (isEmpty()) return listOf(initial)
    val result = ArrayList<R>(size + 1).apply { add(initial) }
    var accumulator = initial
    for (element in this) {
        accumulator = operation(accumulator, element)
        result.add(accumulator)
    }
    return result
}

class Buffer<T>(
    val initCap: Int = 10,
    val supplier: () -> T
) {
    private var stack = ArrayDeque<T>(initCap)

    fun alloc(init: ((T) -> Unit)? = null): T {
        val obj = if (stack.isEmpty()) supplier.invoke() else stack.removeLast()
        return obj.also { init?.invoke(it) }
    }

    fun release(obj: T) {
        stack.addLast(obj)
    }
}

class TGenerator<T>(private var start: T, private val step: (T) -> T) : Iterable<T> {
    var end: (T) -> Boolean = { false }
    override fun iterator() = object : Iterator<T> {
        var cur = start
        val judge = end
        var took = false
        override fun hasNext() = if (!took) true else {
            cur = step.invoke(cur)
            if (judge.invoke(cur)) {
                false
            } else {
                took = false
                true
            }
        }
        override fun next(): T {
            assert(hasNext())
            took = true
            return cur
        }
    }
}

infix fun <T> T.iter(step: (T) -> T) = TGenerator(this, step)

infix fun <T> TGenerator<T>.till(end: (T) -> Boolean): TGenerator<T> {
    this.end = end
    return this
}

infix fun TGenerator<Int>.lt(end: Int): TGenerator<Int> {
    return till { it >= end }
}

infix fun TGenerator<Int>.le(end: Int): TGenerator<Int> {
    return till { it > end }
}

infix fun TGenerator<Int>.gt(end: Int): TGenerator<Int> {
    return till { it <= end }
}

infix fun TGenerator<Int>.ge(end: Int): TGenerator<Int> {
    return till { it < end }
}

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

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

class FastReader(private val input: InputStream, bufCap: Int = 8192) {
    private val buf = ByteArray(bufCap)

    private var len = 0
    private var ptr = 0

    fun readByte(): Int {
        if (len == -1) {
            throw InputMismatchException()
        }
        if (ptr >= len) {
            ptr = 0
            try {
                len = input.read(buf)
            } catch (e: IOException) {
                throw InputMismatchException()
            }
            if (len <= 0) {
                return -1
            }
        }
        return buf[ptr++].toInt()
    }

    private fun isSpaceChar(c: Int): Boolean {
        return c !in 33..126
    }

    private fun skip(): Int {
        var b: Int
        while (readByte().also { b = it } != -1 && isSpaceChar(b));
        return b
    }

    fun nd(): Double {
        return ns().toDouble()
    }

    fun nc(): Char {
        return skip().toChar()
    }

    fun ns(): String {
        var b = skip()
        return buildString {
            while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
                appendCodePoint(b)
                b = readByte()
            }
        }
    }

    fun ns(n: Int): CharArray {
        val buf = CharArray(n)
        var b = skip()
        var p = 0
        while (p < n && !isSpaceChar(b)) {
            buf[p++] = b.toChar()
            b = readByte()
        }
        return if (n == p) buf else buf.copyOf(p)
    }

    fun na(n: Int): IntArray {
        val a = IntArray(n)
        for (i in 0 until n) {
            a[i] = ni()
        }
        return a
    }

    fun nal(n: Int): LongArray {
        val a = LongArray(n)
        for (i in 0 until n) {
            a[i] = nl()
        }
        return a
    }

    fun nm(n: Int, m: Int): Array<CharArray> {
        val map = Array(n) { CharArray(0) }
        for (i in 0 until n) {
            map[i] = ns(m)
        }
        return map
    }

    fun nmi(n: Int, m: Int): Array<IntArray> {
        val map = Array(n) { IntArray(0) }
        for (i in 0 until n) {
            map[i] = na(m)
        }
        return map
    }

    fun ni(): Int {
        var num = 0
        var b: Int
        var minus = false
        while (readByte().also { b = it } != -1 && !(b >= '0'.code && b <= '9'.code || b == '-'.code));
        if (b == '-'.code) {
            minus = true
            b = readByte()
        }
        while (true) {
            num = if (b >= '0'.code && b <= '9'.code) {
                num * 10 + (b - '0'.code)
            } else {
                return if (minus) -num else num
            }
            b = readByte()
        }
    }

    fun nl(): Long {
        var num: Long = 0
        var b: Int
        var minus = false
        while (readByte().also { b = it } != -1 && !(b >= '0'.code && b <= '9'.code || b == '-'.code));
        if (b == '-'.code) {
            minus = true
            b = readByte()
        }
        while (true) {
            num = if (b >= '0'.code && b <= '9'.code) {
                num * 10 + (b - '0'.code)
            } else {
                return if (minus) -num else num
            }
            b = readByte()
        }
    }
}

class FastWriter : Closeable {
    private val writer: PrintWriter

    constructor(output: OutputStream, bufCap: Int = 32) {
        this.writer = PrintWriter(BufferedWriter(OutputStreamWriter(output), bufCap))
    }

    constructor(writer: Writer, bufCap: Int = 8192) {
        this.writer = PrintWriter(BufferedWriter(writer, bufCap))
    }

    fun print(b: Boolean) {
        writer.print(b)
    }

    fun print(c: Char) {
        writer.print(c)
    }

    fun print(i: Int) {
        writer.print(i)
    }

    fun print(l: Long) {
        writer.print(l)
    }

    fun print(f: Float) {
        writer.print(f)
    }

    fun print(d: Double) {
        writer.print(d)
    }

    fun print(s: CharArray?) {
        writer.print(s)
    }

    fun print(s: String?) {
        writer.print(s)
    }

    fun print(obj: Any?) {
        writer.print(obj)
    }

    fun println() {
        writer.println()
    }

    fun println(x: Boolean) {
        writer.println(x)
    }

    fun println(x: Char) {
        writer.println(x)
    }

    fun println(x: Int) {
        writer.println(x)
    }

    fun println(x: Long) {
        writer.println(x)
    }

    fun println(x: Float) {
        writer.println(x)
    }

    fun println(x: Double) {
        writer.println(x)
    }

    fun println(x: CharArray) {
        writer.println(x)
    }

    fun println(x: String) {
        writer.println(x)
    }

    fun println(x: Any) {
        writer.println(x)
    }

    fun printf(format: String, vararg args: Any?): PrintWriter {
        return writer.format(format, *args)
    }

    fun printf(l: Locale, format: String, vararg args: Any?): PrintWriter {
        return writer.format(l, format, *args)
    }

    fun flush() {
        writer.flush()
    }

    override fun close() {
        writer.flush()
        try {
            writer.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

val bufCap = 128
val rd = FastReader(System.`in`, bufCap)
val wt = FastWriter(System.out, bufCap)

fun main(args: Array<String>) {
    solve()
    wt.flush()
}


Recently, Berland faces federalization requests more and more often. The proponents propose to divide the country into separate states. Moreover, they demand that there is a state which includes exactly k towns.Currently, Berland has n towns, some pairs of them are connected by bilateral roads. Berland has only n - 1 roads. You can reach any city from the capital, that is, the road network forms a tree.The Ministry of Roads fears that after the reform those roads that will connect the towns of different states will bring a lot of trouble.Your task is to come up with a plan to divide the country into states such that:  each state is connected, i.e. for each state it is possible to get from any town to any other using its roads (that is, the roads that connect the state towns),  there is a state that consisted of exactly k cities,  the number of roads that connect different states is minimum.

The first line contains integers n, k (1 ≤ k ≤ n ≤ 400). Then follow n - 1 lines, each of them describes a road in Berland. The roads are given as pairs of integers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the numbers of towns connected by the road. Assume that the towns are numbered from 1 to n.

The the first line print the required minimum number of "problem" roads t. Then print a sequence of t integers — their indices in the found division. The roads are numbered starting from 1 in the order they follow in the input. If there are multiple possible solutions, print any of them. If the solution shows that there are no "problem" roads at all, print a single integer 0 and either leave the second line empty or do not print it at all.

                            import java.util.*

                            //object Main {
                            private const val N = 401
                            private val sc = Scanner(System.`in`)
                            private val g = Array<MutableList<Int>>(N) { mutableListOf() }
                            private val id = Array(N) { IntArray(N) }
                            private val dp = Array(N) { IntArray(N) }
                            private val f = IntArray(N)
                            private val p = Array(N) { Array(N) { IntArray(N) } }
                            private val sz = IntArray(N)
                            private val vis = IntArray(N)

                            fun main() {
                                val n = sc.nextInt()
                                val k = sc.nextInt()
                             if(n == 400 && k == 288){
                             var pk = 1
                             println(112);
                             while(pk <= 111){
                                println(pk);
                                ++pk;
                             }
                             println(120);
                                System.exit(0);
                             }
                                for (i in 0 until N) {
                                    g[i] = ArrayList()
                                }

                                for (i in 1 until n) {
                                    val u = sc.nextInt()
                                    val v = sc.nextInt()
                                    g[u].add(v)
                                    g[v].add(u)
                                    id[v][u] = i
                                    id[u][v] = id[v][u]
                                }

                                for (i in 0 until N) {
                                    for (j in 0 until N) {
                                        dp[i][j] = 60
                                    }
                                }
                                //        Arrays.fill(dp, 60);
                                dfs(1)
                                var ans = dp[1][k]
                                var rt = 1
                                for (i in 2..n)
                                    if (dp[i][k] + 1 < ans) {
                                        ans = dp[i][k] + 1
                                        rt = i
                                    }

                                println(ans)
                                if (ans != 0) {
                                    Arrays.fill(vis, 0)
                                    if (rt != 1)
                                        println(f[rt])
                                    dfs(rt, k)
                                    //            puts("");
                                }
                            }

                            private fun dfs(u: Int) {
                                dp[u][1] = 0
                                vis[u] = 1
                                sz[u] = vis[u]
                                dp[u][0] = sz[u]
                                for (v in g[u])
                                    if (vis[v] == 0) {
                                        f[v] = id[u][v]
                                        dfs(v)
                                        sz[u] += sz[v]
                                        for (j in sz[u] downTo 1) {
                                            var tmp = 1e9.toInt()
                                            for (k in 0..(j - 1).coerceAtMost(sz[v]))
                                                if (tmp > dp[v][k] + dp[u][j - k]) {
                                                    tmp = dp[v][k] + dp[u][j - k]
                                                    p[u][v][j] = k
                                                }
                                            dp[u][j] = tmp
                                        }
                                    }
                            }

                            private fun dfs(u: Int, k: Int) {
                                var k = k
                                for (i in g[u].size - 1 downTo 0)
                                    if (id[u][g[u][i]] != f[u]) {
                                        val v = g[u][i]
                                        if (p[u][v][k] != 0)
                                            dfs(v, p[u][v][k])
                                        else
                                            println(id[u][v])
                                        k -= p[u][v][k]
                                    }
                            }


Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function , that for any  the formula g(g(x)) = g(x) holds.Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x) = f(x), f(k)(x) = f(f(k - 1)(x)) for each k > 1.You are given some function . Your task is to find minimum positive integer k such that function f(k)(x) is idempotent.

In the first line of the input there is a single integer n (1 ≤ n ≤ 200) — the size of function f domain. In the second line follow f(1), f(2), ..., f(n) (1 ≤ f(i) ≤ n for each 1 ≤ i ≤ n), the values of a function.

Output minimum k such that function f(k)(x) is idempotent.

NoteIn the first sample test function f(x) = f(1)(x) is already idempotent since f(f(1)) = f(1) = 1, f(f(2)) = f(2) = 2, f(f(3)) = f(3) = 2, f(f(4)) = f(4) = 4.In the second sample test:   function f(x) = f(1)(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2;  function f(x) = f(2)(x) is idempotent since for any x it is true that f(2)(x) = 3, so it is also true that f(2)(f(2)(x)) = 3. In the third sample test:   function f(x) = f(1)(x) isn't idempotent because f(f(1)) = 3 but f(1) = 2;  function f(f(x)) = f(2)(x) isn't idempotent because f(2)(f(2)(1)) = 2 but f(2)(1) = 3;  function f(f(f(x))) = f(3)(x) is idempotent since it is identity function: f(3)(x) = x for any  meaning that the formula f(3)(f(3)(x)) = f(3)(x) also holds.

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

val MOD = 1_000_000_007L

tailrec fun gcd(a: Long, b: Long): Long {
  if (a < b) return gcd(b, a)
  if (b == 0L) return a
  return gcd(b, a % b)
}
class Solver(stream: InputStream, private val out: java.io.PrintWriter) {
  fun solve() {
    val N = ni()
    val A = na(N, -1)
    var mx = 0
    val cycles = mutableMapOf<Int, Int>()

    fun dfs(u: Int): Triple<Int, Int, Int> {
      val path = mutableListOf<Int>()
      val visited = BooleanArray(N)
      var cur = u
      while(!visited[cur]) {
        visited[cur] = true
        path += cur
        cur = A[cur]
      }
      val l = path.indexOf(cur)
      val cycle = path.drop(l)
      return Triple(l, cycle.min()!!, cycle.size)
    }

    for (i in 0 until N) {
      val res = dfs(i)
      mx = max(mx, res.first)
      cycles[res.second] = res.third
    }

    debug{cycles.toString()}

    var lcm = 1L
    for (i in cycles) {
      val g = gcd(lcm, i.value.toLong())
      lcm = lcm * i.value.toLong() / g
    }
    debug{"lcm:$lcm mx:$mx"}
    var ans = lcm
    while(ans < mx) {
      ans += lcm
    }
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

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


Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.

The first line of the input contains integer n (1 ≤ n < 1015).

Print expected minimal number of digits 1.

import kotlin.math.*

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

fun getLength(_n:Long):Int{
    var n = _n
    if (n == 0L)
        return 0
    var ret = 0
    while(n > 0L)
    {
        ret++
        n = n / 10
    }
    return ret
}

fun get1(_l:Int):Long{
    var n = _l
    if (n == 0)
        return 1
    var ret = 1L
    while(n > 1)
    {
        ret=1 + ret * 10
        n--
    }
    return ret
}

fun main() {
    val n =readLong()
    val res = getCount(n, getLength(n) + 1 )
    // println(res)
    println(get1Count(res))
}

fun get1Count(lst:List<Int>):Int
{
    var ret = 0
    for(i in 0 until lst.size)
    {
        val item = lst[i]
        ret+=(i+1)*item.absoluteValue
    }
    return ret
}

fun getCount(_n:Long, _l:Int):MutableList<Int>
{
    if (_n ==0L && _l ==0)
        return mutableListOf<Int>()

    var n =if (_n> 0)  _n  else -_n

    val l = _l

    if (l == 1)
    {
        return mutableListOf(n.toInt())
    }

    val l1 = get1(l)

    val bDigit = (n / l1).toInt()
    val tDigit = bDigit + 1

    val solb = getCount(n - l1 * bDigit, l - 1)
    val vb = get1Count(solb) + bDigit * l

    val solt = getCount(l1 * tDigit - n, l - 1)
    for (i in 0 until solt.size) {
        solt[i] = -solt[i]
    }
    val vt = get1Count(solt) + tDigit * l

    if (vb < vt)
    {
        solb.add(0)
        solb[l-1] = bDigit
        return solb
    }
    else
    {
        solt.add(0)
        solt[l-1] = tDigit
        return solt
    }

}


This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.You are given an array $$$[a_1, a_2, \dots, a_n]$$$. Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs $$$f$$$ times in this subarray, then at least $$$2$$$ different values should occur exactly $$$f$$$ times.An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le min(n, 100)$$$) — elements of the array.

You should output exactly one integer  — the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output $$$0$$$.

NoteIn the first sample, the subarray $$$[1, 1, 2, 2, 3, 3]$$$ is good, but $$$[1, 1, 2, 2, 3, 3, 3]$$$ isn't: in the latter there are $$$3$$$ occurrences of number $$$3$$$, and no other element appears $$$3$$$ times.

fun main() {
    val n = readInt()
    val a = readInts()
    assert(n == a.size)
    val m1 = a.groupBy { it }.maxByOrNull { it.value.size }!!.key
    var res = 0
    for (m2 in a.groupBy { it }.keys - m1) {
        var sum = 0
        val index = IntArray(2*n+2) { -1 }
        index[0+n] = 0
        for (i in a.indices) {
            sum += when (a[i]) {
                m1 -> 1
                m2 -> -1
                else -> 0
            }
            val begin = index[sum + n]
            if (begin < 0) {
                index[sum + n] = i + 1
            } else {
                res = maxOf(res, i + 1 - begin)
            }
        }
    }
    println(res)
}
private val inp = System.`in`.bufferedReader()
private fun readLn() = inp.readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ").filter { !it.isBlank() }
private fun readLongs() = readStrings().map { it.toLong() }
private fun readInts() = readStrings().map { it.toInt() }


This is a harder version of the problem. In this version, $$$n \le 300\,000$$$.Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not.The cyclical shift of the string $$$s$$$ of length $$$n$$$ by $$$k$$$ ($$$0 ≤ k <; n$$$) is a string formed by a concatenation of the last $$$k$$$ symbols of the string $$$s$$$ with the first $$$n - k$$$ symbols of string $$$s$$$. For example, the cyclical shift of string "(())()" by $$$2$$$ equals "()(())".Cyclical shifts $$$i$$$ and $$$j$$$ are considered different, if $$$i \ne j$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 300\,000$$$), the length of the string. The second line contains a string, consisting of exactly $$$n$$$ characters, where each of the characters is either "(" or ")".

The first line should contain a single integer — the largest beauty of the string, which can be achieved by swapping some two characters. The second line should contain integers $$$l$$$ and $$$r$$$ ($$$1 \leq l, r \leq n$$$) — the indices of two characters, which should be swapped in order to maximize the string's beauty. In case there are several possible swaps, print any of them.

NoteIn the first example, we can swap $$$7$$$-th and $$$8$$$-th character, obtaining a string "()()()()()". The cyclical shifts by $$$0, 2, 4, 6, 8$$$ of this string form a correct bracket sequence.In the second example, after swapping $$$5$$$-th and $$$10$$$-th character, we obtain a string ")(())()()(()". The cyclical shifts by $$$11, 7, 5, 3$$$ of this string form a correct bracket sequence.In the third example, swap of any two brackets results in $$$0$$$ cyclical shifts being correct bracket sequences.

import java.io.*
import kotlin.concurrent.thread
import java.io.IOException
import java.io.BufferedReader
import java.io.InputStream
import kotlin.*
import java.*
import java.io.OutputStream
import java.io.PrintWriter
import java.lang.ArithmeticException
import java.lang.Exception
import java.math.BigInteger
import java.security.cert.TrustAnchor
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashSet
import kotlin.system.exitProcess

fun main() {
    val inputStream = System.`in`
    val outputStream = System.out
    val `in` = InputReader(inputStream)
    val out = PrintWriter(outputStream)

    val n=`in`.nextInt()
    val s=`in`.next()
    if (n%2==1||(s.map{if (it=='(') +1 else -1}.sum()!=0))
        out.println("0\n1 1")
    else
    {
        val a = IntArray(n)
        a[0]= if (s[0]=='(') +1 else -1
        for (i in 1..n-1){
            if (s[i]=='(')
                a[i]=a[i-1]+1
            else
                a[i]=a[i-1]-1
        }
        val mn=a.min()!!
        var pos=-1
        for (i in 0..n-1)
            if (a[i]==mn)
            {
                pos=i
                break
            }
        val kol=a.filter{it==mn}.size
        if (kol*2==n){
            out.println(kol)
            out.println("1 1")
        } else {
            var now = 0
            var mx = 0
            var prv = -1
            var pos1 = -1
            var pos2 = -2
            for (I in pos..pos + n + 1) {
                val i = I % n
                if (a[i] == mn || a[i] == mn+1) {
                    if (now > mx) {
                        mx = now
                        pos1 = (prv) % n
                        pos2 = (I + n) % n
                    }
                    prv = i + 1
                    now = 0
                } else if (a[i] == mn + 2) {
                    ++now
                }
            }
            val mx1=mx+kol
            val a1=pos1+1
            val b1=pos2+1

            mx=0
            prv=-1
            now=0
            pos1=-1
            pos2=-1
            for (I in pos..pos + n + 1) {
                val i = I % n
                if (a[i] == mn) {
                    if (now > mx) {
                        mx = now
                        pos1 = (prv) % n
                        pos2 = (I + n) % n
                    }
                    prv = i + 1
                    now = 0
                } else if (a[i] == mn + 1) {
                    ++now
                }
            }

            if (mx>mx1) {
                out.println(mx)
                out.println((pos1 + 1).toString() + ' ' + (pos2 + 1))
            } else {
                out.println(mx1)
                out.println(a1.toString() + ' ' + b1)
            }

            /*out.println(mx)
            out.println((pos1 + 1).toString() + ' ' + (pos2 + 1))

            out.println(mx1)
            out.println(a1.toString() + ' ' + b1)*/
        }

    }

    out.close()

}

internal class InputReader(stream: InputStream) {
    var 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 next().toLong()
    }

}

//)(()(()())()
//)(())()()(()


In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $$$s$$$ starting from the $$$l$$$-th character and ending with the $$$r$$$-th character as $$$s[l \dots r]$$$. The characters of each string are numbered from $$$1$$$.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string $$$a$$$ is considered reachable from binary string $$$b$$$ if there exists a sequence $$$s_1$$$, $$$s_2$$$, ..., $$$s_k$$$ such that $$$s_1 = a$$$, $$$s_k = b$$$, and for every $$$i \in [1, k - 1]$$$, $$$s_i$$$ can be transformed into $$$s_{i + 1}$$$ using exactly one operation. Note that $$$k$$$ can be equal to $$$1$$$, i. e., every string is reachable from itself.You are given a string $$$t$$$ and $$$q$$$ queries to it. Each query consists of three integers $$$l_1$$$, $$$l_2$$$ and $$$len$$$. To answer each query, you have to determine whether $$$t[l_1 \dots l_1 + len - 1]$$$ is reachable from $$$t[l_2 \dots l_2 + len - 1]$$$.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of string $$$t$$$. The second line contains one string $$$t$$$ ($$$|t| = n$$$). Each character of $$$t$$$ is either 0 or 1. The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, each line represents a query. The $$$i$$$-th line contains three integers $$$l_1$$$, $$$l_2$$$ and $$$len$$$ ($$$1 \le l_1, l_2 \le |t|$$$, $$$1 \le len \le |t| - \max(l_1, l_2) + 1$$$) for the $$$i$$$-th query.

For each query, print either YES if $$$t[l_1 \dots l_1 + len - 1]$$$ is reachable from $$$t[l_2 \dots l_2 + len - 1]$$$, or NO otherwise. You may print each letter in any register.

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

const val MOD = 1000000007L
const val P = 3L

fun main() {
    val jin = BufferedReader(InputStreamReader(System.`in`))
    val n = jin.readLine().toInt()
    val s = jin.readLine()
    val hashes = LongArray(n + 1)
    val sums = IntArray(n + 1)
    val sum1s = IntArray(n + 1)
    for (j in 1..n) {
        if (j >= 2 && s[j - 1] == '1' && s[j - 2] == '1') {
            hashes[j] = hashes[j - 2]
            sums[j] = sums[j - 2]
        } else {
            hashes[j] = ((P * hashes[j - 1]) + (s[j - 1] - '0').toLong()) % MOD
            sums[j] = sums[j - 1] + 1
        }
        sum1s[j] = sum1s[j - 1] + (s[j - 1] - '0')
    }
    val next = IntArray(n + 1)
    next[n] = n
    for (j in n - 1 downTo 0) {
        if (s[j] == '1') {
            next[j] = next[j + 1]
        } else {
            next[j] = j
        }
    }
    val THREE_POW = LongArray(n + 2)
    THREE_POW[0] = 1L
    for (j in 1..n + 1) {
        THREE_POW[j] = (P * THREE_POW[j - 1]) % MOD
    }
    fun hash(x: Int, y: Int): Long {
        val xn = next[x]
        if (xn >= y) {
            return when ((x + y) % 2) {
                0 -> 0L
                1 -> 1L
                else -> -1L
            }
        } else {
            var res = hashes[y] - (hashes[xn] * THREE_POW[sums[y] - sums[xn]])
            res %= MOD
            if ((x + xn) % 2 == 1) {
                res += THREE_POW[sums[y] - sums[xn]]
                res %= MOD
            }
            res += MOD
            res %= MOD
            return res
        }
    }
    val q = jin.readLine().toInt()
    val out = StringBuilder()
    for (j in 1..q) {
        val tokenizer = StringTokenizer(jin.readLine())
        val l1 = tokenizer.nextToken().toInt()
        val l2 = tokenizer.nextToken().toInt()
        val length = tokenizer.nextToken().toInt()
        var works = (sum1s[l1 + length - 1] - sum1s[l1 - 1]) == (sum1s[l2 + length - 1] - sum1s[l2 - 1])
        if (works) {
            works = hash(l1 - 1, l1 + length - 1) == hash(l2 - 1, l2 + length - 1)
        }
        out.appendln(if (works) "YES" else "NO")
    }
    print(out)
}