Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit ≠ ermit).Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):   Clerihew (aabb);  Alternating (abab);  Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.

The first line contains two integers n and k (1 ≤ n ≤ 2500, 1 ≤ k ≤ 5) — the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.

Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.

NoteIn the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".

2 1
day
may
sun
fun
test
hill
fest
thrill

import java.io.DataInputStream
import java.io.InputStream
import java.lang.StringBuilder

internal class Parserdoubt(`in`: InputStream) {
    private val BUFFER_SIZE = 1 shl 17

    private val din: DataInputStream
    private val buffer: ByteArray
    private var bufferPointer: Int = 0
    private var bytesRead: Int = 0

    init {
        din = DataInputStream(`in`)
        buffer = ByteArray(BUFFER_SIZE)
        bytesRead = 0
        bufferPointer = bytesRead
    }

    @Throws(Exception::class)
    fun nextString(): String {
        val sb = StringBuffer("")
        var c = read()
        while (c <= ' '.toByte())
            c = read()
        do {
            sb.append(c.toChar())
            c = read()
        } while (c > ' '.toByte())
        return sb.toString()
    }

    @Throws(Exception::class)
    fun wholeLine(): String {
        val sb = StringBuffer("")
        var c = read()
        while (c <= '\n'.toByte())
            c = read()
        do {
            sb.append(c.toChar())
            c = read()
        } while (c > '\n'.toByte())
        return sb.toString()
    }

    @Throws(Exception::class)
    fun nextChar(): Char {
        var c = read()
        while (c <= ' '.toByte())
            c = read()
        return c.toChar()
    }

    @Throws(Exception::class)
    fun nextInt(): Int {
        var ret = 0
        var c = read()
        while (c <= ' '.toByte())
            c = read()
        val neg = c == '-'.toByte()
        if (neg)
            c = read()
        do {
            ret = ret * 10 + c - '0'.toInt()
            c = read()
        } while (c > ' '.toByte())
        return if (neg) -ret else ret
    }

    @Throws(Exception::class)
    fun nextLong(): Long {
        var ret: Long = 0
        var c = read()
        while (c <= ' '.toByte())
            c = read()
        val neg = c == '-'.toByte()
        if (neg)
            c = read()
        do {
            ret = ret * 10 + c - '0'.toLong()
            c = read()
        } while (c > ' '.toByte())
        return if (neg) -ret else ret
    }

