There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one.  At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.

The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists.

Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them.

NoteThe first test sample is the one in the picture.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val str = in.next()
  if (str.contains('R') && !str.contains('L'))
    println(s"${str.indexOf('R') + 1} ${str.lastIndexOf('R') + 2}")
  else if (str.contains('R'))
    println(s"${str.indexOf('R') + 1} ${str.lastIndexOf('R') + 1}")
  else
    println(s"${str.lastIndexOf('L') + 1} ${str.indexOf('L')}")
}

import scala.io.Source

object D {

  def solve(s:String) = {
    val fl = s.indexOf('L')
    val fr = s.indexOf('R')
    val lr = s.lastIndexOf('R')
    def ret(a:Int, b:Int) = a+" "+b
    if (fl == -1) ret(fr, lr+1)
    else if (fr == -1) ret(fl, fl-1)
    else ret(fr, fl-1)
  }

  def main(args: Array[String]) {
    val x = Source.stdin.getLines.toList.last
    println(solve('.' + x))
  }
}

import java.util.Scanner

object A {

  def main(args: Array[String]): Unit = {
     var scan = new Scanner(System.in)
     var T = scan.nextLine.toInt
       var s = scan.nextLine
       var fl = s.indexOf('L')
       var fr = s.indexOf('R')
       if (fl == -1) {
         println((fr+1) + " " + (s.lastIndexOf('R')+2))
       } else if (fr == -1) {
         println ((fl+1)+ " " + fl)
       }
       else println ((fr+1)+ " " +fl)

  }

}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val s = readLine()
    val tr = s.zipWithIndex.filter(t => t._1 == 'R' || t._1 == 'L')
    if (tr(0)._1 == 'R') {
      val first = tr(0)._2 + 1
      val last = tr.find(_._1 == 'L') match {
        case Some(t) => t._2
        case None => tr.last._2 + 2
      }
      println(first + " " + last)
    } else {
      val first = tr.last._2 + 1
      val last = tr.head._2
      println(first + " " + last)
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val str = in.next()
  if (str.contains('R'))
    println(s"${str.indexOf('R') + 1} ${str.lastIndexOf('R') + 1}")
  else
    println(s"${str.lastIndexOf('L') + 1} ${str.indexOf('L') + 1}")
}

import java.util.Scanner

object A {

  def main(args: Array[String]): Unit = {
     var scan = new Scanner(System.in)
     var T = scan.nextLine.toInt
       var s = scan.nextLine
       var fl = s.indexOf('L')
       var fr = s.indexOf('R')
       if (fl == -1) {
         println(fr + " " + (s.lastIndexOf('R')+1))
       } else if (fr == -1) {
         println (fl+ " " + (fl-1))
       }
       else println (fr+ " " +(fl-1))

  }

}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val s = readLine()
    val tr = s.zipWithIndex.filter(t => t._1 == 'R' || t._1 == 'L')
    if (tr(0)._1 == 'R') {
      val first = tr(0)._2 + 1
      val last = tr.find(_._1 == 'L') match {
        case Some(t) => t._2
        case None => tr.last._2 + 2
      }
      println(first + " " + last)
    } else {
      val first = tr.last._2 + 2
      val last = tr.head._2
      println(first + " " + last)
    }
  }
}


You are given a pair of integers $$$(a, b)$$$ and an integer $$$x$$$.You can change the pair in two different ways:   set (assign) $$$a := |a - b|$$$;  set (assign) $$$b := |a - b|$$$,  where $$$|a - b|$$$ is the absolute difference between $$$a$$$ and $$$b$$$.The pair $$$(a, b)$$$ is called $$$x$$$-magic if $$$x$$$ is obtainable either as $$$a$$$ or as $$$b$$$ using only the given operations (i.e. the pair $$$(a, b)$$$ is $$$x$$$-magic if $$$a = x$$$ or $$$b = x$$$ after some number of operations applied). You can apply the operations any number of times (even zero).Your task is to find out if the pair $$$(a, b)$$$ is $$$x$$$-magic or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains three integers $$$a$$$, $$$b$$$ and $$$x$$$ ($$$1 \le a, b, x \le 10^{18}$$$).

For the $$$i$$$-th test case, print YES if the corresponding pair $$$(a, b)$$$ is $$$x$$$-magic and NO otherwise.

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(val a: Int, val 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 = 10010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val a = readLong()
        val b = readLong()
        val k = readLong()
        def find(x: Long, y: Long): String = {
            if (x < k && y < k) {
                return "NO"
            }
            if (x == k || y == k) {
                return "YES"
            }
            if (x == 0 || y == 0) {
                return "NO"
            }
            if (x > y) {
                if (x % y == k % y)
                    return "YES"
                else
                    return find(x%y, y)
            } else {
                if (y % x == k % x)
                    return "YES"
                else
                    return find(y%x, x)
            }
        }
        writer.println(find(a, b))
    }
    writer.flush()
}


The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.Let's consider a rectangular image that is represented with a table of size n × m. The table elements are integers that specify the brightness of each pixel in the image.A feature also is a rectangular table of size n × m. Each cell of a feature is painted black or white.To calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of W - B, where W is the total brightness of the pixels in the image, covered with white feature cells, and B is the total brightness of the pixels covered with black feature cells.Some examples of the most popular Haar features are given below.   Your task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.A prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.You have a variable value, whose value is initially zero. In one operation you can count the sum of pixel values at any prefix rectangle, multiply it by any integer and add to variable value.You are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — the number of rows and columns in the feature. Next n lines contain the description of the feature. Each line consists of m characters, the j-th character of the i-th line equals to "W", if this element of the feature is white and "B" if it is black.

Print a single number — the minimum number of operations that you need to make to calculate the value of the feature.

6 8
BBBBBBBB
BBBBBBBB
BBBBBBBB
WWWWWWWW
WWWWWWWW
WWWWWWWW

NoteThe first sample corresponds to feature B, the one shown in the picture. The value of this feature in an image of size 6 × 8 equals to the difference of the total brightness of the pixels in the lower and upper half of the image. To calculate its value, perform the following two operations:  add the sum of pixels in the prefix rectangle with the lower right corner in the 6-th row and 8-th column with coefficient 1 to the variable value (the rectangle is indicated by a red frame);  add the number of pixels in the prefix rectangle with the lower right corner in the 3-rd row and 8-th column with coefficient  - 2 and variable value.  Thus, all the pixels in the lower three rows of the image will be included with factor 1, and all pixels in the upper three rows of the image will be included with factor 1 - 2 =  - 1, as required.

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, m) = readInts(2)
  val ss = Array.fill(n) { readLine }

  def get(i: Int, j: Int): Int = {
    if (i == n || j == m) 0
    else if (ss(i)(j) == 'W') 1 else -1
  }

  var res = 0

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      if (get(i, j) != get(i + 1, j) + get(i, j + 1) - get(i + 1, j + 1)) res += 1
    }
  }

  println(res)
}

// Looksery Cup 2015 :: D

import java.util.Scanner

object D {

	var n:Int = _
	var m:Int = _
	var w:Array[Array[Int]] = _

