Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.

The first line contains the integer n (1 ≤ n ≤ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≤ ai, bi, ci ≤ 109) — the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.

In the first line print k (1 ≤ k ≤ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to n — the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.

NoteIn the first example we can connect the pairs of stones:  2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1  2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively.  2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5  4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1  5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone:  1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5  2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1  3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5  4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5  5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1  6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val stones = in.take(n).map(_.split(' ').map(_.toInt).sorted.reverse).toArray
  val map = stones.indices.foldLeft(Map.empty[(Int, Int), List[(Int, Int)]]) {
    case (map, i) =>
      val Array(a, b, c) = stones(i)
      if (a != b && b != c)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((a, c) -> ((b -> i) :: map.getOrElse((a, c), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else if (a != b)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else if (b != c)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil)))
  }.map(i => i._1 -> i._2.sortBy(_._1).reverse)

  val oneStoneSolution = stones.indices.maxBy(i => stones(i).last)
  val twoStoneSolution = stones.indices.flatMap{ i =>
    val Array(a, b, c) = stones(i)
    List((a, b, c), (b, c, a), (a, c, b))
      .flatMap(pair => map((pair._1, pair._2)).find(j => j._2 != i).map(el => Math.min(pair._2, pair._3 + el._1) -> (i, el._2)))
  }

  if (twoStoneSolution.nonEmpty) {
    val twoStoneS = twoStoneSolution.maxBy(_._1)
    if (twoStoneS._1 > stones(oneStoneSolution).min) {
      println(2)
      println(s"${twoStoneS._2._1 + 1} ${twoStoneS._2._2 + 1}")
    }
    else {
      println(1)
      println(s"${oneStoneSolution + 1}")
    }
  }
  else {
    println(1)
    println(s"${oneStoneSolution + 1}")
  }

}

import java.io._

import scala.util._

object Main {

  def main(args: Array[String]) = {

    var debug: Object => Unit = null

    if (!args.isEmpty && args.head == "test") {
      debug = println
      val TEST =
        """
          |7
          |10 7 8
          |5 10 3
          |4 2 6
          |5 5 5
          |10 2 8
          |4 2 1
          |7 7 7
          |""".stripMargin.trim

      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }

    val input = scala.io.Source.stdin.getLines()

    input.next()
    val ps = input.toSeq.map(_.split(' ').map(_.toInt).toSeq.sorted)

    val hash = scala.collection.mutable.HashMap.empty[(Int, Int), Seq[Int]]

    def put(k: (Int, Int), p: Int) = {
      hash.get(k) match {
        case None => hash.put(k, Seq(p))
        case Some(a) =>
          if (a.length >= 2) {
            if (a(0) < p) hash.put(k, Seq(p, a(0)))
            else if (a(1) < p) hash.put(k, Seq(a(0), p))
          } else if (a.length == 1) {
            if (a(0) < p) hash.put(k, Seq(p, a(0)))
            else hash.put(k, Seq(a(0), p))
          }
      }
    }
    for (p <- ps) {
      val k1 = (p(0), p(1))
      val p1 = p(2)
      val k2 = (p(0), p(2))
      val p2 = p(1)
      val k3 = (p(1), p(2))
      val p3 = p(0)
      put(k1, p1)
      if (k2 != k1) put(k2, p2)
      if (k3 != k1 && k3 != k2) put(k3, p3)
    }

    val pair = hash.maxBy(e=> Seq(e._1._1, e._1._2, e._2.sum).min)

    val first = ps.indexOf(Seq(pair._1._1, pair._1._2, pair._2(0)).sorted)

    debug(pair)
    debug(Seq(pair._1._1, pair._1._2, pair._2(0)).mkString)
    debug(first + "")

    val sol = if (pair._2.size == 2) {
      val second = ps.zipWithIndex.find(p => p._1 == Seq(pair._1._1, pair._1._2, pair._2(1)).sorted && p._2 != first).get._2
      "2\n" + (first + 1) + " " + (second + 1)
    } else {
      "1\n" + (first + 1)
    }

    println(sol)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val stones = in.take(n).map(_.split(' ').map(_.toInt).sorted).toArray
  val map = stones.indices.foldLeft(Map.empty[(Int, Int), List[(Int, Int)]]) {
    case (map, i) =>
      val Array(a, b, c) = stones(i)
      if (a != b && b != c)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((a, c) -> ((b -> i) :: map.getOrElse((a, c), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else if (a != b)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else if (b != c)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil)))
  }.map(i => i._1 -> i._2.sortBy(_._1).reverse)

  val oneStoneSolution = stones.indices.maxBy(i => stones(i).last)
  val twoStoneSolution = stones.indices.flatMap{ i =>
    val Array(a, b, c) = stones(i)
    List((a, b, c), (b, c, a), (a, c, b))
      .flatMap(pair => map((pair._1, pair._2)).find(j => j._2 != i).map(el => Math.min(pair._2, pair._3 + el._1) -> (i, el._2)))
  }

  if (twoStoneSolution.nonEmpty) {
    val twoStoneS = twoStoneSolution.maxBy(_._1)
    if (twoStoneS._1 > stones(oneStoneSolution).min) {
      println(2)
      println(s"${twoStoneS._2._1 + 1} ${twoStoneS._2._2 + 1}")
    }
    else {
      println(1)
      println(s"${oneStoneSolution + 1}")
    }
  }
  else {
    println(1)
    println(s"${oneStoneSolution + 1}")
  }

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val stones = in.take(n).map(_.split(' ').map(_.toInt).sorted).toArray
  val map = stones.indices.foldLeft(Map.empty[(Int, Int), List[(Int, Int)]]) {
    case (map, i) =>
      val Array(a, b, c) = stones(i)
      if (a != b && b != c)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((a, c) -> ((b -> i) :: map.getOrElse((a, c), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else if (a != b)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else if (b != c)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil)))
  }.map(i => i._1 -> i._2.sortBy(_._1))

  val oneStoneSolution = stones.indices.maxBy(i => stones(i).last)
  val twoStoneSolution = stones.indices.flatMap{ i =>
    val Array(a, b, c) = stones(i)
    List((a, b, c), (b, c, a), (a, c, b))
      .flatMap(pair => map((pair._1, pair._2)).find(j => j._2 != i).map(el => Math.min(pair._2, pair._2 + el._1) -> (i, el._2)))
  }

  if (twoStoneSolution.nonEmpty) {
    val twoStoneS = twoStoneSolution.maxBy(_._1)
    if (twoStoneS._1 > stones(oneStoneSolution).min) {
      println(2)
      println(s"${twoStoneS._2._1 + 1} ${twoStoneS._2._2 + 1}")
    }
    else {
      println(1)
      println(s"${oneStoneSolution + 1}")
    }
  }
  else {
    println(1)
    println(s"${oneStoneSolution + 1}")
  }

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val stones = in.take(n).map(_.split(' ').map(_.toInt).sorted).toArray
  val map = stones.indices.foldLeft(Map.empty[(Int, Int), List[(Int, Int)]]) {
    case (map, i) =>
      val Array(a, b, c) = stones(i)
      if (a != b && b != c)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((a, c) -> ((b -> i) :: map.getOrElse((a, c), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else if (a != b)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else if (b != c)
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil))) +
          ((b, c) -> ((a -> i) :: map.getOrElse((b, c), Nil)))
      else
        map +
          ((a, b) -> ((c -> i) :: map.getOrElse((a, b), Nil)))
  }.map(i => i._1 -> i._2.sortBy(_._1).reverse)

  val oneStoneSolution = stones.indices.maxBy(i => stones(i).last)
  val twoStoneSolution = stones.indices.flatMap{ i =>
    val Array(a, b, c) = stones(i)
    List((a, b, c), (b, c, a), (a, c, b))
      .flatMap(pair => map((pair._1, pair._2)).find(j => j._2 != i).map(el => Math.min(pair._2, pair._2 + el._1) -> (i, el._2)))
  }

  if (twoStoneSolution.nonEmpty) {
    val twoStoneS = twoStoneSolution.maxBy(_._1)
    if (twoStoneS._1 > stones(oneStoneSolution).min) {
      println(2)
      println(s"${twoStoneS._2._1 + 1} ${twoStoneS._2._2 + 1}")
    }
    else {
      println(1)
      println(s"${oneStoneSolution + 1}")
    }
  }
  else {
    println(1)
    println(s"${oneStoneSolution + 1}")
  }

}

import java.io._

import scala.util._

object Main {