    @Throws(Exception::class)
    private fun fillBuffer() {
        bufferPointer = 0
        bytesRead = din.read(buffer, 0, BUFFER_SIZE)
        if (bytesRead == -1)
            buffer[0] = -1
    }

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

fun process(s: String, k: Int):String?{
    var id = s.length - 1
    var seenK = 0
    while(seenK < k && id>=0){
        if("aeiou".contains(s[id]))seenK++
        if(seenK < k)id--
    }
    if(id==-1)return null
    return s.substring(id)
}

fun main(args : Array<String>) {

    val input = Parserdoubt(`in` = System.`in`)
    val NT = 1//input.nextInt()
    val sb = StringBuilder()
    for(test in 1..NT){
        val n= input.nextInt()
        val k= input.nextInt()
        var ans = "aaaa"
        for(i in 0 until n){
            val s = ArrayList<String?>()
            for(j in 0..3){
                s.add(process(input.nextString(), k))
            }
            if(s.contains(null)){
                ans = "NO"
                break
            }
            if(s[0] == s[1] && s[0] == s[2] && s[0] == s[3])
                continue

            if(s[0] == s[1] && s[3] == s[2]){
                if(ans == "aaaa" || ans == "aabb"){
                    ans = "aabb"
                } else {
                    ans = "NO"
                    break
                }
            }

            else if(s[0] == s[2] && s[1] == s[3]){
                if(ans == "aaaa" || ans == "abab"){
                    ans = "abab"
                } else {
                    ans = "NO"
                    break
                }
            }

            else if(s[0] == s[3] && s[1] == s[2]){
                if(ans == "aaaa" || ans == "abba"){
                    ans = "abba"
                } else {
                    ans = "NO"
                    break
                }
            }
            else {
                ans = "NO"
                break
            }
        }
        println(ans)

    }
}

[{'input': '1 1\r\nday\r\nmay\r\nsun\r\nfun\r\n', 'output': ['aabb\r\n']}, {'input': '1 1\r\nday\r\nmay\r\ngray\r\nway\r\n', 'output': ['aaaa\r\n']}, {'input': '2 1\r\na\r\na\r\na\r\na\r\na\r\na\r\ne\r\ne\r\n', 'output': ['aabb\r\n']}, {'input': '2 1\r\nday\r\nmay\r\nsun\r\nfun\r\ntest\r\nhill\r\nfest\r\nthrill\r\n', 'output': ['NO\r\n']}, {'input': '2 5\r\na\r\na\r\na\r\na\r\na\r\na\r\ne\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nrezwbgy\r\nxakgmv\r\njogezwbgy\r\napezwbgy\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\nnuqfxwrb\r\napqfkw\r\nuqfxwrb\r\nnhcuqfxwrb\r\nogkznwncmt\r\nevf\r\nogkznwncmt\r\nogkznwncmt\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\naawjvkxx\r\nawjvkxx\r\nxawjvkxx\r\nawjvkxx\r\n', 'output': ['aaaa\r\n']}, {'input': '2 2\r\nrhcujgxabk\r\nnjgdqpurul\r\nueoedt\r\ncpcfhbyvo\r\nzmfwnieog\r\npkpylassbf\r\nhrfeod\r\ncdwuil\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\nol\r\nol\r\nol\r\nzol\r\nek\r\nek\r\nek\r\nqek\r\n', 'output': ['aaaa\r\n']}, {'input': '3 2\r\nexdaoao\r\nrdwunurp\r\ndunurp\r\ntyqzuxao\r\ndupocgsps\r\nzsiravcm\r\nnqiravcm\r\nlnupocgsps\r\niwashk\r\neepkqcykbv\r\nyviwashk\r\neepkqcykbv\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\ndaihacbnhgfts\r\nsqihpntjvczkw\r\nmihpntjvczkw\r\nvyacbnhgfts\r\ntsvovdpqajmgvcj\r\ncexqkwrvctomb\r\njxbomb\r\ngnpajmgvcj\r\n', 'output': ['abba\r\n']}, {'input': '3 2\r\netba\r\ntfecetba\r\nzkitbgcuuy\r\nuuy\r\nbuxeoi\r\nmekxoi\r\nblviwoehy\r\niwoehy\r\njyfpaqntiz\r\nqvaqntiz\r\nhciak\r\niak\r\n', 'output': ['aabb\r\n']}, {'input': '4 3\r\niixxiojrrdytjcbkvymw\r\nbjqixxiojrrdytjcbkvymw\r\nogjixxiojrrdytjcbkvymw\r\nevixxpfxpgicpg\r\njkotitixiughfhphliuurx\r\ngyubkqtonejprfjzvqxbdpn\r\ndpudxfoqnhekjytbwiuurx\r\noubkqtonejprfjzvqxbdpn\r\npgzaendrxjhsfzjmijv\r\npomuaendrxjhsfzjmijv\r\nafyuyxueaendrxjhsfzjmijv\r\naendrxjhsfzjmijv\r\nyubweicj\r\ntbnsuxqigmxdfnmbipubweicj\r\nfuftydlmoo\r\nmdkuftydlmoo\r\n', 'output': ['NO\r\n']}, {'input': '5 2\r\nqurcmcbxyoddgyyccsmb\r\nlsdzsqoa\r\neurcmcbxyoddgyyccsmb\r\noa\r\nutyxmdhcvaclynmstwsx\r\nmkyycelbmkmdrilmbvr\r\nutyxmdhcvaclynmstwsx\r\nrduyelbmkmdrilmbvr\r\nhmguhvqswwciowwgu\r\nnoe\r\nzmyncuwrowwgu\r\nqrhymghavvbmigzsjoe\r\nbvofhknbzusykztlxwms\r\nbpbfmvjaimkdeddy\r\neofhknbzusykztlxwms\r\nmhivpkxkpazimkdeddy\r\negvywnhmfngllaknmn\r\nmblkvhenlggoftwjgk\r\nzegvywnhmfngllaknmn\r\ngrdenlggoftwjgk\r\n', 'output': ['abab\r\n']}, {'input': '7 3\r\nferwljzwakxedlgwl\r\noerwljzwakxedlgwl\r\nhyqombizhuhxedprb\r\netptjrizhuhxedprb\r\nurtuckar\r\ndkartmwramklcmi\r\nrurtuckar\r\nnurartmwramklcmi\r\niraziomsv\r\nsaziomsv\r\nbprapiqpayzurgij\r\nusyemayzurgij\r\nztstmeecvmkvuu\r\nquexlecvmkvuu\r\nrlhwecvmkvuu\r\nzecvmkvuu\r\niikymgbncljtub\r\nqiikymgbncljtub\r\nbcavhexqamyszgfya\r\nojexqamyszgfya\r\nieyxqinjinjv\r\nxtiudieyxqinjinjv\r\nthtceyxqinjinjv\r\nmuneyxqinjinjv\r\nwreae\r\nqylcjhjzfhteae\r\nozcjthgyuchqo\r\nfcjozcjthgyuchqo\r\n', 'output': ['NO\r\n']}, {'input': '16 1\r\ni\r\ni\r\ni\r\ni\r\ni\r\nu\r\ni\r\ni\r\no\r\na\r\na\r\no\r\na\r\ni\r\na\r\na\r\ni\r\ni\r\no\r\no\r\ni\r\ni\r\ni\r\ni\r\nu\r\nu\r\nu\r\nu\r\no\r\ne\r\ne\r\ne\r\no\r\ni\r\no\r\ni\r\na\r\na\r\na\r\na\r\nu\r\no\r\no\r\nu\r\ni\r\no\r\no\r\ni\r\na\r\na\r\ne\r\ne\r\na\r\na\r\na\r\na\r\na\r\no\r\na\r\na\r\nu\r\na\r\nu\r\nu\r\n', 'output': ['NO\r\n']}, {'input': '16 1\r\neb\r\neb\r\nfe\r\nce\r\ner\r\ner\r\new\r\new\r\nu\r\ncu\r\nu\r\nu\r\nud\r\nik\r\nud\r\nik\r\nve\r\niw\r\niw\r\nne\r\nel\r\nob\r\nel\r\nob\r\no\r\neo\r\no\r\nyo\r\nav\r\nav\r\nei\r\nmi\r\nu\r\noh\r\noh\r\nzu\r\niw\r\niw\r\na\r\nma\r\ni\r\nu\r\nku\r\ngi\r\nac\r\no\r\no\r\nac\r\ni\r\ner\r\nai\r\ner\r\nyu\r\nuf\r\nuf\r\nhu\r\nef\r\nef\r\nef\r\nef\r\nmu\r\nu\r\nqe\r\nie\r\n', 'output': ['NO\r\n']}, {'input': '25 1\r\nw\r\ni\r\nv\r\nx\r\nh\r\ns\r\nz\r\ny\r\no\r\nn\r\nh\r\ni\r\nf\r\nf\r\ny\r\nr\r\nb\r\nu\r\no\r\np\r\nz\r\nh\r\nt\r\no\r\nw\r\nx\r\nh\r\no\r\nj\r\ny\r\nw\r\nj\r\ny\r\nh\r\nh\r\nr\r\ns\r\nb\r\ny\r\nr\r\nw\r\no\r\nl\r\nl\r\nh\r\nh\r\nw\r\nu\r\na\r\nv\r\no\r\nx\r\nd\r\nw\r\nc\r\nf\r\ni\r\ne\r\nj\r\nq\r\nk\r\na\r\ne\r\nl\r\nw\r\nm\r\nf\r\na\r\nc\r\na\r\nb\r\nf\r\nj\r\nb\r\nx\r\ni\r\nx\r\ne\r\nu\r\nh\r\nm\r\no\r\ni\r\nq\r\nm\r\nk\r\nn\r\nd\r\nl\r\np\r\nc\r\nw\r\nu\r\nz\r\nc\r\nk\r\ng\r\ny\r\nj\r\ny\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\ne\r\ne\r\ne\r\n', 'output': ['aaaa\r\n']}, {'input': '1 1\r\na\r\ne\r\ne\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\na\r\ne\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\na\r\ne\r\ne\r\n', 'output': ['aabb\r\n']}, {'input': '1 1\r\ne\r\ne\r\na\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\ne\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\ne\r\na\r\na\r\ne\r\n', 'output': ['abba\r\n']}, {'input': '1 1\r\na\r\na\r\na\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\ne\r\ne\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\ne\r\ne\r\na\r\n', 'output': ['abba\r\n']}, {'input': '1 1\r\ne\r\na\r\ne\r\na\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\na\r\na\r\ne\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\ne\r\na\r\na\r\n', 'output': ['aabb\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\na\r\na\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\na\r\na\r\na\r\n', 'output': ['aaaa\r\n']}, {'input': '1 2\r\neraub\r\nbee\r\naab\r\nttbee\r\n', 'output': ['NO\r\n']}, {'input': '10 1\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\ny\r\n', 'output': ['NO\r\n']}, {'input': '1 2\r\neeereaatktb\r\nbee\r\niaattb\r\nottbee\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nab\r\nac\r\nad\r\naf\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nar\r\nat\r\nay\r\naw\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\ne\r\na\r\ne\r\na\r\na\r\na\r\na\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\ni\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\ne\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\nabbbbbbbbbbbbbbbbcbbbbbbbbbbbbbbbb\r\nabbbbbbbbbbbbbbbbfbbbbbbbbbbbbbbbb\r\nabbbbbbbbbbbbbbbbxbbbbbbbbbbbbbbbb\r\nabbbbbbbbbbbbbbbbdbbbbbbbbbbbbbbbb\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\ne\r\ne\r\na\r\na\r\na\r\na\r\na\r\n', 'output': ['abba\r\n']}, {'input': '1 1\r\nbug\r\nsuy\r\nluh\r\ngut\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nam\r\nat\r\nan\r\nag\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\na\r\ne\r\ne\r\na\r\na\r\na\r\na\r\n', 'output': ['aabb\r\n']}, {'input': '1 4\r\naieoabcd\r\naeioabcd\r\naoeiabcd\r\naoieabcd\r\n', 'output': ['NO\r\n']}, {'input': '1 2\r\naec\r\naed\r\naek\r\naem\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nar\r\nab\r\nak\r\naz\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\na\r\na\r\na\r\na\r\nb\r\nb\r\nb\r\n', 'output': ['NO\r\n']}]


Friday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite game Fur2 and didn't have enough time to do the literature task. As Innocentius didn't want to get an F, he decided to do the task and read the book called "Storm and Calm" during the IT and Math lessons (he never used to have problems with these subjects). When the IT teacher Mr. Watkins saw this, he decided to give Innocentius another task so that the boy concentrated more on the lesson and less — on the staff that has nothing to do with IT. Mr. Watkins said that a palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. A concatenation of strings a, b is a string ab that results from consecutive adding of string b to string a. Of course, Innocentius knew it all but the task was much harder than he could have imagined. Mr. Watkins asked change in the "Storm and Calm" the minimum number of characters so that the text of the book would also be a concatenation of no more than k palindromes. Innocentius can't complete the task and therefore asks you to help him.

The first input line contains a non-empty string s which is the text of "Storm and Calm" (without spaces). The length of the string s does not exceed 500 characters. String s consists of uppercase and lowercase Latin letters. The second line contains a single number k (1 ≤ k ≤ |s|, where |s| represents the length of the string s).

Print on the first line the minimum number of changes that Innocentius will have to make. Print on the second line the string consisting of no more than k palindromes. Each palindrome should be non-empty and consist of uppercase and lowercase Latin letters. Use the character "+" (ASCII-code 43) to separate consecutive palindromes. If there exist several solutions, print any of them. The letters' case does matter, that is an uppercase letter is not considered equivalent to the corresponding lowercase letter.

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

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

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
    val s = readLn()
    val k = readInt()

    val n = s.length
    val C = List(n) { IntArray(n - it + 1) }
    for (l in 2 .. n) {
        for (i in 0 .. n - l) {
            C[i][l] = C[i+1][l-2]
            if(s[i] != s[i+l-1]) C[i][l]++
        }
    }

    val D = List(k+1) { IntArray(n+1) { Int.MAX_VALUE } }
    val P = List(k+1) { IntArray(n+1) }

    D[0][0] = 0

    for(i in 0 until k) {
        for(j in if(i == 0) 0..0 else i until n) {
            for(l in 1 .. n-j) {
                if(D[i+1].setMin(j+l, D[i][j] + C[j][l])) P[i+1][j+l] = l
            }
        }
    }

    val kf = (0..k).minBy { D[it][n] }!!
    val cost = D[kf][n]
    val pals = Array(kf) { "" }
    var j = n
    for(i in kf downTo 1) {
        val l = P[i][j]
        j -= l
        pals[i-1] = buildString {
            val sub = s.substring(j, j + (l/2))
            append(sub)
            if(l and 1 == 1) append(s[j + l/2])
            append(sub.reversed())
        }
    }

    println(cost)
    println(pals.joinToString("+"))
}

fun IntArray.setMin(i: Int, v: Int): Boolean {
    if(v < get(i)) {
        set(i, v)
        return true
    }
    return false
}

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

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

@JvmField val _writer = PrintWriter(OUTPUT, false)

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

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

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

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

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

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

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

fun `please stop removing these imports IntelliJ`() {
    iprintln(max(1, 2))
}


Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n.There are m buses running between the house and the school: the i-th bus goes from stop si to ti (si < ti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to ti - 1 inclusive, but he can get off the i-th bus only on the bus stop ti.Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109 + 7).

The first line contains two space-separated integers: n and m (1 ≤ n ≤ 109, 0 ≤ m ≤ 105). Then follow m lines each containing two integers si, ti. They are the numbers of starting stops and end stops of the buses (0 ≤ si < ti ≤ n).

Print the only number — the number of ways to get to the school modulo 1000000007 (109 + 7).

NoteThe first test has the only variant to get to school: first on bus number one to the bus stop number one; then on bus number two to the bus stop number two.In the second test no bus goes to the third bus stop, where the school is positioned. Thus, the correct answer is 0.In the third test Gerald can either get or not on any of the first four buses to get closer to the school. Thus, the correct answer is 24 = 16.

import java.util.*
import java.util.Arrays.binarySearch

private const val MODULO = 1000000007

fun Long.to(): Int = (this shr 32).toInt()
fun Long.from(): Int = (this and 0xFFFF_FFFFL).toInt()

fun bus(from: Int, to: Int): Long =
        (to.toLong() shl 32) + from

class TaskD(numSegments: Int, val buses: LongArray) {
    val lastStopI: Int
    var countSum: IntArray
    var countSumSize = 0