	def read() = {
		n = in.nextInt
		m = in.nextInt
		in.nextLine

		w = (0 until n).map(i => in.nextLine().toCharArray().map(c => if (c == 'W') 1 else -1).toArray).toArray
	}

	val in:Scanner = new Scanner(System.in)

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

		val targetValue:Int = w(n - 1)(m - 1)

		var add:Array[Int] = Array.fill(m)(0)

		var count:Int = 0

		for (i <- n - 1 to 0 by -1) {
			for (j <- m - 1 to 0 by -1) {
				var value = w(i)(j) + add(j)
				if (value != targetValue) {
					for (k <- 0 to j) {
						add(k) += targetValue - value
					}
					count += 1
				}
			}
		}

		println(count + 1)
	}

}

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

import scala.collection.mutable

object D {

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

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

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

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

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

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

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

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

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

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

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

  var ft1: Array[Array[Int]] = _
  var ft2: Array[Array[Int]] = _
  var in: Array[Array[Char]] = _
  var bValue: Int = -1
  var wValue: Int = 1

  def invert1(x: Int, y: Int, diff: Int) = {
    for (i <- 0 to x)
      for (j <- 0 to y) {
        ft1(i)(j) += diff
      }
  }

//  def invert2(x: Int, y: Int) = {
//    for (i <- 0 to x)
//      for (j <- 0 to y) {
//        ft2(i)(j) = !ft2(i)(j)
//      }
//  }

  def check1(): Boolean = {
    val n = ft1.length
    val m = ft1(0).length
    for (i <- n - 1 to 0 by -1) {
      for (j <- m - 1 to 0 by -1) {
        if (in(i)(j) == 'B' && ft1(i)(j) != bValue) {
          invert1(i, j, bValue - ft1(i)(j))
          return false
        }
        if (in(i)(j) == 'W' && ft1(i)(j) != wValue) {
          invert1(i, j, wValue - ft1(i)(j))
          return false
        }
      }
    }
    true
  }

//  def check2(): Boolean = {
//    val n = ft2.length
//    val m = ft2(0).length
//    for (i <- n - 1 to 0 by -1) {
//      for (j <- m - 1 to 0 by -1) {
//        if ((in(i)(j) == 'B' && ft2(i)(j) != bValue) || (in(i)(j) == 'W' && ft2(i)(j) != wValue)) {
//          invert2(i, j)
//          return false
//        }
//      }
//    }
//    true
//  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    ft1 = new Array[Array[Int]](n)
    ft2 = new Array[Array[Int]](n)
    in = new Array[Array[Char]](n)
    for (i <- 0 until n) {
      ft1(i) = new Array[Int](m)
      ft2(i) = new Array[Int](m)
      in(i) = next.toCharArray
    }
    var ans1 = 0
    while (!check1 && ans1 <= 10000) {
      ans1 += 1
    }
    out.println(ans1)
    return 0
  }
}

import scala.io.StdIn

/**
 * @author chengyi
 */
object HaarFeatures {

  //find the corner from sr, sc in decreasing order, b against a
  def getCorner(a:Array[Array[Int]], b:Array[Array[Int]], sr:Int, sc:Int):(Int,Int)={
    (sc to 0 by -1).foreach(c=>({
        var rsr = 0
        if (c==sc) rsr = sr else rsr = b.length-1
        (rsr to 0 by -1).foreach(r=>({
          if (b(r)(c)!=a(r)(c)) return (r,c)
          }))
      }
      ))

    return (-1,-1)
  }

  //update b to make corner match a's
  def update(a:Array[Array[Int]], b:Array[Array[Int]], r:Int, c:Int) = {
    val delta = a(r)(c) - b(r)(c)
    (0 to r).foreach(rr=>((0 to c).foreach(cc=>(b(rr)(cc)=b(rr)(cc)+delta))))
  }

  def minOp(input:Array[String]):Int={
    val r = input.length
    val c = input(0).length
    val iinput:Array[Array[Int]]=Array.fill(r, c)(0)
    (1 to r).foreach(i=>{
      (1 to c).foreach(j=>if (input(i-1)(j-1)=='W') iinput(i-1)(j-1)=1 else iinput(i-1)(j-1)= -1)
    })

    //println(iinput.deep.mkString("\n"))

    val cur = Array.fill(r, c)(0)
    val sr = r-1
    val sc = c-1
    var (cr, cc) = getCorner(iinput, cur, sr, sc)

    //println("corner:" + cr + ", " + cc)

    var times = 1
    while (cr!= -1){
      update(iinput, cur, cr, cc);

      //println(cur.deep.mkString("\n"))

      val corner = getCorner(iinput, cur, cr, cc)
      cr = corner._1
      cc = corner._2

      //println("corner:" + cr + ", " + cc)

      times = times + 1
    }
    return times-1
  }

  def main(args:Array[String]){
    val rc = StdIn.readLine().split(" ").map { x => x.toInt }
    val r = rc(0)
    val c = rc(1)
    val input = Array.fill(r)("")
    (1 to r).foreach(i=>input(i-1) = StdIn.readLine())
    println(minOp(input))
  }
}

import scala.collection._

object D extends App {

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

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

  val cntB = Array.fill(n, m) { 0 }

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val up = if (i == 0) 0 else cntB(i - 1)(j)
      val left = if (j == 0) 0 else cntB(i)(j - 1)
      val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)
      val prev = up + left - upLeft
      cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)
    }
  }

  val res = Array.fill(n, m) { 0 }
  res(0)(0) = 1

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val ops = if (i == 0 && j == 0) 1
      else if (i == 0 && j > 0) res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)
      else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)
      else {
        val a = ss(i - 1)(j - 1)
        val b = ss(i)(j - 1)
        val c = ss(i - 1)(j)
        val d = ss(i)(j)
        val aR = res(i - 1)(j - 1)
        val bR = res(i)(j - 1)
        val cR = res(i - 1)(j)
        if (a == b && b == c && c == d) bR max cR
        else if (d == b && d == c) bR + cR - 2 * aR + 1
        else if (a == b && d == c) bR max cR
        else if (a == c && d == b) bR max cR
        else if (a == d && c == b) bR + cR - aR + 1
        else if (a == b && a == c) bR + cR + 2
        else 0
      }
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3
      //else if (ss(i)(j) == ss(i - 1)(j - 1)) ((res(i - 1)(j) max res(i)(j - 1)))
      //else ((res(i - 1)(j) max res(i)(j - 1)))
      //println(i, j, ops)
      res(i)(j) = ops
    }
  }

 // for (x <- res) println(x.mkString(" "))

  println(res.last.last)
}

import scala.collection._

object D extends App {

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

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

  val cntB = Array.fill(n, m) { 0 }

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val up = if (i == 0) 0 else cntB(i - 1)(j)
      val left = if (j == 0) 0 else cntB(i)(j - 1)
      val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)
      val prev = up + left - upLeft
      cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)
    }
  }

  val res = Array.fill(n, m) { 0 }
  res(0)(0) = 1

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val ops = if (i == 0 && j == 0) 1
      else if (i == 0 && j > 0) {
       // println(res(i)(j - 1))
        res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)
      }
      else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1
      else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3
      else (res(i - 1)(j) max res(i)(j - 1))
      //println(i, j, ops)
      res(i)(j) = ops
    }
  }

  //for (x <- res) println(x.mkString(" "))

  println(res.last.last)
}

