Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 < i2 < i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.

The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.

Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.

NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.

import scala.collection.mutable
import scala.io.StdIn._

object CF567C extends App {
  val Array(n, k) = readLine().split(" ").map(_.toLong)
  val a = readLine().split(" ").map(_.toLong)

  val l = mutable.Map[Long, Long]().withDefaultValue(0)
  // elements to the left of current element
  val r = mutable.Map[Long, Long]().withDefaultValue(0) // elements to the right of current element

  a.foreach { e => r.update(e, r(e) + 1)}
  // all elements are to the right initially

  var res = 0.toLong
  a.foreach { e =>
    // if current element is divisible by k,
    // retrieve number of elements equal to e/k to the left of the current element
    val nl = if (e % k == 0) l(e / k) else 0

    // put current element from right to left
    l.update(e, l(e) + 1)
    r.update(e, r(e) - 1)

    // retrieve number of elements equal to e*k to the right of the current element
    val nr = r(e * k)

    res += nl * nr
  }

  println(res)
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

// case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)
// object Main {
//   // Document: http://www.scala-lang.org/api/current/#package
//   // -----------------------------------------------------------------------------
//   def main(args: Array[String]) : Unit = {
//     val (n,k) = {
//       val nk = readLine().split(" ").map(_.toLong)
//       (nk(0), nk(1))
//     }
//     val a = readLine().split(" ").map(_.toLong)
//     val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))((r,i) => r match {
//                                                    case R(c,g,r) => {
//                                                      val new_r = r + g.getOrElse(i,0l)
//                                                      val new_c = c + (i->(c.getOrElse(i,0l)+1l))
//                                                      val new_g =
//                                                        if(i % k == 0)
//                                                          g + (i*k->(g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)))
//                                                        else
//                                                          g
//                                                      R(new_c,new_g,new_r)
//                                                    }
//                                                  })
//     println(l.r)
//   }
// }

object Main {
  import scala.collection.mutable.Map
  case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)
  // Document: http://www.scala-lang.org/api/current/#package
  // -----------------------------------------------------------------------------
  def main(args: Array[String]) : Unit = {
    val (n,k) = {
      val nk = readLine().split(" ").map(_.toLong)
      (nk(0), nk(1))
    }
    val a = readLine().split(" ").map(_.toLong)
    val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))(
        (r,i) => r match {
          case R(c,g,r) => {
            val new_r = r + g.getOrElse(i,0l)
            val t = c.getOrElse(i,0l)+1l
            val j = g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)
            c += (i->t)
            if(i % k == 0)
              g += (i*k->j)
            R(c,g,new_r)
          }
        })
    println(l.r)
  }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine
import scala.collection.immutable.HashMap

// ----------------------------------------------------------------------------0
// ----------------------------------------------------------------------------0
object Main {
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  import scala.annotation.tailrec
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println(obj)

    def readIntVector()    : Vector[Int]    = parseLineToVector(() => nextInt)
    def readLongVector()   : Vector[Long]   = parseLineToVector(() => nextLong)
    def readStringVector() : Vector[String] = parseLineToVector(() => nextString)
    def nextInt()          : Int            = nextLong().toInt
    def nextBigInt()       : BigInt         = BigInt(nextString())
    def nextBigDecimal(  ) : BigDecimal     = BigDecimal(nextString())
    def nextDouble()       : Double         = nextString().toDouble
    def nextLong() : Long = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading long failed")
      val sgn = if(peek == '-') -1l else 1
      if(sgn == -1l) read()
      if(peek < '0' || '9' < peek)
        throw new NumberFormatException(s"readLong found only '-' or no number")
      @tailrec
      def readLong(next: Int, cur: Long) : Long =
        if('0' <= next && next <= '9'){
          val _ = read() // is equal to next
          readLong(peek, cur*10 + next-'0')
        }
        else if(isEnd(next) || isSpaceOrControl(next))
          sgn*cur
        else
          throw new NumberFormatException(s"readLong found strange byte $next")
      val res = readLong(peek,0)
      skipTrailingSpaces()
      res
    }
    def nextString() : String = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading String failed")
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isSpaceOrControl(next)){
          builder.toString
        }else{
          builder.append(read().toChar) // here we skip.
          appendCode(peek)
        }
      }
      val res = appendCode(peek)
      skipTrailingSpaces()
      res
    }
    // TODO: refactoring to marge nextString
    def readLine() : String = {
      if(isEnd(peek))
        throw new NoSuchElementException("Reading Line failed")
      skipNewline()
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isNewLine(next)){
          builder.toString
        }else{
          builder.append(next.toChar)
          appendCode(read())
        }
      }
      appendCode(read())
    }
    // helpers
    private[this] var peeked: Option[Int] = None
    private[this] var is_first = true
    private def read() = {
      val res = peeked match {
        case None    => in.read()
        case Some(a) => { peeked = None; a }
      }
      is_first = false
      res
    }
    private def peek() =
      peeked match {
        case None    => {
          val res = in.read()
          peeked  = Some(res)
          res
        }
        case Some(a) => a
      }
    private def isEnd(c: Int)     = c == -1
    private def isCR(c: Int)      = c == 13
    private def isLF(c: Int)      = c == 10
    private def isNewLine(c: Int) = isLF(c) || isCR(c)
    private def isThereReadable() = !isEnd(peek)
    // XXX: this limits c is ASCII?
    private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127
    @tailrec
    final private def goNextNotSpaceNorControl() : Unit =
      if(isSpaceOrControl(peek)){
        read()
        goNextNotSpaceNorControl()
      }
    final private def skipTrailingSpaces() : Unit = {
      @tailrec
      def skipTrailingSpacesAux() : Unit = {
        if(!isNewLine(peek) && isSpaceOrControl(peek)){
          read()
          skipTrailingSpacesAux()
        }
      }
      skipTrailingSpacesAux()
    }
    final private def skipNewline() : Unit = {
      if(is_first){
      }else if(isCR(peek)){
        read()
        if(isLF(peek)) read()
      }else if(isLF(peek)){
        read()
      }
    }
    private def goNextValuable() = {
      goNextNotSpaceNorControl()
      isThereReadable()
    }
    private def parseLineToVector[X](parser: () => X) : Vector[X] = {
      import scala.collection.immutable.VectorBuilder
      val vb = new VectorBuilder[X]()
      skipNewline()
      @tailrec
      def parseLineToVectorAux(first: Boolean=false) : Vector[X] =
        if(isNewLine(peek) || isEnd(peek)) {
          vb.result
        }else{
          vb += parser()
          parseLineToVectorAux()
        }
      parseLineToVectorAux(true)
    }
  }

  // Document: http://www.scala-lang.org/api/current/#package
  // -----------------------------------------------------------------------------
  class Solver(val stdio: MyConsole){
    import stdio._ // shadow Console.~
    case class R(c: HashMap[Long,Long], g: HashMap[Long,Long], r: Long)
    def main() : Unit = {
      val n,k = nextLong()
      val a = readLongVector()
      val l = a.foldLeft(R(HashMap[Long,Long](),HashMap[Long,Long](),0l))((r,i) => r match {
                                                                            case R(c,g,r) => {
                                                                              val new_r = r + g.getOrElse(i,0l)
                                                                              val new_c = c + (i->(c.getOrElse(i,0l)+1l))
                                                                              val new_g =
                                                                                if(i % k == 0 && (c contains i/k))
                                                                                g + (i*k->(g.getOrElse(i*k,0l)+c.get(i/k).get))
                                                                                else
                                                                                g
                                                                              R(new_c,new_g,new_r)
                                                                            }
                                                                          })
      println(l.r)
    }
  }

  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
}

