You are given a palindromic string $$$s$$$ of length $$$n$$$.You have to count the number of indices $$$i$$$ $$$(1 \le i \le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome. For example, consider $$$s$$$ = "aba"  If we remove $$$s_1$$$ from $$$s$$$, the string becomes "ba" which is not a palindrome.  If we remove $$$s_2$$$ from $$$s$$$, the string becomes "aa" which is a palindrome.  If we remove $$$s_3$$$ from $$$s$$$, the string becomes "ab" which is not a palindrome. A palindrome is a string that reads the same backward as forward. For example, "abba", "a", "fef" are palindromes whereas "codeforces", "acd", "xy" are not.

The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^3)$$$  — the number of test cases. Description of the test cases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$  — the length of string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting of lowercase English letters. It is guaranteed that $$$s$$$ is a palindrome. It is guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer  — the number of indices $$$i$$$ $$$(1 \le i \le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome.

NoteThe first test case is described in the statement.In the second test case, the indices $$$i$$$ that result in palindrome after removing $$$s_i$$$ are $$$3, 4, 5, 6$$$. Hence the answer is $$$4$$$. In the third test case, removal of any of the indices results in "d" which is a palindrome. Hence the answer is $$$2$$$.

object PrA extends App {
  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

  def solve_ = {
    in.nextLine()
    val str = in.nextLine()
    val n = str.length
    var curidx = n / 2
    val midchar = str(curidx)
    var acc = (n + 1) % 2 - 1
    while (curidx < n && str(curidx) == midchar){
      acc += 2
      curidx += 1
    }
    out.println(acc)
  }

  def solve = {
    val n = in.nextInt
    in.nextLine
    for (i <- 0 until n) {
      solve_
    }
  }

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

/*
 *  in.nextInt - read int
 *  in.nextLine - read string
 *  in.nextDouble - read double
 *  out.println - putStrLn
 */

object PrA extends App {
  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

  def solve = {
    in.nextLine()
    val str = in.nextLine()
    val n = str.length
    var curidx = n / 2
    val midchar = str(curidx)
    var acc = (n + 1) % 2 - 1
    while (curidx < n && str(curidx) == midchar){
      acc += 2
      curidx += 1
    }
    out.println(acc)
  }

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

/*
 *  in.nextInt - read int
 *  in.nextLine - read string
 *  in.nextDouble - read double
 *  out.println - putStrLn
 */


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Initially all elements of $$$a$$$ are either $$$0$$$ or $$$1$$$. You need to process $$$q$$$ queries of two kinds:  1 x : Assign to $$$a_x$$$ the value $$$1 - a_x$$$.  2 k : Print the $$$k$$$-th largest value of the array. As a reminder, $$$k$$$-th largest value of the array $$$b$$$ is defined as following: Sort the array in the non-increasing order, return $$$k$$$-th element from it. For example, the second largest element in array $$$[0, 1, 0, 1]$$$ is $$$1$$$, as after sorting in non-increasing order it becomes $$$[1, 1, 0, 0]$$$, and the second element in this array is equal to $$$1$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the length of the given array and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, a_3, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$) — elements of the initial array. Each of the following $$$q$$$ lines contains two integers. The first integer is $$$t$$$ ($$$1 \le t \le 2$$$) — the type of query.   If $$$t = 1$$$ the second integer is $$$x$$$ ($$$1 \le x \le n$$$) — the position of the modified number. You have to assign to $$$a_x$$$ the value $$$1 - a_x$$$. If $$$t = 2$$$ the second integer is $$$k$$$ ($$$1 \le k \le n$$$) — you need to print the $$$k$$$-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying $$$t = 2$$$).

For each query of the second type, print a single integer — the answer to the query.

NoteInitially $$$a = [1, 1, 0, 1, 0]$$$.The first operation is printing the third largest value, which is $$$1$$$.The second operation is assigning $$$a_2$$$ the value $$$0$$$, $$$a$$$ becomes $$$[1, 0, 0, 1, 0]$$$.The third operation is printing the third largest value, it is $$$0$$$.The fourth operation is printing the first largest value, it is $$$1$$$.The last operation is printing the fifth largest value, it is $$$0$$$.

object A {
  import InOut._
  def main(args: Array[String]): Unit = {
    val n, q = nextInt
    val as = nextInts(n)
    var ones = as.sum

    for (_ <- 1 to q) {
      val t, x = nextInt
      if (t == 1) {
        as(x - 1) = 1 - as(x - 1)
        if (as(x - 1) == 1) ones += 1 else ones -=1
      } else {
//        println(as.mkString, ones)
        val res = if (x > ones) 0 else 1
        out.println(res)
      }
    }

    out.flush()
  }

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


One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of floors in the house and the number of flats on each floor respectively. Next n lines describe the floors from top to bottom and contain 2·m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.

Print a single integer — the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.

NoteIn the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()

  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val res = (1 to n).flatMap{_ =>
    in.next().split(' ').grouped(2).map{t =>
    t.head == "1" || t.last == "1"}}.count(_ == true)
  println(res)

}

object A595 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val in = Array.fill(n)(readInts(2*m))
    println(in.map{arr => arr.grouped(2).count{a => a(0) == 1 || a(1) == 1}}.sum)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

import scala.collection._

object A extends App {

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

  val Array(n, m) = readInts(2)
  val ss = Array.fill(n){ readInts(2 * m) }

  var cnt = 0

  for (s <- ss) {
    for (i <- 0 until m) {
      if (s(2 * i) + s(2 * i + 1) > 0) cnt += 1
    }
  }

  println(cnt)
}

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

import scala.collection.mutable

object A {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

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

  def nextLong: Long = return java.lang.Long.parseLong(next)

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    var ans = 0
    for (i <- 0 until n) {
      for (j <- 0 until 2 * m by 2) {
        val fst = nextInt
        val snd = nextInt
        if (fst + snd >= 1) {
          ans += 1
        }
      }
    }
    out.println(ans)
    return 0
  }
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._
import scala.math.Ordering.Implicits._

object _595A extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, m) = (nextInt(), nextInt())
    var ans = 0
    repeat(n * m) {
      val (a, b) = (nextInt(), nextInt())
      if (((a | b) & 1) == 1) {
        ans += 1
      }
    }
    ans
  }

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

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

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

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

object Main{
  def main (args: Array[String]){
    val Array(n, m) = io.StdIn.readLine.split(' ').map(_.toInt)
    var ans = 0
    for(i <- 1 to n){
      val al = io.StdIn.readLine.split(' ').map(_.toInt).toList
      ans += test(al)
    }
    println(ans)
  }