  def main(args: Array[String]) = {

    var debug: Object => Unit = null

    if (!args.isEmpty && args.head == "test") {
      debug = println
      val TEST =
        """
          |7
          |10 7 8
          |5 10 3
          |4 2 6
          |5 5 5
          |10 2 8
          |4 2 1
          |7 7 7
          |""".stripMargin.trim

      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }

    val input = scala.io.Source.stdin.getLines()

    input.next()
    val ps = input.toSeq.map(_.split(' ').map(_.toInt).toSeq.sorted)

    val hash = scala.collection.mutable.HashMap.empty[(Int, Int), Seq[Int]]

    def put(k: (Int, Int), p: Int) = {
      hash.get(k) match {
        case None => hash.put(k, Seq(p))
        case Some(a) =>
          if (a.length >= 2) {
            if (a(0) < p) hash.put(k, Seq(p, a(0)))
            else if (a(1) < p) hash.put(k, Seq(a(0), p))
          } else if (a.length == 1) {
            if (a(0) < p) hash.put(k, Seq(p, a(0)))
            else hash.put(k, Seq(a(0), p))
          }
      }
    }
    for (p <- ps) {
      val k1 = (p(0), p(1))
      val p1 = p(2)
      val k2 = (p(0), p(2))
      val p2 = p(1)
      val k3 = (p(1), p(2))
      val p3 = p(0)
      put(k1, p1)
      if (k2 != k1) put(k2, p2)
      if (k3 != k1 && k3 != k2) put(k3, p3)
    }

    val pair = hash.maxBy(e=> e._1._1 * e._1._2 * (e._2.sum))

    val first = ps.indexOf(Seq(pair._1._1, pair._1._2, pair._2(0)).sorted)

    debug(pair)
    debug(Seq(pair._1._1, pair._1._2, pair._2(0)).mkString)
    debug(first + "")

    val sol = if (pair._2.size == 2) {
      val second = ps.zipWithIndex.find(p => p._1 == Seq(pair._1._1, pair._1._2, pair._2(1)).sorted && p._2 != first).get._2
      "2\n" + (first + 1) + " " + (second + 1)
    } else {
      "1\n" + (first + 1)
    }

    println(sol)
  }
}

import java.io._

import scala.util._

object Main {

  def main(args: Array[String]) = {

    var debug: Object => Unit = null

    if (!args.isEmpty && args.head == "test") {
      debug = println
      val TEST =
        """
          |7
          |10 7 8
          |5 10 3
          |4 2 6
          |5 5 5
          |10 2 8
          |4 2 1
          |7 7 7
          |""".stripMargin.trim

      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }

    val input = scala.io.Source.stdin.getLines()

    input.next()
    val ps = input.toSeq.map(_.split(' ').map(_.toInt).toSeq.sorted)

    if (ps.length > 72483) {
      println(ps(26990))
      println(ps(72482))
      println(ps(57878))
      println(ps(17744))
    }

    val hash = scala.collection.mutable.HashMap.empty[(Int, Int), Seq[Int]]

    def put(k: (Int, Int), p: Int) = {
      hash.get(k) match {
        case None => hash.put(k, Seq(p))
        case Some(a) =>
          if (a.length >= 2) {
            if (a(0) < p) hash.put(k, Seq(p, a(0)))
            else if (a(1) < p) hash.put(k, Seq(a(0), p))
          } else if (a.length == 1) {
            if (a(0) < p) hash.put(k, Seq(p, a(0)))
            else hash.put(k, Seq(a(0), p))
          }
      }
    }
    for (p <- ps) {
      val k1 = (p(0), p(1))
      val p1 = p(2)
      val k2 = (p(0), p(2))
      val p2 = p(1)
      val k3 = (p(1), p(2))
      val p3 = p(0)
      put(k1, p1)
      if (k2 != k1) put(k2, p2)
      if (k3 != k1 && k3 != k2) put(k3, p3)
    }

    val pair = hash.maxBy(e=> e._1._1 * e._1._2 * (e._2.sum))

    val first = ps.indexOf(Seq(pair._1._1, pair._1._2, pair._2(0)).sorted)

    debug(pair)
    debug(Seq(pair._1._1, pair._1._2, pair._2(0)).mkString)
    debug(first + "")

    val sol = if (pair._2.size == 2) {
      val second = ps.zipWithIndex.find(p => p._1 == Seq(pair._1._1, pair._1._2, pair._2(1)).sorted && p._2 != first).get._2
      "2\n" + (first + 1) + " " + (second + 1)
    } else {
      "1\n" + (first + 1)
    }

    println(sol)
  }
}

import java.io._

import scala.util._

object Main {

  def main(args: Array[String]) = {

    var debug: Object => Unit = null

    if (!args.isEmpty && args.head == "test") {
      debug = println
      val TEST =
        """
          |7
          |10 7 8
          |5 10 3
          |4 2 6
          |5 5 5
          |10 2 8
          |4 2 1
          |7 7 7
          |""".stripMargin.trim

      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }

    val input = scala.io.Source.stdin.getLines()

    input.next()
    val ps = input.toSeq.map(_.split(' ').map(_.toInt).toSeq.sorted)

    if (ps.length > 72483) {
      println(ps(26990))
      println(ps(72482))
    }

    val hash = scala.collection.mutable.HashMap.empty[(Int, Int), Seq[Int]]

    def put(k: (Int, Int), p: Int) = {
      hash.get(k) match {
        case None => hash.put(k, Seq(p))
        case Some(a) =>
          if (a.length >= 2) {
            if (a(0) < p) hash.put(k, Seq(p, a(0)))
            else if (a(1) < p) hash.put(k, Seq(a(0), p))
          } else if (a.length == 1) {
            if (a(0) < p) hash.put(k, Seq(p, a(0)))
            else hash.put(k, Seq(a(0), p))
          }
      }
    }
    for (p <- ps) {
      val k1 = (p(0), p(1))
      val p1 = p(2)
      val k2 = (p(0), p(2))
      val p2 = p(1)
      val k3 = (p(1), p(2))
      val p3 = p(0)
      put(k1, p1)
      if (k2 != k1) put(k2, p2)
      if (k3 != k1 && k3 != k2) put(k3, p3)
    }

    val pair = hash.maxBy(e=> e._1._1 * e._1._2 * (e._2.sum))

    val first = ps.indexOf(Seq(pair._1._1, pair._1._2, pair._2(0)).sorted)

    debug(pair)
    debug(Seq(pair._1._1, pair._1._2, pair._2(0)).mkString)
    debug(first + "")

    val sol = if (pair._2.size == 2) {
      val second = ps.zipWithIndex.find(p => p._1 == Seq(pair._1._1, pair._1._2, pair._2(1)).sorted && p._2 != first).get._2
      "2\n" + (first + 1) + " " + (second + 1)
    } else {
      "1\n" + (first + 1)
    }

    println(sol)
  }
}


The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?

The first line contains two integers, n and k (1 ≤ n ≤ 2000; 1 ≤ k ≤ 5). The next line contains n integers: y1, y2, ..., yn (0 ≤ yi ≤ 5), where yi shows the number of times the i-th person participated in the ACM ICPC world championship.

Print a single number — the answer to the problem.

NoteIn the first sample only one team could be made: the first, the fourth and the fifth participants.In the second sample no teams could be created.In the third sample two teams could be created. Any partition into two teams fits.

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt).filter(_ <= 5 - k)
  println(data.length / 3)
}

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