// object Main {
//   import scala.collection.mutable.Map
//   case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)
//   // Document: http://www.scala-lang.org/api/current/#package
//   // -----------------------------------------------------------------------------
//   def main(args: Array[String]) : Unit = {
//     val (n,k) = {
//       val nk = readLine().split(" ").map(_.toLong)
//       (nk(0), nk(1))
//     }
//     val a = readLine().split(" ").map(_.toLong)
//     val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))(
//         (r,i) => r match {
//           case R(c,g,r) => {
//             val new_r = r + g.getOrElse(i,0l)
//             val t = c.getOrElse(i,0l)+1l
//             val j = g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)
//             c += (i->t)
//             if(i % k == 0)
//               g += (i*k->j)
//             R(c,g,new_r)
//           }
//         })
//     println(l.r)
//   }
// }

import scala.annotation.tailrec
import scala.io.StdIn.readLine

// case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)
// object Main {
//   // Document: http://www.scala-lang.org/api/current/#package
//   // -----------------------------------------------------------------------------
//   def main(args: Array[String]) : Unit = {
//     val (n,k) = {
//       val nk = readLine().split(" ").map(_.toLong)
//       (nk(0), nk(1))
//     }
//     val a = readLine().split(" ").map(_.toLong)
//     val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))((r,i) => r match {
//                                                    case R(c,g,r) => {
//                                                      val new_r = r + g.getOrElse(i,0l)
//                                                      val new_c = c + (i->(c.getOrElse(i,0l)+1l))
//                                                      val new_g =
//                                                        if(i % k == 0)
//                                                          g + (i*k->(g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)))
//                                                        else
//                                                          g
//                                                      R(new_c,new_g,new_r)
//                                                    }
//                                                  })
//     println(l.r)
//   }
// }

object Main {
  import scala.collection.mutable.Map
  case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)
  // Document: http://www.scala-lang.org/api/current/#package
  // -----------------------------------------------------------------------------
  def main(args: Array[String]) : Unit = {
    val (n,k) = {
      val nk = readLine().split(" ").map(_.toLong)
      (nk(0), nk(1))
    }
    val a = readLine().split(" ").map(_.toLong)
    var r = 0l
    val c = Map[Long,Long]()
    val g = Map[Long,Long]()
    for(i <- a){
      val new_r = r + g.getOrElse(i,0l)
      val t = c.getOrElse(i,0l)+1l
      val j = g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)
      c += (i->t)
      if(i % k == 0)
        g += (i*k->j)
      r = new_r
    }
    println(r)
  }
}

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

import scala.collection.mutable

object C {

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

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

  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 java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    def removeAll(x: T) = {
      map.remove(x)
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val k = nextInt
    val a = new Array[Int](n)
    var ans = 0L
    val left = new MultiHashSet[Long]
    val right = new MultiHashSet[Long]
    for (i <- 0 until n) {
      a(i) = nextInt
      right.add(a(i))
    }
    for (i <- 0 until n) {
      right.remove(a(i))
      if (a(i) % k == 0)
        ans += 1L * left.count(a(i) / k) * right.count(1L * a(i) * k)
      left.add(a(i))
    }
    out.println(ans)
    return 0
  }
}

import io.StdIn._
import scala.collection.mutable._

object Solution {

  def main(args: Array[String]) {
    val line = readLine().split(" ").map(_.toInt)
    val (n, k) = (line(0), line(1))
    val seq = readLine().split(" ").map(_.toInt)
    val l = Map[Int, Int]().withDefaultValue(0)
    val r = Map[Int, Int]().withDefaultValue(0)
    var res = 0L

    for (i <- seq.tail) { r(i) += 1 }
    l(seq.head) = 1
    for (i <- seq.tail) {
      r(i) = Math.max(0, r(i) - 1)
      if (i % k == 0 && Math.abs(i * k.toLong) < 1000000007) {
          res += l(i/k) * r(i*k).toLong
      }
      l(i) += 1
    }

    println(res)

  }

}

import scala.io.StdIn._

object CF567C extends App {
  val Array(n, k) = readLine().split(" ").map(_.toLong)
  val a = readLine().split(" ").map(_.toLong)

  val square = k * k

  var result = 0
  val len = a.length - 1
  for (i <- 0 to len) {
    for (j <- (i + 1) to len) {
      for (m <- (j + 1) to len) {
        val a1 = a(i)
        val a2 = a(j)
        val a3 = a(m)
        if ((a1 == a2 / k) && (a1 == a3 / square)) {
          result += 1
        }
      }
    }
  }

  println(result)
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine
import scala.collection.immutable.HashMap

// ----------------------------------------------------------------------------0
// ----------------------------------------------------------------------------0
object Main {
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  import scala.annotation.tailrec
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println(obj)