  def test(al: List[Int]): Int = al match{
    case Nil | (_ :: Nil) => 0
    case x :: y :: l1 =>
      if(x+y == 0) test(l1)
      else 1 + test(l1)
  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer

object A_330 {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val n = line1.nextToken().toInt //floor
    val m = line1.nextToken().toInt //window

    var result = 0
    for (i <- 0 until n) {
      val line = new StringTokenizer(br.readLine(), " ")
      for (j <- 1 to m) {
        val w1 = line.nextToken().toInt
        val w2 = line.nextToken().toInt
        if (w1 == 1 || w2 == 1) {
          result += 1
        }
      }
    }
    //---------------------------- parameters reading end --------------------------------

    println(result)

  }
}

import scala.io.StdIn

object Main {
  private def readInts(): Array[Int] = StdIn.readLine().split(" ").map(_.toInt)

  def main(args: Array[String]) {
    val Array(n, m) = readInts()
    val sum = (0 until n).map(s => {
      val w = readInts()
      val e = w.zipWithIndex.filter(_._2 % 2 == 0).map(_._1)
      val o = w.zipWithIndex.filter(_._2 % 2 == 1).map(_._1)
      e.zip(o).count(s => s._1 == 1 || s._2 == 1)
    }).sum
    println(sum)
  }
}

object CF595A extends App{
  val Array(n,m) = readLine.split(" ").map(_.toInt)
  print((for(i <- 1 to n) yield (readLine.split(" ").sliding(2,2).count(a => a(0)=="1" || a(1) =="1"))).sum)
}

object Main extends App {
  val Array(n,m) = readLine().split(" ").map(_.toInt)
	var s = 0
	for(i <- 1 to n ) {
	  var r = readLine().split(" ").map(_.toInt)
		val t = for(j <- 0 until r.length by 2) yield { Math.max(r(j) , r(j+1)) }
		s += t.sum
	}
	println(s)
}


Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values $$$p_i$$$ — the index of the router to which the $$$i$$$-th router was connected after being purchased ($$$p_i < i$$$).There are $$$n$$$ routers in Boogle in total now. Print the sequence of routers on the path from the first to the $$$n$$$-th router.

The first line contains integer number $$$n$$$ ($$$2 \le n \le 200000$$$) — the number of the routers. The following line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$), where $$$p_i$$$ is equal to index of the router to which the $$$i$$$-th was connected after purchase.

Print the path from the $$$1$$$-st to the $$$n$$$-th router. It starts with $$$1$$$ and ends with $$$n$$$. All the elements in the path should be distinct.

import java.io.PrintWriter
import java.util
import java.util.Scanner

object Solution {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val pw = new PrintWriter(System.out)

    val n = sc.nextInt()

    val p = new Array[Int](n + 1)

    val g = new Array[util.ArrayList[Int]](n + 1)

    for (i <- 2 to n) {
      p.update(i, sc.nextInt())
      var gg = g.apply(p.apply(i))
      if (gg == null) {
        gg = new util.ArrayList[Int]
      }
      gg.add(i)
    }

    var result = Vector[Int]()

    var cur = n

    while (cur != 1) {
      result = cur +: result
      cur = p.apply(cur)
    }

    result = 1 +: result

    result.foreach(f => {
      pw.print(f + " ")
    })

    sc.close()
    pw.close()
  }
}

import java.io.FileInputStream
import scala.io.StdIn

object ProblemA extends App {
  // Console.withIn(new FileInputStream("inputs/test01.in")) {
    val n = StdIn.readLine().trim.toInt
    val p = -1 +: StdIn.readLine().trim.split("\\s+").map(_.toInt - 1)
    var a = List.empty[Int]
    var f = n - 1
    while (f != 0) {
      a ::= f
      f = p(f)
    }
    a ::= 0
    println(a.map(_ + 1).mkString(" "))
  // }
}


Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.There are $$$n$$$ cities in the republic, some of them are connected by $$$m$$$ directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city $$$1$$$, travel to the city $$$n$$$ by roads along some path, give a concert and fly away.As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads — in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from $$$1$$$ to $$$n$$$, and for security reasons it has to be the shortest possible.Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from $$$1$$$ to $$$n$$$ or the shortest path's length would be greatest possible.A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length.

The first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 500000$$$, $$$0 \leq m \leq 500000$$$) — the number of cities and the number of roads. The $$$i$$$-th of next $$$m$$$ lines contains three integers — $$$u_i$$$, $$$v_i$$$ and $$$t_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$t_i \in \{0, 1\}$$$) — numbers of cities connected by road and its type, respectively ($$$0$$$ — night road, $$$1$$$ — morning road).

In the first line output the length of the desired path (or $$$-1$$$, if it's possible to choose such schedule that there's no path from $$$1$$$ to $$$n$$$). In the second line output the desired schedule — a string of $$$n$$$ digits, where $$$i$$$-th digit is $$$0$$$, if the $$$i$$$-th city is a night one, and $$$1$$$ if it's a morning one. If there are multiple answers, print any.

NoteFor the first sample, if we paint city $$$1$$$ white, the shortest path is $$$1 \rightarrow 3$$$. Otherwise, it's $$$1 \rightarrow 2 \rightarrow 3$$$ regardless of other cities' colors.For the second sample, we should paint city $$$3$$$ black, and there are both black and white roads going from $$$2$$$ to $$$4$$$. Note that there can be a road connecting a city with itself.

//package codeforces.contests._1407

object EgorInTheRepublicOfDagestan {

  import scala.collection.immutable.Queue

