Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1·p2·...·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.

The first line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of primes in factorization of n.  The second line contains m primes numbers pi (2 ≤ pi ≤ 200 000).

Print one integer — the product of all divisors of n modulo 109 + 7.

NoteIn the first sample n = 2·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1·2·3·6 = 36.In the second sample 2·3·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1·2·3·4·6·12 = 1728.

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn
import scala.reflect.ClassTag

object Main {
  final val MOD = 1000000007
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val ct = new mutable.HashMap[Long, Long]().withDefault(k => 0)
    for (v <- StdIn.readLine().split(" ").map(_.toInt)) {
      ct(v) += 1
    }
    val ctl = ct.toArray
    val prod = new SegTree(n)(new ModMul(MOD - 1))
    for (((k, v), i) <- ctl.zipWithIndex) {
      prod(i) = v + 1
    }
    var ans = 1L
    for (((k, v), i) <- ctl.zipWithIndex) {
      prod(i) = 1
      val s = (v * (v + 1) / 2) % (MOD - 1)
      val p = prod.query(0, n) * s % (MOD - 1)
      ans *= modPow(k, p, MOD)
      ans %= MOD
      prod(i) = v + 1
    }
    println(ans)
  }
  def modPow(x: Long, y: Long, mod: Int): Long = {
    @tailrec
    def rec(x: Long, y: Long, r: Long): Long = {
      if (y == 0) r
      else rec(x * x % mod, y / 2, if (y % 2 == 1) r * x % mod else r)
    }
    return rec(x, y, 1)
  }
}
trait Monoid[T] {
  def zero: T
  def mul(a: T, b: T): T
}

class SegTree[T: ClassTag](n0: Int)(m: Monoid[T]) {

  val n = {
    var n1 = 1
    while (n1 < n0) n1 <<= 1
    n1
  }

  val t: Array[T] = Array.fill[T](2 * n - 1)(m.zero)

  def set(a: Array[T]): Unit = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (r - l == 1) {
        if (l < a.length) t(k) = a(l)
        else t(k) = m.zero
        return t(k)
      } else {
        t(k) = m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
        return t(k)
      }
    }
    rec(0, 0, n)
  }

  def update(k0: Int, v: T): Unit = {
    var k = k0 + (n - 1)
    t(k) = v
    while (k > 0) {
      k = (k - 1) / 2
      t(k) = m.mul(t(2 * k + 1), t(2 * k + 2))
    }
  }

  def get(k0: Int): T = {
    return t(k0 + (n - 1))
  }

  def query(a: Int, b: Int): T = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (b <= l || r <= a) {
        return m.zero
      } else if (a <= l && r <= b) {
        return t(k)
      } else {
        return m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
      }
    }
    return rec(0, 0, n)
  }
}

class ModMul(mod: Int) extends Monoid[Long] {
  def zero = 1L
  def mul(a: Long, b: Long) = a * b % mod
}

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(m) = readInts(1)
  val ps = readInts(m)
  val psDist = ps.distinct
  val MOD = 1000000007L

  val cnts = Array.fill(ps.max.toInt + 1){ 0 }

  for (p <- ps) {
    val pi = p.toInt
    cnts(pi) += 1
  }

  val muls = Array.fill(ps.max.toInt + 1){ 0L }
  for (i <- cnts.indices) {
    if (cnts(i) > 0) {
      muls(i) = (cnts(i) + 1L) * cnts(i) / 2
    }
  }

  val powsLeft, powsRight = Array.fill(psDist.size){ 0L }
  var powL, powR = 1L

  for (i <- psDist.indices) {
    powsLeft(i) = powL
    powL = powL * (cnts(psDist(i).toInt) + 1) % (MOD - 1)
  }

  for (i <- psDist.indices.reverse) {
    powsRight(i) = powR
    powR = powR * (cnts(psDist(i).toInt) + 1) % (MOD - 1)
  }

  var res = BigInt(1)
  for (i <- psDist.indices) {
    val p = psDist(i)
    res = res * BigInt(p).modPow(BigInt(muls(p)) * powsLeft(i) * powsRight(i), MOD) % MOD
  }

  println(res)
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn
import scala.reflect.ClassTag

object Main {
  final val MOD = 1000000007
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val ct = new mutable.HashMap[Long, Long]().withDefault(k => 0)
    for (v <- StdIn.readLine().split(" ").map(_.toInt)) {
      ct(v) += 1
    }
    val ctl = ct.toArray
    val prod = new SegTree(n)(new ModMul(MOD - 1))
    for (((k, v), i) <- ctl.zipWithIndex) {
      prod(i) = v + 1
    }
    var ans = 1L
    for (((k, v), i) <- ctl.zipWithIndex) {
      prod(i) = 1
      val s = (v * (v + 1) / 2) % (MOD - 1)
      val p = prod.query(0, n) * s % (MOD - 1)
      ans *= modPow(k, p, MOD)
      ans %= MOD
      prod(i) = v + 1
    }
    println(ans)
  }
  def modPow(x: Long, y: Long, mod: Int): Long = {
    @tailrec
    def rec(x: Long, y: Long, r: Long): Long = {
      if (y == 0) r
      else rec(x * x, y / 2, if (y % 2 == 1) r * x % mod else r)
    }
    return rec(x, y, 1)
  }
}
trait Monoid[T] {
  def zero: T
  def mul(a: T, b: T): T
}

class SegTree[T: ClassTag](n0: Int)(m: Monoid[T]) {

  val n = {
    var n1 = 1
    while (n1 < n0) n1 <<= 1
    n1
  }

  val t: Array[T] = Array.fill[T](2 * n - 1)(m.zero)

  def set(a: Array[T]): Unit = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (r - l == 1) {
        if (l < a.length) t(k) = a(l)
        else t(k) = m.zero
        return t(k)
      } else {
        t(k) = m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
        return t(k)
      }
    }
    rec(0, 0, n)
  }

  def update(k0: Int, v: T): Unit = {
    var k = k0 + (n - 1)
    t(k) = v
    while (k > 0) {
      k = (k - 1) / 2
      t(k) = m.mul(t(2 * k + 1), t(2 * k + 2))
    }
  }

  def get(k0: Int): T = {
    return t(k0 + (n - 1))
  }

  def query(a: Int, b: Int): T = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (b <= l || r <= a) {
        return m.zero
      } else if (a <= l && r <= b) {
        return t(k)
      } else {
        return m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
      }
    }
    return rec(0, 0, n)
  }
}

class ModMul(mod: Int) extends Monoid[Long] {
  def zero = 1L
  def mul(a: Long, b: Long) = a * b % mod
}

import scala.collection._
import scala.util.Random

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(m) = readInts(1)
  val ps = readBigs(m)
  //val ps = Array.fill(m){ BigInt(Random.nextInt(200000) + 2) }
  val MOD = 1000000007L

  var res = BigInt(1)
  for (p <- ps) {
    res = res * p.modPow(m, MOD) % MOD
  }

  println(res)
}

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(m) = readInts(1)
  val ps = readBigs(m)
  val MOD = 1000000007L

  val cnts = Array.fill(ps.max.toInt + 1){ 0 }
  var pow = ps.size.toLong

  for (p <- ps) {
    val pi = p.toInt
    cnts(pi) += 1
  }

  val muls = Array.fill(ps.max.toInt + 1){ 0L }
  for (i <- cnts.indices) {
    if (cnts(i) > 0) {
      muls(i) = (cnts(i) + 1L) * cnts(i) / 2
    }
  }

  var res = BigInt(1)
  for (p <- ps.distinct) {
    val pi = p.toInt
    res = res * p.modPow(muls(pi) * (pow - cnts(pi) + 1), MOD) % MOD
  }

  println(res)
}

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(m) = readInts(1)
  val ps = readInts(m)
  val psDist = ps.distinct
  val MOD = 1000000007L

  val cnts = Array.fill(ps.max.toInt + 1){ 0 }

  for (p <- ps) {
    val pi = p.toInt
    cnts(pi) += 1
  }

  val muls = Array.fill(ps.max.toInt + 1){ 0L }
  for (i <- cnts.indices) {
    if (cnts(i) > 0) {
      muls(i) = (cnts(i) + 1L) * cnts(i) / 2
    }
  }

  val powsLeft, powsRight = Array.fill(psDist.size){ 0L }
  var powL, powR = 1L

  for (i <- psDist.indices) {
    powsLeft(i) = powL
    powL = powL * (cnts(ps(i).toInt) + 1) % (MOD - 1)
  }

  for (i <- psDist.indices.reverse) {
    powsRight(i) = powR
    powR = powR * (cnts(ps(i).toInt) + 1) % (MOD - 1)
  }

  var res = BigInt(1)
  for (i <- psDist.indices) {
    val p = ps(i)
    res = res * BigInt(p).modPow(BigInt(muls(p)) * powsLeft(i) * powsRight(i), MOD) % MOD
  }

  println(res)
}