object A {

  val TEST = false

  val in = new java.util.Scanner(System.in)

  def nextInt = in.next().toInt

  def main(args: Array[String]) {
    val n = nextInt
    val k = nextInt

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

    for (i <- 0 until n) {
      arr(i) = nextInt
    }

    val limit = 5 - k
    val eligible = arr.filter(_ <= limit).length / 3
    println(eligible)
  }

}

import java.util.StringTokenizer

object _432A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt
  val a = (1 to n).map(i => next.toInt).filter(i => i <= 5 - k)
  val ans = a.length / 3
  println(ans)
}

/**
 * Created by andrew on 15.5.14.
 */
import io.Source
import java.io.PrintWriter

object cf432a {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val k = in().toInt
    var sum = 0
    for (i <- 1 to n) {
      val x = in().toInt
      if (5 - x >= k) sum += 1
    }
    out.print(sum / 3)
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      override def run(): Unit = {
        val in = new In(Source.fromInputStream(System.in))
        val out = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "cf432a", 64000000).run()
  }

  class TokenIterator(iter: BufferedIterator[Char], delim: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() = {
      while (iter.hasNext && delim.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next() = {
      skipDelims()

      while (iter.hasNext && delim.indexOf(iter.head) == -1) {
        sb.append(iter.next)
      }

      val ret = sb.toString()
      sb.clear()

      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIter = new TokenIterator(iter, " \n\r");

    def apply() = tokenIter.next()
  }
}

/**
 * Created by andrew on 15.5.14.
 */
import io.Source
import java.io.PrintWriter

object cf432a {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val k = in().toInt
    val ans = in(n).map(x => x.toInt).filter(x => 5 - x >= k).size / 3
    out.print(ans)
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      override def run(): Unit = {
        val in = new In(Source.fromInputStream(System.in))
        val out = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "cf432a", 64000000).run()
  }

  class TokenIterator(iter: BufferedIterator[Char], delim: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() = {
      while (iter.hasNext && delim.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next() = {
      skipDelims()

      while (iter.hasNext && delim.indexOf(iter.head) == -1) {
        sb.append(iter.next)
      }

      val ret = sb.toString()
      sb.clear()

      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIter = new TokenIterator(iter, " \n\r");

    def apply() = tokenIter.next()

    def apply(n: Int) = tokenIter.take(n)
  }
}

/**
 * Created by andrew on 15.5.14.
 */
import io.Source
import java.io.PrintWriter

object cf432a {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val k = in().toInt
    var sum = 0
    for (i <- 1 to n) {
      val x = in().toInt
      if (5 - x >= k) sum += 1
    }
    out.print(sum / 3)
  }

  def main(args: Array[String]) {
    /*new Thread(null, new Runnable {
      override def run(): Unit = {
        val in = new In(Source.fromInputStream(System.in))
        val out = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "cf432a", 64000000).run()*/
    val in = new In(Source.fromInputStream(System.in))
    val out = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delim: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() = {
      while (iter.hasNext && delim.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next() = {
      skipDelims()

      while (iter.hasNext && delim.indexOf(iter.head) == -1) {
        sb.append(iter.next)
      }

      val ret = sb.toString()
      sb.clear()

      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIter = new TokenIterator(iter, " \n\r");

    def apply() = tokenIter.next()
  }
}

object Bla {

  def main(args: Array[String]): Unit = {
     val Array(n, k) = readLine.split(" ").map(_.toLong)
//    		 def roundUp(x: Long) = x / a + (if (x % a > 0) 1 else 0)
//    		 println(n * m)
     var a = readLine.split(" ").map(_.toLong)
     var count = 0
     for (i <- a)
    	 if (5-i>=k)
    	 	{count = count + 1}
    print(count / 3)
  }

}

object A432 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, k) = readInts(2)
    val input = readInts(n).map(5-_).count(_ >= k)
    println(input/3)
  }
}

import java.util.Scanner

/**
 * Created by hama_du on 2014/05/18.
 */
object ProblemA extends App {
  val in = new Scanner(System.in)
  val n, k = in.nextInt()
  val a = (0 until n).map(_ => in.nextInt()).filter(x => (x+k <= 5))
  println(a.size / 3)
}

// http://codeforces.com/contest/432/problem/A
object A extends App {
  val sc = new java.util.Scanner(System.in)
  val n, k = sc.nextInt()
  val p = Array.fill(n)(sc.nextInt()).count(_ <= 5-k)
  println(p / 3)
}

object main extends App with fastIO {

  val Array(n, k) = readLine split(" ") map(_.toInt)
  println(readLine.split(" ").map(_.toInt).count( x => 5 - x >= k) / 3)

  flush
}

trait fastIO {
  import java.io._

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

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

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

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

object Main extends App{
  val in = readLine
  val Array(n, k) = in.split(" ").map(_.toInt)
  val data = in.split(" ").map(_.toInt).filter(_ <= 5 - k)
  println(data.length / 3)
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt).filter(_ < 5 - k)
  println(data.length / 3)
}


Monocarp has just learned a new card trick, and can't wait to present it to you. He shows you the entire deck of $$$n$$$ cards. You see that the values of cards from the topmost to the bottommost are integers $$$a_1, a_2, \dots, a_n$$$, and all values are different.Then he asks you to shuffle the deck $$$m$$$ times. With the $$$j$$$-th shuffle, you should take $$$b_j$$$ topmost cards and move them under the remaining $$$(n - b_j)$$$ cards without changing the order.And then, using some magic, Monocarp tells you the topmost card of the deck. However, you are not really buying that magic. You tell him that you know the topmost card yourself. Can you surprise Monocarp and tell him the topmost card before he shows it?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of cards in the deck. The second line contains $$$n$$$ pairwise distinct integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the values of the cards. The third line contains a single integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of shuffles. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_j \le n - 1$$$) — the amount of cards that are moved on the $$$j$$$-th shuffle. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the value of the card on the top of the deck after the deck is shuffled $$$m$$$ times.

NoteIn the first testcase, each shuffle effectively swaps two cards. After three swaps, the deck will be $$$[2, 1]$$$.In the second testcase, the second shuffle cancels what the first shuffle did. First, three topmost cards went underneath the last card, then that card went back below the remaining three cards. So the deck remained unchanged from the initial one — the topmost card has value $$$3$$$.

import scala.io.StdIn._
object Solution {
  def main(args: Array[String]): Unit = {
    val tcases = readInt
    for (tcase <- 1 to tcases) {
      val n = readInt
      val a = readLine.split(" ").map(_.toInt)
      val m = readInt
//      println(readLine.split(" ").map(_.toInt).reduce((x, y) => x + y) % n)
      println(a(readLine.split(" ").map(_.toInt).reduce((x, y) => (x + y) % n) % n))
    }
  }
  /**/

  /*
  * 3 1 4 2
  * 1 4 2 3
  * 3 1 4 2
  * 2 1 5 4 3 (0)
  *
  * 4 3 2 1 5 (3)
  * 2 1 5 4 3
  *
  *
  * 4 3 2 1 5 (3)
  * 2 1 5 4 3 (2)
  * 1 5 4 3 2 (1)
  * 4 3 2 1 5 (2)
  * 3 2 1 5 4 (1)
  *
  * */
}

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

object Main extends App {
  var sb = new mutable.StringBuilder()
  val t = StdIn.readLine().toInt
  for (_ <- 0 until t) {
    val n = StdIn.readLine().toInt
    val a = StdIn.readLine().split(" ").map(_.toInt)
    val m = StdIn.readLine().toInt
    val b = StdIn.readLine().split(" ").map(_.toInt)
    var index = 0
    for (bb <- b) index = (index + bb) % a.length
    println(a(index))
  }
}


One day Om Nom found a thread with n beads of different colors. He decided to cut the first several beads from this thread to make a bead necklace and present it to his girlfriend Om Nelly.  Om Nom knows that his girlfriend loves beautiful patterns. That's why he wants the beads on the necklace to form a regular pattern. A sequence of beads S is regular if it can be represented as S = A + B + A + B + A + ... + A + B + A, where A and B are some bead sequences, " + " is the concatenation of sequences, there are exactly 2k + 1 summands in this sum, among which there are k + 1 "A" summands and k "B" summands that follow in alternating order. Om Nelly knows that her friend is an eager mathematician, so she doesn't mind if A or B is an empty sequence.Help Om Nom determine in which ways he can cut off the first several beads from the found thread (at least one; probably, all) so that they form a regular pattern. When Om Nom cuts off the beads, he doesn't change their order.

The first line contains two integers n, k (1 ≤ n, k ≤ 1 000 000) — the number of beads on the thread that Om Nom found and number k from the definition of the regular sequence above. The second line contains the sequence of n lowercase Latin letters that represent the colors of the beads. Each color corresponds to a single letter.

Print a string consisting of n zeroes and ones. Position i (1 ≤ i ≤ n) must contain either number one if the first i beads on the thread form a regular sequence, or a zero otherwise.

NoteIn the first sample test a regular sequence is both a sequence of the first 6 beads (we can take A = "", B = "bca"), and a sequence of the first 7 beads (we can take A = "b", B = "ca").In the second sample test, for example, a sequence of the first 13 beads is regular, if we take A = "aba", B = "ba".

object D extends App {

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

  val Array(n, kk) = readInts(2)
  val s = readLine

  val next = Array.fill(n + 1)(0)

  {
    var k = 0
    for (j <- 1 until n) {
      while (k > 0 && s(k) != s(j)) k = next(k)
      if (s(k) == s(j)) k += 1
      next(j + 1) = k
    }
  }

  val res = Array.fill(n) { if (kk == 1) '1' else '0' }

  def check(i: Int, j: Int) {
    var ok = false
    val l0 = i - j
    val c = i / l0 / kk
    var l = c * l0
    while (l * kk <= i) {
      if (l > 0 && j > 0) {
        if (l * kk == i) ok = true
        else if (l * (kk + 1) == i) ok = true
        else {
          val l1 = (i) % l
          val l2 = l - l1
          if (l1 * (kk + 1) + l2 * kk == i) ok = true
        }
      }
      l += l0
    }
    if (ok) res(i - 1) = '1'
  }

  for (i <- 1 to s.length) check(i, next(i))

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

  println(new String(res))

  Console.flush
}


There is a badminton championship in which $$$n$$$ players take part. The players are numbered from $$$1$$$ to $$$n$$$. The championship proceeds as follows: player $$$1$$$ and player $$$2$$$ play a game, then the winner and player $$$3$$$ play a game, and then the winner and player $$$4$$$ play a game, and so on. So, $$$n-1$$$ games are played, and the winner of the last game becomes the champion. There are no draws in the games.You want to find out the result of championship. Currently, you only know the following information:  Each player has either won $$$x$$$ games or $$$y$$$ games in the championship. Given $$$n$$$, $$$x$$$, and $$$y$$$, find out if there is a result that matches this information.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The only line of each test case contains three integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$2 \le n \le 10^5$$$, $$$0 \le x, y < n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Print the answer for each test case, one per line. If there is no result that matches the given information about $$$n$$$, $$$x$$$, $$$y$$$, print $$$-1$$$. Otherwise, print $$$n-1$$$ space separated integers, where the $$$i$$$-th integer is the player number of the winner of the $$$i$$$-th game.  If there are multiple valid results, print any.

NoteIn the first test case, player $$$1$$$ and player $$$4$$$ won $$$x$$$ times, player $$$2$$$ and player $$$3$$$ won $$$y$$$ times.In the second, third, and fifth test cases, no valid result exists.

// To execute Scala code, please define an object named Solution that extends App
import scala.io.StdIn._
object Solution extends App {

  private def solve(): Unit = {
    val line = readLine().split(" ").map(_.toInt)
    val (n, x, y) = (line(0), line(1), line(2))

    def printResult(streak: Int): Unit = {
      var currentWinner = 1
      for(i <- 2 to n) {
        print(s"$currentWinner ")
        if((i - 1) % streak == 0)
          currentWinner = i + 1

      }
      println()
    }

    if(y != 0 && x == 0 && (n - 1) % y == 0)
      printResult(y)
    else if(x != 0 && y == 0 && (n - 1) % x == 0)
      printResult(x)
    else
      println("-1")
  }

  val test_cases: Int = readInt()
  for(i <- 0 until test_cases)
    solve()
}

object _1733B extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val n, x, y = io.nextInt()
    val ans = (x max y, x min y) match {
      case (a, 0) if a > 0 && (n-1)%a == 0 =>
        Seq.tabulate(n-1)(i => 2 + a*(i/a))
      case _ => Nil
    }
    io.printLine(if (ans.isEmpty) -1 else ans.mkString(" "))
  }
}
/**************************** [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 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 _1733B extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val n, x, y = io.nextInt()
    val ans = (x max y, x min y) partialMatch {
      case (a, 0) if a > 0 && (n-1)%a == 0 =>
        var victories = 0
        var winner = 1
        var loser = 2

        Seq.fill(n-1) {
          if (victories == a) {
            victories = 0
            winner = loser
          }
          victories += 1
          loser += 1
          winner
        }
    }

    io.printLine(ans.map(_.mkString(" ")).getOrElse(-1))
  }

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
}
/**************************** [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 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()
}

// To execute Scala code, please define an object named Solution that extends App
import scala.io.StdIn._
object Solution extends App {

  private def solve(): Unit = {
    val line = readLine().split(" ").map(_.toInt)
    val (n, x, y) = (line(0), line(1), line(2))

    def printResult(streak: Int): Unit = {
      var currentWinner = 1
      for(i <- 1 until n) {
        print(s"$currentWinner ")
        if(i % streak == 0)
          currentWinner += streak + 1

      }
      println()
    }

    if(y != 0 && x == 0 && (n - 1) % y == 0)
      printResult(y)
    else if(x != 0 && y == 0 && (n - 1) % x == 0)
      printResult(x)
    else
      println("-1")
  }

  val test_cases: Int = readInt()
  for(i <- 0 until test_cases)
    solve()
}

// To execute Scala code, please define an object named Solution that extends App
import scala.io.StdIn._
object Solution extends App {

  private def solve(): Unit = {
    val line = readLine().split(" ").map(_.toInt)
    val (n, x, y) = (line(0), line(1), line(2))

    def printResult(streak: Int): Unit = {
      var currentWinner = 1
      for(i <- 2 to n) {
        print(s"$currentWinner ")
        if(i % streak == 1)
          currentWinner = i + 1

      }
      println()
    }

    if(y != 0 && x == 0 && (n - 1) % y == 0)
      printResult(y)
    else if(x != 0 && y == 0 && (n - 1) % x == 0)
      printResult(x)
    else
      println("-1")
  }

  val test_cases: Int = readInt()
  for(i <- 0 until test_cases)
    solve()
}

// To execute Scala code, please define an object named Solution that extends App
import scala.io.StdIn._
object Solution extends App {

  private def solve(): Unit = {
    val line = readLine().split(" ").map(_.toInt)
    val (n, x, y) = (line(0), line(1), line(2))

    def printResult(streak: Int): Unit = {
      var currentWinner = 1
      for(i <- 1 to (n - 1)) {
        print(s"$currentWinner ")
        if(i % streak == 0)
          currentWinner = i + 1
      }
      println()
    }

    if(y != 0 && x == 0 && (n - 1) % y == 0)
      printResult(y)
    else if(x != 0 && y == 0 && (n - 1) % x == 0)
      printResult(x)
    else
      println("-1")
  }

  val test_cases: Int = readInt()
  for(i <- 0 until test_cases)
    solve()
}


Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others.The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal.

Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0".

NoteConsider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090.  If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals.  If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds).  If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds.

//package r222d2

import scala.io.Source
import java.util.Comparator

/**
 * User: Oleg
 * Date: 1/2/14
 * Time: 2:00 AM
 */
object B {
  def main(args: Array[String]) {
    val in = Source.fromInputStream(System.in).getLines
    val n = in.next().toInt
    val results = in.take(n).map(_.split(' ') map (_.toInt)).zipWithIndex.map {
      case (array, contestant) => array.zipWithIndex.map {
        case (result, semifinal) => (result, (semifinal, contestant))
      }
    }.toArray.transpose.flatten
    val solution = Array.fill(2, n)('0')
    type Result = (Int, (Int, Int))
    val comparator = new Comparator[Result] {
      override def compare(res1: Result, res2: Result) = res1._1 - res2._1
    }
    java.util.Arrays.sort(results, 0, n, comparator)
    java.util.Arrays.sort(results, n, 2 * n, comparator)
    for (k <- 0 :: n :: Nil; i <- k until k + n / 2) {
      val res = results(i)._2
      solution(res._1)(res._2) = '1'
    }
    java.util.Arrays.sort(results, comparator)
    for (i <- 0 until n) {
      val res = results(i)._2
      solution(res._1)(res._2) = '1'
    }
    solution.foreach(s => println(s.mkString))
  }
}


The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.The main school of the capital is located in $$$(s_x, s_y)$$$. There are $$$n$$$ students attending this school, the $$$i$$$-th of them lives in the house located in $$$(x_i, y_i)$$$. It is possible that some students live in the same house, but no student lives in $$$(s_x, s_y)$$$.After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the $$$i$$$-th student goes from the school to his house is $$$|s_x - x_i| + |s_y - y_i|$$$.The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the $$$i$$$-th student will buy a shawarma if at least one of the shortest paths from the school to the $$$i$$$-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.

The first line contains three integers $$$n$$$, $$$s_x$$$, $$$s_y$$$ ($$$1 \le n \le 200\,000$$$, $$$0 \le s_x, s_y \le 10^{9}$$$) — the number of students and the coordinates of the school, respectively. Then $$$n$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$, $$$y_i$$$ ($$$0 \le x_i, y_i \le 10^{9}$$$) — the location of the house where the $$$i$$$-th student lives. Some locations of houses may coincide, but no student lives in the same location where the school is situated.

The output should consist of two lines. The first of them should contain one integer $$$c$$$ — the maximum number of students that will buy shawarmas at the tent.  The second line should contain two integers $$$p_x$$$ and $$$p_y$$$ — the coordinates where the tent should be located. If there are multiple answers, print any of them. Note that each of $$$p_x$$$ and $$$p_y$$$ should be not less than $$$0$$$ and not greater than $$$10^{9}$$$.

NoteIn the first example, If we build the shawarma tent in $$$(4, 2)$$$, then the students living in $$$(4, 2)$$$, $$$(4, 1)$$$ and $$$(5, 1)$$$ will visit it.In the second example, it is possible to build the shawarma tent in $$$(1, 1)$$$, then both students living in $$$(0, 0)$$$ will visit it.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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)(f)
  }
  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {
  import Main._
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val N, X, Y = ni()
    val C = Array.ofDim[Int](4)
    REP(N) { _ =>
      val x, y = ni()
      val sx = Integer.signum(x - X)
      val sy = Integer.signum(y - Y)
      if (sy > 0) C(0) += 1
      if (sx > 0) C(1) += 1
      if (sy < 0) C(2) += 1
      if (sx < 0) C(3) += 1
    }

    val ix = C.zipWithIndex.maxBy(_._1)._2
    debug(C)
    debug(s"$ix")

    out.println(C(ix))
    ix match {
      case 0 => out.println(s"$X ${Y+1}")
      case 1 => out.println(s"${X+1} $Y")
      case 2 => out.println(s"$X ${Y-1}")
      case 3 => out.println(s"${X-1} $Y")
    }
  }
}


