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

val MOD = 1_000_000_007

class Solver(stream: InputStream, private val out: java.io.PrintWriter) {
  fun solve() {
    val N = ni()
    val P1 = na(N)
    val P = P1.clone()
    zip(P)
    P.reverse()
    val T = ni()
    val Q = na(T, -1)
    val needsOpen = BooleanArray(N)
    for (i in 0 until T) {
      needsOpen[N - 1 - Q[i]] = true
    }
    val negFlg = BooleanArray(N)
    val lstOpen = ArrayDeque<Int>()
    for (i in 0 until N) {
      val canClose = lstOpen.isNotEmpty() && P[lstOpen.last] == P[i]
      val toOpen = needsOpen[i] || !canClose
      if (toOpen) {
        lstOpen.addLast(i)
      } else {
        lstOpen.removeLast()
      }
      negFlg[i] = !toOpen
    }
    if (lstOpen.isNotEmpty()) {
      out.println("NO")
    } else {
      out.println("YES")
      for (i in 0 until N) {
        P1[i] *= if (negFlg[N - 1 - i]) 1 else -1 // 反転するので
      }
      out.println(P1.joinToString(" "))
    }
  }

  fun zip(A: IntArray) {
    val ids = A.distinct().sorted().toIntArray()
    for (i in 0 until A.size) {
      A[i] = lowerBound(ids, 0, A[i])
    }
  }

  fun lowerBound(A: IntArray, s: Int, x: Int): Int {
    var l = s - 1
    var h = A.size
    while(h - l > 1) {
      val m = (h + l) / 2
      if (A[m] >= x) h = m
      else l = m
    }
    return h
  }

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

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

  private fun ni() = next().toInt()
  private fun nl() = next().toLong()
  private fun ns() = next()
  private fun na(n: Int, offset: Int = 0): IntArray {
    return map(n) { ni() + offset }
  }

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

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

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

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

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

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

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

fun <A, B> pair(a: A, b: B) = RPair(a, b)
data class RPair<A, B>(val _1: A, val _2: B)

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

As you know, Vova has recently become a new shaman in the city of Ultima Thule. So, he has received the shaman knowledge about the correct bracket sequences. The shamans of Ultima Thule have been using lots of different types of brackets since prehistoric times. A bracket type is a positive integer. The shamans define a correct bracket sequence as follows:  An empty sequence is a correct bracket sequence.  If {a1, a2, ..., al} and {b1, b2, ..., bk} are correct bracket sequences, then sequence {a1, a2, ..., al, b1, b2, ..., bk} (their concatenation) also is a correct bracket sequence.  If {a1, a2, ..., al} — is a correct bracket sequence, then sequence  also is a correct bracket sequence, where v (v > 0) is an integer. For example, sequences {1, 1,  - 1, 2,  - 2,  - 1} and {3,  - 3} are correct bracket sequences, and {2,  - 3} is not.Moreover, after Vova became a shaman, he learned the most important correct bracket sequence {x1, x2, ..., xn}, consisting of n integers. As sequence x is the most important, Vova decided to encrypt it just in case.Encrypting consists of two sequences. The first sequence {p1, p2, ..., pn} contains types of brackets, that is, pi = |xi| (1 ≤ i ≤ n). The second sequence {q1, q2, ..., qt} contains t integers — some positions (possibly, not all of them), which had negative numbers in sequence {x1, x2, ..., xn}.Unfortunately, Vova forgot the main sequence. But he was lucky enough to keep the encryption: sequences {p1, p2, ..., pn} and {q1, q2, ..., qt}. Help Vova restore sequence x by the encryption. If there are multiple sequences that correspond to the encryption, restore any of them. If there are no such sequences, you should tell so.

The first line of the input contains integer n (1 ≤ n ≤ 106). The second line contains n integers: p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains integer t (0 ≤ t ≤ n), followed by t distinct integers q1, q2, ..., qt (1 ≤ qi ≤ n). The numbers in each line are separated by spaces.

Print a single string "NO" (without the quotes) if Vova is mistaken and a suitable sequence {x1, x2, ..., xn} doesn't exist. Otherwise, in the first line print "YES" (without the quotes) and in the second line print n integers x1, x2, ..., xn (|xi| = pi; xqj < 0). If there are multiple sequences that correspond to the encrypting, you are allowed to print any of them.

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

val MOD = 1_000_000_007

class Solver(stream: InputStream, private val out: java.io.PrintWriter) {
  fun solve() {
    val N = ni()
    val P = na(N)
    val T = ni()
    val Q = na(T, -1)
    val needsOpen = BooleanArray(N)
    for (i in 0 until T) {
      needsOpen[Q[i]] = true
    }
    val closeFlg = BooleanArray(N)
    val lstOpen = ArrayDeque<Int>()
    for (i in N - 1 downTo 0) {
      val canClose = lstOpen.isNotEmpty() && P[lstOpen.last] == P[i]
      val toOpen = needsOpen[i] || !canClose
      if (toOpen) {
        lstOpen.addLast(i)
      } else {
        lstOpen.removeLast()
      }
      closeFlg[i] = !toOpen
    }
    if (lstOpen.isNotEmpty()) {
      out.println("NO")
    } else {
      out.println("YES")
      for (i in 0 until N) {
        P[i] *= if (closeFlg[i]) 1 else -1 // 反転するので
      }
      out.println(P.joinToString(" "))
    }
  }

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

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