  def main(args: Array[String]): Unit = {
    val Array(n, m) = io.StdIn.readLine().split(" ").map(_.toInt)
    val graph = Array.fill[List[(Int, Int)]](n + 1)(Nil)

    (1 to m).foreach { _ =>
      val Array(l, r, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      graph(r) ::= (l, color)
    }

    val visited = new Array[Boolean](n + 1) // true if ever been inside the Queue
    val color, distance = Array.fill[Int](n + 1)(-1)

    @scala.annotation.tailrec
    def bfs(queue: Queue[Int] = Queue(n)): Unit = {
      if (queue.nonEmpty) {
        val (v, q) = queue.dequeue

        val updatedQueue = graph(v).foldLeft(q) { case (q, (u, c)) =>
          color(u) match {
            case -1 => color(u) =
              (c + 1) % 2 // set opposite color, block this edge
              q
            case _ if visited(u) =>
              q
            case `c` =>
              visited(u) = true
              distance(u) = distance(v) + 1
              q.enqueue(u)
            case _ =>
              q
          }
        }

        bfs(updatedQueue)
      }
    }

    color(n) = 1 // doesn't matter
    distance(n) = 0

    visited(n) = true

    bfs()

    println(distance(1))
    println(color.map(x => if (x == -1) 0 else x).view(1, n + 1).mkString(""))
  }
}

//package codeforces.contests._1407

object EgorInTheRepublicOfDagestan {
  def main(args: Array[String]): Unit = {
    val Array(n, m) = io.StdIn.readLine().split(" ").map(_.toInt)
    val graph0, graph1 = Array.fill[List[Int]](n + 1)(Nil)

    (1 to m).foreach { _ =>
      val Array(l, r, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      if (color == 0) graph0(l) ::= r else graph1(l) ::= r
    }

    val visited: Array[Boolean] = new Array[Boolean](n + 1)

    def recur(v: Int, next: List[Int], color: Int): (Int, List[(Int, Int)]) = {
      val neighbours = next.dropWhile(visited)
      val result = if (neighbours.nonEmpty) {
        val u = neighbours.head
        visited(u) = true
        val r = dfs(u)
        visited(u) = false

        val (accC, accList) = neighbours.tail.foldLeft(r) { (acc, u) =>
          if (acc._1 != -1 && !visited(u)) {
            visited(u) = true
            val (c, list) = dfs(u)
            visited(u) = false
            if (c == -1)
              (-1, list)
            else if (c > acc._1)
              (c, list)
            else
              acc
          } else acc
        }

        (if (accC == -1) -1 else accC + 1, (v, color) :: accList)
      } else (-1, List((v, color)))

      result
    }

    def dfs(v: Int): (Int, List[(Int, Int)]) = {
      if (v == n) (0, Nil)
      else {
        val r0@(c0, _) = recur(v, graph0(v), 0)
        if (c0 != -1) {
          val r1@(c1, _) = recur(v, graph1(v), 1)
          if (c1 != -1)
            if (c0 > c1) r0 else r1
          else r1
        } else r0
      }
    }

    val tag = new Array[Int](n + 1)

    visited(1) = true
    val (c, list) = dfs(1)
    visited(1) = false
    list.foreach { case (v, color) => tag(v) = color }

    println(c)
    println(tag.view(1, n + 1).mkString(""))
  }
}

//package codeforces.contests._1407

object EgorInTheRepublicOfDagestan {

  import scala.collection.immutable.Queue

  def main(args: Array[String]): Unit = {
    val Array(n, m) = io.StdIn.readLine().split(" ").map(_.toInt)
    val graph = Array.fill[List[(Int, Int)]](n + 1)(Nil)

    (1 to m).foreach { _ =>
      val Array(l, r, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      graph(r) ::= (l, color)
    }

    val visited = new Array[Boolean](n + 1) // true if ever been inside the Queue
    val color, distance = Array.fill[Int](n + 1)(-1)

    @scala.annotation.tailrec
    def bfs(queue: Queue[Int] = Queue(n)): Unit = {
      if (queue.nonEmpty) {
        val (v, q) = queue.dequeue

        val updatedQueue = graph(v).foldLeft(q) { case (q, (u, c)) =>
          color(u) match {
            case -1 => color(u) = (c + 1) % 2 // set opposite color, block this edge
              q
            case _ if !visited(u) =>
              visited(u) = true
              distance(u) = distance(v) + 1
              q.enqueue(u)
            case _ =>
              q
          }
        }

        bfs(updatedQueue)
      }
    }

    color(n) = 1 // doesn't matter
    distance(n) = 0

    visited(n) = true

    bfs()

    println(distance(1))
    println(color.map(x => if (x == -1) 0 else x).view(1, n + 1).mkString(""))
  }
}


There are $$$n + 1$$$ cities, numbered from $$$0$$$ to $$$n$$$. $$$n$$$ roads connect these cities, the $$$i$$$-th road connects cities $$$i - 1$$$ and $$$i$$$ ($$$i \in [1, n]$$$).Each road has a direction. The directions are given by a string of $$$n$$$ characters such that each character is either L or R. If the $$$i$$$-th character is L, it means that the $$$i$$$-th road initially goes from the city $$$i$$$ to the city $$$i - 1$$$; otherwise it goes from the city $$$i - 1$$$ to the city $$$i$$$.A traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler must go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i. e., if a road is directed from city $$$i$$$ to the city $$$i + 1$$$, it is possible to travel from $$$i$$$ to $$$i + 1$$$, but not from $$$i + 1$$$ to $$$i$$$. After the traveler moves to a neighboring city, all roads change their directions to the opposite ones. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to.The goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city $$$i$$$, calculate the maximum number of different cities the traveler can visit during exactly one journey if they start in the city $$$i$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters, each character is either L or R. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print $$$n + 1$$$ integers. The $$$i$$$-th integer should be equal to the maximum number of different cities the traveler can visit during one journey if this journey starts in the $$$i$$$-th city.

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val s = nextLine
      val left, right, res = Array.fill(n + 1)(0)

      var prev = ' '
      var stride = 0
      for (i <- 1 to n) {
        val c = s(i - 1)
        if (c != prev) stride += 1
        else stride = 1
        if (c == 'L') left(i) = stride
        prev = c
      }

      prev = ' '
      stride = 0
      for (i <- n-1 to 0 by -1) {
        val c = s(i)
        if (c != prev) stride += 1
        else stride = 1
//        println(i,c, prev, stride)
        if (c == 'R') right(i) = stride
        prev = c
      }
//println(left.mkString(" "))
//      println(right.mkString(" "))
      for (i <- res.indices) {
        res(i) = 1 + left(i) + right(i)
      }

      out.println(res.mkString(" "))
    }

    out.flush()
  }

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


Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition:  These k dots are different: if i ≠ j then di is different from dj.  k is at least 4.  All dots belong to the same color.  For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.

The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.

Output "Yes" if there exists a cycle, and "No" otherwise.

7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB

NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).

import scala.io.Source