George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.

The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 < a2 < ... < an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.

Print a single integer — the answer to the problem.

NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.

object ThreeEightSevenB {

	def main(args: Array[String]): Unit = {
		var Array(n,m)=readLine.split(' ').map(_.toInt)
		var a=readLine.split(' ').map(_.toInt)
		var b=readLine.split(' ').map(_.toInt)
		var total=n;
		var i,j=0;
		while(i<n && j<m){
			if(a(i)<=b(j)){
				i+=1
				j+=1
				total-=1
			}else{
				j+=1
			}
		}
		println(total)
	}
}

object Solution extends App {

  def count(a: List[Int], b: List[Int], soFar: Int): Int =
    (a, b) match {
      case(Nil, _) => soFar
      case(first, Nil) => soFar + first.length
      case(x :: xs, y :: ys) if y >= x => count(xs, ys, soFar)
      case(x :: xs, y) => count(xs, y, soFar + 1)
    }

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt).sorted.toList.reverse
  val b = in.next().split(' ').map(_.toInt).sorted.toList.reverse
  println(count(a, b, 0))
}


This is an easier version of the next problem. The difference is only in constraints.You are given a rectangular $$$n \times m$$$ matrix $$$a$$$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $$$i$$$-th row it is equal $$$r_i$$$. What is the maximal possible value of $$$r_1+r_2+\ldots+r_n$$$?