import scala.collection._

object D extends App {

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

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

  val cntB = Array.fill(n, m) { 0 }

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val up = if (i == 0) 0 else cntB(i - 1)(j)
      val left = if (j == 0) 0 else cntB(i)(j - 1)
      val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)
      val prev = up + left - upLeft
      cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)
    }
  }

  val res = Array.fill(n, m) { 0 }
  res(0)(0) = 1

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val ops = if (i == 0 && j == 0) 1
      else if (i == 0 && j > 0) res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)
      else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)
      else {
        val a = ss(i - 1)(j - 1)
        val b = ss(i)(j - 1)
        val c = ss(i - 1)(j)
        val d = ss(i)(j)
        val aR = res(i - 1)(j - 1)
        val bR = res(i)(j - 1)
        val cR = res(i - 1)(j)
        if (a == b && b == c && c == d) bR max cR
        else if (d == b && d == c) (bR max cR)
        else if (a == b && d == c) bR max cR
        else if (a == c && d == b) bR max cR
        else if (a == d && c == b) bR + cR - aR + 1
        else if (a == b && a == c) bR + cR + 2
        else 0
      }
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3
      //else if (ss(i)(j) == ss(i - 1)(j - 1)) ((res(i - 1)(j) max res(i)(j - 1)))
      //else ((res(i - 1)(j) max res(i)(j - 1)))
      //println(i, j, ops)
      res(i)(j) = ops
    }
  }

 //for (x <- res) println(x.mkString(" "))

  println(res.last.last)
}

import scala.collection._

object D extends App {

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

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

  val cntB = Array.fill(n, m) { 0 }

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val up = if (i == 0) 0 else cntB(i - 1)(j)
      val left = if (j == 0) 0 else cntB(i)(j - 1)
      val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)
      val prev = up + left - upLeft
      cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)
    }
  }

  val res = Array.fill(n, m) { 0 }
  res(0)(0) = 1

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val ops = if (i == 0 && j == 0) 1
      else if (i == 0 && j > 0) {
       // println(res(i)(j - 1))
        res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)
      }
      else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)
      else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1
      else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1
      else (res(i - 1)(j) max res(i)(j - 1))
      //println(i, j, ops)
      res(i)(j) = ops
    }
  }

  //for (x <- res) println(x.mkString(" "))

  println(res.last.last)
}

import scala.collection._

object D extends App {

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

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

  val cntB = Array.fill(n, m) { 0 }

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val up = if (i == 0) 0 else cntB(i - 1)(j)
      val left = if (j == 0) 0 else cntB(i)(j - 1)
      val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)
      val prev = up + left - upLeft
      cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)
    }
  }

  val res = Array.fill(n, m) { 0 }
  res(0)(0) = 1

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val ops = if (i == 0 && j == 0) 1
      else if (i == 0 && j > 0) res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)
      else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)
      else {
        val a = ss(i - 1)(j - 1)
        val b = ss(i)(j - 1)
        val c = ss(i - 1)(j)
        val d = ss(i)(j)
        val aR = res(i - 1)(j - 1)
        val bR = res(i)(j - 1)
        val cR = res(i - 1)(j)
        if (a == b && b == c && c == d) bR max cR
        else if (d == b && d == c) bR max cR
        else if (a == b && d == c) bR max cR
        else if (a == c && d == b) bR max cR
        else if (a == d && c == b) bR + cR - aR + 1
        else if (a == b && a == c) bR + cR + 2
        else 0
      }
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3
      //else if (ss(i)(j) == ss(i - 1)(j - 1)) ((res(i - 1)(j) max res(i)(j - 1)))
      //else ((res(i - 1)(j) max res(i)(j - 1)))
      //println(i, j, ops)
      res(i)(j) = ops
    }
  }

 //for (x <- res) println(x.mkString(" "))

  println(res.last.last)
}

import scala.collection._

object D extends App {

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

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

  val cntB = Array.fill(n, m) { 0 }

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val up = if (i == 0) 0 else cntB(i - 1)(j)
      val left = if (j == 0) 0 else cntB(i)(j - 1)
      val upLeft = if (j == 0 || i == 0) 0 else cntB(i - 1)(j - 1)
      val prev = up + left - upLeft
      cntB(i)(j) = prev + (if (ss(i)(j) == 'B') 1 else 0)
    }
  }

  val res = Array.fill(n, m) { 0 }
  res(0)(0) = 1

  for (i <- 0 until n) {
    for (j <- 0 until m) {
      val ops = if (i == 0 && j == 0) 1
      else if (i == 0 && j > 0) res(i)(j - 1) + (if (ss(i)(j) != ss(i)(j - 1)) 1 else 0)
      else if (i > 0 && j == 0) res(i - 1)(j) + (if (ss(i)(j) != ss(i - 1)(j)) 1 else 0)
      else {
        val a = ss(i - 1)(j - 1)
        val b = ss(i)(j - 1)
        val c = ss(i - 1)(j)
        val d = ss(i)(j)
        val aR = res(i - 1)(j - 1)
        val bR = res(i)(j - 1)
        val cR = res(i - 1)(j)
        if (a == b && b == c && c == d) bR max cR
        else if (d == b && d == c) bR + cR - 2 * aR + 1
        else if (a == b && d == c) bR max cR
        else if (a == c && d == b) bR max cR
        else if (a == d && c == b) bR + cR - aR + 1
        else if (a == b && a == c) bR + cR + 2
        else 0
      }
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) != ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) + res(i - 1)(j - 1) + 1
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1) && ss(i)(j) == ss(i - 1)(j - 1)) (res(i - 1)(j) + res(i)(j - 1)) - res(i - 1)(j - 1) + 1
      //else if (ss(i)(j) != ss(i - 1)(j) && ss(i)(j) != ss(i)(j - 1)) res(i - 1)(j - 1) + 3
      //else if (ss(i)(j) == ss(i - 1)(j - 1)) ((res(i - 1)(j) max res(i)(j - 1)))
      //else ((res(i - 1)(j) max res(i)(j - 1)))
      //println(i, j, ops)
      res(i)(j) = ops
    }
  }

  //for (x <- res) println(x.mkString(" "))

  println(res.last.last)
}


All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.Treasure Island may be represented as a rectangular table $$$n \times m$$$ which is surrounded by the ocean. Let us number rows of the field with consecutive integers from $$$1$$$ to $$$n$$$ from top to bottom and columns with consecutive integers from $$$1$$$ to $$$m$$$ from left to right. Denote the cell in $$$r$$$-th row and $$$c$$$-th column as $$$(r, c)$$$. Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell $$$(n, m)$$$.Vasya got off the ship in cell $$$(1, 1)$$$. Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell $$$(x, y)$$$ he can move only to cells $$$(x+1, y)$$$ and $$$(x, y+1)$$$. Of course Vasya can't move through cells with impassable forests.Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells $$$(1, 1)$$$ where Vasya got off his ship and $$$(n, m)$$$ where the treasure is hidden.Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.