  private fun ni() = next().toInt()
  private fun nl() = next().toLong()
  private fun ns() = next()
  private fun na(n: Int, offset: Int = 0): IntArray {
    return map(n) { ni() + offset }
  }

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

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

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

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

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

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

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

fun <A, B> pair(a: A, b: B) = RPair(a, b)
data class RPair<A, B>(val _1: A, val _2: B)

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


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

val MOD = 1_000_000_007L

inline fun just(c: Char) = run {
  when(c) {
    '*', '?', '.' -> -1
    else -> c - '0'
  }
}

inline fun bombable(c: Char) = run {
  when(c) {
    '*', '?' -> true
    else -> false
  }
}

class Solver(stream: InputStream, private val out: java.io.PrintWriter) {
  fun solve() {
    val S = "..${ns()}.."
    val N = S.length
    val dp = Array(N){Array(2){LongArray(2)} }
    dp[1][0][0] = 1

    for (i in 2 until N) {
      for (cur in 0 until 2) {
        if (!bombable(S[i]) && cur == 1) continue
        for (pre in 0 until 2) {
          for (prepre in 0 until 2) {
            val preJust = just(S[i - 1])
            if (preJust != -1 && preJust != cur + prepre) continue

            dp[i][pre][cur] += dp[i - 1][prepre][pre]
            if (dp[i][pre][cur] >= MOD) dp[i][pre][cur] -= MOD
          }
        }
      }
      debug{"DP($i)"}
      debugDim(dp[i])
    }

    val ans = dp[N-1][0][0]
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.

The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square.

Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7).

NoteIn the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.

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

val MOD = 1_000_000_007L

inline fun just(c: Char) = run {
  when(c) {
    '*', '?', '.' -> -1
    else -> c - '0'
  }
}

inline fun bombable(c: Char) = run {
  when(c) {
    '*', '?' -> true
    else -> false
  }
}

class Solver(stream: InputStream, private val out: java.io.PrintWriter) {
  fun solve() {
    val S = "..${ns()}.."
    val N = S.length
    val dp = Array(N){Array(2){LongArray(2)} }
    dp[1][0][0] = 1

    for (i in 2 until N) {
      for (cur in 0 until 2) {
        if (!bombable(S[i]) && cur == 1) continue
        if (S[i] == '*' && cur == 0) continue

        for (pre in 0 until 2) {
          for (prepre in 0 until 2) {
            val preJust = just(S[i - 1])
            if (preJust != -1 && preJust != cur + prepre) continue

            dp[i][pre][cur] += dp[i - 1][prepre][pre]
            if (dp[i][pre][cur] >= MOD) dp[i][pre][cur] -= MOD
          }
        }
      }
      debug{"DP($i)"}
      debugDim(dp[i])
    }

    val ans = dp[N-1][0][0]
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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


@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 0 until n) {
            if(D[i][j] == Int.MAX_VALUE) continue
            for(l in 1 .. n-j) {
                if(D[i+1].setMin(j+l, D[i][j] + C[i][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))
}

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))
}


import java.util.*

private const val MODULO = 1000000007

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

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

class TaskD(numSegments: Int, val buses: LongArray) {
    var count: IntArray
    var countSum: IntArray

    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)