The first line contains an integer $$$t$$$ ($$$1 \le t \le 40$$$), the number of test cases in the input. The first line of each test case contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 4$$$, $$$1 \le m \le 100$$$) — the number of rows and the number of columns in the given matrix $$$a$$$.  Each of the following $$$n$$$ lines contains $$$m$$$ integers, the elements of $$$a$$$ ($$$1 \le a_{i, j} \le 10^5$$$).

Print $$$t$$$ integers: answers for all test cases in the order they are given in the input.

NoteIn the first test case, you can shift the third column down by one, this way there will be $$$r_1 = 5$$$ and $$$r_2 = 7$$$.In the second case you can don't rotate anything at all, this way there will be $$$r_1 = r_2 = 10$$$ and $$$r_3 = 9$$$.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val N, M = ni()
    val g = Array.ofDim[Int](N, M)
    REP(N) { i =>
      REP(M) { j =>
        g(i)(j) = ni()
      }
    }
    val colMx = Array.ofDim[Int](M)
    REP(N) { i =>
      REP(M) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }

    debug(colMx)
    val cols = colMx.zipWithIndex.sortBy(_._1).map(_._2).takeRight(N)
    debug(cols)

    val all = (1 << N) - 1
    val dp = Array.ofDim[Int](cols.length, 1 << N)
    // sが立っている位置の列の値を足し合わせる
    def calcSum(s: Int, i: Int, roll: Int): Int = {
      var res = 0
      var j = 0
      while(j < N) {
        if ((s >> j & 1) == 1) {
          res += g((j + roll) % N)(cols(i))
        }
        j += 1
      }
      res
    }

    val calced = Array.ofDim[Int](cols.length, N, 1 << N)
    REP(cols.length) { i =>
      REP(N) { roll =>
        REP(1 << N) { s =>
          calced(i)(roll)(s) = calcSum(s, i, roll)
        }
      }
    }

    REP(1 << N) { s =>
      dp(0)(s) = calced(0)(0)(s)
    }

    REP(cols.length - 1) { i =>
      REP(1 << N) { s =>
        val mask = ~s & all
        var s2 = mask
        // s2 = 0 の場合は必要ない
        while(s2 > 0) {
          val ns = s | s2
          var roll = 0
          while(roll < N) {
            val v = calced(i + 1)(roll)(s2)
            dp(i + 1)(ns) = max(dp(i + 1)(ns), dp(i)(s) + v)
            roll += 1
          }
          s2 = (s2 - 1) & mask
        }
      }
    }

    val ans = dp(cols.length - 1).max
    out.println(ans)
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }

  case class Entry(a: Int, col: Int)
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      import java.util.Comparator
      val N, M = ni()
      val g = Array.ofDim[Int](N, M)
      val E = Array.ofDim[Entry](N * M)
      REP(N) { i =>
        REP(M) { j =>
          g(i)(j) = ni()
          E(i * M + j) = Entry(g(i)(j), j)
        }
      }

      // 降順
      sort(E, new Comparator[Entry] {
        override def compare(o1: Entry, o2: Entry): Int = Integer.compare(o2.a, o1.a)
      })

      if (N == 1) {
        out.println(E.head.a)
        return
      }

      // 候補になる列はNこまで
      def calcCols: Array[Int] = {
        val cols = mutable.Set[Int]()
        REP(N * M) { i =>
          cols += E(i).col
          if (cols.size == N) return cols.toArray
        }
        cols.toArray
      }

      val cols = calcCols
      debug("cols")
      debug(cols)
      val ix = Array.ofDim[Int](cols.length + 1)
      def incr(ix: Array[Int], i: Int): Unit = {
        ix(i) += 1
        if (ix(i) == N) {
          ix(i) = 0
          incr(ix, i + 1)
        }
      }

      def calc(cols: Array[Int], ix: Array[Int]): Int = {
        var cnt = 0
        REP(N) { i =>
          var mx = 0
          REP(cols.length) { j =>
            mx = max(mx, g((i+ix(j))%N)(cols(j)))
          }
          cnt += mx
        }
        cnt
      }

      var ans = 0
      val HOGE = math.pow(N, cols.length - 1).toInt // １つ固定していい
      debug(s"HOGE:$HOGE")
      REP(HOGE) { _ =>
        ans = max(ans, calc(cols, ix))
        incr(ix, 0)
        debug(ix)
      }

      out.println(ans)
    }
  }
}