First line of input contains two positive integers $$$n$$$, $$$m$$$ ($$$3 \le n \cdot m \le 1\,000\,000$$$), sizes of the island. Following $$$n$$$ lines contains strings $$$s_i$$$ of length $$$m$$$ describing the island, $$$j$$$-th character of string $$$s_i$$$ equals "#" if cell $$$(i, j)$$$ contains an impassable forest and "." if the cell is free and passable. Let us remind you that Vasya gets of his ship at the cell $$$(1, 1)$$$, i.e. the first cell of the first row, and he wants to reach cell $$$(n, m)$$$, i.e. the last cell of the last row. It's guaranteed, that cells $$$(1, 1)$$$ and $$$(n, m)$$$ are empty.

Print the only integer $$$k$$$, which is the minimum number of cells Evil Witch has to turn into impassable forest in order to prevent Vasya from reaching the treasure.

NoteThe following picture illustrates the island in the third example. Blue arrows show possible paths Vasya may use to go from $$$(1, 1)$$$ to $$$(n, m)$$$. Red illustrates one possible set of cells for the Witch to turn into impassable forest to make Vasya's trip from $$$(1, 1)$$$ to $$$(n, m)$$$ impossible.

object D {

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

  val n, m = nextInt
  val grid = Array.fill(n)(nextToken.toCharArray)

  def dfs1(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = '*'
      var done = false
      if (c < m - 1 && grid(r)(c + 1) == '.') {
        done = dfs1(r, c + 1)
      }
      if (!done && r < n - 1 && grid(r + 1)(c) == '.') {
        done = dfs1(r + 1, c)
      }
      done
    }
  }

  def dfs2(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = '*'
      var done = false
      if (r < n - 1 && grid(r + 1)(c) == '.') {
        done = dfs2(r + 1, c)
      }
      if (!done && c < m - 1 && grid(r)(c + 1) == '.') {
        done = dfs2(r, c + 1)
      }
      done
    }
  }

  val can1 = dfs1(0, 0)
  val can2 = dfs2(0, 0)
  var res = 0
  if (can1) res += 1
  if (can2) res += 1

  out.println(res)
  out.flush()

  object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object D {

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

  val n, m = nextInt
  val grid = new Array[Array[Char]](n)
  var i = 0
  while (i < n) {
    grid(i) = nextToken.toCharArray
    i += 1
  }

  def dfs1(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = '*'
      var done = false
      if (c < m - 1 && grid(r)(c + 1) == '.') {
        done = dfs1(r, c + 1)
      }
      if (!done && r < n - 1 && grid(r + 1)(c) == '.') {
        done = dfs1(r + 1, c)
      }
      done
    }
  }

  def dfs2(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = '*'
      var done = false
      if (r < n - 1 && grid(r + 1)(c) == '.') {
        done = dfs2(r + 1, c)
      }
      if (!done && c < m - 1 && grid(r)(c + 1) == '.') {
        done = dfs2(r, c + 1)
      }
      done
    }
  }

  val can1 = dfs1(0, 0)
  val can2 = dfs2(0, 0)
  var res = 0
  if (can1) res += 1
  if (can2) res += 1

  out.println(res)
  out.flush()

  object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object D {

  def main(args: Array[String]): Unit = {}
  @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)) }

  val Array(n, m) = readInts(2)
  val grid = Array.fill(n)(readLine.toCharArray.map(_ == '#'))

  def dfs1(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = true
      var done = false
      if (c < m - 1 && !grid(r)(c + 1)) {
        done = dfs1(r, c + 1)
      }
      if (!done && r < n - 1 && !grid(r + 1)(c)) {
        done = dfs1(r + 1, c)
      }
      done
    }
  }

  def dfs2(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = true
      var done = false
      if (r < n - 1 && !grid(r + 1)(c)) {
        done = dfs2(r + 1, c)
      }
      if (!done && c < m - 1 && !grid(r)(c + 1)) {
        done = dfs2(r, c + 1)
      }
      done
    }
  }

  val can1 = dfs1(0, 0)
  val can2 = dfs2(0, 0)
  var res = 0
  if (can1) res += 1
  if (can2) res += 1

  println(res)
}

object D {

  import IO._
  def main(args: Array[String]): Unit = {}

  val n, m = nextInt
  val grid = Array.fill(n)(nextToken.toCharArray.map(_ == '#'))

  def dfs1(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = true
      var done = false
      if (c < m - 1 && !grid(r)(c + 1)) {
        done = dfs1(r, c + 1)
      }
      if (!done && r < n - 1 && !grid(r + 1)(c)) {
        done = dfs1(r + 1, c)
      }
      done
    }
  }

  def dfs2(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = true
      var done = false
      if (r < n - 1 && !grid(r + 1)(c)) {
        done = dfs2(r + 1, c)
      }
      if (!done && c < m - 1 && !grid(r)(c + 1)) {
        done = dfs2(r, c + 1)
      }
      done
    }
  }

  val can1 = dfs1(0, 0)
  val can2 = dfs2(0, 0)
  var res = 0
  if (can1) res += 1
  if (can2) res += 1

  out.println(res)
  out.flush()

  object IO {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object D {

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

  val n, m = nextInt
  val grid = new Array[Array[Char]](n)
  for (i <- 0 until n) {
    grid(i) = nextToken.toCharArray
  }

  def dfs1(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = '*'
      var done = false
      if (c < m - 1 && grid(r)(c + 1) == '.') {
        done = dfs1(r, c + 1)
      }
      if (!done && r < n - 1 && grid(r + 1)(c) == '.') {
        done = dfs1(r + 1, c)
      }
      done
    }
  }

  def dfs2(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = '*'
      var done = false
      if (r < n - 1 && grid(r + 1)(c) == '.') {
        done = dfs2(r + 1, c)
      }
      if (!done && c < m - 1 && grid(r)(c + 1) == '.') {
        done = dfs2(r, c + 1)
      }
      done
    }
  }

  val can1 = dfs1(0, 0)
  val can2 = dfs2(0, 0)
  var res = 0
  if (can1) res += 1
  if (can2) res += 1

  out.println(res)
  out.flush()

  object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}

object D {

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

  val n, m = nextInt
  val grid = new Array[Array[Char]](n)
  var i = 0
  while (i < n) {
    grid(i) = in.readLine.toCharArray
    i += 1
  }

  def dfs1(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = '*'
      var done = false
      if (c < m - 1 && grid(r)(c + 1) == '.') {
        done = dfs1(r, c + 1)
      }
      if (!done && r < n - 1 && grid(r + 1)(c) == '.') {
        done = dfs1(r + 1, c)
      }
      done
    }
  }

  def dfs2(r: Int, c: Int): Boolean = {
    if (r == n - 1 && c == m - 1) true
    else {
      grid(r)(c) = '*'
      var done = false
      if (r < n - 1 && grid(r + 1)(c) == '.') {
        done = dfs2(r + 1, c)
      }
      if (!done && c < m - 1 && grid(r)(c + 1) == '.') {
        done = dfs2(r, c + 1)
      }
      done
    }
  }

  val can1 = dfs1(0, 0)
  val can2 = dfs2(0, 0)
  var res = 0
  if (can1) res += 1
  if (can2) res += 1

  out.println(res)
  out.flush()

  object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    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 readInts(n: Int) = Array.fill(n)(nextInt)
    def readLongs(n: Int) = Array.fill(n)(nextLong)
    def readBigs(n: Int) = Array.fill(n)(nextBig)
  }
}