        val stopIndices = sortedMapOf<Int, Int>()
        for (i in 0 until allStops.size)
            stopIndices[allStops[i]] = i

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

        buses.sort()

        count = IntArray(stopIndices.size)
        count[0] = 1
        countSum = IntArray(count.size, { 1 })
        countSum[0] = 0
    }

    fun result() = mod(count.last(), MODULO)

    fun run() {
        var lastTo = 0
        var total = 0
        for (b in buses) {
            val countDelta = mod(countSum[b.to()] - countSum[b.from()], MODULO)
            addCount(b.to(), countDelta)
        }

//        addCount(lastTo, total)
    }

    fun addCount(i: Int, d: Int) {
        count[i] = (count[i] + d) % MODULO
        for (j in i + 1 until countSum.size)
            countSum[j] = (countSum[j] + d) % MODULO
    }

    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()
}

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()
}


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

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)
    if (n < 3) {
        out.println("0")
    } else {
        val graph = Graph(n)
        for (i in 0 until m) {
            val (u, v) = sc.readLine()!!.split(" ").map { it.toInt() - 1 }
            graph.addEdge(u, v)
        }
        graph.checkDeep()
        out.println(graph.count)
    }
    out.close()
}

internal class Node(val id: Int) {
    val links = LinkedList<Node>()
}

internal class Graph(var n: Int) {
    var graphArray = Array(n) { Node(it) }
    private val colors = Array(n) { 0 }
    var count: Long = 0

    fun addEdge(from: Int, to: Int) {
        graphArray[from].links.add(graphArray[to])
        graphArray[to].links.add(graphArray[from])
    }

    fun checkDeep() {
        for (i in 0 until n) {
            if (colors[i] == 0) {
                colors[i] = 1
                dfs(graphArray[i])
            }
        }
    }

    private fun dfs(n: Node) {
        for (it in n.links) {
            if (colors[it.id] == 0) {
                colors[it.id] = 1
                dfs(it)
            } else if (colors[it.id] == colors[n.id]) {
                count++
            }
        }
        colors[n.id] = 0
    }
}

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()
}


/**
 * 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 = 3
    div.add(1)
    while (i * i <= n) {
        if (n % i == 0) {
            div.add(i)
            if (n / i != i && n / 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() }

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() }


import kotlin.math.*

private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }

fun main(){
    val (n, k) = readInts()
    val a = readInts().sorted()
    println(a)
    var cnt = IntArray(200005, {0})
    var ans = IntArray(200005, {0})
    for (i in 0 until n){
        var temp = a[i]
        var d = 0
        while (temp > 0){
            if (cnt[temp] < k) {
                cnt[temp]++;
                ans[temp] += d
            }
            temp /= 2
            d++
        }
    }
    var res = Int.MAX_VALUE
    for (i in 1..a[n - 1]){
        if (cnt[i] == k) res = min(res, ans[i])
    }
    print(res)
}

The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.

import kotlin.math.*
fun main() {
    var (n, m) = readLine()!!.split(" ").map { it.toInt() }
    var vals = readLine()!!.split(" ").map { it.toInt() }.sorted()
    var cnts = IntArray(200005, { 0 })
    var answ = IntArray(200005, { 0 })
    for (i in 0 until n) {
        var curr = vals[i]
        var indx = 0
        while (curr > 0) {
            if (cnts[curr] < m) {
                cnts[curr]++
                answ[curr] += indx
            }
            curr /= 2
            indx++

        }

    }
    var result = Int.MAX_VALUE
    for (i in 1..vals[n - 1]) {
        if (cnts[i] == m) result = min(result, answ[i])
    }
    println(result)
}

/*

 */


import java.util.*

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

    val adj = Array(n, { _ ->
        BooleanArray(n, { _ ->
            false
        })
    })

    for (i in 1..rr) {
        val a = scanner.nextInt()
        val b = scanner.nextInt()

        adj[a - 1][b - 1] = true
        adj[b - 1][a - 1] = true
    }

    val rrExists = adj[0][n - 1]

    val distance = IntArray(n, { _ -> Int.MAX_VALUE })
    val q = LinkedList<Int>()
    q.push(1)
    distance[0] = 0

    while (q.isNotEmpty()) {
        var curr = q.poll()

        adj[curr - 1].indices
                .filter { distance[it] > distance[curr - 1] + 1 && rrExists != adj[curr - 1][it] }
                .forEach {
                    distance[it] = distance[curr - 1] + 1
                    q.push(it + 1)
                }

    }

    if (distance[n - 1] == 0) {
        println(-1)
    } else {
        println(distance[n - 1])
    }

}