President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.

Print the only number — the amount of President's deputies.

object P6B {
    def main(args : Array[String]) {
        val Array(nS, mS, cS) = readLine split ' '
        val (n, m, c) = (nS.toInt, mS.toInt, cS.head)
        val a = Array.fill(n){readLine}
        val d = for {
            x <- 0 until n
            y <- 0 until m
            if (a(x)(y) == c)
            (xA, yA) <- Array((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1))
            if (0 <= xA && xA < n)
            if (0 <= yA && yA < m)
            z = a(xA)(yA)
            if (z != '.' && z != c)
        } yield z
        println(d.distinct.size)
    }
}

import java.util._
object B {
  def main(args: Array[String]) = {
    val scanner = new Scanner(System.in)
    val n = scanner.nextInt
    val m = scanner.nextInt
    val color = scanner.nextLine.trim
    val input = for {
      i <- 0 until n
    } yield scanner.nextLine.trim.split("").toVector
    val desks = for {
      i <- 0 until n
      j <- 0 until m
      if input(i)(j) == color
      x <- (i-1).max(0) to (i+1).min(n-1)
      y <- (j-1).max(0) to (j+1).min(m-1)
      if (x - i).abs != (y - j).abs
    } yield input(x)(y)
    println(desks.toSet.filter(c => c != "." && c != color).size)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m, rs) = in.next().split(' ')
  val r = rs.head
  val data = (1 to n.toInt).map(_ => in.next().toCharArray)
  val lineSet = data.foldLeft(Set.empty[Char]) {
    case (set, line) => line.sliding(2).foldLeft(set) {
      case (nSet, Array(x, y)) if x == r || y == r => nSet + y + x
      case (nSet, _) => nSet
    }
  }
  val res = (0 until m.toInt).foldLeft(lineSet) {
    case (set, column) => data.map(_(column)).toArray.sliding(2).foldLeft(set) {
      case (nSet, Array(x, y)) if x == r || y == r => nSet + y + x
      case (nSet, _) => nSet
    }
  } - r - '.'
  println(res.size)
}

import java.util.Scanner

object BPresidentRoom extends App {

  val scanner = new Scanner(System.in)

  val rows = scanner.nextInt()
  val cols = scanner.nextInt()
  val col = scanner.next()(0)

  val room = Array.ofDim[Char](rows, cols)

  for (y <- 0 until rows) yield {
    room(y) = scanner.next().toCharArray
  }

  val c = for (y <- 0 until rows;
               x <- 0 until cols;
               p = (y, x) if room(y)(x) == col) yield neighbours(p._1, p._2)

  val res: List[(Int, Int)] = c.flatten.toList

  println(res.map(i => room(i._1)(i._2)).filter(p => p != '.' && p != col).distinct.size)

  def neighbours(x: Int, y: Int): List[(Int, Int)] = {
    def n(a: Int, b: Int): List[(Int, Int)] = if (a < 0 || b < 0 || a >= rows || b >= cols) Nil else List((a, b))
    n(x - 1, y) ++ n(x + 1, y) ++ n(x, y - 1) ++ n(x, y + 1)
  }

}

object B6 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m, c) = {
      val tl = tokenizeLine
      Array(tl.nextToken.toInt, tl.nextToken.toInt, tl.nextToken.head)
    }
    val set = cu.Set.empty[Int]
    val room = Array.fill(n)(read.toCharArray)
    val delta = Array((0,1), (-1,0), (1,0), (0,-1))
    for(i <- 0 until n; j <- 0 until m if room(i)(j) == c) {
      for((dx, dy) <- delta) {
        if(i+dx >= 0 && i+dx < n && j+dy >= 0 && j+dy < m && !Array('.', c).contains(room(i+dx)(j+dy)))
          set.add(room(i+dx)(j+dy))
      }
    }
    println(set.size)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

import scala.collection.mutable

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF6B extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val n = nextInt
    val m = nextInt
    val c = nextString.charAt(0)
    val matrix = Array.ofDim[Char](n, m)

    var minX = -1
    var minY = -1
    var maxX = -1
    var maxY = -1

    (0 until n).foreach { i =>
      val s = nextString
      (0 until m).foreach { j =>
        matrix(i)(j) = s.charAt(j)

        if (matrix(i)(j) == c) {
          if (minX == -1 && minY == -1) {
            minX = i
            minY = j
          }

          maxX = i
          maxY = j
        }
      }
    }

    val topLeft = (minX, minY)
    val bottomLeft = (maxX, minY)
    val topRight = (minX, maxY)
    val bottomRight = (maxX, maxY)

    var count = 0

    // top
    if (minX > 0) {
      val set = mutable.HashSet[Char]()
      (minY to maxY).foreach { j =>
        val color = matrix(minX - 1)(j)
        if (color != '.')
          set += color
      }
      count += set.size
    }

    // left
    if (minY > 0) {
      val set = mutable.HashSet[Char]()
      (minX to maxX).foreach { i =>
        val color = matrix(i)(minY - 1)
        if (color != '.')
          set += color
      }

      count += set.size
    }

    // bottom
    if (maxX < n - 1) {
      val set = mutable.HashSet[Char]()
      (minY to maxY).foreach { j =>
        val color = matrix(maxX + 1)(j)
        if (color != '.')
          set += color
      }

      count += set.size
    }

    // right
    if (maxY < m - 1) {
      val set = mutable.HashSet[Char]()
      (minX to maxX).foreach { i =>
        val color = matrix(i)(maxY + 1)
        if (color != '.')
          set += color
      }
      count += set.size
    }

    out.println(count)
  }

  try {
    solve
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush
    out.close
  }
}

import java.util
import java.util._
import java.lang._
import java.io._

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

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

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def solve = {
    val n = nextInt
    val m = nextInt
    val presidentColor = next.toCharArray()(0)
    val cabinet = new Array[Array[Char]](n + 2)
    for (i <- 0 until n + 2) {
      cabinet(i) = new Array[Char](m + 2)
      Arrays.fill(cabinet(i), '.')
    }
    for (i <- 1 to n) {
      val str = next.toCharArray
      for (j <- 1 to m) {
        cabinet(i)(j) = str(j - 1)
      }
    }
    var ans = 0
    val colors = new util.HashSet[Char]()
    val dx = Array(-1, 1, 0, 0)
    val dy = Array(0, 0, -1, 1)
    for (i <- 1 to n) {
      for (j <- 1 to m) {
        if (cabinet(i)(j) == presidentColor) {
          for (k <- 0 until 4) {
            val testedColor = cabinet(i + dx(k))(j + dy(k))
            if (testedColor != presidentColor && testedColor != '.' && !colors.contains(testedColor)) {
              ans += 1
              colors.add(testedColor)
            }
          }
        }
      }
    }
    out.println(ans)

  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var in = readLine.split(" ")
    var Array(n, m) = Array(in(0).toInt, in(1).toInt);
    var c = in(2).head;
    var arr = Array.ofDim[Char](n, m);
    for (i <- 0 until n) {
      arr(i) = readLine.toCharArray();
    }
    //doSomething(array, i, j)
    var set = Set[Char]();
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (arr(i)(j) == c) {
          if (j < m - 1 && arr(i)(j + 1) != '.' && arr(i)(j + 1) != c) {
            set.add(arr(i)(j + 1));
          }
          if (j > 0 && arr(i)(j - 1) != '.' && arr(i)(j - 1) != c) {
            set.add(arr(i)(j - 1));
          }
          if (i < n - 1 && arr(i + 1)(j) != '.' && arr(i + 1)(j) != c) {
            set.add(arr(i + 1)(j));
          }
          if (i > 0 && arr(i - 1)(j) != '.' && arr(i - 1)(j) != c) {
            set.add(arr(i - 1)(j));
          }
        }
      }
    }
    println(set.size);
  }

}