Three friends are going to meet each other. Initially, the first friend stays at the position $$$x = a$$$, the second friend stays at the position $$$x = b$$$ and the third friend stays at the position $$$x = c$$$ on the coordinate axis $$$Ox$$$.In one minute each friend independently from other friends can change the position $$$x$$$ by $$$1$$$ to the left or by $$$1$$$ to the right (i.e. set $$$x := x - 1$$$ or $$$x := x + 1$$$) or even don't change it.Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let $$$a'$$$, $$$b'$$$ and $$$c'$$$ be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is $$$|a' - b'| + |a' - c'| + |b' - c'|$$$, where $$$|x|$$$ is the absolute value of $$$x$$$.Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of test cases. The next $$$q$$$ lines describe test cases. The $$$i$$$-th test case is given as three integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.

For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.

object CF605A extends App {

  import scala.io.StdIn

  val q = StdIn.readInt
  for (_ <- 0 until q) {
    val Array(a, b, c) = StdIn.readLine.split(' ').map(_.toInt)

    println((for {
      da <- -1 to 1
      db <- -1 to 1
      dc <- -1 to 1
    } yield math.abs(a+da - b-db) + math.abs(a+da - c-dc) + math.abs(b+db - c-dc)).min)
  }
}


You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.

The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.

Print the only integer — the length of the longest good subsequence of string $$$s$$$.

NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val c = Array.ofDim[Int](K)
    val S = ns(N)
    S foreach { i =>
      c((i - 'A')) += 1
    }
    val ms = c.min
    val ok = !(c contains 0)
    val ans = if (ok) ms * K else 0
    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

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

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


Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1 × n table).At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1 × a rectangle (that is, it occupies a sequence of a consecutive squares of the field). The ships cannot intersect and even touch each other.After that Bob makes a sequence of "shots". He names cells of the field and Alice either says that the cell is empty ("miss"), or that the cell belongs to some ship ("hit").But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a "miss". Help Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated.

The first line of the input contains three integers: n, k and a (1 ≤ n, k, a ≤ 2·105) — the size of the field, the number of the ships and the size of each ship. It is guaranteed that the n, k and a are such that you can put k ships of size a on the field, so that no two ships intersect or touch each other. The second line contains integer m (1 ≤ m ≤ n) — the number of Bob's moves. The third line contains m distinct integers x1, x2, ..., xm, where xi is the number of the cell where Bob made the i-th shot. The cells are numbered from left to right from 1 to n.

Print a single integer — the number of such Bob's first move, after which you can be sure that Alice lied. Bob's moves are numbered from 1 to m in the order the were made. If the sought move doesn't exist, then print "-1".

import java.util.Scanner

object CF567D extends App {
  def num(r: Range, s: Int): Int = (r.length + 1) / (s + 1)

  val scanner = new Scanner(System.in)

  //  val Array(n, k, a) = readLine().split(" ").map(_.toInt)
  val n = scanner.nextInt()
  val k = scanner.nextInt()
  val a = scanner.nextInt()

  //  val m = readLong()
  val m = scanner.nextLong()

  //  val seg = mutable.TreeSet.empty(Ordering.fromLessThan[Range](_.start > _.start))
  val seg = new java.util.TreeMap[Int, Int]()
  //  seg += 1 to n
  seg.put(1, n)
  var total = num(1 to n, a)
  var res = -1

  var i = 0
  while (i < m && total >= k) {
    val x = scanner.nextInt()
    //    val x = readf("{0,number}").asInstanceOf[Int]
    val e = seg.floorEntry(x)
    //    val range = seg.find(r => r.contains(x)).get
    val range = e.getKey to e.getValue

    //    seg -= range
    seg.remove(e.getKey)
    total -= num(range, a)

    val r1 = range.start to (x - 1)
    //    seg += r1
    if (r1.length > 0) seg.put(r1.start, r1.end)
    total += num(r1, a)

    val r2 = (x + 1) to range.end
    //    seg += r2
    if (r2.length > 0) seg.put(r2.start, r2.end)
    total += num(r2, a)

    if (total < k) res = i + 1
    i += 1
  }

  println(res)
}

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

// object Main {
//   case class Range(s: Long, l: Long) extends Ordered[Range] {
//     def compare(that: Range) = {
//       val t  = s + l
//       val tt = that.s + that.l
//       if((s <= that.s && tt <= t) || (that.s <= s && t <= tt))
//         0
//       else
//         (s - that.s).toInt
//     }
//   }
//   case class State(ts: TreeSet[Range], size: Long)
//   def howMany(r: Range, a: Long) : Long =
//     r match {
//       case Range(s, l) => {
//         val h = l / (a+1)
//         val r = l % (a+1)
//         h + (if(r == a) 1 else 0)
//       }
//     }
//   def split(r: Range, i: Long) : List[Range] =
//     if(r.l == 1)
//       List()
//     else if(r.s == i)
//       List(Range(i+1,r.l-1))
//     else if(r.s+r.l-1 == i)
//       List(Range(r.s,r.l-1))
//     else
//       List(Range(r.s,i-r.s), Range(i+1,r.l-(i-r.s+1)))

//   // Document: http://www.scala-lang.org/api/current/#package
//   // -----------------------------------------------------------------------------
//   def main(args: Array[String]) : Unit = {
//     val (n,k,a) = {
//       val nka = readLine().split(" ").map(_.toLong)
//       (nka(0), nka(1), nka(2))
//     }
//     val m = readLine().toLong
//     val x = readLine().split(" ").map(_.toLong-1)
//     val ini = Range(0,n)
//     var index = 0
//     var kotae = -1
//     val ans = x.foldLeft(State(TreeSet[Range](ini), howMany(ini,a)))(
//         (state,x) => state match {
//           case State(ts, size) => {
//             index += 1
//             val r   = ts.iteratorFrom(Range(x,1)).next()
//             val sub = howMany(r,a)
//             val add_range = split(r,x)
//             val add_cnt = add_range.map(howMany(_,a)).sum
//             val new_ts = add_range.foldLeft(ts-r)((t,a) => t+a)
//             val cnt = size - sub + add_cnt
//             if(cnt < k && kotae == -1){
//               kotae = index
//             }
//             State(new_ts, cnt)
//           }})
//     println(kotae)
//   }
// }