One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly:   It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains).  There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false. If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n, a ≠ b).

The output consists of one line, containing either yes or no depending on whether the nervous system is valid.

/**
  * Created by John Compitello on 7/25/16.
  */
object Easy {
  def main(args: Array[String]): Unit = {
    val lines: Array[String] = (for (ln <- io.Source.stdin.getLines) yield ln).toArray
    val line0: Array[Int] = lines(0).split(" ").map(_ toInt)
    val (numBrains, numConnectors): (Int, Int) = (line0(0), line0(1))

    if(numConnectors != numBrains - 1) {
      println("no")
    }
    else {
      val connectionList: List[(Int, Int)] = (for {
        connection <- 1 to numConnectors
        tempArray: Array[Int] = lines(connection).split(" ").map(x => x.toInt - 1)
      } yield (tempArray(0), tempArray(1))).toList

      val uf: UnionFind = new UnionFind(Vector.tabulate(numBrains)(x => x))
      val betterUf = connectionList.foldLeft(uf)((tempUf, pair) => tempUf.union(pair._1, pair._2))

      val rootList: List[Int] = (0 until numBrains).map(betterUf.root(_)) toList
      val bool: Boolean = rootList.forall(_ == rootList.head)

      if (bool) print("yes") else print("no")
    }
  }
}

class UnionFind(val vect: Vector[Int]) {

  def root(n : Int): Int = {
    val pointsTo: Int = vect(n)
    if(n == pointsTo) n else root(pointsTo)
  }

  def union(a: Int, b: Int): UnionFind = {
    //Make it so that a's root points to b's root.
    val aRoot = root(a)
    val bRoot = root(b)
    new UnionFind(vect.updated(aRoot, bRoot))
  }
}


You are playing a game on a $$$n \times m$$$ grid, in which the computer has selected some cell $$$(x, y)$$$ of the grid, and you have to determine which one. To do so, you will choose some $$$k$$$ and some $$$k$$$ cells $$$(x_1, y_1),\, (x_2, y_2), \ldots, (x_k, y_k)$$$, and give them to the computer. In response, you will get $$$k$$$ numbers $$$b_1,\, b_2, \ldots b_k$$$, where $$$b_i$$$ is the manhattan distance from $$$(x_i, y_i)$$$ to the hidden cell $$$(x, y)$$$ (so you know which distance corresponds to which of $$$k$$$ input cells). After receiving these $$$b_1,\, b_2, \ldots, b_k$$$, you have to be able to determine the hidden cell. What is the smallest $$$k$$$ for which is it possible to always guess the hidden cell correctly, no matter what cell computer chooses?As a reminder, the manhattan distance between cells $$$(a_1, b_1)$$$ and $$$(a_2, b_2)$$$ is equal to $$$|a_1-a_2|+|b_1-b_2|$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows.  The single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the number of rows and the number of columns in the grid.

For each test case print a single integer — the minimum $$$k$$$ for that test case.

NoteIn the first test case, the smallest such $$$k$$$ is $$$2$$$, for which you can choose, for example, cells $$$(1, 1)$$$ and $$$(2, 1)$$$.Note that you can't choose cells $$$(1, 1)$$$ and $$$(2, 3)$$$ for $$$k = 2$$$, as both cells $$$(1, 2)$$$ and $$$(2, 1)$$$ would give $$$b_1 = 1, b_2 = 2$$$, so we wouldn't be able to determine which cell is hidden if computer selects one of those.In the second test case, you should choose $$$k = 1$$$, for it you can choose cell $$$(3, 1)$$$ or $$$(1, 1)$$$.

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 Main2 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(val a: Int, val b:  Int, c: Double)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (b == that.b)
                return -1 * c.compareTo(that.c)
            else
                return -1 * b.compareTo(that.b)
        }
    }

    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 mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        if (n == 1 && m == 1)
            writer.println(0)
        else if (m == 1 || n == 1)
            writer.println(1)
        else
            writer.println(2)
    }
    writer.flush()
}

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 Main2 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(val a: Int, val b:  Int, c: Double)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (b == that.b)
                return -1 * c.compareTo(that.c)
            else
                return -1 * b.compareTo(that.b)
        }
    }

    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 mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        if (n == 1 && m == 1)
            writer.println(0)
        else
            writer.println(min(n, m))
    }
    writer.flush()
}


The Bitlandians are quite weird people. They have very peculiar customs.As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.

The first line contains integer n (1 ≤ n ≤ 106) — the number of eggs. Next n lines contain two integers ai and gi each (0 ≤ ai, gi ≤ 1000; ai + gi = 1000): ai is the price said by A. for the i-th egg and gi is the price said by G. for the i-th egg.

If it is impossible to assign the painting, print "-1" (without quotes). Otherwise print a string, consisting of n letters "G" and "A". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as Sa, and the money Uncle J. must pay G. for the painting as Sg, then this inequality must hold: |Sa  -  Sg|  ≤  500.  If there are several solutions, you are allowed to print any of them.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val res = (1 to n).map(_ => in.next().split(' ').map(_.toInt)).foldLeft(0, 0, List.empty[Char]) {
    case ((a, b, list), Array(f, s)) if a + f - b > 500 => (a, b + s, 'G' :: list)
    case ((a, b, list), Array(f, s)) => (a + f, b, 'A' :: list)
  }
  if (Math.abs(res._1 - res._2) <= 500)
    println(res._3.reverse.mkString)
  else
    println(-1)

}

import java.util.Scanner
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.nio.CharBuffer
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

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

  object Input {
    import java.lang.Character._

    lazy val in = new BufferedReader(new InputStreamReader(java.lang.System.in))
    var buf: Array[Char] = Array()
    var pos: Int = 0

    def next(): String = {
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      while (isWhitespace(buf(pos))) {
        pos += 1
      }
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      val s = pos
      while (pos < buf.length && !isWhitespace(buf(pos))) {
        pos += 1
      }
      new java.lang.String(buf, s, pos - s)
    }

    def nextInt(): Int = next.toInt

    def nextLong(): Long = next.toLong

    def nextFloat(): Float = next.toFloat

    def nextDouble(): Double = next.toDouble

    val nextString: () => String = next _
  }

  import Input._

  def solve(): String = {
    val N = nextInt
    val buf = CharBuffer.allocate(N)

    @tailrec
    def loop(n: Int, d: Int): Unit = {
      if (n == N) ()
      else {
        val a, g = nextInt
        if (d + a <= 500) {
          buf.put('A')
          loop(n + 1, d + a)
        }
        else {
          buf.put('G')
          loop(n + 1, d - g)
        }
      }
    }

    loop(0, 0)
    buf.flip
    buf.toString
  }

  out.println(solve)
  out.flush
}

object Main {
  def main(args: Array[String]) {
    def n = readInt
    var dif = 0
    for(_ <- 1 to n) {
      val a = readLine().split(" ").map(_.toInt)
      if(dif + a(0) > 500) {
        print("G")
        dif -= a(1)
      } else {
        print("A")
        dif += a(0)
      }
    }
  }
}