    init {
        var allStops = IntArray(buses.size * 2 + 2)
        for (i in 0 until buses.size) {
            allStops[i * 2] = buses[i].from()
            allStops[i * 2 + 1] = buses[i].to()
        }
        allStops[allStops.size - 2] = 0
        allStops[allStops.size - 1] = numSegments
        allStops.sort()
        var i = 0
        var j = 1
        while (j < allStops.size) {
            if (allStops[i] != allStops[j]) {
                allStops[++i] = allStops[j++]
            } else {
                j++
            }
        }
        allStops = allStops.copyOf(i + 1)
        lastStopI = allStops.size - 1

        for (i in buses.indices) {
            val bus = buses[i]
            val from = binarySearch(allStops, bus.from())
            val to = binarySearch(allStops, bus.to())
            buses[i] = bus(from, to)
        }

        buses.sort()

        countSum = IntArray(allStops.size + 1)
        countSum[0] = 0
        countSum[1] = 1
        countSumSize = 2
    }

    fun result() =
            if (lastStopI + 1 >= countSumSize) 0
            else mod(countSum[lastStopI + 1] - countSum[lastStopI], MODULO)

    fun run() {
        for (b in buses) {
            val currTo = b.to()
            countSumEnsureSize(currTo + 2)
            val countDelta = mod(countSum[currTo] - countSum[b.from()], MODULO)
            addCount(currTo, countDelta)
        }
    }