object Main {
  import scala.collection.mutable.TreeSet
  case class Range(s: Int, l: Int) extends Ordered[Range] {
    def compare(that: Range) = {
      val t  = s + l
      val tt = that.s + that.l
      if((s <= that.s && tt <= t) || (that.s <= s && t <= tt))
        0
      else
        (s - that.s).toInt
    }
  }
  @inline
  def howMany(r: Range, a: Int) : Int =
    r match {
      case Range(s, l) => {
        val h = l / (a+1)
        val r = l % (a+1)
        h + (if(r == a) 1 else 0)
      }
    }
  @inline
  def split(r: Range, i: Int) : List[Range] =
    if(r.l == 1)
      List()
    else if(r.s == i)
      List(Range(i+1,r.l-1))
    else if(r.s+r.l-1 == i)
      List(Range(r.s,r.l-1))
    else
      List(Range(r.s,i-r.s), Range(i+1,r.l-(i-r.s+1)))

  // Document: http://www.scala-lang.org/api/current/#package
  // -----------------------------------------------------------------------------
  def main(args: Array[String]) : Unit = {
    val (n,k,a) = {
      val nka = readLine().split(" ").map(_.toInt)
      (nka(0), nka(1), nka(2))
    }
    val m = readLine().toInt
    val xk = readLine().split(" ").map(_.toInt-1)
    val ini = Range(0,n)
    var index = 0
    var kotae = -1
    val ts   = TreeSet[Range](ini)
    var size = howMany(ini,a)
    for(x <- xk){
      index += 1
      val r = ts.iteratorFrom(Range(x,1)).next()
      ts -= r
      val add_range = split(r,x)
      size -= howMany(r,a)
      add_range.foreach(i => {size += howMany(i,a)})
      add_range.foreach(a => {ts += a})
      if(size < k && kotae == -1){
        kotae = index
      }
    }
    println(kotae)
  }
}

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

// object Main {
//   case class Range(s: Long, l: Long) extends Ordered[Range] {
//     def compare(that: Range) = {
//       val t  = s + l
//       val tt = that.s + that.l
//       if((s <= that.s && tt <= t) || (that.s <= s && t <= tt))
//         0
//       else
//         (s - that.s).toInt
//     }
//   }
//   case class State(ts: TreeSet[Range], size: Long)
//   def howMany(r: Range, a: Long) : Long =
//     r match {
//       case Range(s, l) => {
//         val h = l / (a+1)
//         val r = l % (a+1)
//         h + (if(r == a) 1 else 0)
//       }
//     }
//   def split(r: Range, i: Long) : List[Range] =
//     if(r.l == 1)
//       List()
//     else if(r.s == i)
//       List(Range(i+1,r.l-1))
//     else if(r.s+r.l-1 == i)
//       List(Range(r.s,r.l-1))
//     else
//       List(Range(r.s,i-r.s), Range(i+1,r.l-(i-r.s+1)))

//   // Document: http://www.scala-lang.org/api/current/#package
//   // -----------------------------------------------------------------------------
//   def main(args: Array[String]) : Unit = {
//     val (n,k,a) = {
//       val nka = readLine().split(" ").map(_.toLong)
//       (nka(0), nka(1), nka(2))
//     }
//     val m = readLine().toLong
//     val x = readLine().split(" ").map(_.toLong-1)
//     val ini = Range(0,n)
//     var index = 0
//     var kotae = -1
//     val ans = x.foldLeft(State(TreeSet[Range](ini), howMany(ini,a)))(
//         (state,x) => state match {
//           case State(ts, size) => {
//             index += 1
//             val r   = ts.iteratorFrom(Range(x,1)).next()
//             val sub = howMany(r,a)
//             val add_range = split(r,x)
//             val add_cnt = add_range.map(howMany(_,a)).sum
//             val new_ts = add_range.foldLeft(ts-r)((t,a) => t+a)
//             val cnt = size - sub + add_cnt
//             if(cnt < k && kotae == -1){
//               kotae = index
//             }
//             State(new_ts, cnt)
//           }})
//     println(kotae)
//   }
// }

object Main {
  import scala.collection.mutable.TreeSet
  case class Range(s: Int, l: Int) extends Ordered[Range] {
    def compare(that: Range) = {
      val t  = s + l
      val tt = that.s + that.l
      if((s <= that.s && tt <= t) || (that.s <= s && t <= tt))
        0
      else
        (s - that.s).toInt
    }
  }
  case class State(ts: TreeSet[Range], size: Int)
  def howMany(r: Range, a: Int) : Int =
    r match {
      case Range(s, l) => {
        val h = l / (a+1)
        val r = l % (a+1)
        h + (if(r == a) 1 else 0)
      }
    }
  def split(r: Range, i: Int) : List[Range] =
    if(r.l == 1)
      List()
    else if(r.s == i)
      List(Range(i+1,r.l-1))
    else if(r.s+r.l-1 == i)
      List(Range(r.s,r.l-1))
    else
      List(Range(r.s,i-r.s), Range(i+1,r.l-(i-r.s+1)))

  // Document: http://www.scala-lang.org/api/current/#package
  // -----------------------------------------------------------------------------
  def main(args: Array[String]) : Unit = {
    val (n,k,a) = {
      val nka = readLine().split(" ").map(_.toInt)
      (nka(0), nka(1), nka(2))
    }
    val m = readLine().toInt
    val xk = readLine().split(" ").map(_.toInt-1)
    val ini = Range(0,n)
    var index = 0
    var kotae = -1

    val ts   = TreeSet[Range](ini)
    var size = howMany(ini,a)
    for(x <- xk){
      index += 1
      val r   = ts.iteratorFrom(Range(x,1)).next()
      val sub = howMany(r,a)
      val add_range = split(r,x)
      val add_cnt = add_range.map(howMany(_,a)).sum
      ts -= r
      add_range.foreach((a) => {ts += a})
      val cnt = size - sub + add_cnt
      if(cnt < k && kotae == -1){
        kotae = index
      }
    }
    println(kotae)
  }
}


Nezzar has $$$n$$$ balls, numbered with integers $$$1, 2, \ldots, n$$$. Numbers $$$a_1, a_2, \ldots, a_n$$$ are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that $$$a_i \leq a_{i+1}$$$ for all $$$1 \leq i < n$$$.Nezzar wants to color the balls using the minimum number of colors, such that the following holds.  For any color, numbers on balls will form a strictly increasing sequence if he keeps balls with this chosen color and discards all other balls.  Note that a sequence with the length at most $$$1$$$ is considered as a strictly increasing sequence.Please help Nezzar determine the minimum number of colors.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases.  The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that $$$a_1 \leq a_2 \leq \ldots \leq a_n$$$.

For each test case, output the minimum number of colors Nezzar can use.

NoteLet's match each color with some numbers. Then:In the first test case, one optimal color assignment is $$$[1,2,3,3,2,1]$$$.In the second test case, one optimal color assignment is $$$[1,2,1,2,1]$$$.

object Hello {
  def main(args: Array[String]): Unit = {
    var T = scala.io.StdIn.readInt()

    for (t <- 0 until T) {
      var n = scala.io.StdIn.readInt()
      //var a = new Array[Int](n)
      var a = scala.io.StdIn.readLine().split(" ").map(_.toInt).toArray
      /*for (i <- 0 until n - 1) {
        a(i) = scala.io.StdIn.readInt()
      }*/
      var ans = 1
      var cur = 1
      for (i <- 1 until n) {
        if (a(i) == a(i - 1)) {
          cur += 1
        } else {
          ans = Math.max(cur, ans)
          cur = 1
        }
      }
      ans = Math.max(cur, ans)
      println(ans)
    }
  }
}