object CF173Div2B {
  def main(args: Array[String]){
    val n = readLine.toInt
    val pay = (1 to n).map(_ => readLine.split(" ").map(_.toInt))
    val (_,res) = pay.foldLeft((0,new StringBuilder))((b,a)=>if(b._1 + a(0) <= 500) (b._1+a(0),b._2+'A') else (b._1-a(1),b._2+'G'))
    println(res.toString)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val res = (1 to n).foldLeft(0, 0, List.empty[Char]) {
    case ((a, b, list), _) if a > b => (a, b + in.next().split(' ').last.toInt, 'G' :: list)
    case ((a, b, list), _) => (a + in.next().split(' ').last.toInt, b, 'A' :: list)
  }
  if (Math.abs(res._1 - res._2) <= 500)
    println(res._3.reverse.mkString)
  else
    println(-1)

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

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

  val N = sc.nextLine.toInt

  @tailrec
  def loop(acc: Int, i: Int): Int =
    if (i == N) acc
    else {
      val l = sc.nextLine
      if (l == "X++" || l == "++X") loop(acc + 1, i + 1)
      else loop(acc - 1, i + 1)
    }

  def solve: Int = loop(0, 0)

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.nio.CharBuffer
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Unit = {
    val N = sc.nextInt
    //val buf = CharBuffer.allocate(N)

    var d = 0
    for (_ <- 0 until N) {
      val a, g = sc.nextInt
      if (d + a <= 500) {
        out.print("A")
        //buf.put('A')
        d += a
      }
      else {
        out.print("G")
        //buf.put('G')
        d -= a
      }
    }

    //buf.flip
    //buf.toString
  }

  solve
  out.flush
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.nio.CharBuffer
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.collection.JavaConversions._
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Unit = {
    val N = sc.nextInt
    val buf = CharBuffer.allocate(N)

    var sa, sg = 0
    for (_ <- 0 until N) {
      val a, g = sc.nextInt
      if ((sa + a - sg).abs <= 500) {
        buf.put('A')
        sa += a
      }
      else {
        buf.put('G')
        sg += g
      }
    }

    buf.flip
    buf.toString
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.nio.CharBuffer
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): String = {
    val N = sc.nextInt
    val buf = CharBuffer.allocate(N)

    @tailrec
    def loop(n: Int, d: Int): Unit = {
      if (n == N) ()
      else {
        val a, g = sc.nextInt
        if (d + a <= 500) {
          buf.put('A')
          loop(n + 1, d + a)
        }
        else {
          buf.put('G')
          loop(n + 1, d - a)
        }
      }
    }

    loop(0, 0)
    buf.flip
    buf.toString
  }

  println(solve.toString)
  //  out.close
}

object Main {
  def main(args: Array[String]) {
    def n = readInt
    var dif = 0
    for(_ <- 1 to n) {
      val a = readLine().split(" ").map(_.toInt)
      if(dif + a(0) > 500) {
        print("G")
        dif -= a(1)
      } else {
        print("A")
        dif -= a(0)
      }
    }
  }
}


Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (xk, yk).The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like.  Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!

The first line of the input contains fix integers n, m, x, y, z, p (1 ≤ n, m ≤ 109; 0 ≤ x, y, z ≤ 109; 1 ≤ p ≤ 105). Each of the following p lines contains two integers xk, yk (1 ≤ xk ≤ n; 1 ≤ yk ≤ m) — the initial coordinates of the k-th candy. Two candies can lie on the same cell.

For each of the p candies, print on a single line its space-separated new coordinates.

NoteJust for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:QWER      REWQ ASDF  ->  FDSAZXCV      VCXZ

import java.util.Scanner
import scala.collection.immutable.HashSet

/**
 * Created by hama_du on 2014/02/24.
 */
object ProblemC extends App {
  val in = new Scanner(System.in)

  val n,m,x,y,z,p = in.nextInt()
  (0 until p).foreach(_ => {
    val i,j = in.nextInt()
    val newPosition = convert((n,m),(x%4,y%2,z%4),(i-1,j-1))
    println((newPosition._1+1) + " " + (newPosition._2+1))
  })

  def convert(mat:(Int,Int), ops:(Int,Int,Int), from:(Int,Int)): (Int,Int) = {
    val stat1 = (0 until ops._1).foldLeft((mat,from))((a,b) => convert90(a))
    val stat2 = (0 until ops._2).foldLeft(stat1)((a,b) => convertHFlip(a))
    val stat3 = (0 until ops._3).foldLeft(stat2)((a,b) => convert270(a))
    stat3._2
  }

  // ((n,m),(y,x)) => ((m,n),(y',x'))
  def convert90(state:((Int,Int),(Int,Int))): ((Int,Int),(Int,Int)) = {
    val map = state._1
    val pos = state._2
    ((map._2,map._1),(pos._2,map._1-pos._1-1))
  }

  def convertHFlip(state:((Int,Int),(Int,Int))): ((Int,Int),(Int,Int)) = {
    val map = state._1
    val pos = state._2
    ((map._1,map._2),(pos._1,map._2-pos._2-1))
  }

  def convert270(state:((Int,Int),(Int,Int))): ((Int,Int),(Int,Int)) = {
    val map = state._1
    val pos = state._2
    ((map._2,map._1),(map._2-pos._2-1,pos._1))
  }
}


You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:  Write parity(a) to the end of a. For example, .  Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.

The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.

Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.

NoteIn the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110

import java.util.Scanner

object C {

  def main(args: Array[String]): Unit = {
    val scan = new Scanner(System.in)
    var s1 = scan.next
    var s2 = scan.next
    var c1 = s1.count(c => c=='1')
    var c2 = s2.count(c => c=='1')
    if( c1>= c2)println( "YES")
    else if(c1+1==c2 && c1%2==1)println( "YES")
    else println("NO")

  }

}

object Main {
  def main(args: Array[String]) = {
    val a = readLine()
    val b = readLine()

    def countOnes(a: String) = a.count(_ == '1')
    def parity(a: String) = countOnes(a) % 2

    println(if (countOnes(a) + parity(a) >= countOnes(b)) "YES" else "NO")
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line1 = in.next().count(_ == '1')
  val line2 = in.next().count(_ == '1')

  if ((line1 + line1 % 2) >= line2)
    println("YES")
  else
    println("NO")

}


Polycarp has $$$n$$$ different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".Polycarp wants to offer his set of $$$n$$$ binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:  the final set of $$$n$$$ words still contains different words (i.e. all words are unique);  there is a way to put all words of the final set of words in the order so that the final sequence of $$$n$$$ words is consistent with the game rules. Polycarp wants to reverse minimal number of words. Please, help him.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of words in the Polycarp's set. Next $$$n$$$ lines contain these words. All of $$$n$$$ words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed $$$4\cdot10^6$$$. All words are different. Guaranteed, that the sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed $$$4\cdot10^6$$$.

Print answer for all of $$$t$$$ test cases in the order they appear. If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain $$$k$$$ ($$$0 \le k \le n$$$) — the minimal number of words in the set which should be reversed. The second line of the output should contain $$$k$$$ distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from $$$1$$$ to $$$n$$$ in the order they appear. If $$$k=0$$$ you can skip this line (or you can print an empty line). If there are many answers you can print any of them.

import scala.collection.immutable.HashMap

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val n = readInt
        val as = (0 until n).map((x) => (readLine, x + 1))
        val (has0, has1, hasl, zo, oz) = as.foldLeft((false, false, false, HashMap[String, Int](), HashMap[String, Int]())){
            case ((h0, h1, hl, zo, oz), (s, i)) => (s(0), s(s.length - 1)) match {
                case ('0', '0') => (true, h1, hl, zo, oz)
                case ('1', '1') => (h0, true, hl, zo, oz)
                case ('1', '0') => if (zo.contains(s.reverse)){
                    (h0, h1, true, zo - s.reverse, oz)
                }
                else {
                     (h0, h1, hl, zo, oz + (s -> i))
                }
                case ('0', '1') => if (oz.contains(s.reverse)){
                    (h0, h1, true, zo, oz - s.reverse)
                } else {
                    (h0, h1, hl, zo + (s -> i), oz)
                }
                case _ => throw new Exception("")
            }
        }
        if (zo.size == 0 && oz.size == 0) {
            if (hasl || ((has0 && !has1) || (!has0 && has1))) {
                println(0)
                println("")
            } else {
                println(-1)
            }
        }
        else {
        val total = zo.size + oz.size
        val (s1, s2) = (total / 2, total - (total / 2))
        val (k, il) = if (zo.size < oz.size) {
            (oz.size - s2, oz.values.take(oz.size - s2))
        } else {
            (zo.size - s2, zo.values.take(zo.size - s2))
        }
        println(k)
        println(il.mkString(" "))
        }
    }
  }