object Solution extends App {

def go(symbol: Int, number: Int, i: Int, j: Int, prevI: Int, prevJ: Int, data: Array[Array[Int]]): Boolean = {
if (i < 0 || j < 0 || i >= data.length || j >= data.head.length)
false
else if (data(i)(j) == number) true
else if (data(i)(j) == symbol) {
data(i)(j) = number
((i + 1 != prevI || j != prevJ) && go(symbol, number, i + 1, j, i, j, data)) ||
((i != prevI || j + 1 != prevJ) && go(symbol, number, i, j + 1, i, j, data)) ||
((i - 1 != prevI || j != prevJ) && go(symbol, number, i - 1, j, i, j, data)) ||
((i != prevI || j - 1 != prevJ) && go(symbol, number, i, j - 1, i, j, data))
} else
false
}

def solveIndex(line: Int, column: Int, data: Array[Array[Int]]) = {
val symbol = data(line)(column)
val number = - (line * data.head.length + column + 1)
if (symbol < 0)
false
else {
go(symbol: Int, number: Int, line, column, line, column, data)
}
}

def solve(data: Array[Array[Int]]): Boolean = {
data.indices.exists{ line =>
data.head.indices.exists(column => solveIndex(line, column, data))
}
}

val in = Source.stdin.getLines()
val Array(n, m) = in.next().split(' ').map(_.toInt)
val data = (1 to n).map(_ => in.next().map(_.toInt).toArray).toArray
if (solve(data))
println("Yes")
else
println("No")
}

import collection.mutable.Set
import collection.mutable.Queue

object Main extends App {
  val Array(n,m) = readLine.split(" ").map(_.toInt)

  val land = (1 to n) map { _ => readLine.trim }

  val dirs = List((0,1), (1,0), (-1,0), (0,-1))

  def eqColor(color: Char)(pos: (Int, Int)): List[(Int, Int)] = pos match {
    case (x, y) =>
      if(x >= 0 && x < n && y >= 0 && y < m && land(x)(y) == color) List(pos)
      else List()
  }

  def steps(node: (Int, Int)): List[(Int, Int)] = node match {
     case (x, y) =>
       val color = land(x)(y)
       dirs map { case (dx, dy) => (x+dx, y+dy) } flatMap eqColor(color)
  }

  val white = Set((for {
    i <- 0 to n-1
    j <- 0 to m-1
  } yield (i, j)): _*)
  val gray = Set[(Int, Int)]()
  val black = Set[(Int, Int)]()

  def dfs(prev: (Int, Int), node: (Int, Int)): Unit = {
    white.remove(node)
    gray.add(node)
    steps(node) foreach { k =>
        if(k != prev) {
          if(gray.contains(k)) {
            println("Yes")
            System.exit(0)
          }

          if(!black.contains(k)) dfs(node, k)
        }
    }
    gray.remove(node)
    black.add(node)
  }

  while(white.size > 0) {
    dfs((-1,-1), white.head)
  }

  println("No")
}

import scala.math._
import scala.util.control.Breaks

object Problem extends App {
  import Scanner._

  val n, m = readInt

  val game = Array.fill(n)(readString.toArray)
  val visited = Array.ofDim[Boolean](n, m)
  def hasCycle(x: Int, y: Int, lx: Int, ly: Int): Boolean = {
    if(x < 0 || x >= n || y < 0 || y >= m || game(x)(y) != game(lx)(ly))
      return false
    if(!visited(x)(y)) {
      visited(x)(y) = true

      if(x != lx+1 && hasCycle(x-1, y, x, y))
        return true
      if(x != lx-1 && hasCycle(x+1, y, x, y))
        return true
      if(y != ly+1 && hasCycle(x, y-1, x, y))
        return true
      if(y != ly-1 && hasCycle(x, y+1, x, y))
        return true
      false
    } else true
  }

  for(x <- 0 until n; y <- 0 until m; if !visited(x)(y)) {
    if(hasCycle(x, y, x, y)) {
      println("Yes")
      System.exit(0)
    }
  }
  println("No")

  /*
   * val names = Array.fill(readInt)(readString)
  val order = List[Char]()

  for(name <- names) {
    val c = name(0)
  }
   */
}

case class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {
  private val cache = new scala.collection.mutable.HashMap[A, B] {
    override def initialSize = size
  }
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

/**
 * @author pvasilyev
 * @since 04 Aug 2016
 */
object B510 extends App {

  // 0 - left
  // 1 - down
  // 2 - up
  // 3 - right
  def recursiveFoo(row: Int, col: Int, mainSymbol: Char, field: Array[Array[Char]],
                   mask: Array[Array[Boolean]], n: Int, m: Int, movement: Int): Boolean = {
    if (mask(row)(col)) {
      return true
    }
    mask(row)(col) = true
    var b = false
    if (row + 1 < n && field(row + 1)(col) == mainSymbol && movement != 2) {
      b |= recursiveFoo(row + 1, col, mainSymbol, field, mask, n, m, 1)
    }
    if (row - 1 >= 0 && field(row - 1)(col) == mainSymbol && movement != 1) {
      b |= recursiveFoo(row - 1, col, mainSymbol, field, mask, n, m, 2)
    }
    if (col + 1 < m && field(row)(col + 1) == mainSymbol && movement != 0) {
      b |= recursiveFoo(row, col + 1, mainSymbol, field, mask, n, m, 3)
    }
    if (col - 1 >= 0 && field(row)(col - 1) == mainSymbol && movement != 3) {
      b |= recursiveFoo(row, col - 1, mainSymbol, field, mask, n, m, 0)
    }
    return b
  }

  def runFoo(row: Int, col: Int, field: Array[Array[Char]], mask: Array[Array[Boolean]], n: Int, m: Int): Boolean = {
    recursiveFoo(row, col, field(row)(col), field, mask, n, m, 1)
  }

  def solve() = {
    val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val field: Array[Array[Char]] = Array.ofDim[Char](n, m)
    for (i <- 0 until n) {
      field(i) = scala.io.StdIn.readLine().toCharArray
    }
    if (foo(n, m, field)) {
      println("Yes")
    } else {
      println("No")
    }
  }

  def foo(n: Int, m: Int, field: Array[Array[Char]]): Boolean = {
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        val mask: Array[Array[Boolean]] = Array.ofDim[Boolean](n, m)
        if (runFoo(i, j, field, mask, n, m))
          return true
      }
    }

    false
  }

  solve()

}

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

import scala.collection.mutable._

/**
  * @author Mehdi Maick
  */
object Main {