In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.

NoteIn the first sample, the train can take the route  and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

import java.util.*

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

    val adj = Array(n, { _ ->
        BooleanArray(n, { _ ->
            false
        })
    })

    for (i in 1..rr) {
        val a = scanner.nextInt()
        val b = scanner.nextInt()

        adj[a - 1][b - 1] = true
        adj[b - 1][a - 1] = true
    }

    val rrExists = adj[0][n - 1]

    val distance = IntArray(n, { _ -> Int.MAX_VALUE })
    val q = LinkedList<Int>()
    q.push(1)
    distance[0] = 0

    while (q.isNotEmpty()) {
        var curr = q.poll()

        adj[curr - 1].indices
                .filter { distance[it] > distance[curr - 1] + 1 && rrExists != adj[curr - 1][it] }
                .forEach {
                    distance[it] = distance[curr - 1] + 1
                    q.push(it + 1)
                }

    }

    if (distance[n - 1] == Int.MAX_VALUE) {
        println(-1)
    } else {
        println(distance[n - 1])
    }

}


<?php
$n = trim(fgets(STDIN));
$a = explode(' ',trim(fgets(STDIN)));
$m = trim(fgets(STDIN));
$b = explode(' ',trim(fgets(STDIN)));

$max = 0;
$r = 0;
for($i=0;$i<$n;$i++)
 for($j=0;$j<$m;$j++)
  if($b[$j] % $a[$i] == 0)
   if($b[$j]/$a[$i] == $max) $r++; else {$max = $b[$j]/$a[$i]; $r = 1;}

print $r;
?>

Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
$c = trim(fgets(STDIN));
$d = explode(" ", trim(fgets(STDIN)));
$e = array();
for($x = 0; $x < $c; $x++)
{
    for($y = 0; $y < $a; $y++)
    {
        if($d[$x] % $b[$y] == 0)
        {
            array_push($e, $d[$x] / $b[$y]);
        }
    }
}
rsort($e);
array_push($e, "end");
$f = array_unique($e);
$g = array_keys($f);
print $g[1] - $g[0];
?>


<?php

$s = trim(fgets(STDIN));

$sign = true;
if ($s[0] === '-') {
    $s = substr($s, 1);
    $sign = false;
}
$s .= (strpos($s, '.') === false ? '.00' : '00');
$pos = strpos($s, '.');
$s = '$' . number_format(substr($s, 0, $pos)) . substr($s, $pos, 3);
echo($sign ? $s : '(' . $s . ')') . 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").


#include<string.h>
#include<stdio.h>
#define MAXN 100008
char sa[MAXN],sb[MAXN];
int main(){

     int  i,L,counta,countb,La,count;
	while(scanf("%s%s",sa,sb)!=EOF){
		L=strlen(sa);
		La=0;
		counta=0;countb=0;count=0;
		for(i=0;i<L;i++)
			if(sa[i]!=sb[i]){
				La++;
				if(sa[i]=='7')counta++;
				if(sb[i]=='7')countb++;
		   }
			if(countb>counta){
				count=countb-counta;
				La-=count;
				count+=La/2;
		   }
			else if(countb<counta){
				count=counta-countb;
				La-=count;
				count+=La/2;

			}
			else count=La/2;

	  printf("%d\n",count);
	}
	return 0;

}

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.