A class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object.There are $$$n$$$ students in the class, and you are given an array $$$s$$$ in non-decreasing order, where $$$s_i$$$ is the shoe size of the $$$i$$$-th student. A shuffling of shoes is valid only if no student gets their own shoes and if every student gets shoes of size greater than or equal to their size. You have to output a permutation $$$p$$$ of $$$\{1,2,\ldots,n\}$$$ denoting a valid shuffling of shoes, where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student ($$$p_i \ne i$$$). And output $$$-1$$$ if a valid shuffling does not exist.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq10^5$$$) — the number of students. The second line of each test case contains $$$n$$$ integers $$$s_1, s_2,\ldots,s_n$$$ ($$$1\leq s_i\leq10^9$$$, and for all $$$1\le i<n$$$, $$$s_i\le s_{i+1}$$$) — the shoe sizes of the students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the answer in a single line using the following format. If a valid shuffling does not exist, print the number $$$-1$$$ as the answer. If a valid shuffling exists, print $$$n$$$ space-separated integers — a permutation $$$p$$$ of $$$1,2,\ldots,n$$$ denoting a valid shuffling of shoes where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student. If there are multiple answers, then print any of them.

NoteIn the first test case, any permutation $$$p$$$ of $$$1,\ldots,n$$$ where $$$p_i\ne i$$$ would represent a valid shuffling since all students have equal shoe sizes, and thus anyone can wear anyone's shoes.In the second test case, it can be shown that no valid shuffling is possible.

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

object Sol {
  def main(args: Array[String]): Unit = {
    val tests = StdIn.readLine().toInt
    (0 until tests).foreach { _ =>
      val _ = StdIn.readLine().toInt
      val numbers = StdIn.readLine().split(" ").map(_.toInt)

      val permutation = mutable.ListBuffer[Int]()

      var i = 1
      var sameCount = 0
      var failed = false

      while(i < numbers.length && !failed) {
        if(numbers(i) == numbers(i - 1)) {
          sameCount += 1
          permutation += i + 1
        } else {
          if(sameCount == 0) {
            failed = true
          } else {
            permutation += i - sameCount
            sameCount = 0
          }
        }
        i += 1
      }

      if(sameCount == 0) {
        failed = true
      } else {
        permutation += i - sameCount
        sameCount = 0
      }

      if(failed) {
        println(-1)
      } else {
        println(permutation.mkString(" "))
      }
    }
  }
}

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

object Sol {
  def main(args: Array[String]): Unit = {
    val tests = StdIn.readLine().toInt
    (0 until tests).foreach { _ =>
      val _ = StdIn.readLine().toInt
      val numbers = StdIn.readLine().split(" ").map(_.toInt)

      val permutation = mutable.ListBuffer[Int]()

      var i = 1
      var sameCount = 0
      var failed = false

      while(i < numbers.length && !failed) {
        if(numbers(i) == numbers(i - 1)) {
          sameCount += 1
          permutation += i + 1
        } else {
          if(sameCount == 0) {
            failed = true
          } else {
            permutation += i - sameCount + 1
            sameCount = 0
          }
        }
        i += 1
      }

      if(sameCount == 0) {
        failed = true
      } else {
        permutation += i - sameCount
        sameCount = 0
      }

      if(failed) {
        println(-1)
      } else {
        println(permutation.mkString(" "))
      }
    }
  }
}


Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alphabet to be written on it in a string of length more than ai. For example, if a1 = 2 he can't write character 'a' on this paper in a string of length 3 or more. String "aa" is allowed while string "aaa" is not.Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be n and they shouldn't overlap. For example, if a1 = 2 and he wants to send string "aaa", he can split it into "a" and "aa" and use 2 magical papers, or into "a", "a" and "a" and use 3 magical papers. He can't split it into "aa" and "aa" because the sum of their lengths is greater than n. He can split the message into single string if it fulfills the conditions.A substring of string s is a string that consists of some consecutive characters from string s, strings "ab", "abc" and "b" are substrings of string "abc", while strings "acb" and "ac" are not. Any string is a substring of itself.While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions:   How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is n and they don't overlap? Compute the answer modulo 109 + 7.  What is the maximum length of a substring that can appear in some valid splitting?  What is the minimum number of substrings the message can be spit in? Two ways are considered different, if the sets of split positions differ. For example, splitting "aa|a" and "a|aa" are considered different splittings of message "aaa".

The first line contains an integer n (1 ≤ n ≤ 103) denoting the length of the message. The second line contains the message s of length n that consists of lowercase English letters. The third line contains 26 integers a1, a2, ..., a26 (1 ≤ ax ≤ 103) — the maximum lengths of substring each letter can appear in.

Print three lines. In the first line print the number of ways to split the message into substrings and fulfill the conditions mentioned in the problem modulo 109  +  7. In the second line print the length of the longest substring over all the ways. In the third line print the minimum number of substrings over all the ways.

NoteIn the first example the three ways to split the message are:   a|a|b  aa|b  a|ab The longest substrings are "aa" and "ab" of length 2.The minimum number of substrings is 2 in "a|ab" or "aa|b".Notice that "aab" is not a possible splitting because the letter 'a' appears in a substring of length 3, while a1 = 2.

import scala.io.StdIn.readLine

object MahmudAndMessage extends App {
  case class Result(ways: Int, maxLen: Int, minCount: Int) {
    def +(other: Option[Result]) = other.fold(this) { that ⇒
      Result(
        (ways + that.ways) % mod,
        maxLen max that.maxLen,
        minCount min that.minCount)
    }
    def move(len: Int) = Result(ways, maxLen max len, minCount + 1)
    def output = s"$ways\n$maxLen\n$minCount"
  }

  val mod = 1000000007
  def solution(str: String, limits: IndexedSeq[Int]) =
    str.map(c ⇒ limits(c - 'a'))
      .foldLeft(List.empty[(Int, Result)]) {
        case (history, charLimit) ⇒
          def go(hist: List[(Int, Result)], res: Option[Result], charLim: Int, len: Int): Result = hist match {
            case Nil ⇒ Result(1, len, 1) + res
            case (limit, pres) :: tail ⇒
              val next = pres.move(len) + res
              val nextLim = charLim min limit
              if (nextLim >= len) go(tail, Some(next), nextLim, len + 1) else next
          }
          (charLimit, go(history, None, charLimit, 1)) :: history
      }

  readLine()
  val str = readLine()
  val limits = readLine().split(' ').map(_.toInt - 1)
  val hist@((_, res) :: _) = solution(str, limits)
  println(res.output)
}


You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n × n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile — then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.You would like to purify all n × n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.

The first line will contain a single integer n (1 ≤ n ≤ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise.

If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell.

NoteThe first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously.   In the second example, it is impossible to purify the cell located at row 1 and column 1.For the third example:

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next())
  val linesSolution = data.map(_.indexOf('.'))
  val rowsSolution = (0 until n).map(i => (0 until n).find(j => data(j)(i) == '.').getOrElse(-1))
  val r = if (linesSolution.forall(_ >= 0)) {
    (0 until n).map(i => s"${i + 1} ${linesSolution(i) + 1}").mkString("\n")
  } else if (rowsSolution.forall(_ >= 0)) {
    (0 until n).map(i => s"${rowsSolution(i) + 1} ${i + 1}").mkString("\n")
  } else "-1"
  println(r)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next())
  val linesSolution = data.map(_.indexOf('.'))
  val rowsSolution = (0 until n).map(i => (0 until n).find(j => data(j)(i) == '.').getOrElse(-1))
  val r = if (linesSolution.forall(_ >= 0)) {
    (0 until n).map(i => s"${i + 1} ${linesSolution(i) + 1}").mkString("\n")
  } else if (rowsSolution.forall(_ >= 0)) {
    (0 until n).map(i => s"${linesSolution(i) + 1} ${i + 1}").mkString("\n")
  } else "-1"
  println(r)
}