  def solve(in: InputReader): Unit = {
    val n = in.next.toInt
    val m = in.next.toInt
    var grid: Array[Array[Char]] = new Array[Array[Char]](n)
    (0 until n).foreach((i) => grid(i) = in.next.toCharArray)
    var hasCycle = false
    var visited: Array[Array[Boolean]] = null

    def fill(): Array[Array[Boolean]] = {
      var ret = new Array[Array[Boolean]](n)
      (0 until n).foreach((i) => ret(i) = new Array[Boolean](m))
      ret
    }

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

    def dfs(x: Int, y: Int, parentX: Int, parentY: Int, c: Char, cycleCount: Int): Boolean = {
      if (visited(x)(y)) {
        if(cycleCount >= 4){
          println("Yes")
          System.exit(0)
        }
        return false
      }
      visited(x)(y) = true
      var ans = false
      for (i <- 0 until 4) {
        val xx = x + dx(i)
        val yy = y + dy(i)
        if (xx >= 0 && yy >= 0 && xx < n && ((parentX, parentY) != (xx, yy)) && yy < m && grid(xx)(yy) == c) {
          ans |= dfs(xx, yy, x, y, c, cycleCount + 1)
        }
      }
      return ans
    }

    for (i <- 0 until n) {
      for (j <- 0 until m) {
        visited = fill
        hasCycle |= dfs(i, j, -1, -1, grid(i)(j), 0)
        if(hasCycle){

        }
      }
    }
    println(if (hasCycle) "Yes" else "No")
  }

  def main(args: Array[String]): Unit = {
    val in = new InputReader
    solve(in)
  }

  class InputReader() {
    var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var st: StringTokenizer = null

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

    def nextLine(): String = in.readLine
  }

}

import scala.math._
import scala.util.control.Breaks

object Problem extends App {
  import Scanner._

  val n, m = readInt

  val game = Array.fill(n)(readString.toArray)
  val path = Array.ofDim[Boolean](n, m)
  val visited = Array.ofDim[Boolean](n, m)
  def hasCycle(x: Int, y: Int, last: Char): Boolean = {
    if(x < 0 || x >= n || y < 0 || y >= n)
      return false
    val c = game(x)(y)
    if(last != c)
      return false
    if(!path(x)(y)) {
      if(!visited(x)(y)) {
        visited(x)(y) = true
        path(x)(y) = true

        if(hasCycle(x+1, y, c) || hasCycle(x-1, y, c) || hasCycle(x, y+1, c) || hasCycle(x, y-1, c))
          return true

        path(x)(y) = false
      }
      false
    } else true
  }

  for(x <- 0 until n; y <- 0 until m; if !visited(x)(y)) {
    if(hasCycle(x, y, game(x)(y))) {
      println("Yes")
      System.exit(0)
    }
  }
  println("No")

  /*
   * val names = Array.fill(readInt)(readString)
  val order = List[Char]()

  for(name <- names) {
    val c = name(0)
  }
   */
}

case class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {
  private val cache = new scala.collection.mutable.HashMap[A, B] {
    override def initialSize = size
  }
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

/**
 * @author pvasilyev
 * @since 04 Aug 2016
 */
object B510 extends App {

  // 0 - left
  // 1 - down
  // 2 - up
  // 3 - right
  def recursiveFoo(row: Int, col: Int, mainSymbol: Char, field: Array[Array[Char]],
                   mask: Array[Array[Boolean]], n: Int, m: Int, movement: Int): Boolean = {
    if (mask(row)(col)) {
      return true
    }
    mask(row)(col) = true
    if (row + 1 < n && field(row + 1)(col) == mainSymbol && movement != 2) {
      recursiveFoo(row + 1, col, mainSymbol, field, mask, n, m, 1)
    } else if (row - 1 >= 0 && field(row - 1)(col) == mainSymbol && movement != 1) {
      recursiveFoo(row - 1, col, mainSymbol, field, mask, n, m, 2)
    } else if (col + 1 < m && field(row)(col + 1) == mainSymbol && movement != 0) {
      recursiveFoo(row, col + 1, mainSymbol, field, mask, n, m, 3)
    } else if (col - 1 >= 0 && field(row)(col - 1) == mainSymbol && movement != 3) {
      recursiveFoo(row, col - 1, mainSymbol, field, mask, n, m, 0)
    } else {
      return false
    }
  }

  def runFoo(row: Int, col: Int, field: Array[Array[Char]], mask: Array[Array[Boolean]], n: Int, m: Int): Boolean = {
    recursiveFoo(row, col, field(row)(col), field, mask, n, m, 1)
  }

  def solve() = {
    val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val field: Array[Array[Char]] = Array.ofDim[Char](n, m)
    for (i <- 0 until n) {
      field(i) = scala.io.StdIn.readLine().toCharArray
    }
    if (foo(n, m, field)) {
      println("Yes")
    } else {
      println("No")
    }
  }

  def foo(n: Int, m: Int, field: Array[Array[Char]]): Boolean = {
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        val mask: Array[Array[Boolean]] = Array.ofDim[Boolean](n, m)
        if (runFoo(i, j, field, mask, n, m))
          return true
      }
    }

    false
  }

  solve()

}


Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≤ i ≤ n). Help Polycarpus determine the length of the city phone code.

The first line of the input contains an integer n (2 ≤ n ≤ 3·104) — the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn — the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.

Print the number of digits in the city phone code.

NoteA prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209".In the first sample the city phone code is string "00".In the second sample the city phone code is an empty string.In the third sample the city phone code is string "770123456789".

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val str = in.next()
  val r = (2 to n).foldLeft(str.toSeq) {
    case (s, _) => s.zip(in.next()).takeWhile(i => i._1 == i._2).map(_._1)
  }
  println(r.length)
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._

object P172A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N = sc.nextInt
  sc.nextLine

  val res = List.fill(N)(sc.nextLine.toList).transpose.takeWhile(_.distinct.size == 1).size

  out.println(res)
  out.close
}

import java.io._

object Solution {
  def main(args: Array[String]) {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val n = in.readLine().toInt
    def commonPrefix(s: String, t: String) = {
      var i = 0
      while(i < s.length && i < t.length && s(i) == t(i)) i = i + 1
      s.substring(0, i)
    }
    val x = (for(i <- 1 to n) yield in.readLine).reduceLeft(commonPrefix(_, _))
    println(x.length)
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = (1 to n).map(_ => readLine())

    val e = a(0)
    val a1 = a.drop(1).map(_.zip(e))
    val a2 = a1.map(_.takeWhile(t => t._1 == t._2).size)
    val r = a2.min

    println(r)
  }
}


When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!

The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj.

In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant.

NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5.

/**
 * @author netman
 */

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

object HelloWorld {

  class InputReader(reader: BufferedReader) {

    var tokenizer: StringTokenizer = null;