    def readIntVector()    : Vector[Int]    = parseLineToVector(() => nextInt)
    def readLongVector()   : Vector[Long]   = parseLineToVector(() => nextLong)
    def readStringVector() : Vector[String] = parseLineToVector(() => nextString)
    def nextInt()          : Int            = nextLong().toInt
    def nextBigInt()       : BigInt         = BigInt(nextString())
    def nextBigDecimal(  ) : BigDecimal     = BigDecimal(nextString())
    def nextDouble()       : Double         = nextString().toDouble
    def nextLong() : Long = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading long failed")
      val sgn = if(peek == '-') -1l else 1
      if(sgn == -1l) read()
      if(peek < '0' || '9' < peek)
        throw new NumberFormatException(s"readLong found only '-' or no number")
      @tailrec
      def readLong(next: Int, cur: Long) : Long =
        if('0' <= next && next <= '9')
          readLong(readWithoutCheckingPeeked(), cur*10 + next-'0')
        else if(isEnd(next) || isSpaceOrControl(next))
          sgn*cur
        else
          throw new NumberFormatException(s"readLong found strange byte $next")
      val res = readLong(read(),0)
      skipTrailingSpaces()
      res
    }
    def nextString() : String = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading String failed")
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isSpaceOrControl(next)){
          builder.toString
        }else{
          builder.append(next.toChar)
          appendCode(readWithoutCheckingPeeked())
        }
      }
      val res = appendCode(read())
      skipTrailingSpaces()
      res
    }
    // TODO: refactoring to marge nextString
    def readLine() : String = {
      if(isEnd(peek))
        throw new NoSuchElementException("Reading Line failed")
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isNewLine(next)){
          builder.toString
        }else{
          builder.append(next.toChar)
          appendCode(read())
        }
      }
      appendCode(read())
    }
    // helpers
    private[this] var peeked: Option[Int] = None
    private[this] var last = -1
    private def read() = {
      val res = peeked match {
          case None    => in.read()
          case Some(a) => { peeked = None; a }
        }
      last = res
      res
    }
    @inline private def readWithoutCheckingPeeked() = {
      val res = in.read()
      last = res
      res
    }
    @inline private def peek() =
      peeked match {
        case None    => {
          val res = in.read()
          peeked  = Some(res)
          res
        }
        case Some(a) => a
      }
    @inline private def isEnd(c: Int)    = c == -1
    @inline private def isNewLine(c: Int) = c == 10 || c == 13     // LF and CR
    @inline private def isThereReadable() = !isEnd(peek)
    // XXX: this limits c is ASCII?
    @inline private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127
    @tailrec
    final private def goNextNotSpaceNorControl() : Unit =
      if(isSpaceOrControl(peek)){
        read()
        goNextNotSpaceNorControl()
      }
    final private def skipTrailingSpaces() : Unit = {
      @tailrec
      def skipTrailingSpacesAux() : Unit = {
        if(!isNewLine(last) && !isNewLine(peek) && isSpaceOrControl(peek)){
          read()
          skipTrailingSpacesAux()
        }
      }
      skipTrailingSpacesAux
      if(!isNewLine(last) && isNewLine(peek)) read()
    }
    @tailrec
    final private def skipTrailingSpacesAndNewline() : Unit =
      if(isNewLine(peek)){
        val _ = read() // windows causes error. maybe.
      }else if(isSpaceOrControl(peek)){
        read()
        skipTrailingSpacesAndNewline()
      }
    @inline private def goNextValuable() = {
      goNextNotSpaceNorControl()
      isThereReadable()
    }
    @inline private def parseLineToVector[X](parser: () => X) : Vector[X] = {
      import scala.collection.immutable.VectorBuilder
      val vb = new VectorBuilder[X]()
      @tailrec
      def parseLineToVectorAux(first: Boolean=false) : Vector[X] =
        if((!first && isNewLine(last)) || isNewLine(peek) || isEnd(peek)) {
          vb.result
        }else{
          vb += parser()
          parseLineToVectorAux()
        }
      parseLineToVectorAux(true)
    }
  }

  // Document: http://www.scala-lang.org/api/current/#package
  // -----------------------------------------------------------------------------
  class Solver(val stdio: MyConsole){
    import stdio._ // shadow Console.~
    case class R(c: HashMap[Long,Long], g: HashMap[Long,Long], r: Long)
    def main() : Unit = {
      val n,k = nextLong()
      val a = readLongVector()
      val l = a.foldLeft(R(HashMap[Long,Long](),HashMap[Long,Long](),0l))((r,i) => r match {
                                                                            case R(c,g,r) => {
                                                                              val new_r = r + g.getOrElse(i,0l)
                                                                              val new_c = c + (i->(c.getOrElse(i,0l)+1l))
                                                                              val new_g =
                                                                                if(i % k == 0)
                                                                                g + (i*k->(g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)))
                                                                                else
                                                                                g
                                                                              R(new_c,new_g,new_r)
                                                                            }
                                                                          })
      println(l.r)
    }
  }

  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
}

// object Main {
//   import scala.collection.mutable.Map
//   case class R(c: Map[Long,Long], g: Map[Long,Long], r: Long)
//   // Document: http://www.scala-lang.org/api/current/#package
//   // -----------------------------------------------------------------------------
//   def main(args: Array[String]) : Unit = {
//     val (n,k) = {
//       val nk = readLine().split(" ").map(_.toLong)
//       (nk(0), nk(1))
//     }
//     val a = readLine().split(" ").map(_.toLong)
//     val l = a.foldLeft(R(Map[Long,Long](),Map[Long,Long](),0l))(
//         (r,i) => r match {
//           case R(c,g,r) => {
//             val new_r = r + g.getOrElse(i,0l)
//             val t = c.getOrElse(i,0l)+1l
//             val j = g.getOrElse(i*k,0l)+c.getOrElse(i/k,0l)
//             c += (i->t)
//             if(i % k == 0)
//               g += (i*k->j)
//             R(c,g,new_r)
//           }
//         })
//     println(l.r)
//   }
// }

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

import scala.collection.mutable

object C {

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

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

  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 java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    def removeAll(x: T) = {
      map.remove(x)
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val k = nextInt
    val a = new Array[Int](n)
    var ans = 0L
    val left = new MultiHashSet[Int]
    val right = new MultiHashSet[Int]
    for (i <- 0 until n) {
      a(i) = nextInt
      right.add(a(i))
    }
    for (i <- 0 until n) {
      right.remove(a(i))
      if (a(i) % k == 0)
        ans += 1L * left.count(a(i) / k) * right.count(a(i) * k)
      left.add(a(i))
    }
    out.println(ans)
    return 0
  }
}

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

import scala.collection.mutable

object C {

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

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

  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 java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    def removeAll(x: T) = {
      map.remove(x)
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val k = nextInt
    val a = new Array[Int](n)
    var ans = 0L
    val left = new MultiHashSet[Int]
    val right = new MultiHashSet[Int]
    for (i <- 0 until n) {
      a(i) = nextInt
      right.add(a(i))
    }
    for (i <- 0 until n) {
      right.remove(a(i))
      if (a(i) % k == 0)
        ans += left.count(a(i) / k) * right.count(a(i) * k)
      left.add(a(i))
    }
    out.println(ans)
    return 0
  }
}

import io.StdIn._
import scala.collection.mutable._

object Solution {

  def main(args: Array[String]) {
    val line = readLine().split(" ").map(_.toInt)
    val (n, k) = (line(0), line(1))
    val seq = readLine().split(" ").map(_.toInt)
    val l = Map[Int, Int]().withDefaultValue(0)
    val r = Map[Int, Int]().withDefaultValue(0)
    var res = 0

    for (i <- seq.tail) { r(i) += 1 }
    l(seq.head) = 1
    for (i <- seq.tail) {
      r(i) = Math.max(0, r(i) - 1)
      if (i % k == 0 && i * k.toLong < 1000000007) {
          res += l(i/k) * r(i*k)
      }
      l(i) += 1
    }

    println(res)

  }

}

import io.StdIn._
import scala.collection.mutable._

object Solution {