object main extends App with fastIO {

  val dx = Array(-1, 0, 1, 0)
  val dy = Array(0, -1, 0, 1)

  val Array(n :Int, m :Int, p :String) = readLine split(" ") map(s => if (s(0).isDigit) s.toInt else s)
  val a = Array.fill(n)(readLine)

  def ok(x :Int, y :Int) = x >= 0 && y >= 0 && x < n && y < m

  var set = Set[Char]()
  for (i <- 0 until n; j <- 0 until m if a(i)(j) == p(0))
  for (k <- 0 until 4 if ok(i + dx(k), j + dy(k)))
    set += a(i + dx(k))(j + dy(k))

  println(set count(c => c != '.' && c != p(0)))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def nextInt :Int = { in.nextToken; in.nval.toInt }
  def nextLong :Long ={ in.nextToken; in.nval.toLong }
  def nextDouble :Double = { in.nextToken; in.nval.toDouble }
  def readLine = bf.readLine

  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)

  def flush = out.flush
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m, rs) = in.next().split(' ')
  val r = rs.head
  val data = (1 to n.toInt).map(_ => in.next().toCharArray)
  val lineSet = data.foldLeft(Set.empty[Char]) {
    case (set, line) => line.sliding(2).foldLeft(set) {
      case (nSet, Array(x, y)) if (x == r || y == r) && x != '.' && y != '.' => nSet + y + x
      case (nSet, _) => nSet
    }
  }
  val res = (0 until m.toInt).foldLeft(lineSet) {
    case (set, column) => data.map(_(column)).toArray.sliding(2).foldLeft(set) {
      case (nSet, Array(x, y)) if x == r || y == r && x != '.' && y != '.' => nSet + y + x
      case (nSet, _) => nSet
    }
  } - r
  println(res.size)
}

import java.util.Scanner

object BPresidentRoom extends App {

  val scanner = new Scanner(System.in)

  val rows = scanner.nextInt()
  val cols = scanner.nextInt()
  val col = scanner.next()(0)

  val room = Array.ofDim[Char](rows, cols)

  for (y <- 0 until rows) yield {
    room(y) = scanner.next().toCharArray
  }

  val c = for (y <- 0 until rows;
               x <- 0 until cols;
               p = (y, x) if room(y)(x) == col) yield neighbours(p._1, p._2)

  val res: List[(Int, Int)] = c.flatten.toList

  println(res.map(i => room(i._1)(i._2)).filter(p => p != '.' && p != col).distinct.size)

  def neighbours(x: Int, y: Int): List[(Int, Int)] = {
    def n(a: Int, b: Int): List[(Int, Int)] = if (a < 0 || b < 0 || a >= cols || b >= rows) Nil else List((a, b))
    n(x - 1, y) ++ n(x + 1, y) ++ n(x, y - 1) ++ n(x, y + 1)
  }

}

object main extends App with fastIO {

  val dx = Array(-1, 0, 1, 0)
  val dy = Array(0, -1, 0, 1)

  val Array(n :Int, m :Int, p :String) = readLine split(" ") map(s => if (s(0).isDigit) s.toInt else s)
  val a = Array.fill(n)(readLine)

  def ok(x :Int, y :Int) = x >= 0 && y >= 0 && x < n && y < m

  var set = Set[Char]()
  for (i <- 0 until n; j <- 0 until m if a(i)(j) == p(0))
  for (k <- 0 until 4 if ok(i + dx(k), j + dy(k)))
    set += a(i + dx(k))(j + dy(k))

  println(set.size)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def nextInt :Int = { in.nextToken; in.nval.toInt }
  def nextLong :Long ={ in.nextToken; in.nval.toLong }
  def nextDouble :Double = { in.nextToken; in.nval.toDouble }
  def readLine = bf.readLine

  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)

  def flush = out.flush
}


Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order. for (int i = 1; i < n; i = i + 1){   int j = i;    while (j > 0 && a[j] < a[j - 1])   {      swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1]      j = j - 1;   }}Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to n - 1. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.

The first line contains a single integer n (2 ≤ n ≤ 5000) — the length of the permutation. The second line contains n different integers from 0 to n - 1, inclusive — the actual permutation.

Print two integers: the minimum number of times the swap function is executed and the number of such pairs (i, j) that swapping the elements of the input permutation with indexes i and j leads to the minimum number of the executions.

NoteIn the first sample the appropriate pairs are (0, 3) and (0, 4). In the second sample the appropriate pairs are (0, 4), (1, 4), (2, 4) and (3, 4).

import scala.collection._

object C extends App {

  def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val n = readInt
  val as = readInts(n)

  var swaps = 0

  val dR = Array.fill(n, n)(0)

  for (i <- n - 2 to 0 by - 1) {
  	for (x <- 0 until as(i + 1)) dR(i)(x) = dR(i + 1)(x)
  	for (x <- as(i + 1) until n) dR(i)(x) = dR(i + 1)(x) + 1
  	swaps += dR(i)(as(i))
  }

  var minSwaps = swaps
  var count = 0

  for (i <- 0 until n) {
    val swapsii = dR(i)(as(i))
    for (j <- i + 1 until n) if (as(j) < as(i)) {
    	val swapsij = dR(j)(as(i))
    	val swapsji = dR(i)(as(j))
    	val swapsjj = dR(j)(as(j))
    	val swaps2 = swaps - 2 * (swapsii + swapsjj - swapsij - swapsji) - 1
    	if (swaps2 < minSwaps) {
    		minSwaps = swaps2
    		count = 1
    	} else if (swaps2 == minSwaps) count += 1
    }
  }

  println(minSwaps + " " + count)
}

import scala.collection._

object A extends App {

  def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val n = readInt

  println()
}


You are given $$$n$$$ blocks, each of them is of the form [color$$$_1$$$|value|color$$$_2$$$], where the block can also be flipped to get [color$$$_2$$$|value|color$$$_1$$$]. A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C.The value of the sequence is defined as the sum of the values of the blocks in this sequence.Find the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence.

The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of given blocks. Each of the following $$$n$$$ lines describes corresponding block and consists of $$$\mathrm{color}_{1,i}$$$, $$$\mathrm{value}_i$$$ and $$$\mathrm{color}_{2,i}$$$ ($$$1 \le \mathrm{color}_{1,i}, \mathrm{color}_{2,i} \le 4$$$, $$$1 \le \mathrm{value}_i \le 100\,000$$$).

Print exactly one integer — the maximum total value of the subset of blocks, which makes a valid sequence.