    fun addCount(i: Int, d: Int) {
        for (j in (i + 1)..(countSumSize - 1))
            countSum[j] = mod(countSum[j] + d, MODULO)
    }

    fun countSumEnsureSize(size: Int) {
        if (countSumSize >= size) return
        for (i in (countSumSize - 1 + 1)..(size - 1))
            countSum[i] = countSum[i - 1]
        countSumSize = size
    }

    fun print() {
        println(result())
    }
}

fun mod(n: Int, m: Int): Int = (n % m + m) % m

fun cfd() = with(Scanner(System.`in`)) {
    val numSegments = nextInt();
    val numbuses = nextInt()
    val buses = LongArray(numbuses) {
        val from = nextInt()
        val to = nextInt()
        bus(from, to)
    }

    with(TaskD(numSegments, buses)) {
        run()
        print()
    }
}

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


Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time t + 1, unless there are more travellers arriving at time t + 1 to the same planet.Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n.

The first line contains two space-separated integers: n (2 ≤ n ≤ 105), the number of planets in the galaxy, and m (0 ≤ m ≤ 105) — the number of pairs of planets between which Jack can travel using stargates. Then m lines follow, containing three integers each: the i-th line contains numbers of planets ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which are connected through stargates, and the integer transfer time (in seconds) ci (1 ≤ ci ≤ 104) between these planets. It is guaranteed that between any pair of planets there is at most one stargate connection. Then n lines follow: the i-th line contains an integer ki (0 ≤ ki ≤ 105) that denotes the number of moments of time when other travellers arrive to the planet with index i. Then ki distinct space-separated integers tij (0 ≤ tij < 109) follow, sorted in ascending order. An integer tij means that at time tij (in seconds) another traveller arrives to the planet i. It is guaranteed that the sum of all ki does not exceed 105.

Print a single number — the least amount of time Jack needs to get from planet 1 to planet n. If Jack can't get to planet n in any amount of time, print number -1.

NoteIn the first sample Jack has three ways to go from planet 1. If he moves to planet 4 at once, he spends 8 seconds. If he transfers to planet 3, he spends 3 seconds, but as other travellers arrive to planet 3 at time 3 and 4, he can travel to planet 4 only at time 5, thus spending 8 seconds in total. But if Jack moves to planet 2, and then — to planet 4, then he spends a total of only 2 + 5 = 7 seconds.In the second sample one can't get from planet 1 to planet 3 by moving through stargates.

import java.io.DataInputStream
import java.io.InputStream
import java.util.PriorityQueue

fun main() {
    val inputStream = Main.Parserdoubt(System.`in`)
    val solver = Main.Solver()
    solver.solve(inputStream)
}

object Main {
    data class Edge(val target: Planet, val cost: Int)
    data class Planet(val id: Int,val routes: ArrayList<Edge> = ArrayList(), val delays: HashMap<Int, Int> = HashMap(), var minTime: Int = Int.MAX_VALUE)
    class State  (
        val idPlanet: Int,
        val time: Int
    ): Comparable<State> {
        override fun compareTo(other: State): Int {
            return time - other.time
        }
    }

    internal class Solver(){
        fun solve(input: Parserdoubt){
            val N = input.nextInt()
            val planets = Array(N) {id -> Planet(id)}
            val M = input.nextInt()
            for(m in 1..M){
                val a = input.nextInt() - 1
                val b = input.nextInt() - 1
                val c = input.nextInt()
                planets[a].routes.add(Edge(planets[b], c))
                planets[b].routes.add(Edge(planets[a], c))
            }

            for(i in 0 until N){
                val c = input.nextInt()
                if(c > 0) {
                    var start = input.nextInt()
                    var last = start + 1
                    for (j in 1 until c) {
                        val t = input.nextInt()
                        if(t == last){
                            last = t + 1
                        } else {
                            for(x in start until last)
                                planets[i].delays[x] = last
                            start = t
                            last = start + 1
                        }
                    }
                    for(x in start until last)
                        planets[i].delays[x] = last
                }
            }
            val q = PriorityQueue<State>()
            q.add(State(0, 0))
            planets[0].minTime = 0
            while(q.isNotEmpty()){
                val s = q.poll()
                if(s.idPlanet == N - 1)break
                if(planets[s.idPlanet].minTime < s.time)continue

                for(e in planets[s.idPlanet].routes){
                    var timeNow = s.time
                    if(planets[s.idPlanet].delays.containsKey(timeNow))
                        timeNow = planets[s.idPlanet].delays[timeNow]!!
                    timeNow += e.cost
                    if(e.target.minTime > timeNow){
                        e.target.minTime = timeNow
                        q.add(State(e.target.id, timeNow))
                    }
                }
            }
            var ans = planets[N - 1].minTime
            if(ans == Int.MAX_VALUE)ans = -1
            println(ans)
        }
    }

    internal class Parserdoubt(`in`: InputStream) {
        private val BUFFER_SIZE = 1 shl 17

        private val din: DataInputStream
        private val buffer: ByteArray
        private var bufferPointer: Int = 0
        private var bytesRead: Int = 0

        init {
            din = DataInputStream(`in`)
            buffer = ByteArray(BUFFER_SIZE)
            bytesRead = 0
            bufferPointer = bytesRead
        }

        @Throws(Exception::class)
        fun nextString(): String {
            val sb = StringBuffer("")
            var c = read()
            while (c <= ' '.toByte())
                c = read()
            do {
                sb.append(c.toChar())
                c = read()
            } while (c > ' '.toByte())
            return sb.toString()
        }

        @Throws(Exception::class)
        fun wholeLine(): String {
            val sb = StringBuffer("")
            var c = read()
            while (c <= '\n'.toByte())
                c = read()
            do {
                sb.append(c.toChar())
                c = read()
            } while (c > '\n'.toByte())
            return sb.toString()
        }

        @Throws(Exception::class)
        fun nextChar(): Char {
            var c = read()
            while (c <= ' '.toByte())
                c = read()
            return c.toChar()
        }

        @Throws(Exception::class)
        fun nextInt(): Int {
            var ret = 0
            var c = read()
            while (c <= ' '.toByte())
                c = read()
            val neg = c == '-'.toByte()
            if (neg)
                c = read()
            do {
                ret = ret * 10 + c - '0'.toInt()
                c = read()
            } while (c > ' '.toByte())
            return if (neg) -ret else ret
        }