import scala.collection.mutable

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

  val t = nextInt
  for (_ <- 1 to t) {
    val n = nextInt
    val have01, have10 = mutable.Map.empty[String, Int]
    var have00, have11, haveMixed = false
    var i = 1
    while (i <= n) {
      val s = nextLine
      val l = s.length - 1
      if (s(0) == '0' && s(l) == '0') have00 = true
      else if (s(0) == '1' && s(l) == '1') have11 = true
      else {
        haveMixed = true
        val rev = s.reverse
        if (s(0) == '0' && s(l) == '1') {
          if (have10.contains(rev)) have10 -= rev
          else have01 += s -> i
        } else {
          if (have01.contains(rev)) have01 -= rev
          else have10 += s -> i
        }
      }
      i += 1
    }
    if (have00 && have11 && !haveMixed) out.println(-1)
    else {
      val need = Math.abs(have01.size - have10.size) / 2
      out.println(need)
      val res = if (have01.size > have10.size) have01 else have10
      out.println(res.values.toIterator.take(need).mkString(" "))
    }
  }

  out.println()
  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
  }
}

import scala.collection.immutable.HashMap

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val n = readInt
        val as = (0 until n).map((x) => (readLine, x + 1))
        val (has0, has1, hasl, zo, oz) = as.foldLeft((false, false, false, HashMap[String, Int](), HashMap[String, Int]())){
            case ((h0, h1, hl, zo, oz), (s, i)) => (s(0), s(s.length - 1)) match {
                case ('0', '0') => (true, h1, hl, zo, oz)
                case ('1', '1') => (h0, true, hl, zo, oz)
                case ('1', '0') => if (zo.contains(s.reverse)){
                    (h0, h1, true, zo - s.reverse, oz)
                }
                else {
                     (h0, h1, hl, zo, oz + (s -> i))
                }
                case ('0', '1') => if (oz.contains(s.reverse)){
                    (h0, h1, true, zo, oz - s.reverse)
                } else {
                    (h0, h1, hl, zo + (s -> i), oz)
                }
                case _ => throw new Exception("")
            }
        }
        if (zo.size == 0 && oz.size == 0) {
            if (hasl || ((has0 && !has1) || (!has0 && has1))) {
                println(0)
                println("")
            } else {
                println(-1)
            }
        }
        val total = zo.size + oz.size
        val (s1, s2) = (total / 2, total - (total / 2))
        val (k, il) = if (zo.size < oz.size) {
            (oz.size - s2, oz.values.take(oz.size - s2))
        } else {
            (zo.size - s2, zo.values.take(zo.size - s2))
        }
        println(k)
        println(il.mkString(" "))
    }
  }

import scala.collection.mutable

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

  val t = nextInt
  for (_ <- 1 to t) {
    val n = nextInt
    val have = mutable.Map.empty[String, Int]
    var have00, have11, haveMixed = false
    var i = 1
    while (i <= n) {
      val s = nextLine
      val l = s.length - 1
      if (s(0) == '0' && s(l) == '0') have00 = true
      else if (s(0) == '1' && s(l) == '1') have11 = true
      else {
        haveMixed = true
        val rev = s.reverse
        if (have.contains(rev)) have -= rev
        else have += s -> i
      }
      i += 1
    }
    if (have00 && have11 && !haveMixed) out.println(-1)
    else {
      val need = have.size / 2
      out.println(need)
      out.println(have.values.toIterator.take(need).mkString(" "))
    }
  }

  out.println()
  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
  }
}


There are $$$n$$$ pillars aligned in a row and numbered from $$$1$$$ to $$$n$$$.Initially each pillar contains exactly one disk. The $$$i$$$-th pillar contains a disk having radius $$$a_i$$$.You can move these disks from one pillar to another. You can take a disk from pillar $$$i$$$ and place it on top of pillar $$$j$$$ if all these conditions are met:  there is no other pillar between pillars $$$i$$$ and $$$j$$$. Formally, it means that $$$|i - j| = 1$$$;  pillar $$$i$$$ contains exactly one disk;  either pillar $$$j$$$ contains no disks, or the topmost disk on pillar $$$j$$$ has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $$$n$$$ disks on the same pillar simultaneously?

The first line contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of pillars. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_i$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the radius of the disk initially placed on the $$$i$$$-th pillar. All numbers $$$a_i$$$ are distinct.

Print YES if it is possible to place all the disks on the same pillar simultaneously, and NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

NoteIn the first case it is possible to place all disks on pillar $$$3$$$ using the following sequence of actions:  take the disk with radius $$$3$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$;  take the disk with radius $$$1$$$ from pillar $$$1$$$ and place it on top of pillar $$$2$$$;  take the disk with radius $$$2$$$ from pillar $$$4$$$ and place it on top of pillar $$$3$$$;  take the disk with radius $$$1$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$.

//package codeforces.contest1197

object Pillars {

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val seqWithIndex: Array[(Int, Int)] = io.StdIn.readLine().split(" ").map(_.toInt).zipWithIndex

    val (maxValue, index) = seqWithIndex.maxBy(_._1)

    val seq = seqWithIndex.map(_._1)

    def loop(top: Int, l: Int, r: Int): Boolean = {
      val lProspect = if (l >= 0) Some(seq(l)) else None
      val rProspect = if (r < n) Some(seq(r)) else None

      (lProspect, rProspect) match {
        case (Some(ll), Some(rr)) if ll < top && rr < top && ll != rr =>
          if (ll > rr) loop(ll, l - 1, r) else loop(rr, l, r + 1)
        case (Some(ll), None) if ll < top =>
          loop(ll, l - 1, n)
        case (None, Some(rr)) if rr < top =>
          loop(rr, -1, r + 1)
        case (None, None) =>
          true
        case _ =>
          false
      }
    }