NoteIn the first example, it is possible to form a valid sequence from all blocks.One of the valid sequences is the following:[4|2|1] [1|32|2] [2|8|3] [3|16|3] [3|4|4] [4|1|2]The first block from the input ([2|1|4] $$$\to$$$ [4|1|2]) and second ([1|2|4] $$$\to$$$ [4|2|1]) are flipped.In the second example, the optimal answers can be formed from the first three blocks as in the following (the second or the third block from the input is flipped):[2|100000|1] [1|100000|1] [1|100000|2]In the third example, it is not possible to form a valid sequence of two or more blocks, so the answer is a sequence consisting only of the first block since it is the block with the largest value.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val color = Array(
      (1, 1),
      (2, 2),
      (3, 3),
      (4, 4),
      (1, 2),
      (1, 3),
      (1, 4),
      (2, 3),
      (2, 4),
      (3, 4)
    ) map (a => (a._1 - 1, a._2 - 1))

    val edge = {
      val map = color.zipWithIndex.toMap

      (c1: Int, c2: Int) => {
        map(min(c1, c2), max(c1, c2))
      }
    }

    val E = Array.fill[ArrayBuffer[Int]](10)(ArrayBuffer())

    rep(N) { _ =>
      val c1 = ni() - 1
      val v = ni()
      val c2 = ni() - 1
      E(edge(c1, c2)) += v
    }

    val sum = E map (_.sum)
    val ms = E map (a => if (a.isEmpty) -1 else a.min)

    def containsEdge(colors: Array[Int], e: Int) = {
      val (c1, c2) = color(e)
      (colors contains c1) && (colors contains c2)
    }

    var ans = 0
    rep(1 << 10) { bitSet =>
      var valid = true // このsetの辺の削除を行えるか
      val uf = new UnionFind(4)
      rep(10) { i =>
        val len = if ((bitSet & (1 << i)) > 0) E(i).length - 1 else E(i).length
        if (len < 0) valid = false
        else if (len > 0){
          val (c1, c2) = color(i)
          uf.unite(c1, c2)
        }
      }
      if (valid) {
        disjointSets(uf).filter(_.nonEmpty) foreach { set =>
          val deg = Array.ofDim[Int](4)
          var S = 0
          rep(10) { i =>
            if (containsEdge(set, i)) {
              val (c1, c2) = color(i)
              val remove = (bitSet & (1 << i)) > 0
              val len = if (remove) E(i).length - 1 else E(i).length
              deg(c1) += len
              deg(c2) += len
              S += sum(i) - (if (remove) ms(i) else 0)
            }
          }
          val odds = deg count (_ % 2 == 1)
          if (odds == 0 || odds == 2) ans = max(ans, S)
        }
      }
    }

    out.println(ans)
  }

  def disjointSets(uf: UnionFind): Array[Array[Int]] = {
    val N = uf.n
    val cnt = Array.ofDim[Int](N)
    val disjoints = Array.ofDim[Array[Int]](N)
    rep(N) { i => cnt(uf.find(i)) += 1 }
    rep(N) { i => disjoints(i) = Array.ofDim(cnt(uf.find(i))) }
    rep(N) { i =>
      val id = uf.find(i)
      disjoints(id)(cnt(id) - 1) = i
      cnt(id) -= 1
    }
    disjoints
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val color = Array(
      (1, 1),
      (2, 2),
      (3, 3),
      (4, 4),
      (1, 2),
      (1, 3),
      (1, 4),
      (2, 3),
      (2, 4),
      (3, 4)
    ) map (a => (a._1 - 1, a._2 - 1))

    val edge = {
      val map = color.zipWithIndex.toMap

      (c1: Int, c2: Int) => {
        map(min(c1, c2), max(c1, c2))
      }
    }

    val E = Array.fill[ArrayBuffer[Int]](10)(ArrayBuffer())
    val deg = Array.ofDim[Int](4)
    val uf = new UnionFind(4)

    rep(N) { _ =>
      val c1 = ni() - 1
      val v = ni()
      val c2 = ni() - 1
      uf.unite(c1, c2)
      E(edge(c1, c2)) += v
      deg(c1) += 1
      deg(c2) += 1
    }

    val joints = Array.fill[mutable.Set[Int]](4)(mutable.Set())
    rep(4) { i =>
      joints(uf.find(i)) += i
    }

    val ms = E map (a => if (a.isEmpty) -1 else a.min)

    def containsEdge(colors: mutable.Set[Int], e: Int) = {
      val (c1, c2) = color(e)
      (colors contains c1) && (colors contains c2)
    }

    var ans = 0
    joints.filter(_.nonEmpty) foreach { colors =>
      val S = E.zipWithIndex
        .filter(a => containsEdge(colors, a._2))
        .map(_._1.sum).sum

      rep(1 << 10) { set =>
        val d = deg.clone()
        var valid = true // このsetの辺の削除を行えるか
        var subtracts = 0
        rep(10) { i =>
          if (((set >>> i) & 1) > 0) {
            if (ms(i) == -1 || !containsEdge(colors, i)) valid = false
            else {
              val (c1, c2) = color(i)
              d(c1) -= 1
              d(c2) -= 1
              subtracts += ms(i)
            }
          }
        }
        val odds = d count (_ % 2 == 1)
        if (valid && odds == 0 || odds == 2) ans = max(ans, S - subtracts)
      }
    }

    out.println(ans)
  }

  class UnionFind(n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val color = Array(
      (1, 1),
      (2, 2),
      (3, 3),
      (4, 4),
      (1, 2),
      (1, 3),
      (1, 4),
      (2, 3),
      (2, 4),
      (3, 4)
    ) map (a => (a._1 - 1, a._2 - 1))

    val edge = {
      val map = color.zipWithIndex.toMap

      (c1: Int, c2: Int) => {
        map(min(c1, c2), max(c1, c2))
      }
    }

    val E = Array.fill[ArrayBuffer[Int]](10)(ArrayBuffer())
    val deg = Array.ofDim[Int](4)
    val uf = new UnionFind(4)

    rep(N) { _ =>
      val c1 = ni() - 1
      val v = ni()
      val c2 = ni() - 1
      uf.unite(c1, c2)
      E(edge(c1, c2)) += v
      deg(c1) += 1
      deg(c2) += 1
    }

    val joints = Array.fill[mutable.Set[Int]](4)(mutable.Set())
    rep(4) { i =>
      joints(uf.find(i)) += i
    }

    val ms = E map (a => if (a.isEmpty) -1 else a.min)

    def containsEdge(colors: mutable.Set[Int], e: Int) = {
      val (c1, c2) = color(e)
      (colors contains c1) && (colors contains c2)
    }

    var ans = 0
    joints.filter(_.nonEmpty) foreach { colors =>
      val S = E.zipWithIndex
        .filter(a => containsEdge(colors, a._2))
        .map(_._1.sum).sum

      rep(1 << 10) { set =>
        val d = Array.ofDim[Int](4)
        rep(4)(i => if (containsEdge(colors, i)) d(i) = deg(i)) // colorsに含まれているものだけコピーする

        var valid = true // このsetの辺の削除を行えるか
        var subtracts = 0
        rep(10) { i =>
          if (((set >>> i) & 1) > 0) {
            if (ms(i) == -1 || !containsEdge(colors, i)) valid = false
            else {
              val (c1, c2) = color(i)
              d(c1) -= 1
              d(c2) -= 1
              subtracts += ms(i)
            }
          }
        }
        val odds = d count (_ % 2 == 1)
        if (valid && odds == 0 || odds == 2) ans = max(ans, S - subtracts)
      }
    }

    out.println(ans)
  }

  class UnionFind(n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}