        @Throws(Exception::class)
        fun nextLong(): Long {
            var ret: Long = 0
            var c = read()
            while (c <= ' '.toByte())
                c = read()
            val neg = c == '-'.toByte()
            if (neg)
                c = read()
            do {
                ret = ret * 10 + c - '0'.toLong()
                c = read()
            } while (c > ' '.toByte())
            return if (neg) -ret else ret
        }

        @Throws(Exception::class)
        private fun fillBuffer() {
            bufferPointer = 0
            bytesRead = din.read(buffer, 0, BUFFER_SIZE)
            if (bytesRead == -1)
                buffer[0] = -1
        }

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


There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

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

fun main(args: Array<String>) {
    val (n, k) = readLine()!!.split(' ').map {it.toInt()}
    val a = readLine()!!.split(' ').map {it.toInt()}
    var l = 0
    val cnt = TreeMap<Int, Int>()
    var maxLen = 0
    val index = ArrayList<Int>()
    for (r in 0 until n) {
        cnt[a[r]] = cnt.getOrDefault(a[r], 0) + 1
        while (cnt.lastKey() - cnt.firstKey() > k) {
            val x = cnt[a[l]]!! - 1
            if (x == 0)
                cnt.remove(a[l])
            else
                cnt[a[l]] = x
            l++
        }
        if (r - l + 1 > maxLen) {
            maxLen = r - l + 1
            index.clear()
        }
        if (r - l + 1 == maxLen) {
            index.add(l)
        }
    }
    println("$maxLen ${index.size}")
    for (i in index)
        println("${i+1} ${i+maxLen}")
}


Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges.

The first line of input contains two integers n and m (1 ≤ n ≤ 19, 0 ≤ m) – respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two integers a and b, (1 ≤ a, b ≤ n, a ≠ b) indicating that vertices a and b are connected by an undirected edge. There is no more than one edge connecting any pair of vertices.

Output the number of cycles in the given graph.

NoteThe example graph is a clique and contains four cycles of length 3 and three cycles of length 4.

import java.io.*

fun main(args: Array<String>) {
    val sc = BufferedReader(InputStreamReader(System.`in`))
    val out = PrintWriter(BufferedOutputStream(System.out))
    val (n, m) = sc.readLine()!!.split(" ").map(String::toInt)
    val maxm = 1 shl n
    val graph = Array(n) { Array(n) { false } }
    val dp = Array(maxm) { Array(n) { 0L } }

    fun first(num: Int): Int {
        var i = 0
        while ((num and (1 shl i++)) == 0){}
        return i-1
    }

    for (i in 0 until m) {
        val (from, to) = sc.readLine()!!.split(" ").map { it.toInt() - 1 }
        graph[from][to] = true
        graph[to][from] = true
    }

    for(mask in 1 until maxm) {
        for(i in 0 until n) {
            val eI = (mask and (1 shl i)) > 0
            val bk = Integer.bitCount(mask)
            if(bk == 1 && eI) {
                dp[mask][i] = 1
            } else if(bk > 1 && eI && first(mask) != i) {
                var sum = 0L
                for(j in 0 until n) {
                    if(graph[i][j]) sum += dp[mask xor (1 shl i)][j]
                }
                dp[mask][i] = sum
            }
        }
    }

    var count = 0L
    for (mask in 7 until maxm) {
        for(i in 0 until n) {
            if (Integer.bitCount(mask) >= 3 && graph[first(mask)][i]) {
                count += dp[mask][i]
            }
        }
    }

    out.println(count / 2)
    out.close()
}


Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.

The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.

Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.

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

var n = 0
var a = IntArray(100005)
var gg = 2

fun main() {
    val inp = Scanner(System.`in`)
    val out = PrintWriter(System.out)
    n=inp.nextInt();
    for(i in 0 until n){
        a[i]=inp.nextInt();
    }
    if(n==1){
        out.println(0);
    }else if(n==2){
        out.println(if(a[0]==0 && a[1]!=0) 1 else 0)
    }else{
        gg=2
        go(a[1].toDouble(), if (a[1]==0) 0.0 else (1.0 * a[2]) / a[1])
        go(a[0].toDouble(), if (a[0]==0) 0.0 else (1.0 * a[2]) / a[0])
        go(a[0].toDouble(), if (a[0]==0) 0.0 else (1.0 * a[1]) / a[0])
        out.println(gg);
    }
    out.close()
}

fun go(x: Double, y: Double) {
    var x:Double = x
    var i = 0
    var cnt = 0
    //println("$x $y")
    while (i < n) {
        //println(abs(x-a[i]));
        if (abs(x - a[i]) > 1e-8) cnt++ else x *= y
        ++i
    }
    //println(gg)
    gg = Math.min(gg, cnt)
    //println(cnt)
}


Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line.  Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.

The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.

Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.

NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.

import java.util.*
import kotlin.system.exitProcess

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() } // list of ints
private fun exit() : Nothing = exitProcess(0)

inline fun <T : Comparable<T> > min(x : T, y : T): T{
    if(x < y){return x;}
    else{return y;}
}

inline fun <T : Comparable<T> > max(x : T, y : T): T{
    if(x > y){return x;}
    else{return y;}
}

class Fenwick(val n : Int){
    var t = IntArray(n + 1);

    fun upd(pos : Int, v : Int){
        var idx = pos;
        while(idx <= n){
            t[idx] = max(t[idx], v);
            idx += idx and (-idx);
        }
    }