    def this(stream: InputStream) = {
      this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));
    }

    def this(f: File) = {
      this(new BufferedReader(new FileReader(f), (1 << 20)));
    }

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

    def nextInt(): Int = next().toInt

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

    def close() = reader.close();
  }

  class OutputWriter(writer: PrintWriter) {
    def this(stream: OutputStream) {
      this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));
    }

    def this(f: File) = {
      this(new PrintWriter(new BufferedWriter(new FileWriter(f))));
    }

    def print(x: Any) = writer.print(x);

    def println(x: Any) = writer.println(x);

    def close() = writer.close();
  }

  val in = new InputReader(System.in)
  val out = new OutputWriter(System.out)

  var (n, m, k) = (0, 0, 0)
  var a: Array[Int] = null
  var mat: Array[Array[Int]] = null
  var f: Array[Array[Long]] = null

  def main(args: Array[String]): Unit = {
    n = in.nextInt
    m = in.nextInt
    k = in.nextInt

    a = new Array[Int](n + 1)

    for (i <- 0 until n) {
      a(i) = in.nextInt
    }

    mat = ofDim(n, n)
    f = ofDim((1 << n), n)

    for (i <- 1 to k) {
      val (x, y, c) = (in.nextInt - 1, in.nextInt - 1, in.nextInt)
      mat(x)(y) = c
    }

    for (i <- 0 until n) {
      f(1 << i)(i) = a(i)
    }

    for (mask <- 1 until (1 << n)) {
      for (x <- 0 until n) {
        if ((mask & (1 << x)) != 0) {
          for (y <- 0 until n) {
            if ((mask & (1 << y)) == 0) {
              val t = f(mask)(x) + a(y) + mat(x)(y)
              if (t > f(mask | (1 << y))(y)) f(mask | (1 << y))(y) = t
            }
          }
        }
      }
    }

    var result = 0L

    for (mask <- 0 until (1 << n)) {
      var cnt = 0
      var x = mask
      while (x > 0) {
        cnt += 1
        x &= x - 1
      }
      if (cnt == m) {
        for (x <- 0 until n) {
          if ((mask & (1 << x)) != 0) result = math.max(result, f(mask)(x))
        }
      }
    }

    out.println(result)

    out.close
  }
}


So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city — that's the strategy the flatlanders usually follow when they besiege cities.The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack. Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r ≥ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point. In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range — as a disk (including the border) with the center at the point where the radar is placed.

The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| ≤ 104; 1 ≤ ri ≤ 104) — the city's coordinates and the distance from the city to the flatlanders, correspondingly. It is guaranteed that the cities are located at different points.

Print a single real number — the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.

NoteThe figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).   The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).

object Solution {
  class Point(xin: Long, yin: Long) {
    val x = xin;
    val y = yin;
  }

  def sqr(x: Long): Long = x*x

  def sqrDist(p1: Point, p2: Point): Long = {
    return sqr(p1.x - p2.x) + sqr(p1.y - p2.y)
  }

  class Circle(centerin: Point, radiusin: Long) {
    val center = centerin;
    val radius = radiusin;

    def contains(p: Point): Boolean = sqrDist(p, center) <= sqr(radius)

    def intersects(other: Circle): Boolean = {
      sqr(radius) + 2*radius*other.radius + sqr(other.radius) >= sqrDist(center, other.center)
    }

    def contains(other: Circle): Boolean = {
      val d = math.sqrt(sqrDist(center, other.center))
      d + other.radius <= radius
    }
  }

  def readCircle(): Circle = {
    val tokens = readLine().split(" ").map(_.toInt)
    new Circle(new Point(tokens(0), tokens(1)), tokens(2))
  }

  def solve(c1: Circle, c2: Circle): Double = {
    val d = math.sqrt(sqrDist(c1.center, c2.center))
    if (c1 contains c2) {
      c1.radius - (d + c2.radius)
    } else if (c2 contains c1) {
      c2.radius - (d + c1.radius)
    } else if (c1 intersects c2) {
      0
    } else {
      d - (c1.radius + c2.radius)
    }
  }

  def main(args: Array[String]) {
    printf("%.12f\n", solve(readCircle(), readCircle()) / 2)
  }
}

// codeforces 190B

object Okrushenie extends App {
  val t1 = (Console.readLine.split(" ")) map (_.toInt)
  val t2 = (Console.readLine.split(" ")) map (_.toInt)
  val (x0, y0, r0) = (t1(0), t1(1), t1(2))
  val (x1, y1, r1) = (t2(0), t2(1), t2(2))
  val dx = (x0.toDouble - x1.toDouble)
  val dy = (y0.toDouble - y1.toDouble)
  val d = Math.sqrt(dx*dx + dy*dy)
  if (d > r0+r1) println((d-r0-r1)/2)
  else {
    val rmx = Math.max(r0,r1)
    val rmn = Math.min(r0,r1)
    if (rmn + d >= rmx) println(0)
    else println((rmx - d - rmn) / 2)
  }
}

object Solution {
  class Point(xin: Long, yin: Long) {
    val x = xin;
    val y = yin;
  }

  def sqr(x: Long): Long = x*x

  def sqrDist(p1: Point, p2: Point): Long = {
    return sqr(p1.x - p2.x) + sqr(p1.y - p2.y)
  }

  class Circle(centerin: Point, radiusin: Long) {
    val center = centerin;
    val radius = radiusin;

    def contains(p: Point): Boolean = sqrDist(p, center) <= sqr(radius)

    def intersects(other: Circle): Boolean = {
      sqr(radius) + 2*radius*other.radius + sqr(other.radius) >= sqrDist(center, other.center)
    }

    def contains(other: Circle): Boolean = {
      val d = math.sqrt(sqrDist(center, other.center))
      d + other.radius <= radius
    }
  }

  def readCircle(): Circle = {
    val tokens = readLine().split(" ").map(_.toInt)
    new Circle(new Point(tokens(0), tokens(1)), tokens(2))
  }

  def solve(c1: Circle, c2: Circle): Double = {
    val d = math.sqrt(sqrDist(c1.center, c2.center))
    if (c1 contains c2) {
      c1.radius - (d + c2.radius)
    } else if (c2 contains c1) {
      c2.radius - (d + c1.radius)
    } else if (c1 intersects c2) {
      c1.radius + c2.radius - d
    } else {
      d - (c1.radius + c2.radius)
    }
  }

  def main(args: Array[String]) {
    printf("%.12f\n", solve(readCircle(), readCircle()) / 2)
  }
}


Recently, the students of School 179 have developed a unique algorithm, which takes in a binary string $$$s$$$ as input. However, they soon found out that if some substring $$$t$$$ of $$$s$$$ is a palindrome of length greater than 1, the algorithm will work incorrectly. Can the students somehow reorder the characters of $$$s$$$ so that the algorithm will work correctly on the string?A binary string is a string where each character is either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.A palindrome is a string that reads the same backwards as forwards.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the string $$$s$$$. The second line of each test case contains the string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.