One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day.Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume that the string contains the letters of some users of the R1 mail. Recovering letters is a tedious mostly manual work. So before you start this process, it was decided to estimate the difficulty of recovering. Namely, we need to calculate the number of different substrings of the saved string that form correct e-mail addresses.We assume that valid addresses are only the e-mail addresses which meet the following criteria:  the address should begin with a non-empty sequence of letters, numbers, characters '_', starting with a letter;  then must go character '@';  then must go a non-empty sequence of letters or numbers;  then must go character '.';  the address must end with a non-empty sequence of letters. You got lucky again and the job was entrusted to you! Please note that the substring is several consecutive characters in a string. Two substrings, one consisting of the characters of the string with numbers l1, l1 + 1, l1 + 2, ..., r1 and the other one consisting of the characters of the string with numbers l2, l2 + 1, l2 + 2, ..., r2, are considered distinct if l1 ≠ l2 or r1 ≠ r2.

The first and the only line contains the sequence of characters s1s2... sn (1 ≤ n ≤ 106) — the saved string. It is guaranteed that the given string contains only small English letters, digits and characters '.', '_', '@'.

Print in a single line the number of substrings that are valid e-mail addresses.

NoteIn the first test case all the substrings that are correct e-mail addresses begin from one of the letters of the word agapov and end in one of the letters of the word com.In the second test case note that the e-mail x@x.x is considered twice in the answer. Note that in this example the e-mail entries overlap inside the string.

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import Character._

object E extends App {

  val s = readLine.toCharArray
  var res = 0L

  var start = 0
  while (start < s.length) {
    val c = s(start)
    if (isLetter(c)) {
      var eta = start + 1
      var let = 1L
      while (eta < s.length && (isLetterOrDigit(s(eta)) || s(eta) == '_')) {
        if (isLetter(s(eta))) let += 1
        eta += 1
      }
      if (eta < s.length && s(eta) == '@') {
        var dot = eta + 1
        while (dot < s.length && isLetterOrDigit(s(dot))) dot += 1
        if (dot > eta + 1 && dot < s.length && s(dot) == '.') {
          var end = dot + 1
          while (end < s.length && isLetter(s(end))) end += 1
          res += let * (end - dot - 1)
          start = dot
        } else start = eta
      } else start = eta
    }
    start += 1
  }

  println(res)
}


You are given an array of integers $$$a_1,a_2,\ldots,a_n$$$. Find the maximum possible value of $$$a_ia_ja_ka_la_t$$$ among all five indices $$$(i, j, k, l, t)$$$ ($$$i<j<k<l<t$$$).

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t\le 2 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$5\le n\le 10^5$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$-3\times 10^3\le a_i\le 3\times 10^3$$$) — given array. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print one integer — the answer to the problem.

NoteIn the first test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\cdot (-2) \cdot (-3)\cdot (-4)\cdot (-5)=-120$$$.In the second test case, choosing $$$a_1,a_2,a_3,a_5,a_6$$$ is a best choice: $$$(-1)\cdot (-2) \cdot (-3)\cdot 2\cdot (-1)=12$$$.In the third test case, choosing $$$a_1,a_2,a_3,a_4,a_5$$$ is a best choice: $$$(-1)\cdot 0\cdot 0\cdot 0\cdot (-1)=0$$$.In the fourth test case, choosing $$$a_1,a_2,a_3,a_4,a_6$$$ is a best choice: $$$(-9)\cdot (-7) \cdot (-5)\cdot (-3)\cdot 1=945$$$.

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt).sorted

    val ans = (0 until 5)
      .foldLeft(List.empty[Int])((is, i) => i :: (n - i - 1) :: is)
      .distinct
      .combinations(5)
      .foldLeft(Long.MinValue)(_ max _.foldLeft(1L)(_ * an(_)))

    println(ans)

  }
}

import scala.collection.mutable.ArrayBuffer

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m    = in.nextInt()
      val data = in.nextLineInt(m)

      var (largest1, largest2, largest3, largest4, largest5) =
        (Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue)
      var (smallest1, smallest2, smallest3, smallest4) = (Int.MaxValue, Int.MaxValue, Int.MaxValue, Int.MaxValue)

      data.foreach(d => {
        if (d <= smallest1) {
          smallest4 = smallest3
          smallest3 = smallest2
          smallest2 = smallest1
          smallest1 = d
        } else if (d <= smallest2) {
          smallest4 = smallest3
          smallest3 = smallest2
          smallest2 = d
        } else if (d <= smallest3) {
          smallest4 = smallest3
          smallest3 = d
        } else if (d <= smallest4) {
          smallest4 = d
        }
        if (d >= largest1) {
          largest5 = largest4
          largest4 = largest3
          largest3 = largest2
          largest2 = largest1
          largest1 = d
        } else if (d >= largest2) {
          largest5 = largest4
          largest4 = largest3
          largest3 = largest2
          largest2 = d
        } else if (d >= largest3) {
          largest5 = largest4
          largest4 = largest3
          largest3 = d
        } else if (d >= largest4) {
          largest5 = largest4
          largest4 = d
        } else if (d >= largest5) {
          largest5 = d
        }
      })
      val r1 = smallest1.toLong * smallest2 * smallest3 * smallest4 * largest1
      val r2 = smallest1.toLong * smallest2 * largest1 * largest2 * largest3
      val r3 = largest1.toLong * largest2 * largest3 * largest4 * largest5

      /*println((largest1, largest2, largest3, largest4, largest5))
      println((smallest1, smallest2, smallest3, smallest4))
      println(r1, r2, r3)*/

      val r = math.max(math.max(r1, r2), r3)
      println(r)
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toLong).sorted

    // format: off
    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList
    // format: on

    val ans = xs.indices.foldLeft(Long.MinValue) {
      case (ans, i) if ys.length >= 1 - i =>
        val x = xs.take(i + 1).product
        val y = ys.takeRight(1 - i).product
        val z = an(n + 2 * i - 3)
        ans max (x * y * z)
      case (ans, _) => ans
    }

    println(ans)
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  // format: off
  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toLong).sorted

    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val zs =
      if (xs.length == 2 && ys.length == 1) xs
      else (xs ++ ys).sorted(Ordering.Long.reverse).take(2)

    val ans = an(n - 2 * zs.diff(xs).length - 1) * zs.product

    println(ans)
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toLong).sorted

    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
  case Array(a, b) => a * b
    }.toList

    val zs = (xs ++ ys).sorted(Ordering.Long.reverse).take(2)

    val ans = an(n - 2 * zs.diff(xs).length - 1) * zs.product

    println(ans)
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toLong).sorted

    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

val zs =
  if (ys.length == 1)
    xs.sorted(Ordering.Long.reverse)
  else
    (xs ++ ys).sorted(Ordering.Long.reverse).take(2)

    val ans = an(n - 2 * zs.diff(xs).length - 1) * zs.product

    println(ans)
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toLong).sorted

    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
  case Array(a, b) => a * b
    }.toList

    val zs = (xs ++ ys).sorted(Ordering.Long.reverse).take(2)

    val ans = an(n - zs.diff(xs).length - 1) * zs.product

    println(ans)
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt).sorted

    val ans = (0 until 4)
      .foldLeft(List.empty[Int])((is, i) => i :: (n - i - 1) :: is)
      .distinct
      .combinations(5)
      .map(_.foldLeft(1L)((p, i) => p * an(i)))
      .toList
      .sorted(Ordering.Long.reverse)
      .head

    println(ans)

  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toLong).sorted

    // format: off
    val xs = an.take(4).filter(_ < 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList

    val ys = an.takeRight(4).filter(_ >= 0).sliding(2, 2).collect {
      case Array(a, b) => a * b
    }.toList
    // format: on

    val ans = (0 to xs.length).foldLeft(Long.MinValue) {
      case (product, count) =>
        val x = xs.take(2 - (2 - count).min(ys.length)).product
        val y = ys.takeRight(2 - count).product
        val z = an(n - 2 * (2 - count).min(ys.length) - 1)
        product max (x * y * z)
    }

    println(ans)
  }
}