    fun pref(pos : Int): Int{
        var ans = 0;
        var idx = pos;
        while(idx != 0){
            ans = max(ans, t[idx]);
            idx -= idx and (-idx);
        }
        return ans;
    }
}

fun main(){
    var n = readInt();
    var a = readInts();
    var b = readInts().toIntArray();
    var pos = IntArray(1+n);
    b.reverse();
    for(i in 0..n-1){
        pos[a[i]] = i;
    }
    for(i in 0..n-1){
        b[i] = pos[b[i]];
    }
    var t = Fenwick(n);
    var ans = 0;
    for(i in 0..n-1){
        var curr = t.pref(b[i]);
        ans = max(ans, curr + 1);
        t.upd(b[i] + 1, curr + 1);
    }
    println(ans);
}


Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.

The first input line contains two integers n and m (6 ≤ n ≤ 35, 1 ≤ m ≤ 10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow m lines, each containing space-separated si and ci which correspondingly indicate Vasya’s attempt (a line containing n numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).

Print the single number which indicates how many possible code variants that do not contradict the m system responses are left.

fun c(n: Int, k: Int): Sequence<Long> {
    return when {
        k < 0 || k > n -> emptySequence()
        n == 0 -> sequenceOf(0)
        else -> sequence {
            yieldAll(c(n - 1, k).map {it.shl(1)})
            yieldAll(c(n - 1, k - 1).map {it.shl(1) + 1})
        }
    }
}

fun main(args: Array<String>) {
    val (n, m) = readLine()!!.split(" ").map {it.toInt()}
    val a = Array(m) {
        val s = readLine()!!.split(" ")
        Pair(s[0].toLong(2), s[1].toInt())
    }
    val answers = c(n, n - a[0].second).map {a[0].first xor it}
    println(answers.filter {ans -> a.filter {java.lang.Long.bitCount(it.first xor ans) != n - it.second}.isEmpty()}.toList().size)
}


Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer.So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.

The first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds.

Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".

NoteIn the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4.

enum class Comparison {
    TOO_BIG, TOO_SMALL, FINE
}

var n = 0
var a = IntArray(0)

var following = 0

fun compare(m : Double) : Comparison {
    var cur = m
    var station = 0
    a.forEach {
        val nxt = Math.floor(cur / 10).toInt() + station
        if (nxt < it) return Comparison.TOO_SMALL
        if (nxt > it) return Comparison.TOO_BIG
        cur -= (it - station) * 10.0
        station = it
        cur += m
    }
    following = Math.floor(cur / 10).toInt() + station
    return Comparison.FINE
}

fun main(args : Array<String>) {
    n = readLine()!!.toInt()
    a = readLine()!!.split(" ").map { it.toInt() }.toIntArray()
    var l = 10.0
    var r = 1e18
    for (i in 1..700) {
        val m = (l + r) / 2.0
        if (compare(m) == Comparison.TOO_SMALL) {
            l = m
        } else {
            r = m
        }
    }
    val min = l
    val nxtmin = following

    l = 10.0
    r = 1e18
    for (i in 1..700) {
        val m = (l + r) / 2.0
        if (compare(m) == Comparison.TOO_BIG) {
            r = m
        } else {
            l = m
        }
    }
    val max = l
    val nxtmax = following

    if (nxtmax == nxtmin) {
        println("unique\n$nxtmax")
    } else {
        println("not unique")
    }
}


There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.  King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.

The first line contains number n, which is the number of knights at the round table (3 ≤ n ≤ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.

Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".

/**
 * author: Andreeha
 * created: 2020-04-25 16:56
 */

import java.util.*

fun main() {
    var n = readInt()
    var a = readInts()
    var div = MutableList<Int>(size = 0, init = {0})

    var i = 2
    div.add(1)
    while (i * i <= n) {
        if (n % i == 0) {
            if (n / i > 2)
                div.add(i)
            if (n / i != i && i > 2)
                div.add(n/i)
        }
        i += 1
    }
    var can = false
    for (i in 0 until div.size) {
        for (j in 0 until div[i]) {
            var all = 1;
            for (k in 0 until n / div[i]) {
                all = a[(k * div[i] + j) % n]
                if (all == 0)
                    break
            }
            if (all == 1) {
                can = true
                break
            }
        }
        if (can) break
    }
    println(if (can) "YES" else "NO")
}

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


Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 10^9, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 10^9, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.

The first line contains a single integer n (1≤n≤10^5), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 10^9, inclusive.

Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.

<?php

$n = (int)trim(fgets(STDIN));
$a = array_map('intval', explode(' ', trim(fgets(STDIN))));

if (max($a) == 1) {
    $a[$n - 1] = 2;
} else {
    $a[] = 0;
    sort($a);
    $a[0] = 1;
    unset($a[$n]);
}
echo implode(' ', $a) , PHP_EOL;


For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer.The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows:   A number contains the integer part and the fractional part. The two parts are separated with a character "." (decimal point).  To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character "," (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678  In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests).  When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets.  Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency — snakes ($), that's why right before the number in the financial format we should put the sign "$". If the number should be written in the brackets, then the snake sign should also be inside the brackets. For example, by the above given rules number 2012 will be stored in the financial format as "$2,012.00" and number -12345678.9 will be stored as "($12,345,678.90)".The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?

The input contains a number that needs to be converted into financial format. The number's notation length does not exceed 100 characters, including (possible) signs "-" (minus) and "." (decimal point). The number's notation is correct, that is:
  The number's notation only contains characters from the set {"0" – "9", "-", "."}.  The decimal point (if it is present) is unique and is preceded and followed by a non-zero quantity on decimal digits  A number cannot start with digit 0, except for a case when its whole integer part equals zero (in this case the integer parts is guaranteed to be a single zero: "0").  The minus sign (if it is present) is unique and stands in the very beginning of the number's notation  If a number is identically equal to 0 (that is, if it is written as, for example, "0" or "0.000"), than it is not preceded by the minus sign.  The input data contains no spaces.  The number's notation contains at least one decimal digit.

Print the number given in the input in the financial format by the rules described in the problem statement.

Pay attention to the second and third sample tests. They show that the sign of a number in the financial format (and consequently, the presence or absence of brackets) is determined solely by the sign of the initial number. It does not depend on the sign of the number you got after translating the number to the financial format.

<?php
    $s=readline();
    $minus=false;
    if($s[0]=="-"){
        echo ("(");
        $minus=true;
        $s=ltrim($s,$s[0]);
    }
    echo "$";

    preg_match('/^[^\d]*\d+/',$s,$lei);
    $lei=$lei[0];
    $s=ltrim($s,'/^[^\d]*\d+/');
    $lei=strrev($lei);
    $lei=chunk_split($lei,3,",");
    $lei=substr($lei,0,-1);
    $lei=strrev($lei);
    echo $lei;

    if(strpos($s,'.')){
        $s=strrev($s);
        preg_match('/^[^\d]*\d+/',$s,$bani);
        $bani=$bani[0];
        $bani=strrev($bani);

        echo ".".$bani[0];
        if(strlen($bani)>=2){
            echo $bani[1];
        }else{
            echo '0';
        }
    }else{
        echo ".00";
    }
    if($minus){
        echo ")";
    }
?>


A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".You are given a string s, consisting of lowercase Latin letters and characters "?". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = «aba», then the string "a??" is good, and the string «?bc» is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).

The first line is non-empty string s, consisting of no more than 10^5 lowercase Latin letters and characters "?". The second line is non-empty string p, consisting of no more than 10^5 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.

Print the single number representing the number of good substrings of string s.
Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.

Consider the first sample test. Here the string s has two good substrings: "b??" (after we replace the question marks we get "baa"), "???" (after we replace the question marks we get "baa").
Let's consider the second sample test. Here the string s has two good substrings: "ab?" ("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a").


Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types:   replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4);  swap any pair of digits in string a. Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.

The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 10^5.

Print on the single line the single number — the minimum number of operations needed to convert string a into string b.

In the first sample it is enough simply to swap the first and the second digit.
In the second sample we should replace the second digit with its opposite.
In the third number we should replace all three digits with their opposites.


The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti — the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that:   the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n),  the sum of the ti values of the remaining sculptures is maximized. Help the Vice Rector to analyze the criticism — find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.

The first input line contains an integer n (3≤n≤20000) — the initial number of sculptures. The second line contains a sequence of integers t1,t2,...,tn, ti — the degree of the i-th sculpture's attractiveness (-1000≤ti≤1000). The numbers on the line are separated by spaces.

Print the required maximum sum of the sculptures' attractiveness.

In the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 и 3.


Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj,bj) can close marker (xi,yi) only if their diameters match, that is, bj=yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj=xi.Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.

The first input line contains two space-separated integers n and m (1≤n,m≤10^5) — the number of markers and the number of caps, correspondingly.
Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1≤xi,yi≤1000) — the i-th marker's color and diameter, correspondingly.
Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1≤aj,bj≤1000) — the color and diameter of the j-th cap, correspondingly.