  def main(args: Array[String]) {
    val line = readLine().split(" ").map(_.toInt)
    val (n, k) = (line(0), line(1))
    val seq = readLine().split(" ").map(_.toInt)
    val l = Map[Int, Int]().withDefaultValue(0)
    val r = Map[Int, Int]().withDefaultValue(0)
    var res = 0L

    for (i <- seq.tail) { r(i) += 1 }
    l(seq.head) = 1
    for (i <- seq.tail) {
      r(i) = Math.max(0, r(i) - 1)
      if (i % k == 0 && i * k.toLong < 1000000007) {
          res += l(i/k) * r(i*k).toLong
      }
      l(i) += 1
    }

    println(res)

  }

}


Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation.For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers a1, a2, ..., an. He also wrote a square matrix b of size n × n. The element of matrix b that sits in the i-th row in the j-th column (we'll denote it as bij) equals:  the "bitwise AND" of numbers ai and aj (that is, bij = ai & aj), if i ≠ j;  -1, if i = j. Having written out matrix b, Polycarpus got very happy and wiped a off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly.Help Polycarpus, given matrix b, restore the sequence of numbers a1, a2, ..., an, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 109.

The first line contains a single integer n (1 ≤ n ≤ 100) — the size of square matrix b. Next n lines contain matrix b. The i-th of these lines contains n space-separated integers: the j-th number represents the element of matrix bij. It is guaranteed, that for all i (1 ≤ i ≤ n) the following condition fulfills: bii = -1. It is guaranteed that for all i, j (1 ≤ i, j ≤ n; i ≠ j) the following condition fulfills: 0 ≤ bij ≤ 109, bij = bji.

Print n non-negative integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the sequence that Polycarpus wiped off the board. Separate the numbers by whitespaces.  It is guaranteed that there is sequence a that satisfies the problem conditions. If there are multiple such sequences, you are allowed to print any of them.

NoteIf you do not know what is the "bitwise AND" operation please read: http://en.wikipedia.org/wiki/Bitwise_operation.

object Main extends App{
  val n = readInt()
  for (i <- 0 until n){
    val arr = readLine().split(" ").map(_.toInt)
    var x = 0
    for (j <- arr){
      if (j > 0) x = x | j
    }
    print (x)
    print (if(i == n-1) "\n" else " ")
  }
}

import scala.collection.mutable._

object Main extends App {
  val sc = new java.util.Scanner(System.in)

  val n = sc.nextInt()

  val m = Array.tabulate(n, n)((_, _) => sc.nextInt())

  val ans = (0 until n) map { i =>
    (0 until n) map (j => if (i != j) (m(i)(j) | m(j)(i)) else 0) reduce (_ | _)
  }

  println(ans.mkString("\n"))
}


Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.

The only line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the set and the desired bitwise-xor, respectively.

If there is no such set, print "NO" (without quotes). Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.

NoteYou can read more about the bitwise-xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XORFor the first sample .For the second sample .

import scala.collection.immutable.HashSet

/**
  * @see http://codeforces.com/contest/862/problem/C
  */

object CMahmoudAndEhabAndTheXor extends App {
  def set(n: Int, x: Int): List[Int] = {
    if (n == 1) List(x)
    else if (n == 2) {
      if (x == 0) List.empty
      else List(0, x)
    }
    else {
      val s = (1 to n - 3) ++: List.empty[Int]
      val y = s.foldLeft(0)(_ ^ _)
      val a = 1 << 17
      if (x == y) {
        val b = 1 << 18
        List[Int](a, b, a ^ b) ::: s
      } else {
        List[Int](0, a, a ^ x ^ y) ::: s
      }
    }
  }

  /**
    * 1 <= n <= 100000
    * 0 <= x <= 100000
    */
  val Array(n, x) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val s = set(n, x)
  if (s.isEmpty) println("NO")
  else println("YES\n" + s.mkString(" "))
}


This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury has chosen a string $$$s$$$ consisting of $$$n$$$ characters; each character of $$$s$$$ is a lowercase Latin letter. Your task is to guess this string; initially, you know only its length.You may ask queries of two types:  $$$1$$$ $$$i$$$ — the query of the first type, where $$$i$$$ is an integer from $$$1$$$ to $$$n$$$. In response to this query, the jury will tell you the character $$$s_i$$$;  $$$2$$$ $$$l$$$ $$$r$$$ — the query of the second type, where $$$l$$$ and $$$r$$$ are integers such that $$$1 \le l \le r \le n$$$. In response to this query, the jury will tell you the number of different characters among $$$s_l, s_{l+1}, \dots, s_r$$$. You are allowed to ask no more than $$$26$$$ queries of the first type, and no more than $$$6000$$$ queries of the second type. Your task is to restore the string $$$s$$$.For each test in this problem, the string $$$s$$$ is fixed beforehand, and will be the same for every submission.

Initially, the jury program sends one integer $$$n$$$ on a separate line — the size of $$$s$$$ ($$$1 \le n \le 1000$$$).

To give the answer, print one line ! s with a line break in the end, where $$$s$$$ should be the string picked by the jury. After that, your program should flush the output and terminate gracefully.

NoteLet's analyze the example of interaction.The string chosen by the jury is guess, so initially the jury sends one integer $$$5$$$.  the first query is ? 2 1 5, which means "count the number of different characters among $$$s_1, s_2, \dots, s_5$$$". The answer to it is $$$4$$$.  the second query is ? 1 2, which means "tell which character is $$$s_2$$$". The answer to it is u.  the third query is ? 2 1 2, which means "count the number of different characters among $$$s_1$$$ and $$$s_2$$$". The answer to it is $$$2$$$.  the fourth query is ? 1 1, which means "tell which character is $$$s_1$$$". The answer to it is g.  the fifth query is ? 1 3, which means "tell which character is $$$s_3$$$". The answer to it is e.  the sixth query is ? 1 4, which means "tell which character is $$$s_4$$$". The answer to it is s.  the seventh query is ? 2 4 5, which means "count the number of different characters among $$$s_4$$$ and $$$s_5$$$". The answer to it is $$$1$$$, so it's possible to deduce that $$$s_4$$$ is the same as $$$s_5$$$.In the end, the answer is submitted as ! guess, and it is deduced correctly.

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

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

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

  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    def ask1(i: Int): String = {
      output.println("? 1 " + i.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val l = tokenizer.nextToken()
      Console.flush()
      l
    }
    def ask2(l: Int, r:Int): Int = {
      output.println("? 2 " + l.toString +" " + r.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val ll = tokenizer.nextToken().toInt
      Console.flush()
      ll
    }
    val q = tokenizer.nextToken().toInt
    val a = ask1(1)
    var n = 1
    val Map = mutable.Map[String,Int]()
    var st = ""
    st+=a
    Map += (a -> 1)
    for (i <- 2 to q){
      if (ask2(1,i) > n){
        val b = ask1(i)
        Map += (b -> i)
        n+=1
        st+=b
      }
      else {
        val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)
        var le = 0
        var ri = n
        while ((ri - le) > 1){
          if (ask2(Mapp((le + ri)/2)._2,i) == n - ((le + ri)/2)) {
            le = (le + ri)/2
          }
          else ri = (le + ri)/2
        }
        Map(Mapp(le)._1) = i
        st+=Mapp(le)._1
      }
    }

    output.println("! "+st)
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

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

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

  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    def ask1(i: Int): String = {
      output.println("? 1 " + i.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val l = tokenizer.nextToken()
      Console.flush()
      l
    }
    def ask2(l: Int, r:Int): Int = {
      output.println("? 2 " + l.toString +" " + r.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val ll = tokenizer.nextToken().toInt
      Console.flush()
      ll
    }
    val q = tokenizer.nextToken().toInt
    val a = ask1(1)
    var n = 1
    val Map = mutable.Map[String,Int]()
    var st = ""
    st+=a
    Map += (a -> 1)
    for (i <- 2 to q){
      if (ask2(1,i) > n){
        val b = ask1(i)
        Map += (b -> i)
        n+=1
        st+=b
      }
      else {
        val Mapp = Map.toList.sortWith((a, b) => a._2 < b._2)
        println(Mapp)
        var le = 0
        var ri = n
        while ((ri - le) > 1) {
          if (ask2(Mapp((le + ri) / 2)._2, i) == n - ((le + ri) / 2)) {
            le = (le + ri) / 2
          }
          else ri = (le + ri) / 2
        }
        Map(Mapp(le)._1) = i
        st += Mapp(le)._1

      }
    }
    output.println("! "+st)
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

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

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

  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    def ask1(i: Int): String = {
      output.println("? 1 " + i.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val l = tokenizer.nextToken()
      Console.flush()
      l
    }
    def ask2(l: Int, r:Int): Int = {
      output.println("? 2 " + l.toString +" " + r.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val ll = tokenizer.nextToken().toInt
      Console.flush()
      ll
    }
    val q = tokenizer.nextToken().toInt
    val a = ask1(1)
    var n = 1
    val Map = mutable.Map[String,Int]()
    var st = ""
    st+=a
    Map += (a -> 1)
    for (i <- 2 to q){
      if (ask2(1,i) > n){
        val b = ask1(i)
        Map += (b -> i)
        n+=1
        st+=b
      }
      else {
        val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)
        var le = 0
        var ri = n-1
        if (ask2(Mapp(ri)._2,i) != 1) {
          while ((ri - le) > 1){
            if (ask2(Mapp((le + ri)/2)._2,i) == n - ((le + ri)/2)) {
              le = (le + ri)/2
            }
            else ri = (le + ri)/2
          }
          Map(Mapp(le)._1) = i
          st+=Mapp(le)._1
        }
        else {Map(Mapp(n-1)._1) = i
          st+=Mapp(n-1)._1}
      }
    }
    output.println("! "+st)
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

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

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

  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    def ask1(i: Int): String = {
      output.println("? 1 " + i.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val l = tokenizer.nextToken()
      Console.flush()
      l
    }
    def ask2(l: Int, r:Int): Int = {
      output.println("? 2 " + l.toString +" " + r.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val ll = tokenizer.nextToken().toInt
      Console.flush()
      ll
    }
    val q = tokenizer.nextToken().toInt
    val a = ask1(1)
    var n = 1
    val Map = mutable.Map[String,Int]()
    var st = ""
    st+=a
    Map += (a -> 1)
    var pov = 0
    for (i <- 2 to q){
      if (ask2(1,i) > n+pov){
        val b = ask1(i)
        Map += (b -> i)
        n+=1
        st+=b
      }
      else {
        val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)
        var le = 0
        var ri = n-1
        if (ask2(Mapp(ri)._2,i) != 1) {
          while ((ri - le) > 1){
            if (ask2(Mapp((le + ri)/2)._2,i) == (le + ri)/2) {
              le = (le + ri)/2
            }
            else ri = (le + ri)/2
          }
          Map(Mapp(le)._1) = i
          st+=Mapp(le)._1
        }
        else {Map(Mapp(n-1)._1) = i
          st+=Mapp(n-1)._1}
        pov+=1
      }
    }
    output.println("! "+st)
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

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

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

  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    def ask1(i: Int): String = {
      output.println("? 1 " + i.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val l = tokenizer.nextToken()
      Console.flush()
      l
    }
    def ask2(l: Int, r:Int): Int = {
      output.println("? 2 " + l.toString +" " + r.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val ll = tokenizer.nextToken().toInt
      Console.flush()
      ll
    }
    val q = tokenizer.nextToken().toInt
    val a = ask1(1)
    var n = 1
    val Map = mutable.Map[String,Int]()
    var st = ""
    st+=a
    Map += (a -> 1)
    for (i <- 2 to q){
      if (ask2(1,i) > n){
        val b = ask1(i)
        Map += (b -> i)
        n+=1
        st+=b
      }
      else {
        val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)
        var le = 0
        var ri = n-1
        if (ask2(Mapp(ri)._2,i) != 1) {
          while ((ri - le) > 1){
            if (ask2(Mapp((le + ri)/2)._2,i) == (le + ri)/2) {
              le = (le + ri)/2
            }
            else ri = (le + ri)/2
          }
          Map(Mapp(le)._1) = i
          st+=Mapp(le)._1
        }
        else {Map(Mapp(n-1)._1) = i
          st+=Mapp(n-1)._1}
      }
    }
    output.println("! "+st)
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

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

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

  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    def ask1(i: Int): String = {
      output.println("? 1 " + i.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val l = tokenizer.nextToken()
      Console.flush()
      l
    }
    def ask2(l: Int, r:Int): Int = {
      output.println("? 2 " + l.toString +" " + r.toString)
      tokenizer = new StringTokenizer(input.readLine())
      val ll = tokenizer.nextToken().toInt
      Console.flush()
      ll
    }
    val q = tokenizer.nextToken().toInt
    val a = ask1(1)
    var n = 1
    val Map = mutable.Map[String,Int]()
    var st = ""
    st+=a
    Map += (a -> 1)
    for (i <- 2 to q){
      if (ask2(1,i) > n){
        val b = ask1(i)
        Map += (b -> i)
        n+=1
        st+=b
      }
      else {
        val Mapp = Map.toList.sortWith((a,b) => a._2 < b._2)
        var le = 0
        var ri = n-1
        if (ask2(Mapp(ri)._2,i) != 1) {
          while (le - ri > 1){
            if (ask2(Mapp((le + ri)/2)._2,i) == (le + ri)/2) {
              le = (le + ri)/2
            }
            else ri = (le + ri)/2
          }
          Map(Mapp(le)._1) = i
          st+=Mapp(le)._1
        }
        else {Map(Mapp(n-1)._1) = i
          st+=Mapp(n-1)._1}
      }
    }
    output.println("! "+st)
  }
}


Monocarp has been collecting rare magazines for quite a while, and now he has decided to sell them. He distributed the magazines between $$$n$$$ boxes, arranged in a row. The $$$i$$$-th box contains $$$a_i$$$ magazines. Some of the boxes are covered with lids, others are not. Suddenly it started to rain, and now Monocarp has to save as many magazines from the rain as possible. To do this, he can move the lids between boxes as follows: if the $$$i$$$-th box was covered with a lid initially, he can either move the lid from the $$$i$$$-th box to the box $$$(i-1)$$$ (if it exists), or keep the lid on the $$$i$$$-th box. You may assume that Monocarp can move the lids instantly at the same moment, and no lid can be moved more than once. If a box will be covered with a lid after Monocarp moves the lids, the magazines in it will be safe from the rain; otherwise they will soak.You have to calculate the maximum number of magazines Monocarp can save from the rain.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of the testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of boxes. The second line contains a string of $$$n$$$ characters 0 and/or 1. If the $$$i$$$-th character is 1, the $$$i$$$-th box is initially covered with a lid. If the $$$i$$$-th character is 0, the $$$i$$$-th box is initially not covered. The third line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the number of magazines in the $$$i$$$-th box. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print one integer — the maximum number of magazines Monocarp can save from the rain.

NoteIn the first testcase of the example, Monocarp can move the lid from the second box to the first box, so the boxes $$$1$$$, $$$3$$$ and $$$4$$$ are covered, and $$$10 + 8 + 9 = 27$$$ magazines are saved.In the second testcase, Monocarp can move the lid from the second box to the first box, then from the third box to the second box, then from the fifth box to the fourth box, and then from the sixth box to the fifth box. The boxes $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$ will be covered, so $$$20 + 10 + 30 + 20 = 80$$$ magazines can be saved.There are no lids in the third testcase, so it's impossible to save even a single magazine.

object _1743C extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val n = io.nextInt()
    val hasLid = "0" + io.nextLine()
    val mags = IndexedSeq.tabulate(n+1)(i => if (i == 0) 0 else io.nextInt())

    val ans = "01+".r.findAllMatchIn(hasLid).toList.sumWith({m =>
      val segment = mags.slice(m.start, m.end)
      segment.sum - segment.min
    })

    io.printLine(ans)
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B =
      t.foldLeft(n.zero)({ case (c, x) => n.plus(c, f(x)) })
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextBool(): Boolean = nextInt() == 1
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): this.type = { out.print(xs.mkString(" ")); this }
  def printLine(xs: Any*): this.type = { out.println(xs.mkString(" ")); this }
  def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }

  override def close() = out.close()
}

object _1743C extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val n = io.nextInt()
    val hasLid = "0" + io.nextLine()
    val mags = Seq.fill(n)(io.nextInt())

    val ans = "01+".r.findAllMatchIn(hasLid).map({m =>
      val segment = mags.slice(m.start-1, m.end-1)
      segment.sum - segment.min
    }).sum

    io.printLine(ans)
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextBool(): Boolean = nextInt() == 1
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): this.type = { out.print(xs.mkString(" ")); this }
  def printLine(xs: Any*): this.type = { out.println(xs.mkString(" ")); this }
  def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }

  override def close() = out.close()
}