import scala.collection.mutable.ArrayBuffer

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m    = in.nextInt()
      val data = in.nextLineInt(m)

      var (largest1, largest2, largest3, largest4, largest5) =
        (Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue, Int.MinValue)
      var (smallest1, smallest2, smallest3, smallest4) = (Int.MaxValue, Int.MaxValue, Int.MaxValue, Int.MaxValue)

      data.foreach(d => {
        if (d <= smallest1) {
          smallest4 = smallest3
          smallest3 = smallest2
          smallest2 = smallest1
          smallest1 = d
        } else if (d <= smallest2) {
          smallest4 = smallest3
          smallest3 = smallest2
          smallest2 = d
        } else if (d <= smallest3) {
          smallest4 = smallest3
          smallest3 = d
        } else if (d <= smallest4) {
          smallest4 = d
        }
        if (d >= largest1) {
          largest5 = largest4
          largest4 = largest3
          largest3 = largest2
          largest2 = largest1
          largest1 = d
        } else if (d >= largest2) {
          largest5 = largest4
          largest4 = largest3
          largest3 = largest2
          largest2 = d
        } else if (d >= largest3) {
          largest5 = largest4
          largest4 = largest3
          largest3 = d
        } else if (d >= largest4) {
          largest5 = largest4
          largest4 = d
        } else if (d >= largest5) {
          largest5 = d
        }
      })

      val r1 = smallest1 * smallest2 * smallest3 * smallest4 * largest1
      val r2 = smallest1 * smallest2 * largest1 * largest2 * largest3
      val r3 = largest1 * largest2 * largest3 * largest4 * largest5

      /*      println((largest1, largest2, largest3, largest4, largest5))
      println((smallest1, smallest2, smallest3, smallest4))
      println(r1, r2, r3)*/

      val r = math.max(math.max(r1, r2), r3)
      println(r)
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}


You are given a set Y of n distinct positive integers y1, y2, ..., yn.Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X:  Take any integer xi and multiply it by two, i.e. replace xi with 2·xi.  Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. Note that integers in X are not required to be distinct after each operation.Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal.Note, that any set of integers (or its permutation) generates itself.You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible.

The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y. The second line contains n integers y1, ..., yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct.

Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them.

import scala.collection.mutable

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val ys = readInts(n)

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  val xs = Array.ofDim[Int](n)

  def can(limit: Long): Boolean = {
    var i = 0
    val isUsed = mutable.HashSet.empty[Int]
    var ok = true
    while (i < n) {
      var y = ys(i)
      //println(limit, y)
      while (y > 1 && (y > limit || isUsed(y))) {
        //y = if ((y & 1) == 0) y / 2 else (y - 1) / 2
        y >>= 1
      }
      if (isUsed(y)) {
        ok = false
        i = n
      } else {
        xs(i) = y
        isUsed += y
      }
      i += 1
    }
    ok
  }

  val max = binSearch(n, ys.max)
  can(max)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(xs.mkString(" "))

  Console.flush
}

object CF{
	import scala.io.StdIn.{readLine, readInt}
	import scala.collection.mutable.{Set, PriorityQueue}

	def main(args: Array[String]){
		val n:Int = readInt()
		val Y: List[Int] = readLine().split(" ").map(_.toInt).toList

		val s: Set[Int] = Set[Int](Y:_*)
		val pq: PriorityQueue[Int] = PriorityQueue[Int](Y:_*)

		val fpq = finalpq(pq, s)

		fpq.foreach(println(_))
	}

	def transform(s:Set[Int], y:Int): Int = y match{
		case 0 => 0
		case _ if s.contains(y) => transform(s, y/2)
		case _ => {
			s += y
			y
		}
	}

	def finalpq(pq:PriorityQueue[Int], s:Set[Int]): PriorityQueue[Int] = {
		val head = pq.head
		val at = transform(s, head)
		at match{
			case 0 => pq
			case _ => {
				pq.dequeue()
				pq += at
				finalpq(pq, s)
			}
		}
	}

}

object CF{
	import scala.io.StdIn.{readLine, readInt}
	import scala.collection.mutable.{Set, PriorityQueue}

	def main(args: Array[String]){
		val n:Int = readInt()
		val Y: List[Int] = readLine().split(" ").map(_.toInt).toList

		val s: Set[Int] = Set[Int](Y:_*)
		var pq: PriorityQueue[Int] = PriorityQueue[Int](Y:_*)

		var at = transform(s, pq.head)

		finalpq(pq, s)

		pq.foreach(println(_))
	}

	def transform(s:Set[Int], y:Int): Int = y match{
		case 0 => 0
		case _ if s.contains(y) => transform(s, y/2)
		case _ => {
			s += y
			y
		}
	}

	def finalpq(pq:PriorityQueue[Int], s:Set[Int]): PriorityQueue[Int] = {
		val head = pq.head
		val at = transform(s, head)
		at match{
			case 0 => pq
			case _ => {
				pq.dequeue()
				pq += at
				finalpq(pq, s)
			}
		}
	}

}


You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .

import java.util.Scanner
import Array._

object Codeforces extends App {
  val in = new Scanner(System.in)
  val na = in.nextInt()
  val nb = in.nextInt()
  val k = in.nextInt()
  val m = in.nextInt()
  var a = ofDim[Int](na)
  var b = ofDim[Int](nb)
  for (i <- 0 until na) {
    a(i) = in.nextInt()
  }
  for (i <- 0 until nb) {
    b(i) = in.nextInt()
  }
  if (a(k - 1) < b(nb - m)) {
    println("YES")
  } else {
    println("NO")
  }
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  in.next()
  val Array(k, m) = in.next().split(" ").map(_.toInt)
  val a = in.next().split(" ").map(_.toInt).sorted.take(k).max
  val b = in.next().split(" ").map(_.toInt).sorted.reverse.take(m).min
  if (a < b) println("YES")
  else println("NO")
}

object A572 {
  @inline def read = scala.io.StdIn.readLine

  @inline def tokenizeLine = new java.util.StringTokenizer(read)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(na, nb) = readInts(2)
    val Array(k, m) = readInts(2)

    val a = readInts(na)
    val b = readInts(nb)