Print two space-separated integers u,v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.

In the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed — the first and the third markers.


A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.Polycarpus has already began the process and he partially emptied the Ber-Cola bottle. Now the first mug has a1 milliliters of the drink, the second one has a2 milliliters and so on. The bottle has b milliliters left and Polycarpus plans to pour them into the mugs so that the main equation was fulfilled.Write a program that would determine what volume of the drink Polycarpus needs to add into each mug to ensure that the following two conditions were fulfilled simultaneously:   there were b milliliters poured in total. That is, the bottle need to be emptied;  after the process is over, the volumes of the drink in the mugs should be equal.

The first line contains a pair of integers n, b (2≤n≤100,1≤b≤100), where n is the total number of friends in the group and b is the current volume of drink in the bottle. The second line contains a sequence of integers a1,a2,...,an (0≤ai≤100), where ai is the current volume of drink in the i-th mug.

Print a single number "-1" (without the quotes), if there is no solution. Otherwise, print n float numbers c1,c2,...,cn, where ci is the volume of the drink to add in the i-th mug. Print the numbers with no less than 6 digits after the decimal point, print each ci on a single line. Polycarpus proved that if a solution exists then it is unique.
Russian locale is installed by default on the testing computer. Make sure that your solution use the point to separate the integer part of a real number from the decimal, not a comma.

<?php

list($n, $b) = array_map('intval', explode(' ', trim(fgets(STDIN))));
$a = array_map('intval', explode(' ', trim(fgets(STDIN))));

$mx = max($a);
$sm = array_sum($a);
$b -= $mx * $n - $sm;
if ($b < 0) {
    echo -1 . PHP_EOL;
} else {
    $b /= $n;
    for ($i = 0; $i < $n; ++$i) {
        echo sprintf('%.6f', $mx - $a[$i] + $b) . PHP_EOL;
    }
}


Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date.The clock's face can display any number from 1 to d. It is guaranteed that ai≤d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d+1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1.Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1.

The first line contains the single number d — the maximum number of the day that Vasya's clock can show (1≤d≤10^6).
The second line contains a single integer n — the number of months in the year (1≤n≤2000).
The third line contains n space-separated integers: ai (1≤ai≤d) — the number of days in each month in the order in which they follow, starting from the first one.

Print a single number — the number of times Vasya manually increased the day number by one throughout the last year.

In the first sample the situation is like this:
  Day 1. Month 1. The clock shows 1. Vasya changes nothing.  Day 2. Month 1. The clock shows 2. Vasya changes nothing.  Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1.  Day 2. Month 2. The clock shows 2. Vasya changes nothing.  In total, Vasya manually changed the day number by 1 exactly 2 times.

<?php

$d = (int) trim(fgets(STDIN));
$n = (int) trim(fgets(STDIN));
$a = array_map('intval', explode(' ', trim(fgets(STDIN))));

echo $d * ($n - 1) - array_sum($a) + $a[$n - 1].PHP_EOL;


Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that user A sent user B a message at time t1, and user B sent user A a message at time t2. If 0<t2-t1≤d, then user B's message was an answer to user A's one. Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message.You are given the log of messages in chronological order and a number d. Find all pairs of users who will be considered to be friends.

The first line of the input contains two integers n and d (1≤n,d≤1000). The next n lines contain the messages log. The i-th line contains one line of the log formatted as "Ai Bi ti" (without the quotes), which means that user Ai sent a message to user Bi at time ti (1≤i≤n). Ai and Bi are non-empty strings at most 20 characters long, consisting of lowercase letters ('a' ... 'z'), and ti is an integer (0≤ti≤10000). It is guaranteed that the lines are given in non-decreasing order of ti's and that no user sent a message to himself. The elements in the lines are separated by single spaces.

In the first line print integer k — the number of pairs of friends. In the next k lines print pairs of friends as "Ai Bi" (without the quotes). You can print users in pairs and the pairs themselves in any order. Each pair must be printed exactly once.

In the first sample test case Vasya and Petya are friends because their messages' sending times are one second apart. Anya and Ivan are not, because their messages' sending times differ by more than one second.

4 1
vasya petya 1
petya vasya 2
anya ivan 2
ivan anya 4