For each test case, print YES (case-insensitive) if it is possible to reorder the characters of $$$s$$$ so that there are no substrings that are a palindrome of length greater than 1, or NO (case-insensitive) otherwise.

NoteIn the first three test cases, the given strings do not contain palindromes of length greater than 1, so the answers are YES.In the last test case, it is impossible to reorder the characters so that the string does not contain palindromes of length greater than 1, so the answer is NO.

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val size = readInt()
    val string = readLine()
    val answer = size match {
      case 1 => "YES"
      case 2 => if (string(0) != string(1)) "YES" else "NO"
      case _ => "NO"
    }
    println(answer)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

object _1632AScala {
  import scala.io.StdIn.{readInt, readLine}
  def main(args: Array[String]): Unit = {
    var t = readInt
    while(t > 0){
      t -= 1
      val n = readInt
      val ch = readLine.toCharArray
      if(n == 1)println("YES")
      else if(n >= 3) println("NO")
      else{
        if(ch(0) != ch(1))println("YES")
        else println("NO");
      }
    }
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.Source

object Main extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val n = input.next().toInt
  val res = new ArrayBuffer[String](n)
  for (i <- 0 until n) {
    val ls = input.next().toInt
    val s = input.next()
    if (ls == 1 || "01".equals(s) || "10".equals(s)) res.append("YES")
    else res.append("NO")
  }
  res.foreach(println)
}

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(var a: Int, var b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val s = readString()
        if (n > 2) {
            writer.println("NO")
        } else if (n == 1) {
            writer.println("YES")
        } else {
            if (s(0) == s(1)) {
                writer.println("NO")
            } else {
                writer.println("YES")
            }
        }
        def check(kk: Long, fi: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long, fi:Long): Long = {
            if (en - st <= 1L) {
                if (check(st, fi))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid, fi))
                return bs(st, mid, fi)
            else
                return bs(mid, en, fi)
        }
    }
    writer.flush()
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val size = readInt()
    val string = readLine()
    val answer = if (size < 3) "YES" else "NO"
    println(answer)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}


Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers $$$n$$$ pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the $$$i$$$-th from the left sushi as $$$t_i$$$, where $$$t_i = 1$$$ means it is with tuna, and $$$t_i = 2$$$ means it is with eel.Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment $$$[2, 2, 2, 1, 1, 1]$$$ is valid, but subsegment $$$[1, 2, 1, 2, 1, 2]$$$ is not, because both halves contain both types of sushi.Find the length of the longest continuous subsegment of sushi Arkady can buy.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100\,000$$$) — the number of pieces of sushi. The second line contains $$$n$$$ integers $$$t_1$$$, $$$t_2$$$, ..., $$$t_n$$$ ($$$t_i = 1$$$, denoting a sushi with tuna or $$$t_i = 2$$$, denoting a sushi with eel), representing the types of sushi from left to right. It is guaranteed that there is at least one piece of sushi of each type. Note that it means that there is at least one valid continuous segment.

Print a single integer — the maximum length of a valid continuous segment.

NoteIn the first example Arkady can choose the subsegment $$$[2, 2, 1, 1]$$$ or the subsegment $$$[1, 1, 2, 2]$$$ with length $$$4$$$.In the second example there is no way but to choose one of the subsegments $$$[2, 1]$$$ or $$$[1, 2]$$$ with length $$$2$$$.In the third example Arkady's best choice is the subsegment $$$[1, 1, 1, 2, 2, 2]$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N) :+ 0
    var tpe = 0
    var cnt = 0
    var prevCnt = 0
    var ans = 0
    REP(N + 1) { i =>
      if (A(i) == tpe) {
        cnt += 1
      } else {
        ans = max(ans, min(prevCnt, cnt) * 2)
        tpe = A(i)
        prevCnt = cnt
        cnt = 1
      }
    }

    out.println(ans)
  }

  private val oj = System.getProperty("ONLINE_JUDGE") != null ||
    System.getenv("ATCODER_DEBUG") == null

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

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

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

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

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

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

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

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

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

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

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

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


You have a permutation: an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of distinct integers from $$$1$$$ to $$$n$$$. The length of the permutation $$$n$$$ is odd.Consider the following algorithm of sorting the permutation in increasing order.A helper procedure of the algorithm, $$$f(i)$$$, takes a single argument $$$i$$$ ($$$1 \le i \le n-1$$$) and does the following. If $$$a_i > a_{i+1}$$$, the values of $$$a_i$$$ and $$$a_{i+1}$$$ are exchanged. Otherwise, the permutation doesn't change.The algorithm consists of iterations, numbered with consecutive integers starting with $$$1$$$. On the $$$i$$$-th iteration, the algorithm does the following:   if $$$i$$$ is odd, call $$$f(1), f(3), \ldots, f(n - 2)$$$;  if $$$i$$$ is even, call $$$f(2), f(4), \ldots, f(n - 1)$$$. It can be proven that after a finite number of iterations the permutation will be sorted in increasing order.After how many iterations will this happen for the first time?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 999$$$; $$$n$$$ is odd) — the length of the permutation. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the permutation itself.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$999$$$.

For each test case print the number of iterations after which the permutation will become sorted in increasing order for the first time. If the given permutation is already sorted, print $$$0$$$.

NoteIn the first test case, the permutation will be changing as follows:   after the $$$1$$$-st iteration: $$$[2, 3, 1]$$$;  after the $$$2$$$-nd iteration: $$$[2, 1, 3]$$$;  after the $$$3$$$-rd iteration: $$$[1, 2, 3]$$$. In the second test case, the permutation will be changing as follows:   after the $$$1$$$-st iteration: $$$[4, 5, 1, 7, 2, 3, 6]$$$;  after the $$$2$$$-nd iteration: $$$[4, 1, 5, 2, 7, 3, 6]$$$;  after the $$$3$$$-rd iteration: $$$[1, 4, 2, 5, 3, 7, 6]$$$;  after the $$$4$$$-th iteration: $$$[1, 2, 4, 3, 5, 6, 7]$$$;  after the $$$5$$$-th iteration: $$$[1, 2, 3, 4, 5, 6, 7]$$$. In the third test case, the permutation is already sorted and the answer is $$$0$$$.

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

  val t = readInt()

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

    val count = {
      @annotation.tailrec
      def go(i: Int): Int =
        if (an.isSorted) i
        else {
          ((i % 2) until (n - 1, 2)).foreach {
            case i if an(i) > an(i + 1) => an.swap(i, i + 1)
            case _                      =>
          }
          go(i + 1)
        }
      go(0)
    }

    println(count)
  }

  implicit final class ArrayOps[T](private val xs: Array[T]) extends AnyVal {
    def swap(i: Int, j: Int): Unit = {
      val xi = xs(i)
      xs(i) = xs(j)
      xs(j) = xi
    }

    def isSorted(implicit ord: Ordering[T]): Boolean =
      (0 until (xs.length - 1)).forall(i => ord.lteq(xs(i), xs(i + 1)))
  }

}