<?php
$count = fgets(STDIN);
while ($s = fgets(STDIN))
{
    $friends[] = explode(" ", $s);
}
$param = explode(" ", $count);
$num = 0;
for ($i = 0; $i < $param[0]; $i++)
{
    for ($j = 1; $j < $param[0]; $j++)
    {
        $new_buf = $friends[$i][0] . " " . $friends[$i][1];
        $new_buf1 = $friends[$j][0] . " " . $friends[$j][1];

        if ($new_buf == $buf or $new_buf1 == $buf1)
        {
            unset($friends[$j]);
        }
        if ($friends[$i][0] == $friends[$j][1] and $friends[$i][1] == $friends[$j][0])
        {
            $buf = $friends[$i][0] . " " . $friends[$i][1];
            $buf1 = $friends[$j][0] . " " . $friends[$j][1];
            $razn = $friends[$j][2] - $friends[$i][2];
            if ($razn > 0 and $razn <= $param[1])
            {
                $itogfr[] = $friends[$i][1] . " " . $friends[$j][1];
                $num++;
                unset($friends[$j]);
                break;
            }
        }
    }

}
echo $num;
for ($i = 0; $i < count($itogfr); $i++)
{
    echo "\n" . $itogfr[$i];
}

?>

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


<?php
$fileName = 'php://stdin';
$file = fopen($fileName, "r");

list($n, $m) = explode(" ", trim(fgets($file)));

for ($i = 0; $i < $n; $i++) {
  list($fc[$i], $fd[$i]) = explode(" ", trim(fgets($file)));
  $f[] = $fc[$i].$fd[$i];
}

for ($i = 0; $i < $m; $i++) {
  list($kc[$i], $kd[$i]) = explode(" ", trim(fgets($file)));
  $k[] = $kc[$i].$kd[$i];
}

function couple($x, $y) {
  $ans = 0;
  $a = array_count_values($x);
  $b = array_count_values($y);

  foreach ($a as $key => $val) {
    if (isset($b[$key])) {
      if ($b[$key] >= $val) { $ans += $val; }
      else { $ans += $b[$key]; }
    }
  }
  return $ans;
}

echo couple($fd, $kd).' '.couple($f, $k);

?>

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.


<?php
	$stdin = fopen("php://stdin","r");
	$stdout = fopen("php://stdout","w");
	$n = 0;
	$b = 0;
	$cur = array();
	fscanf($stdin,"%d%d",$n,$b);
	$total = (double) ($b);
	$str = fgets($stdin);
    $cur=	explode(" ",$str);
	for ($i=0;$i!=$n;++$i)
		$total+=(double)($cur[$i]);
	$everyone = $total / (double)$n;
	for ($i=0;$i!=$n;++$i)
	{
		$added[$i] = $everyone - (double)($cur[$i]);
		if ($added[$i]<0) die("-1\n");
	}
	for ($i=0;$i!=$n;++$i)
		fprintf($stdout,"%.2lf\n",$added[$i]);
?>

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;
    }
}


<?php
$n = trim(fgets(STDIN));
$pol = $n;
$k = $pol;
while ($pol != 1)
{
    if ($pol % 2 === 0)
    {
        $pol = $pol / 2;
        $k += $pol;
    }
    else
    {
        $pol = 1;
        $k += $pol;
    }

}
echo $k;
?>

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;


You are given n points on a plane. All points are different.Find the number of different groups of three points (A,B,C) such that point B is the middle of segment AC. The groups of three points are considered unordered, that is, if point B is the middle of segment AC, then groups (A,B,C) and (C,B,A) are considered the same.

The first line contains a single integer n (3≤n≤3000) — the number of points.
Next n lines contain the points. The i-th line contains coordinates of the i-th point: two space-separated integers xi,yi (-1000≤xi,yi≤1000).
It is guaranteed that all given points are different.

Print the single number — the answer to the problem.


<?php

error_reporting(0);

solve();

function solve(){

	//$Input = new Input("input.txt");
	$Input = new Input();

	$N = (int)$Input->in();

	$sum = 0;

	$points = array();
	$costs = array();
	$c = array_fill(0, 5, 0);

	for ($i = 0; $i < $N; $i++) $points[] = (int)$Input->in();

	for ($i = 0; $i < 5; $i++) $costs[] = (int)$Input->in();

	for ($i = 0; $i < $N; $i++)
	{
		$sum += $points[$i];

		$pos = 1;

		while ($sum >= $costs[0])
		{
			if ($costs[$pos] > $sum)
			{
				$c[$pos - 1]++;
				$sum -= $costs[$pos - 1];
				$pos = 0;

			} else if ($costs[$pos] <= $sum && $pos === 4)
			{
				$c[$pos]++;
				$sum -= $costs[$pos];
				$pos = 0;
			}

			$pos++;
		}
	}

	print(implode(" ", $c).PHP_EOL);
	print($sum);
}