Drazil is a monkey. He lives in a circular park. There are n trees around the park. The distance between the i-th tree and (i + 1)-st trees is di, the distance between the n-th tree and the first tree is dn. The height of the i-th tree is hi.Drazil starts each day with the morning run. The morning run consists of the following steps:  Drazil chooses two different trees  He starts with climbing up the first tree  Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it  Then he finally climbs down the second tree. But there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees.If the two trees Drazil chooses are x-th and y-th, we can estimate the energy the morning run takes to him as 2(hx + hy) + dist(x, y). Since there are children on exactly one of two arcs connecting x and y, the distance dist(x, y) between trees x and y is uniquely defined.Now, you know that on the i-th day children play between ai-th tree and bi-th tree. More formally, if ai ≤ bi, children play around the trees with indices from range [ai, bi], otherwise they play around the trees with indices from .Please help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day.

The first line contains two integer n and m (3 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting number of trees and number of days, respectively.  The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 109), the distances between consecutive trees. The third line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 109), the heights of trees. Each of following m lines contains two integers ai and bi (1 ≤ ai, bi ≤ n) describing each new day. There are always at least two different trees Drazil can choose that are not affected by children.

For each day print the answer in a separate line.

object C extends App {

  case class SegTree(as: Array[Long]) {

    val n = as.length
    val t = Array.ofDim[(Long, Int)](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = (as(tl), tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = if (t(v2)._1 > t(v2 + 1)._1) t(v2) else t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): (Long, Int) = {
      if (l > r) (Long.MinValue, -1)
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        val t1 = query(l, Math.min(r, tm), v2, tl, tm)
        val t2 = query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
        if (t1._1 > t2._1) t1 else t2
      }
    }

  }

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