    if(a(k-1) < b(nb-m)) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _572A extends CodeForcesApp[String]({scanner => import scanner._
  val (na, nb, k, m) = (nextInt, nextInt, nextInt, nextInt)
  val (a, b) = (IndexedSeq.fill(na)(nextInt), IndexedSeq.fill(nb)(nextInt))
  val maxA = a(k-1)
  val remB = b.dropWhile(_ <= maxA)
  if (remB.size >= m) "YES" else "NO"
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object A extends App {
  val Array(na, nb) = readLine().split(" ").map(_.toInt)
  val Array(k, m) = readLine().split(" ").map(_.toInt)
  val A = readLine().split(" ").map(_.toInt)
  val B = readLine().split(" ").map(_.toInt)

  if (k > A.length || m > B.length || A.take(k).last >= B.takeRight(m).head) println("NO") else println("YES")
}

import scala.util.control.Breaks._

object GukiZ {
  def main(args: Array[String]) {
    val firstLine = scala.io.StdIn.readLine()
    val arraysLength = firstLine.split(" ") map (_.toInt)
    val aLength: Int = arraysLength(0)
    val bLength: Int = arraysLength(1)
    val secondLine = scala.io.StdIn.readLine()
    val limits = secondLine.split(" ") map (_.toInt)
    val k: Int = limits(0)
    val m: Int = limits(1)
    val thirdLine = scala.io.StdIn.readLine()
    val arrayA = thirdLine.split(" ") map (_.toInt)
    val fourthLine = scala.io.StdIn.readLine()
    val arrayB = fourthLine.split(" ") map (_.toInt)
    var mayor = false

    for (i <- 0 until k) {
      breakable{for(j <- (bLength-m) until bLength){
        if (arrayA(i) >= arrayB(j))
        mayor = true
        break
      }}

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

  }

}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object Vraag1 {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def main(args: Array[String]) {
     val _ = readInts()
     val km = readInts()
     val a = readInts
     val b = readInts
     val k = km(0)
     val m = km(1)
     if (a(k-1) < b.reverse(m-1)) println("YES") else println("NO")

   }

}

object A572 {
  @inline def read = scala.io.StdIn.readLine

  @inline def tokenizeLine = new java.util.StringTokenizer(read)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(na, nb) = readInts(2)
    val Array(k, m) = readInts(2)

    val a = readInts(na)
    val b = readInts(nb)

    if(a(m-1) < b(nb-m)) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

import scala.io.StdIn._

object A extends App {
//  val Array(na, nb) = readLine().split(" ").map(_.toInt)
//  val Array(k, m) = readLine().split(" ").map(_.toInt)
//  val A = readLine().split(" ").map(_.toInt)
//  val B = readLine().split(" ").map(_.toInt)
  val k = 5
  val m = 2
  val A = Array(1, 1, 1, 1, 1)
  val B = Array(2, 2)

  if (k > A.length || m > B.length || A.take(k).last >= B.takeRight(m).head) println("NO") else println("YES")
}

object GukiZ {
  def main(args: Array[String]) {
    val firstLine = scala.io.StdIn.readLine()
    val arraysLength = firstLine.split(" ") map (_.toInt)
    val aLength: Int = arraysLength(0)
    val bLength: Int = arraysLength(1)
    val secondLine = scala.io.StdIn.readLine()
    val limits = secondLine.split(" ") map (_.toInt)
    val k: Int = limits(0)
    val m: Int = limits(1)
    val thirdLine = scala.io.StdIn.readLine()
    val arrayA = thirdLine.split(" ") map (_.toInt)
    val fourthLine = scala.io.StdIn.readLine()
    val arrayB = fourthLine.split(" ") map (_.toInt)
    var mayor = false

    for (i <- 0 until k) {
      for(j <- 0 until m){
        if (arrayA(i) >= arrayB(j))
        mayor = true
      }

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

  }

}

object GukiZ {
  def main(args:Array[String]){
    val firstLine = scala.io.StdIn.readLine()
    val arraysLength = firstLine.split(" ") map (_.toInt)
    val aLength:Int = arraysLength(0)
    val bLength:Int = arraysLength(1)
    val secondLine = scala.io.StdIn.readLine()
    val limits = secondLine.split(" ") map (_.toInt)
    val k:Int = limits(0)
    val m:Int = limits(1)
    val thirdLine = scala.io.StdIn.readLine()
    val arrayA = thirdLine.split(" ") map (_.toInt)
    val fourthLine = scala.io.StdIn.readLine()
    val arrayB = fourthLine.split(" ") map (_.toInt)

    if(arrayA(k-1) >= arrayB(0))
      println("NO")
    else println("YES")
  }

}

object GukiZ {
  def main(args: Array[String]) {
    val firstLine = scala.io.StdIn.readLine()
    val arraysLength = firstLine.split(" ") map (_.toInt)
    val aLength: Int = arraysLength(0)
    val bLength: Int = arraysLength(1)
    val secondLine = scala.io.StdIn.readLine()
    val limits = secondLine.split(" ") map (_.toInt)
    val k: Int = limits(0)
    val m: Int = limits(1)
    val thirdLine = scala.io.StdIn.readLine()
    val arrayA = thirdLine.split(" ") map (_.toInt)
    val fourthLine = scala.io.StdIn.readLine()
    val arrayB = fourthLine.split(" ") map (_.toInt)
    var mayor = false
    val startFor = aLength - (k)

    for (i <- 0 until k) {
      for(j <- 0 until m){
        if (arrayA(i) >= arrayB(j))
        mayor = true
      }

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

  }

}


Luke likes to eat. There are $$$n$$$ piles of food aligned in a straight line in front of him. The $$$i$$$-th pile contains $$$a_i$$$ units of food. Luke will walk from the $$$1$$$-st pile towards the $$$n$$$-th pile, and he wants to eat every pile of food without walking back. When Luke reaches the $$$i$$$-th pile, he can eat that pile if and only if $$$|v - a_i| \leq x$$$, where $$$x$$$ is a fixed integer, and $$$v$$$ is Luke's food affinity.Before Luke starts to walk, he can set $$$v$$$ to any integer. Also, for each $$$i$$$ ($$$1 \leq i \leq n$$$), Luke can change his food affinity to any integer before he eats the $$$i$$$-th pile.Find the minimum number of changes needed to eat every pile of food.Note that the initial choice for $$$v$$$ is not considered as a change.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of test cases follows. For each test case, the first line contains two integers, $$$n, x$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq x \leq 10^9$$$) — the number of piles, and the maximum difference between the size of a pile and Luke's food affinity, such that Luke can eat the pile. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots , a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output an integer on a separate line, which is the minimum number of changes needed.

NoteIn the first test case, Luke can set $$$v$$$ to $$$5$$$ before he starts to walk. And he can walk straight to eat every piles of food without changing $$$v$$$.In the second test case, Luke can set $$$v$$$ to $$$3$$$ before he starts to walk. And he could change $$$v$$$ to $$$10$$$ before he eats the second pile. After that, he can walk straight to eat remaining food without changing $$$v$$$.In the fourth test case, Luke can set $$$v$$$ to $$$3$$$ before he starts to walk. And he could change $$$v$$$ to $$$8$$$ before he eats the sixth pile. After that, he can walk straight to eat remaining food without changing $$$v$$$.In the fifth test case, Luke can set $$$v$$$ to $$$4$$$ before he starts to walk. And he could change $$$v$$$ to $$$6$$$ before he eats the fourth pile. Then he could change $$$v$$$ to $$$12$$$ before he eats the seventh pile. After that, he can walk straight to eat remaining food without changing $$$v$$$.

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      var c: Long = 0
      tokenizer = new StringTokenizer(input.readLine())
      val l1 = tokenizer.nextToken().toInt
      val l2 = tokenizer.nextToken().toInt * 2
      tokenizer = new StringTokenizer(input.readLine())
      val a0 = tokenizer.nextToken().toInt
      var l = a0
      var m = a0
      for (i <- 1 until l1) {
        val a = tokenizer.nextToken().toInt
        l = min(a,l)
        m = max(a,m)
        if (m-l > l2) {
          l = a
          m = a
          c+=1
        }
      }
      println(c)
    }
  }
}


Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ — length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even)  — length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$)  — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.

For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) — number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.

NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.

//package codeforces.contests._1407

object Ahahahahahahahaha {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val n = io.StdIn.readInt()
      val seq = io.StdIn.readLine.split(" ").map(_.toInt)

      val ones = seq.count(_ == 1)

      if (ones <= n / 2) {
        println(s"${n / 2}\n${(1 to n/2).map(_ => 0).mkString(" ")}")
      } else {
        val req = if ((n / 2) % 2 == 0) n / 2 else n / 2 + 1
        println(s"$req\n${(1 to req).map(_ => 1).mkString(" ")}")
      }
    }
  }
}

/**
 * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
 */

import scala.io.StdIn._

object Main {
  def f(ayes: Array[Int]): Array[Int] = {
    val n = ayes.length
    val cnt1 = ayes.count(x => x == 1)
    val cnt0 = n - cnt1

    val res = if (cnt1 <= n / 2)
      for (_ <- 0 until cnt0) yield 0
    else
      for (_ <- 0 until (cnt1 - cnt1 % 2)) yield 1

     res.toArray
  }