class Input{
	private $handle = "";
	private $values = array();
	private $index = 0;

	public function __construct($localfile){

		if (is_file($localfile)) {

			$this->handle = fopen($localfile, "r");
			$contents = stream_get_contents($this->handle);

		} else {

			$contents = stream_get_contents(STDIN);

		}

		$no_newlines = str_replace(array("\r\n", "\r", "\n"), " ", $contents);
		$this->values = explode(" ", $no_newlines);
	}

	public function in(){

		return $this->values[$this->index++];

	}

	public function close(){

		if (is_file($localfile) && feof($this->handle)) fclose($this->handle);

	}
}

?>

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.


In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.

The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).

Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.

NoteIn the first example the ranks will be raised in the following manner:1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.


Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.


<?php
	$filename = "php://stdin";
	$fh = fopen($filename,'r');
	$n = intval(fgets($fh));
	$up = array();
	$down = array();
	for($i = 0;$i < $n; $i++){
		$line = fgets($fh);
		list($u,$d) = explode(' ',$line);
		$u = intval($u);
		$d = intval($d);
		if (array_key_exists($u,$up)){
			$up[$u]++;
		}else{
			$up[$u] = 1;
			if (intval($u) != intval($d)){
				if (array_key_exists($d, $down)){
					$down[$d]++;
				} else $down[$d] = 1;
			}
		}
	}
	$ku = array_keys($up);
	$kd = array_keys($down);

	$half = intval(($n+1)/2);
	$res = 1<<30;
	if ($n==1000){
		print $up[1]." ".$up[2]." ".$up[3]."\n";
		print $down[1]." ".$down[2]." ".$down[3]."\n";
	}
	foreach($ku as $value){
		$value = intval($value);
		$uv = 0; $ud = 0;
		if (array_key_exists($value, $up)) $uv = intval($up[$value]);
		if (array_key_exists($value, $down)) $ud = intval($down[$value]);
		$total = $uv + $ud;

		if ($total < $half) continue;
		if ($uv >= $half){
			print 0;
			die();
		}
		$res = min($res,$half - $uv);
	}

	foreach($kd as $value){
		$value = intval($value);
		$uv = 0; $ud = 0;
		if (array_key_exists($value, $up)) $uv = intval($up[$value]);
		if (array_key_exists($value, $down)) $ud = intval($down[$value]);
		$total = $uv + $ud;

		if (intval($total) < $half) continue;
		if ($uv >= $half){
			print 0;
			die();
		}
		$res = min($res,$half - $uv);
	}

	if ($res == (1<<30)) print -1; else	print $res;
?>

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.


<?php

class Companions{

    private $count;

    private $volume;

    private $poured = array();

    public $result;

    public function __construct(){
        $this->init();
    }
    // init params
    private function init()
    {
        fscanf(STDIN, "%d %d", $this->count, $this->volume);
        $this->poured = explode (" ", trim(fgets(STDIN)));

    }

    public function execute()
    {
        $maxVolume = $this->volume + array_sum($this->poured);
        $dose = $maxVolume/$this->count;
        if ($dose*$this->count == $maxVolume){
            $res = array();
            $all = 0;

            foreach($this->poured as $v){
                $res[] = number_format(($dose - $v), 6, '.', '');
                $all += abs($dose-$v);
            }
            $this->result = ($this->volume - $all) ? -1 : implode("\n", $res);

        } else {
            $this->result = -1;
        }
        return $this->result;
    }

}

$test = new Companions();
echo $test->execute();

?>

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

    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');

    $n = fgets($stdin);
    $weights = explode(" ", fgets($stdin));
    $wants = explode(" ", fgets($stdin));

    $verdict = 0;
    for($i=$wants[0];$i<$wants[1];++$i){
        $verdict+=$weights[$i-1];
    }

    fputs($stdout, $verdict);
?>

The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
list($c, $d) = explode(" ", trim(fgets(STDIN)));
$e = array_slice($b, $c - 1);
$f = array_slice($e, 0, $d - 1 - ($c - 1));
$g = array_sum($f);
print $g;
?>


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.


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.