  val Array(n, m) = readInts(2)
  val ds = readLongs(n)
  val hs = readLongs(n)

  val lToR, rToL = Array.ofDim[Long](2 * n)

  var dSum = 0L
  for (i <- 0 until 2 * n) {
    lToR(i) = dSum + hs(i % n) * 2
    rToL(i) = hs(i % n) * 2 - dSum
    dSum += ds(i % n)
  }

  val stLToR = SegTree(lToR)
  val stRToL = SegTree(rToL)

  for (i <- 0 until m) {
    val Array(a, b) = readInts(2).map(_ - 1)
    val (u, v) = if (a <= b) (b + 1, n + a - 1) else (b + 1, a - 1)
    val x = {
      val l = stLToR.query(u, v)
      val r1 = stRToL.query(u, l._2 - 1)
      val r2 = stRToL.query(l._2 + 1, v)
      val r = if (r1._1 > r2._1) r1 else r2
      l._1 + r._1
    }
    val y = {
      val r = stRToL.query(u, v)
      val l1 = stLToR.query(u, r._2 - 1)
      val l2 = stLToR.query(r._2 + 1, v)
      val l = if (l1._1 > l2._1) l1 else l2
      l._1 + r._1
    }
    println(x max y)
  }

  Console.flush
}

object C extends App {

  case class SegTree(as: Array[Long]) {

    val n = as.length
    val t = Array.ofDim[(Long, Int)](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = (as(tl), tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = if (t(v2)._1 > t(v2 + 1)._1) t(v2) else t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): (Long, Int) = {
      if (l > r) (Long.MinValue, -1)
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        val t1 = query(l, Math.min(r, tm), v2, tl, tm)
        val t2 = query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
        if (t1._1 > t2._1) t1 else t2
      }
    }

  }

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

  val Array(n, m) = readInts(2)
  val ds = readLongs(n)
  val hs = readLongs(n)

  val lToR, rToL = Array.ofDim[Long](2 * n)

  var dSum = 0L
  for (i <- 0 until 2 * n) {
    lToR(i) = dSum + hs(i % n) * 2
    rToL(i) = hs(i % n) * 2 - dSum
    dSum += ds(i % n)
  }

  val stLToR = SegTree(lToR)
  val stRToL = SegTree(rToL)

  for (i <- 0 until m) {
    val Array(a, b) = readInts(2).map(_ - 1)
    val (u, v) = if (a <= b) (b + 1, n + a - 1) else (a + 1, n + b - 1)
    val x = {
      val l = stLToR.query(u, v)
      val r1 = stRToL.query(u, l._2 - 1)
      val r2 = stRToL.query(l._2 + 1, v)
      val r = if (r1._1 > r2._1) r1 else r2
      l._1 + r._1
    }
    val y = {
      val r = stRToL.query(u, v)
      val l1 = stLToR.query(u, r._2 - 1)
      val l2 = stLToR.query(r._2 + 1, v)
      val l = if (l1._1 > l2._1) l1 else l2
      l._1 + r._1
    }
    println(x max y)
  }

  Console.flush
}


You are given two strings of equal length $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.For example, if $$$s$$$ is "acbc" you can get the following strings in one operation:   "aabc" (if you perform $$$s_2 = s_1$$$);  "ccbc" (if you perform $$$s_1 = s_2$$$);  "accc" (if you perform $$$s_3 = s_2$$$ or $$$s_3 = s_4$$$);  "abbc" (if you perform $$$s_2 = s_3$$$);  "acbb" (if you perform $$$s_4 = s_3$$$); Note that you can also apply this operation to the string $$$t$$$.Please determine whether it is possible to transform $$$s$$$ into $$$t$$$, applying the operation above any number of times.Note that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is represented by two consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \le |s| \le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \le |t| \leq 100$$$, $$$|t| = |s|$$$) consisting of lowercase Latin letters.

For each query, print "YES" if it is possible to make $$$s$$$ equal to $$$t$$$, and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes", and "YES" will all be recognized as positive answer).