  def main(args: Array[String]): Unit = {
    // Write your solution here
    val t = readInt

    for (_ <- 0 until t) {
      val _ = readInt
      val ayes = readLine.split(" ").map(_.toInt)
      val result = f(ayes)
      println(result.length)
      println(result.mkString(" "))
    }
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val m  = n / 2
    val an = readLine()

    val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))

    if (zeros >= m) {
      println(m)
      println("0 " * m)
    } else if (m % 2 == 0) {
      println(m)
      println("1 " * m)
    } else {
      println(m + 1)
      println("1 " * (m + 1))
    }
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val m  = n / 2
    val an = readLine()

    val zeros = an.count(_ == '0')

    if (zeros >= m) {
      println(m)
      println("0 " * m)
    } else {
      // format: off
      println(m + m % 2)
      println("1 " * (m + m % 2))
    }
  }
}

//package codeforces.contests._1407

object Ahahahahahahahaha {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val n = io.StdIn.readInt()
      val seq = io.StdIn.readLine.split(" ").map(_.toInt)

      val ones = seq.count(_ == 1)

      if (ones <= n / 2) {
        println(s"${n / 2}\n${(1 to n/2).map(_ => 0).mkString(" ")}")
      } else {
        val req = if ((n / 2) % 2 == 0) n / 2 else n / 2 + 1
        println(s"${n / 2}\n${(1 to req).map(_ => 1).mkString(" ")}")
      }
    }
  }
}

/**
* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
*/

import scala.io.StdIn._

object Main {
   def isAha(ayes: Array[Int]): Boolean = {
      val n = ayes.length

      if (n == 1) {
         ayes(0) == 0
      } else {
         val flippedOthers = for ((a, i) <- ayes.zipWithIndex) yield
            if (i % 2 == 0) a else -a
         flippedOthers.sum == 0
      }
   }

   def f(n: Int, ayes: Array[Int]): Array[Int] = {
      if (n == 2) {
         if (isAha(ayes.slice(0, 1))) ayes.slice(0, 1)
         else ayes.slice(1, 2)
      } else if (isAha(ayes)){
         ayes
      } else {
         ayes.slice(2, n)
      }
   }

   def main(args: Array[String]): Unit = {
      // Write your solution here
      val t = readInt

      for (_ <- 0 until t) {
         val n = readInt
         val ayes = readLine.split(" ").map(_.toInt)
         val result = f(n, ayes)
         println(result.length)
         println(result.mkString(" "))
      }
   }
}

/**
 * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
 */

import scala.io.StdIn._

object Main {
  def f(ayes: Array[Int]): Array[Int] = {
    val n = ayes.length
    val cnt1 = ayes.count(x => x == 1)
    val cnt0 = n - cnt1

    val res = if (cnt1 <= n / 2)
      for (_ <- 0 until cnt0) yield 0
    else
      for (_ <- 0 until (cnt1 - cnt1 % 2)) yield 0

     res.toArray
  }

  def main(args: Array[String]): Unit = {
    // Write your solution here
    val t = readInt

    for (_ <- 0 until t) {
      val _ = readInt
      val ayes = readLine.split(" ").map(_.toInt)
      val result = f(ayes)
      println(result.length)
      println(result.mkString(" "))
    }
  }
}

/**
* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
*/

import scala.io.StdIn._

object Main {
   def f(n: Int, ayes: Array[Int]): Array[Int] = {
      Array(0)
   }

   def main(args: Array[String]): Unit = {
      // Write your solution here
      val t = readInt

      for (_ <- 0 until t) {
         val n = readInt
         val ayes = readLine.split(" ").map(_.toInt)
         val result = f(n, ayes)
         println(result.length)
         println(result.mkString(" "))
      }
   }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine()

    val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))

    if (n == 2) {
      if (zeros > 0) println("1\n0")
      else println("2\n1 1")
    } else {
      if (ones > zeros) println(s"${n / 2}\n${"1 " * (n / 2)}")
      else println(s"${n / 2}\n${"0 " * (n / 2)}")
    }
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val (ones, zeros) = (an.count(_ == 1), an.count(_ == 0))

    val base = if (ones > zeros) 1 else 0
    val ans = an
      .foldLeft((List.empty[Int], n / 2)) {
        case ((bs, 0), a) => (a :: bs, 0)
        case ((bs, r), a) => if (a == base) (bs, r - 1) else (a :: bs, r)
      }
      ._1
      .reverse

    println(n / 2)
    println(ans.mkString(" "))
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine()

    val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))

    val ans = (if (ones > zeros) "1 " else "0 ") * (n / 2)

    println(n / 2)
    println(ans.trim)
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine()

    val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))

    val ans = (if (ones > zeros) "1 " else "0 ") * (n / 2)

    println(n / 2)
    println(ans)
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val (ones, zeros) = (an.count(_ == 1), an.count(_ == 0))

    val ans =
      if (ones > zeros) List.fill(n / 2)(1)
      else List.fill(n / 2)(0)

    println(n / 2)
    println(ans.mkString(" "))
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val m  = n / 2
    val an = readLine()

    val (ones, zeros) = (an.count(_ == '1'), an.count(_ == '0'))

    if (zeros > m) {
      println(m)
      println("0 " * m)
    } else if (m % 2 == 0) {
      println(m)
      println("1 " * m)
    } else {
      println(m + 1)
      println("1 " * (m + 1))
    }
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val (ones, zeros) = (an.count(_ == 1), an.count(_ == 0))

    val ans =
      if (ones == n) List.fill(n)(1)
      else if (ones > zeros) List.fill(n / 2)(1)
      else List.fill(n / 2)(0)

    println(n / 2)
    println(ans.mkString(" "))
  }
}


You have an array $$$a$$$ of length $$$n$$$. For every positive integer $$$x$$$ you are going to perform the following operation during the $$$x$$$-th second:  Select some distinct indices $$$i_{1}, i_{2}, \ldots, i_{k}$$$ which are between $$$1$$$ and $$$n$$$ inclusive, and add $$$2^{x-1}$$$ to each corresponding position of $$$a$$$. Formally, $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ for $$$j = 1, 2, \ldots, k$$$. Note that you are allowed to not select any indices at all. You have to make $$$a$$$ nondecreasing as fast as possible. Find the smallest number $$$T$$$ such that you can make the array nondecreasing after at most $$$T$$$ seconds.Array $$$a$$$ is nondecreasing if and only if $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the minimum number of seconds in which you can make $$$a$$$ nondecreasing.

NoteIn the first test case, if you select indices $$$3, 4$$$ at the $$$1$$$-st second and $$$4$$$ at the $$$2$$$-nd second, then $$$a$$$ will become $$$[1, 7, 7, 8]$$$. There are some other possible ways to make $$$a$$$ nondecreasing in $$$2$$$ seconds, but you can't do it faster.In the second test case, $$$a$$$ is already nondecreasing, so answer is $$$0$$$.In the third test case, if you do nothing at first $$$2$$$ seconds and select index $$$2$$$ at the $$$3$$$-rd second, $$$a$$$ will become $$$[0, 0]$$$.

object C extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n         = scala.io.StdIn.readInt()
    val an        = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val (_, diff) = an.tail.foldLeft((an.head, 0)) { case ((p, d), c) => if (c >= p) (c, d) else (p, d.max(p - c)) }
    val sec       = 1 + -1.max(math.floor(math.log10(diff) / math.log10(2)).toInt)

    println(sec)
  }
}


Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do:   If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$;  if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$;  if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.

For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.

NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.

object C1183 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    var q = readInt
    while (q > 0) {
      val Array(k, n, a, b) = readLongs(4)
      var res = -1L
      var s = 0L
      var e = math.min(n, k / a)
      while (s <= e) {
        val mid = (e + s) / 2
        if (k > (mid * a) + ((n - mid) * b)) {
          res = mid
          s = mid + 1
        } else {
          e = mid - 1
        }
      }
      out.println(res)
      q -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

object _1183C extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val queries = io.read[Seq[(Long, Long, Long, Long)]]

    val ans = queries map { case (k, n, a, b) =>
      val x = ((k - b*n)/(1.0 * (a - b))).ceil.toLong - 1
      (x max - 1) min n
    }

    io.writeLines(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}