<?php
$a = trim(fgets(STDIN));
$b = trim(fgets(STDIN));
if(strlen($b) % 2 == 0)
{
    $c = str_split($b, 2);
    print implode("-", $c);
}
else
{
    $c = substr($b, 0, 3);
    $d = substr($b, 3);
    $e = str_split($d, 2);
    print $c . "-" . implode("-", $e);
}
?>

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

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

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

<?php
$a = trim(fgets(STDIN));
$b = trim(fgets(STDIN));
if((strlen($b) == 2) || (strlen($b) == 3))
{
    print $b;
}
else
{
    if(strlen($b) % 2 == 0)
    {
        $c = str_split($b, 2);
        print implode("-", $c);
    }
    else
    {
        $c = substr($b, 0, 3);
        $d = substr($b, 3);
        $e = str_split($d, 2);
        print $c . "-" . implode("-", $e);
    }
}
?>


<?php
function go($who, $num, $n)
{
    if ($num==$n)
        return;
    if ($num>1)
        printf(" ");
    printf("%d",$who);
    go(($who+$num+1)%(int)$n,$num+1, $n);
}
$file=fopen("input.txt","r");
$n=fgets($file);
go(2,1,$n);
printf("\n");
?>

A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.


<?php

###### IO ######
error_reporting(E_ALL);
error_reporting(0);

function readString($f) {
	$r = array(
		"\r" => '',
		"\n" => '',
	);
	return strtr(fgets($f), $r);
}

function readNumString($f) {
	return trim(fgets($f));
}

function stringToArray($str) {
	return str_split($str);
}

function readNum($f, $is_int = false) {
	$v = readNumString($f);
	return $is_int ? intval($v) : floatval($v);
}

function readStringExplode($f, $delimiter = ' ') {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = 'trim';
	return array_map($callf, $return);
}

function readStringExplodeNum($f, $delimiter = ' ', $is_int = false) {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = $is_int ? 'intval' : 'floatval';
	return array_map($callf, $return);
}

###### /IO ######

function diffCnt($baseTime, $time) {
	$return = 0;
	for ($i = 0; $i < 5; $i++) {
		if ($baseTime[$i] != $time[$i]) {
			$return++;
		}
	}
	return $return;
}

function getAnswer($is_test = false, $f = false) {
	$stream = STDIN;
	if ($is_test)
		$stream = $f;
	/* begin body */
	$format = readNum($stream);
	$baseTime = readString($stream);
	$answer = array(
		'res' => '',
		'diff' => 55,
	);
	$minHour = 0;
	$maxHour = 23;
	if ($format == 12) {
		$minHour = 1;
		$maxHour = 12;
	}
	for ($hour = $minHour; $hour < $maxHour; $hour++) {
		for ($minute = 0; $minute < 60; $minute++) {
			$checkHour = $hour;
			while (strlen($checkHour) < 2)
				$checkHour = '0' . $checkHour;
			$checkMinute = $minute;
			while (strlen($checkMinute) < 2)
				$checkMinute = '0' . $checkMinute;
			$checkTime = "{$checkHour}:{$checkMinute}";
			$diff = diffCnt($baseTime, $checkTime);
			if ($diff < $answer['diff']) {
				$answer['diff'] = $diff;
				$answer['res'] = $checkTime;
			}
		}
	}
	echo $answer['res'];
	/* / end body */
}

if (empty($is_test))
	getAnswer();

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.


<?php
$cntInput = fgets(STDIN);
$arInput =  explode(' ',trim(fgets(STDIN)));
for($i=0;$i<$cntInput;$i++){
    for($k=$i+1;$k<$cntInput;$k++){
        $rkey = array_search($arInput[$i]+$arInput[$k],$arInput);
        if ($rkey>0){
            echo ($rkey+1).' '.($i+1).' '.($k+1);
            exit;
        }
    }
}
echo -1;

?>

Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of lengths of the other two forms. Help him to do this.

The first line contains integer n (3 ≤ n ≤ 100) — amount of worm's forms. The second line contains n space-separated integers ai (1 ≤ ai ≤ 1000) — lengths of worms of each form.

Output 3 distinct integers i j k (1 ≤ i, j, k ≤ n) — such indexes of worm's forms that ai = aj + ak. If there is no such triple, output -1. If there are several solutions, output any of them. It possible that aj = ak.