    println(if (loop(maxValue, index - 1, index + 1)) "YES" else "NO")
  }

}

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 = {
    val N = ni()
    val A = na(N)
    val p = A.indexWhere(_ == N)
    var ok = true
    var i = p - 1
    while(i >= 0) {
      ok &&= A(i + 1) > A(i) // 単調増加
      i -= 1
    }
    i = p + 1
    while(i < N) {
      ok &&= A(i) < A(i - 1) // 単調減少
      i += 1
    }
    if (ok) out.println("YES")
    else out.println("NO")
  }
}

import java.util.StringTokenizer

object problemB {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
    var itsUp = true
    var prev = reader.nextToken().toInt
    var hasAnswer = true
    (1 until n).takeWhile { _ =>
      val current = reader.nextToken().toInt
      if (itsUp) {
        itsUp = current > prev
      } else {
        hasAnswer = hasAnswer && current < prev
      }
      prev = current
      hasAnswer
    }
    println(if (hasAnswer) "YES" else "NO")
  }
}

import java.util.StringTokenizer

object problemB {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
    var itsUp = true
    var prev = reader.nextToken().toInt
    var hasAnswer = true
    (1 until n).takeWhile { _ =>
      val current = reader.nextToken().toInt
      if (itsUp) {
        val change = current < prev
        if (change) {
          prev = current
          itsUp = false
        }
      } else {
        hasAnswer = hasAnswer && current <= prev
        prev = current
      }
      hasAnswer
    }
    println(if (hasAnswer) "YES" else "NO")
  }
}

import java.util.StringTokenizer

object problemB {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
    var itsUp = true
    var prev = reader.nextToken().toInt
    var hasAnswer = true
    (1 until n).takeWhile { _ =>
      val current = reader.nextToken().toInt
      if (itsUp) {
        val change = current <= prev
        if (change) {
          prev = current
          itsUp = false
        }
      } else {
        hasAnswer = hasAnswer && current < prev
        prev = current
      }
      hasAnswer
    }
    println(if (hasAnswer) "YES" else "NO")
  }
}

import java.util.StringTokenizer

object problemB {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
    var itsUp = true
    var prev = reader.nextToken().toInt
    var hasAnswer = true
    (1 until n).takeWhile { _ =>
      val current = reader.nextToken().toInt
      if (itsUp) {
        val change = current < prev
        if (change) {
          prev = current
          itsUp = false
        }
      } else {
        hasAnswer = hasAnswer && current < prev
        prev = current
      }
      hasAnswer
    }
    println(if (hasAnswer) "YES" else "NO")
  }
}


Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.

The first line of the input contains one integer, n (1 ≤ n ≤ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive.

Print the maximum possible even sum that can be obtained if we use some of the given integers.

NoteIn the first sample, we can simply take all three integers for a total sum of 6.In the second sample Wet Shark should take any four out of five integers 999 999 999.

/**
  * Created by octavian on 31/01/2016.
  */
object Wet {

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("./src/wet.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/wet.out")))

    val n = readInt()
    val numbers : Array[Int] = readLine.split(" ").map(_.toInt).sortWith(_ < _)

    var undesired = -1
    if(oddOdds(numbers)) {
      undesired = firstOdd(numbers)
    }

    var sum: BigInt = 0
    for(i <- 0 until numbers.length) {
      if(i != undesired) {
        sum += numbers(i)
      }
    }

    println(sum)
  }

  def oddOdds(numbers: Array[Int]): Boolean = {
    var odds = 0
    for(i <- 0 until numbers.length) {
      if(numbers(i) % 2 == 1) {
        odds += 1
      }
    }
    return(odds % 2 == 1)
  }

  def firstOdd(numbers: Array[Int]): Int = {
    for(i <- 0 until numbers.length) {
      if(numbers(i) % 2 == 1) {
        return i
      }
    }
    return  0
  }

}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toLong)
    val odd = a.filter((v) => v % 2 == 1)
    val even = a.filter((v) => v % 2 == 0)
    println(even.sum + odd.sum - (if (odd.length % 2 == 1) odd.min else 0))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val (even, odd) = data.partition(_ % 2 == 0)
  println(even.sum + odd.sum - (if (odd.length % 2 == 0) 0 else odd.min))
}

object A621 {
  @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) = readInts(1)
    val input = readLongs(n).sortBy(identity)
    if(input.exists(_%2 == 0) || (input.length > 1 && input(0)%2 == 1)) {
      var sum = input.sum
      var i = 0
      while (i < n && sum % 2 != 0) {
        if(input(i)%2 == 1)
          sum -= input(i)
        i += 1
      }
      println(sum)
    } else {
      println("0")
    }
  }
}

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) = readInts(1)
  val xs = readLongs(n)
  val (evens, odds) = xs.partition(_ % 2 == 0)

  val evensSum = evens.sum
  val oddsSum = if (odds.size % 2 == 1) odds.sorted.drop(1).sum else odds.sum
  val res = evensSum + oddsSum

  println(res)
}

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

object Task {

    def solve(in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = Array.fill(n) { in.nextLong() }
        val s = a.sum
        val answer = if (s % 2 == 0) s else s - a.view.filter(_ % 2 == 1).min
        out.println(answer)
    }

    def main(args: Array[String]) {
        val in = new InputReader(System.in)
        val out = new PrintWriter(System.out)

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch  {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

    def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def nextLong(): Long = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0l
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while(!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

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

    def close(): Unit = {
        inputStream.close()
    }
}

// So you like object Task
import java.io.{IOException, InputStream, PrintWriter}
import java.util.InputMismatchException

/**
  * Created with IntelliJ IDEA.
  * User: xie
  * Date: 2/6/16
  * Time: 2:03 PM
  */
object Task {

    def solve(in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = Array.fill(n) { in.nextLong() }
        val s = a.sum
        val answer = if (s % 2 == 0) s else s - a.view.filter(_ % 2 == 1).min
        out.println(answer)
    }

    def main(args: Array[String]) {
        val in = new InputReader(System.in)
        val out = new PrintWriter(System.out)

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch  {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

    def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def nextLong(): Long = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0l
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while(!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

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

    def close(): Unit = {
        inputStream.close()
    }
}

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

object Solution {

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

  def main(args: Array[String]) {

    val n = readLine().toInt
    val a = readInts(n)

    var res:Long = 0
    var firstOdd: Long = 0
    a.sorted(Ordering[Int].reverse).foreach { v =>
      if (v % 2 == 0) res += v
      else  {
        if (firstOdd == 0) firstOdd = v
        else {
          res += firstOdd + v
          firstOdd = 0
        }
      }
    }

    println(res)

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import scala.io.Source

/**
  * Created by yanluchen on 16/3/14.
  */

object A extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val row = in.next().split(" ").map(_.toLong)
  //  val (even,odd) = row.partition(_ % 2==0)
  val odd = row.filter(_ % 2 != 0)
  val ans = row.sum - (if (odd.length % 2 == 0) 0 else odd.min)
  println(ans)
}