object A extends App {

  import scala.io.StdIn._

  val t = readInt()

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

    def isSorted: Boolean = (0 until (n - 1)).forall(i => an(i) <= an(i + 1))

    @annotation.tailrec
    def go(i: Int): Int =
      if (isSorted) i
      else {
        ((i % 2) until (n - 1, 2)).foreach {
          case i if an(i) > an(i + 1) =>
            val ai = an(i)
            an(i) = an(i + 1)
            an(i + 1) = ai
          case _                      =>
        }
        go(i + 1)
      }

    println(go(0))
  }

}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {
        while (!st.hasMoreTokens) {
            st = new StringTokenizer(reader.readLine())
        }
        st.nextToken()
    }

    def readInt() = next.toInt
    def readLong() = next.toLong
    def readString() = next()
    def readArrayInt(n: Int = 0): Array[Int] = {
        if (n == 0)
            return reader.readLine().split(" ").map(_.toInt)

        val a = new Array[Int](n)
        for (i <- 0 until n) {
            a(i) = readInt()
        }
        a
    }

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val a = readArrayInt(n)

        var c = 0
        while ({
            var i = 0
            while (i < n && a(i) == i + 1) i +=1
            i != n
        }) {
            c += 1
            if (c % 2 > 0) {
                for (i <- 0 until n - 1 by 2 if a(i) > a(i + 1)) {
                    val k = a(i)
                    a(i) = a(i + 1)
                    a(i + 1) = k
                }
            } else {
                for (i <- 1 until n - 1 by 2 if a(i) > a(i + 1)) {
                    var k = a(i)
                    a(i) = a(i + 1)
                    a(i + 1) = k
                }
            }
        }

        writer.println(c)
    }

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}

object A extends App {

  def count: Seq[Int] => Int = _.zipWithIndex.sorted.zipWithIndex.foldLeft(0) {
    case (c, ((_, i), j)) if i == j => c
    case (c, ((_, i), j))           => c max (math.abs(i - j) + (i + 1) % 2)
  }

  import scala.io.StdIn._

  val t = readInt()

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

    println(count(an))
  }

}


Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.Mike has $$$n$$$ sweets with sizes $$$a_1, a_2, \ldots, a_n$$$. All his sweets have different sizes. That is, there is no such pair $$$(i, j)$$$ ($$$1 \leq i, j \leq n$$$) such that $$$i \ne j$$$ and $$$a_i = a_j$$$.Since Mike has taught for many years, he knows that if he gives two sweets with sizes $$$a_i$$$ and $$$a_j$$$ to one child and $$$a_k$$$ and $$$a_p$$$ to another, where $$$(a_i + a_j) \neq (a_k + a_p)$$$, then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset. Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can. Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.

The first line contains one integer $$$n$$$ ($$$2 \leq n \leq 1\,000$$$) — the number of sweets Mike has. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — the sizes of the sweets. It is guaranteed that all integers are distinct.

Print one integer — the maximum number of children Mike can invite giving each of them two sweets in such way that nobody will be upset.

NoteIn the first example, Mike can give $$$9+2=11$$$ to one child, $$$8+3=11$$$ to another one, and $$$7+4=11$$$ to the third child. Therefore, Mike can invite three children. Note that it is not the only solution.In the second example, Mike can give $$$3+9=12$$$ to one child and $$$1+11$$$ to another one. Therefore, Mike can invite two children. Note that it is not the only solution.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)

    // 重複カウントしないので単純に全組み合わせ
    val C = Array.ofDim[Int](2e5.toInt + 1)
    REP(N - 1) { i =>
      TO(i + 1, N - 1) { j =>
        C(A(i) + A(j)) += 1
      }
    }

    val ans = C.max
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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


There are $$$n$$$ piles of sand where the $$$i$$$-th pile has $$$a_i$$$ blocks of sand. The $$$i$$$-th pile is called too tall if $$$1 < i < n$$$ and $$$a_i > a_{i-1} + a_{i+1}$$$. That is, a pile is too tall if it has more sand than its two neighbours combined. (Note that piles on the ends of the array cannot be too tall.)You are given an integer $$$k$$$. An operation consists of picking $$$k$$$ consecutive piles of sand and adding one unit of sand to them all. Formally, pick $$$1 \leq l,r \leq n$$$ such that $$$r-l+1=k$$$. Then for all $$$l \leq i \leq r$$$, update $$$a_i \gets a_i+1$$$.What is the maximum number of piles that can simultaneously be too tall after some (possibly zero) operations?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq k \leq n$$$) — the number of piles of sand and the size of the operation, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of the piles. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the maximum number of piles that are simultaneously too tall after some (possibly zero) operations.

NoteIn the first test case, we can perform the following three operations:   Add one unit of sand to piles $$$1$$$ and $$$2$$$: $$$[\color{red}{3}, \color{red}{10}, 2, 4, 1]$$$.  Add one unit of sand to piles $$$4$$$ and $$$5$$$: $$$[3, 10, 2, \color{red}{5}, \color{red}{2}]$$$.  Add one unit of sand to piles $$$3$$$ and $$$4$$$: $$$[3, 10, \color{red}{3}, \color{red}{6}, 2]$$$.  Now piles $$$2$$$ and $$$4$$$ are too tall, so in this case the answer is $$$2$$$. It can be shown that it is impossible to make more than $$$2$$$ piles too tall.In the second test case, any operation will increase all piles by $$$1$$$ unit, so the number of too tall piles will always be $$$0$$$.In the third test case, we can increase any pile by $$$1$$$ unit of sand. It can be shown that the maximum number of too tall piles is $$$1$$$.

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

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

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

  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val k = tokenizer.nextToken().toInt
      tokenizer = new StringTokenizer(input.readLine())
      val A = ListBuffer.empty[Int]
      for (i <- 1 to n)
         A+= tokenizer.nextToken().toInt
      val B = A.toArray
      var c = 0
      if (k!=1) {
        for (i <- B.indices) {
          if ((i > 0) & ( i < B.length-1)){
            if (B(i) > B(i-1) + B(i+1)) {
              c+=1
            }
          }
        }
        println(c)
      }
      else {
        println((n - 1) /2)
      }
    }
  }

}