NoteIn the first query, you can perform two operations $$$s_1 = s_2$$$ (after it $$$s$$$ turns into "aabb") and $$$t_4 = t_3$$$ (after it $$$t$$$ turns into "aabb"). In the second query, the strings are equal initially, so the answer is "YES".In the third query, you can not make strings $$$s$$$ and $$$t$$$ equal. Therefore, the answer is "NO".

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

  override def apply(io: IO): io.type = {
    val input = io.read[Seq[(String, String)]]
    val ans = input map {case (a, b) => a.toSet.intersect(b.toSet).nonEmpty.toEnglish.toUpperCase() }
    io.writeAll(ans, separator = "\n")
  }
}
/****************************[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 = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[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
      }
    }
  }
}


You might have remembered Theatre square from the problem 1A. Now it's finally getting repaved.The square still has a rectangular shape of $$$n \times m$$$ meters. However, the picture is about to get more complicated now. Let $$$a_{i,j}$$$ be the $$$j$$$-th square in the $$$i$$$-th row of the pavement.You are given the picture of the squares:  if $$$a_{i,j} = $$$ "*", then the $$$j$$$-th square in the $$$i$$$-th row should be black;  if $$$a_{i,j} = $$$ ".", then the $$$j$$$-th square in the $$$i$$$-th row should be white. The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles:  $$$1 \times 1$$$ tiles — each tile costs $$$x$$$ burles and covers exactly $$$1$$$ square;  $$$1 \times 2$$$ tiles — each tile costs $$$y$$$ burles and covers exactly $$$2$$$ adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into $$$1 \times 1$$$ tiles. You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.What is the smallest total price of the tiles needed to cover all the white squares?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of testcases. Then the description of $$$t$$$ testcases follow. The first line of each testcase contains four integers $$$n$$$, $$$m$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100$$$; $$$1 \le m \le 1000$$$; $$$1 \le x, y \le 1000$$$) — the size of the Theatre square, the price of the $$$1 \times 1$$$ tile and the price of the $$$1 \times 2$$$ tile. Each of the next $$$n$$$ lines contains $$$m$$$ characters. The $$$j$$$-th character in the $$$i$$$-th line is $$$a_{i,j}$$$. If $$$a_{i,j} = $$$ "*", then the $$$j$$$-th square in the $$$i$$$-th row should be black, and if $$$a_{i,j} = $$$ ".", then the $$$j$$$-th square in the $$$i$$$-th row should be white. It's guaranteed that the sum of $$$n \times m$$$ over all testcases doesn't exceed $$$10^5$$$.

For each testcase print a single integer — the smallest total price of the tiles needed to cover all the white squares in burles.

NoteIn the first testcase you are required to use a single $$$1 \times 1$$$ tile, even though $$$1 \times 2$$$ tile is cheaper. So the total price is $$$10$$$ burles.In the second testcase you can either use two $$$1 \times 1$$$ tiles and spend $$$20$$$ burles or use a single $$$1 \times 2$$$ tile and spend $$$1$$$ burle. The second option is cheaper, thus the answer is $$$1$$$.The third testcase shows that you can't rotate $$$1 \times 2$$$ tiles. You still have to use two $$$1 \times 1$$$ tiles for the total price of $$$20$$$.In the fourth testcase the cheapest way is to use $$$1 \times 1$$$ tiles everywhere. The total cost is $$$6 \cdot 3 = 18$$$.

//package codeforces.contests._1359

object _2 {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val Array(n, _, t1, t2) = io.StdIn.readLine.split(" ").map(_.toInt)

      val ans = (1 to n).foldLeft(0) { (acc, _) =>

        val chars = io.StdIn.readLine.toList

        @scala.annotation.tailrec
        def loop(input: List[Char], result: Int = 0): Int = {
          if (input.isEmpty) result
          else {
            val (dots, tail) = input.span(_ == '.')

            val size = dots.length

            val current = if (t1 * 2 <= t2) size * t1 else (size / 2) * t2 + (if ((size & 1) == 1) t1 else 0)

            loop(tail.dropWhile(_ == '*'), result + current)
          }

        }

        acc + loop(chars)
      }

      println {
        ans
      }
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 0 until t){
      val input = StdIn.readLine.trim.split(" ").map(_.toInt)
      val (n, m, x, y) = (input(0), input(1), input(2), input(3))
      val board = Array.fill(n)("")
      var b1, b2 = 0
      for (row <- 0 until n) {
        board(row) = StdIn.readLine
        val (bc1, bc2) = board(row).split("\\*").foldLeft((0,0))((acc, str) => {
          (acc._1 + str.length % 2, acc._2 + str.length / 2)
        })
        b1 += bc1
        b2 += bc2
      }
      val res = (b1+b2*2)*x min (b1*x+b2*y)
      println(res)
    }
  }
}

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

  (0 until t).foreach { _ =>
    val Array(n, m, x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val z                 = y min (2 * x)

    val ans = (0 until n).foldLeft(0) { (sum, _) =>
      val am = scala.io.StdIn.readLine().split("").map(c => if (c == ".") 1 else 0)

      val (s, t) = am.foldLeft((sum, 0)) {
        case ((s, l), r) =>
          if (l == 0) (s, r)
          else if (l == r) (s + z, 0)
          else (s + x, 0)
      }

      s + t * x
    }

    println(ans)

  }
}

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

  (0 until t).foreach { _ =>
    val Array(n, m, x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val z                 = y min (2 * x)

    val ans = (0 until n).foldLeft(0) { (sum, _) =>
      val am = scala.io.StdIn.readLine().split("").map(c => if (c == ".") 1 else 0)

      var a = 0
      val r = am.reduce { (l, r) =>
        if (l == 0) r
        else if (l == r) { a += z; 0 }
        else { a += x; 0 }
      }

      sum + a + r * x
    }

    println(ans)

  }
}

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()
  for (_ <- 1 to t) {
    val n =  in.nextInt()
    val m = in.nextInt()
    val x = in.nextInt()
    val y = in.nextInt()

    var whiteCount = 0
    var res = 0

    def incRes(): Unit = {
      if (x * 2 <= y) {
        res = res + whiteCount * x
      } else {
        res = res + whiteCount / 2 * y + whiteCount % 2 * x
      }
      whiteCount = 0
    }

    for (i <- 0 until n) {
      val s = in.nextToken()
      s.foreach(c => if (c == '.') whiteCount = whiteCount + 1 else incRes())
      incRes()
    }

    println(res)

  }

}


You are given a grid with $$$n$$$ rows and $$$m$$$ columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number $$$k > 0$$$ written on it, then exactly $$$k$$$ of its neighboring cells have a number greater than $$$0$$$ written on them. Note that if the number in the cell is $$$0$$$, there is no such restriction on neighboring cells.You are allowed to take any number in the grid and increase it by $$$1$$$. You may apply this operation as many times as you want, to any numbers you want. Perform some operations (possibly zero) to make the grid good, or say that it is impossible. If there are multiple possible answers, you may find any of them.Two cells are considered to be neighboring if they have a common edge.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 300$$$)  — the number of rows and columns, respectively. The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line $$$a_{i, j}$$$ is the number written in the $$$j$$$-th cell of the $$$i$$$-th row ($$$0 \le a_{i, j} \le 10^9$$$). It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^5$$$.

If it is impossible to obtain a good grid, print a single line containing "NO". Otherwise, print a single line containing "YES", followed by $$$n$$$ lines each containing $$$m$$$ integers, which describe the final state of the grid. This final grid should be obtainable from the initial one by applying some operations (possibly zero). If there are multiple possible answers, you may print any of them.

NoteIn the first test case, we can obtain the resulting grid by increasing the number in row $$$2$$$, column $$$3$$$ once. Both of the cells that contain $$$1$$$ have exactly one neighbor that is greater than zero, so the grid is good. Many other solutions exist, such as the grid $$$$$$0\;1\;0\;0$$$$$$ $$$$$$0\;2\;1\;0$$$$$$ $$$$$$0\;0\;0\;0$$$$$$ All of them are accepted as valid answers.In the second test case, it is impossible to make the grid good.In the third test case, notice that no cell has a number greater than zero on it, so the grid is automatically good.

object B {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val as = Array.fill(n)(nextInts(m))
      val sln = Array.fill(n, m)(4)
      for (i <- 1 to (m - 2)) {
        sln(0)(i) = 3
        sln(n - 1)(i) = 3
      }
      for (j <- 1 to (n - 2)) {
        sln(j)(0) = 3
        sln(j)(m - 1) = 3
      }
      sln(0)(0) = 2
      sln(0)(m - 1) = 2
      sln(n - 1)(0) = 2
      sln(n - 1)(m - 1) = 2

      var ok = true
      for (i <- 0 until n) {
        for (j <- 0 until m) {
          if (as(i)(j) > sln(i)(j)) ok = false
        }
      }

      if (ok) {
        out.println("YES")
        sln.foreach(row => out.println(row.mkString(" ")))
      } else {
        out.println("NO")
      }
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val base        = if (n == 1 || m == 1) 3 else 4

    var check = true
    val b = (0 until n).map { i =>
      val input = readLine().split(" ").map(_.toInt)

      val row = (0 until m).map(j => base - (if (i == 0 || i == n - 1) 1 else 0) - (if (j == 0 || j == m - 1) 1 else 0))

      check &&= input.zip(row).forall { case (x, y) => x <= y }

      row
    }

    if (check) {
      println("YES")
      println(b.map(_.mkString(" ")).mkString("\n"))
    } else println("NO")
  }
}


Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the $$$i$$$-th of them will start during the $$$x_i$$$-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes $$$x_1, x_2, \dots, x_n$$$, so he will be awake during each of these minutes (note that it does not matter if his alarm clock will ring during any other minute).Ivan can choose two properties for the alarm clock — the first minute it will ring (let's denote it as $$$y$$$) and the interval between two consecutive signals (let's denote it by $$$p$$$). After the clock is set, it will ring during minutes $$$y, y + p, y + 2p, y + 3p$$$ and so on.Ivan can choose any minute as the first one, but he cannot choose any arbitrary value of $$$p$$$. He has to pick it among the given values $$$p_1, p_2, \dots, p_m$$$ (his phone does not support any other options for this setting).So Ivan has to choose the first minute $$$y$$$ when the alarm clock should start ringing and the interval between two consecutive signals $$$p_j$$$ in such a way that it will ring during all given minutes $$$x_1, x_2, \dots, x_n$$$ (and it does not matter if his alarm clock will ring in any other minutes).Your task is to tell the first minute $$$y$$$ and the index $$$j$$$ such that if Ivan sets his alarm clock with properties $$$y$$$ and $$$p_j$$$ it will ring during all given minutes $$$x_1, x_2, \dots, x_n$$$ or say that it is impossible to choose such values of the given properties. If there are multiple answers, you can print any.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 3 \cdot 10^5, 1 \le m \le 3 \cdot 10^5$$$) — the number of events and the number of possible settings for the interval between signals. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^{18}$$$), where $$$x_i$$$ is the minute when $$$i$$$-th event starts. It is guaranteed that all $$$x_i$$$ are given in increasing order (i. e. the condition $$$x_1 < x_2 < \dots < x_n$$$ holds). The third line of the input contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_j \le 10^{18}$$$), where $$$p_j$$$ is the $$$j$$$-th option for the interval between two consecutive signals.

If it's impossible to choose such values $$$y$$$ and $$$j$$$ so all constraints are satisfied, print "NO" in the first line. Otherwise print "YES" in the first line. Then print two integers $$$y$$$ ($$$1 \le y \le 10^{18}$$$) and $$$j$$$ ($$$1 \le j \le m$$$) in the second line, where $$$y$$$ is the first minute Ivan's alarm clock should start ringing and $$$j$$$ is the index of the option for the interval between two consecutive signals (options are numbered from $$$1$$$ to $$$m$$$ in the order they are given input). These values should be chosen in such a way that the alarm clock will ring during all given minutes $$$x_1, x_2, \dots, x_n$$$. If there are multiple answers, you can print any.

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 java.util.Arrays.sort

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

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

  def solve(): Unit = {
    val N, M = ni()
    val X = nal(N)
    val P = nal(M)
    val D = Array.ofDim[Long](N - 1)
    REP(N -1) { i =>
      D(i) = X(i + 1) - X(i)
    }

    debug(D)
    val g = gcd(D)
    debug(s"gcd:$g")

    REP(M) { i =>
      if (g % P(i) == 0) {
        out.println("YES")
        val y = X(0) // X0より手前から始める理由がない
        out.println(s"$y ${i+1}")
        return
      }
    }

    out.println("NO")
  }

  def gcd(a: Long, b: Long): Long = {
    if (b == 0) a
    else gcd(b, a % b)
  }

  def gcd(as: Array[Long]): Long = {
    var res = as(0)
    REP(as.length - 1, 1) { i =>
      res = gcd(res, as(i))
    }
    res
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


There are $$$n$$$ houses numbered from $$$1$$$ to $$$n$$$ on a circle. For each $$$1 \leq i \leq n - 1$$$, house $$$i$$$ and house $$$i + 1$$$ are neighbours; additionally, house $$$n$$$ and house $$$1$$$ are also neighbours.Initially, $$$m$$$ of these $$$n$$$ houses are infected by a deadly virus. Each morning, Cirno can choose a house which is uninfected and protect the house from being infected permanently.Every day, the following things happen in order:  Cirno chooses an uninfected house, and protect it permanently.  All uninfected, unprotected houses which have at least one infected neighbor become infected. Cirno wants to stop the virus from spreading. Find the minimum number of houses that will be infected in the end, if she optimally choose the houses to protect.Note that every day Cirno always chooses a house to protect before the virus spreads. Also, a protected house will not be infected forever.

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. Description of test cases follows. The first line of each test case consists of two positive integers $$$n, m$$$ ($$$5 \leq n \leq 10^9$$$, $$$1 \leq m \leq \min(n, 10^5)$$$) — the number of houses on the circle, and the number of houses that are initially infected.  The second line of each test case consists of $$$m$$$ distinct positive integers $$$a_1, a_2, \cdots , a_m$$$ ($$$1 \leq a_i \leq n$$$) — the indices of the houses infected initially. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output an integer on a separate line, which is the minimum number of infected houses in the end.

NoteIn the first test case:At the start of the first day, house $$$3$$$, $$$6$$$, $$$8$$$ are infected. Choose house $$$2$$$ to protect.At the start of the second day, house $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, $$$7$$$, $$$8$$$, $$$9$$$ are infected. Choose house $$$10$$$ to protect.At the start of the third day, no more houses are infected.In the second test case:At the start of the first day, house $$$2$$$, $$$5$$$ are infected. Choose house $$$1$$$ to protect.At the start of the second day, house $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$ are infected. No more available houses can be protected.

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) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val m = tokenizer.nextToken().toInt
      val A = new Array[Long](m)
      tokenizer = new StringTokenizer(input.readLine())
      for (i <- 0 until m) {
        A(i) = tokenizer.nextToken().toInt
      }
      val B = A.sorted
      val C = new Array[Long](m)
      for (i <- 0 until m-1) {
        C(i) = B(i+1) - B(i) - 1
      }
      C(m-1) = n - B.last + B.head - 1
      val D = C.sorted.reverse
      var cou:Long = 0
      for (i <- 0 until D.length){
        cou += {if (D(i)-4*i > 1) D(i) - 4*i - 1 else if (D(i)-4*i == 1) 1 else 0}
      }
      println(n-cou)
    }
  }
}