[{'input': ['4 1\r\nvasya petya 1\r\npetya vasya 2\r\nanya ivan 2\r\nivan anya 4\r\n'], 'output': ['1\r\npetya vasya\r\n']}, {'input': ['1 1000\r\na b 0\r\n'], 'output': ['0\r\n']}, {'input': ['2 1\r\na b 0\r\nb a 0\r\n'], 'output': ['0\r\n']}, {'input': ['3 1\r\na b 1\r\nb c 2\r\nc d 3\r\n'], 'output': ['0\r\n']}, {'input': ['10 2\r\nlutdc xfavzancwrokyzzkpco 0\r\nxfavzancwrokyzzkpco lutdc 1\r\nlutdc vydvatbnibttqgn 2\r\nxfavzancwrokyzzkpco vydvatbnibttqgn 2\r\nvydvatbnibttqgn lutdc 3\r\nlutdc xfavzancwrokyzzkpco 4\r\nlutdc vydvatbnibttqgn 5\r\nlutdc vydvatbnibttqgn 6\r\nlutdc xfavzancwrokyzzkpco 6\r\nvydvatbnibttqgn xfavzancwrokyzzkpco 6\r\n'], 'output': ['2\r\nlutdc vydvatbnibttqgn\r\nlutdc xfavzancwrokyzzkpco\r\n']}, {'input': ['10 2\r\nrvmykneiddpqyf jdhmt 0\r\nwcsjvh jdhmt 0\r\njdhmt rvmykneiddpqyf 1\r\nrvmykneiddpqyf jdhmt 1\r\nwcsjvh rvmykneiddpqyf 2\r\nrvmykneiddpqyf jdhmt 2\r\njdhmt rvmykneiddpqyf 3\r\njdhmt wcsjvh 5\r\njdhmt wcsjvh 5\r\nrvmykneiddpqyf jdhmt 6\r\n'], 'output': ['1\r\njdhmt rvmykneiddpqyf\r\n']}, {'input': ['10 2\r\nliazxawm spxwktiqjgs 0\r\nnolq liazxawm 1\r\nliazxawm nolq 2\r\nliazxawm spxwktiqjgs 2\r\nnolq liazxawm 3\r\nspxwktiqjgs liazxawm 3\r\nspxwktiqjgs liazxawm 3\r\nspxwktiqjgs liazxawm 3\r\nspxwktiqjgs nolq 3\r\nnolq spxwktiqjgs 4\r\n'], 'output': ['3\r\nliazxawm nolq\r\nliazxawm spxwktiqjgs\r\nnolq spxwktiqjgs\r\n']}, {'input': ['10 2\r\nfxn ipntr 0\r\nipntr fxn 1\r\nfxn ipntr 1\r\npfvpfteadph ipntr 2\r\nfxn pfvpfteadph 4\r\nipntr fxn 4\r\npfvpfteadph fxn 5\r\nfxn pfvpfteadph 5\r\npfvpfteadph ipntr 6\r\nipntr pfvpfteadph 6\r\n'], 'output': ['2\r\nfxn ipntr\r\nfxn pfvpfteadph\r\n']}, {'input': ['10 2\r\nyltec xnzdtcgzxqqltvpfr 0\r\nfxxhcmbzzg xnzdtcgzxqqltvpfr 0\r\nfxxhcmbzzg xnzdtcgzxqqltvpfr 0\r\nfxxhcmbzzg yltec 1\r\nfxxhcmbzzg xnzdtcgzxqqltvpfr 2\r\nfxxhcmbzzg yltec 2\r\nyltec fxxhcmbzzg 3\r\nyltec xnzdtcgzxqqltvpfr 3\r\nyltec xnzdtcgzxqqltvpfr 5\r\nfxxhcmbzzg yltec 6\r\n'], 'output': ['1\r\nfxxhcmbzzg yltec\r\n']}, {'input': ['10 2\r\nrclgdpxdefqu abrfhwigaihoqq 0\r\nabrfhwigaihoqq rclgdpxdefqu 1\r\nrclgdpxdefqu bvkfwutdtvxgvx 1\r\nrclgdpxdefqu abrfhwigaihoqq 1\r\nabrfhwigaihoqq bvkfwutdtvxgvx 2\r\nbvkfwutdtvxgvx abrfhwigaihoqq 2\r\nbvkfwutdtvxgvx abrfhwigaihoqq 3\r\nabrfhwigaihoqq rclgdpxdefqu 5\r\nabrfhwigaihoqq rclgdpxdefqu 6\r\nrclgdpxdefqu bvkfwutdtvxgvx 6\r\n'], 'output': ['2\r\nabrfhwigaihoqq bvkfwutdtvxgvx\r\nabrfhwigaihoqq rclgdpxdefqu\r\n']}, {'input': ['3 1\r\na b 1\r\na b 2\r\nb a 2\r\n'], 'output': ['1\r\na b\r\n']}]


The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a>1). Note that the Beaver must use all the pebbles he has, i. e. n=a·b.   10 pebbles are arranged in two rows, each row has 5 pebbles Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble. The game process can be represented as a finite sequence of integers c1,...,ck, where:   c1=n  ci+1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1≤i<k). Note that ci>ci+1.  ck=1 The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.

The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
  2≤n≤50  The input limitations for getting 100 points are:
  2≤n≤10^9

Print a single number — the maximum possible result of the game.

Consider the first example (c1=10). The possible options for the game development are:
  Arrange the pebbles in 10 rows, one pebble per row. Then c2=1, and the game ends after the first move with the result of 11.  Arrange the pebbles in 5 rows, two pebbles per row. Then c2=2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3=1, and the game ends with the result of 13.  Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2=5,c3=1, and the game ends with the result of 16 — the maximum possible result.

<?php

$n = (int) trim(fgets(STDIN));

$tmp = 2;
$sm = $n;
while ($n > 1) {
    $flg = true;
    for ($i = $tmp; $i * $i <= $n && $flg; ++$i) {
        if (0 == $n % $i) {
            $tmp = $i;
            $n /= $i;
            $sm += $n;
            $flg = false;
        }
    }
    if ($flg) {
        ++$sm;
        break;
    }
}
echo $sm.PHP_EOL;


Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.


There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.

The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.

If there is no way to assigns seats to parliamentarians in a proper way print -1. Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.

NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.


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.

[{'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']}]


Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.

The first line contains two integers n and m — the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b — the numbers of students tied by the i-th lace (1 ≤ a, b ≤ n, a ≠ b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.

Print the single number — the number of groups of students that will be kicked out from the club.

NoteIn the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.

<?php
$count=explode(' ',trim(fgets(STDIN)));
$link_count = intval(trim($count[1]));
$child_count = intval(trim($count[0]));
$link = array();
for($i=0;$i<$link_count;$i++) {
    $input=explode(' ',trim(fgets(STDIN)));
    $n1=intval(trim($input[0]));
    $n2=intval(trim($input[1]));
    $link[$n1][]=$n2;
    $link[$n2][]=$n1;
}
$result = 0;
$completed = false;
while($completed === false) {
    $excl = array();
    foreach($link as $k => $v) {
        if(count($v) === 1) {
            $excl[$k] = reset($v);
        }
    }
    if(count($excl) > 0) {
        foreach($excl as $k => $v) {
            if(isset($link[$v])) {
                sort($link[$v]);
                for($i=0;$i<count($link[$v]);$i++) {
                    if($link[$v][$i] === $k) {
                        unset($link[$v][$i]);
                        if(count($link[$v]) < 1) {
                            unset($link[$v]);
                            break;
                        }
                    }
                }
            }
            if(isset($link[$k])) {
                unset($link[$k]);
            }
        }
        $result ++;
    }
    else {
        $completed = true;
    }
}

echo( $result );


The first line contains a pair of integers n, b (2 ≤ n ≤ 100, 1 ≤ b ≤ 100), where n is the total number of friends in the group and b is the current volume of drink in the bottle. The second line contains a sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the current volume of drink in the i-th mug.

Print a single number "-1" (without the quotes), if there is no solution. Otherwise, print n float numbers c1, c2, ..., cn, where ci is the volume of the drink to add in the i-th mug. Print the numbers with no less than 6 digits after the decimal point, print each ci on a single line. Polycarpus proved that if a solution exists then it is unique. Russian locale is installed by default on the testing computer. Make sure that your solution use the point to separate the integer part of a real number from the decimal, not a comma.


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.


The Little Elephant loves to play with color cards.He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces.

On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.

NoteIn the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.


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.