import scala.collection.mutable

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

  val t = nextInt
  def expected(i: Int): Char = if (i % 2 == 0) '(' else ')'

  for (_ <- 1 to t) {

    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = 0
    var r = n - 1
    val res = new mutable.ArrayBuffer[String]

    while (l < r) {
      while (l < r && s(l) == expected(l)) l += 1
      while (l < r && s(r) == expected(r)) r -= 1
      if (l < r) {
        var rr = r
        var ll = l
        while (s(rr) != expected(l)) rr -= 1
        res += s"${ll + 1} ${rr + 1}"
        while (ll < rr) {
          val tmp = s(ll)
          s(ll) = s(rr)
          s(rr) = tmp
          ll += 1
          rr -= 1
        }
      }
    }

    for (i <- 0 until n / 2 - k) {
      val l = 2 * i + 1
      val r = l + 1
      res += s"${l + 1} ${r + 1}"
    }

    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    out.flush()
  }

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

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

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

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

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

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

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

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._
}

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

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

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

  def mkT(N: Int, K: Int): String = {
    val str = StringBuilder.newBuilder
    REP(K - 1) { _ =>
      str.append("()")
    }
    REP(N/2 - (K-1)) { _ =>
      str.append("(")
    }
    REP(N/2 - (K-1)) { _ =>
      str.append(")")
    }
    str.toString
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N, K = ni()
      val S = ns(N)
      val T = mkT(N, K).toCharArray
      debug(S.mkString)
      debug(T.mkString)
      val ans = ArrayBuffer[(Int, Int)]()
      val pos1, pos2 = new java.util.ArrayDeque[Int]()
      def pos(i: Int) = if (S(i) == '(') pos1 else pos2
      def pos_rev(i: Int) = if (S(i) == '(') pos2 else pos1
      REP(N) { i =>
        pos(i).addLast(i)
      }
      REP(N) { i =>
        if (S(i) == T(i)) {
          pos(i).poll()
        }
        if (S(i) != T(i)) {
          pos(i).poll()
          val j = pos_rev(i).poll()
          pos(i).addFirst(j)
          debug(s"$i,$j")
          ans += ((i, j))
          if (j - i > 2) ans += ((i + 1, j - 1))
          val t = S(j)
          S(j) = S(i)
          S(i) = t
        }
      }
      out.println(ans.length)
      REP(ans.length) { i =>
        out.println(s"${ans(i)._1+1} ${ans(i)._2+1}")
      }
    }
  }
}

import scala.collection.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) pCount += 1
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    val l = s.indexOfSlice("((")
    val r = s.indexOf(')', l)
    s(l + 1) = ')'
    s(r) = '('
    s"${l + 1} $r"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' =>
          x += 1
          if (x == 1 && l > 0) done = true
        case ')' =>
          x -= 1
      }
      l += 1
    }
    l -= 2
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    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.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) pCount += 1
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    val l = s.indexOfSlice("((")
    val r = s.indexOf(')', l)
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' =>
          x += 1
          if (x == 1 && l > 0) done = true
        case ')' =>
          x -= 1
      }
      l += 1
    }
    l -= 2
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    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.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    while (s(l) != ')' || s(l + 1) != '(') l += 1
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    if (s.length == 2000) {
      println(s.drop(1533).mkString)
      System.exit(0)
    }
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    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.mutable

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

  val t = nextInt

  for (_ <- 1 to t) {

    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = 0
    val res = new mutable.ArrayBuffer[String]

    while (l < n) {
      val left = if (l % 2 == 0) '(' else ')'
      if (s(l) != left) {
        var r = n - 1
        while (s(r) != left) r -= 1
        res += s"${l + 1} ${r + 1}"
        var ll = l
        var rr = r
        while (ll < rr) {
          val tmp = s(ll)
          s(ll) = s(rr)
          s(rr) = tmp
          ll += 1
          rr -= 1
        }
      }
      l += 1
    }

    for (i <- 0 until n / 2 - k) {
      val l = 2 * i + 1
      val r = l + 1
      res += s"${l + 1} ${r + 1}"
    }

    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    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.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    while (s(l) != ')' || s(l + 1) != '(') l += 1
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    if (s.length == 2000) {
      println(s.mkString)
      System.exit(0)
    }
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    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.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    while (s(l) != ')' || s(l + 1) != '(') l += 1
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    if (s.length == 2000) {
      println(s.drop(511).mkString)
      System.exit(0)
    }
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    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.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    while (s(l) != ')' || s(l + 1) != '(') l += 1
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    if (s.length == 2000) {
      println(s.drop(1022).mkString)
      System.exit(0)
    }
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    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.mutable

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

  val t = nextInt

  for (_ <- 1 to t) {

    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = 0
    var r = n - 1
    val res = new mutable.ArrayBuffer[String]

    while (l < r) {
      val left = if (l % 2 == 0) '(' else ')'
      if (s(l) != left) {
        while (s(r) != left) r -= 1
        res += s"${l + 1} ${r + 1}"
        var ll = l
        var rr = r
        while (ll < rr) {
          val tmp = s(ll)
          s(ll) = s(rr)
          s(rr) = tmp
          ll += 1
          rr -= 1
        }
      }
      l += 1
    }

    for (i <- 0 until n / 2 - k) {
      val l = 2 * i + 1
      val r = l + 1
      res += s"${l + 1} ${r + 1}"
    }

    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    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.mutable

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

  val t = nextInt

  def checkLeft(s: Array[Char]): Int = {
    var x = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x < 0) return i
      }
      i += 1
    }
    -1
  }

  def checkRight(s: Array[Char]): Int = {
    var x = 0
    var i = s.length - 1
    while (i >= 0) {
      s(i) match {
        case '(' =>
          x -= 1
          if (x < 0) return i
        case ')' =>
          x += 1
      }
      i -= 1
    }
    -1
  }

  def checkPrefixes(s: Array[Char], k: Int): Int = {
    var x, pCount = 0
    var i = 0
    while (i < s.length) {
      s(i) match {
        case '(' => x += 1
        case ')' => x -= 1
      }
      if (x == 0) {
        pCount += 1
      }
      i += 1
    }
    pCount
  }

  def increase(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' => x += 1
        case ')' =>
          x -= 1
          if (x > 0) {
            done = true
          }
      }
      l += 1
    }
    l -= 2
    s(l) = ')'
    s(l + 1) = '('
    s"${l + 1} ${l + 2}"
  }

  def reduce(s: Array[Char]): String = {
    var l = 0
    var x = 0
    var done = false
    while (!done) {
      s(l) match {
        case '(' =>
          x += 1
          if (x == 1 && l > 0) {
            done = true
          }
        case ')' =>
          x -= 1
      }
      l += 1
    }
    l -= 2
    s(l) = '('
    s(l + 1) = ')'
    s"${l + 1} ${l + 2}"
  }

  for (test <- 1 to t) {
    val n, k = nextInt
    val s = nextLine.toCharArray
    var l = checkLeft(s)
    val res = new mutable.ArrayBuffer[String]
    while (l >= 0) {
      var r = checkRight(s)
      res += s"${l + 1} ${r + 1}"
      while (l < r) {
        val tmp = s(l)
        s(l) = s(r)
        s(r) = tmp
        l += 1
        r -= 1
      }
      l = checkLeft(s)
    }
    var pCount = checkPrefixes(s, k)
    while (pCount > k) {
      res += reduce(s)
      pCount = checkPrefixes(s, k)
    }
    while (pCount < k) {
      res += increase(s)
      pCount = checkPrefixes(s, k)
    }
    out.println(res.size)
    if (res.nonEmpty) out.println(res.mkString("\n"))
    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.io.StdIn.readLine
import scala.io.StdIn.readInt

object ChatOnline {

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

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def overlap(i1 : (Int,Int), i2: (Int,Int)) : Boolean = {
     return Math.max(i1._1,i2._1) <=  Math.min(i1._2,i2._2)
   }

   def main(args: Array[String]) {
     val (p,q,l,r) = readQuad()
     val ab = for {
       i <- 1 to p
       t = readTuple()
     } yield t
     val cd = for {
       i <- 1 to q
       t = readTuple()
     } yield t
    /* val zschedule = new Array[Boolean](ab.last._2 + 1)
     for (i <- 1 to zschedule.size) {
       val cur = ab(i)
       for (j <- cur._1 to cur._2) zschedule(j) = true
     }
     val xschedule = new Array[Boolean](ab.last._2 + 1)
     for (i <- 1 to xschedule.size) {
       val cur = cd(i)
       for (j <- cur._1 to cur._2) zschedule(j) = true
     }*/
     var t = l
     var sum = 0
     var bool = false
     while (t <= r) {
       var i = 0
       var ok = false
       while (i < ab.size && !ok) {
         var j = 0
         while (j < cd.size && !ok) {
           val ccd = (cd(j)._1+t, cd(j)._2+t)
           if (overlap(ab(i),ccd)) {
             sum += 1
             ok = true
           }
           j +=1
         }
         i += 1
       }
       t+=1

     }
     println(sum)

   }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(p, q, l, r) = in.next().split(" ").map(_.toInt)
  val first = (1 to p).map{ _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt)
    (a, b)
  }
  val second = (1 to q).map{ _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt)
    (a, b)
  }

  def intersect(a: Seq[(Int, Int)], b: Seq[(Int, Int)]): Boolean = {
    if (a.isEmpty || b.isEmpty) false
    else if ((a.head._1 >= b.head._1 && a.head._1 <= b.head._2) ||
      (a.head._2 >= b.head._1 && a.head._2 <= b.head._2) ||
      (b.head._1 >= a.head._1 && b.head._1 <= a.head._2) ||
      (b.head._2 >= a.head._1 && b.head._2 <= a.head._2)) {
      true
    } else {
      if (b.head._2 > a.head._2)
        intersect(a.tail, b)
      else
        intersect(a, b.tail)
    }
  }

  val res = (l to r).count(i => intersect(first, second.map(t => (t._1 + i, t._2 + i))))
  println(res)
}

object Main extends App {
  val Array(p, q, l, r) = readLine.split(" ").map(_.toInt)

  def readSegments(count: Int) = {
    (1 to count).map(i => {
      val Array(v1, v2) = readLine.split(" ").map(_.toInt)
      (v1, v2)
    })
  }

  val pSegments = readSegments(p)
  val qSegments = readSegments(q)

  def intersect(seg1: (Int, Int), seg2: (Int, Int)) = {
    seg1._1 <= seg2._2 && seg1._2 >= seg2._1
  }

  def commonMoment(shift: Int) = {
    qSegments.map(x => (x._1 + shift, x._2 + shift))
      .exists(qSeg => pSegments.exists(pSeg => intersect(pSeg, qSeg)))
  }

  println((l to r).count(commonMoment))
}


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

/**
 * Created by dmitry on 11.02.17.
 */
object Main3 {
  def main(args: Array[String]) {
    val graphMap: mutable.Map[Int, mutable.MutableList[Int]] = mutable.HashMap()
    /*graphMap += (1 -> graph)*/
    val n: Int = StdIn.readInt()
    for (i <- 0 until n - 1) {
      val input: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
      formGraph(graphMap, input.head, input.last)
      formGraph(graphMap, input.last, input.head)
    }
    val inputColors: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
    val colorsMap: mutable.Map[Int, Int] = mutable.HashMap()
    var j: Int = 1
    for (i <- inputColors) {
      colorsMap += (j -> i)
      j += 1
    }
    for (entry <- graphMap) {
      for (connectedVert <- entry._2) {
        if (colorsMap.get(entry._1).get != colorsMap.get(connectedVert).get) {
          var rz = solve(graphMap, colorsMap, entry._1, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          }
          rz = solve(graphMap, colorsMap, connectedVert, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          } else {
            println("NO")
            return
          }
        }
      }
    }
    for (entry <- graphMap) {
      for (connectedVert <- entry._2) {
        println("YES\n" + connectedVert)
        return
      }
    }
  }

  def formGraph(graphMap: mutable.Map[Int, mutable.MutableList[Int]], a: Int, b: Int): Unit = {
    if (!graphMap.contains(a))
      graphMap += (a -> (new mutable.MutableList[Int] += b))
    else {
      val listOfVertex: mutable.MutableList[Int] = graphMap.get(a).get
      listOfVertex += b
    }
  }

  def solve(graphMap: mutable.Map[Int, mutable.MutableList[Int]], colorGraph: mutable.Map[Int, Int], start: Int, size: Int): (String, Int) = {
    //usedVertexes(start) = true
    val linkedVertexes = new mutable.Queue[Int]
    linkedVertexes ++= graphMap.get(start).get
    val q: mutable.Queue[Int] = new mutable.Queue[Int]
    val setOfColors: mutable.HashSet[Int] = new mutable.HashSet
    val usedVertexes: Array[Boolean] = new Array(size + 1)
    while (linkedVertexes.nonEmpty) {
      usedVertexes(start) = true
      q.clear()
      setOfColors.clear()
      q.enqueue(linkedVertexes.dequeue())
      while (q.nonEmpty) {
        val vert = q.dequeue()
        if (!usedVertexes(vert)) {
          setOfColors += colorGraph.get(vert).get
          if (setOfColors.size > 1)
            return ("NO", -1)
          val lv = graphMap.get(vert).get
          for (v <- lv)
            q.enqueue(v)
          usedVertexes(vert) = true
        }
      }
    }
    ("YES", start)
  }
}

import Utils._, annotation._, collection._, util._, control._, math.Ordering.Implicits._, Searching._

object _764C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val edges = newMultiMap[Int, Int]
    repeat(n - 1) {
      val u, v = read[Int]
      edges(u) += v
      edges(v) += u
    }
    val colors = read[Vector, Int](n)
    /************************************/

    val cache = mutable.Map.empty[(Int, Int), Option[Int]]

    def singleColor(u: Int, parent: Int): Option[Int] = cache.getOrElseUpdate((u, parent), {
      val myColor = colors(u - 1)
      val isOkay = edges(u).forall(v => v == parent || singleColor(v, parent = u).contains(myColor))
      //debug(parent, u, isOkay)
      when(isOkay)(myColor)
    })

    def isOkay(root: Int) = edges(root).forall(u => singleColor(u, parent = root).isDefined)

    val out = (1 to n).find(isOkay) match {
      case Some(i) => s"YES\n$i"
      case _ => "NO"
    }

    write(out)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

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

/**
 * Created by dmitry on 11.02.17.
 */
object Main3 {
  def main(args: Array[String]) {
    val graphMap: mutable.Map[Int, mutable.MutableList[Int]] = mutable.HashMap()
    /*graphMap += (1 -> graph)*/
    val n: Int = StdIn.readInt()
    for (i <- 0 until n - 1) {
      val input: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
      formGraph(graphMap, input.head, input.last)
      formGraph(graphMap, input.last, input.head)
    }
    for (entry <- graphMap) {
      //println(entry._1 + " " + entry._2.toString())
    }
    val inputColors: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
    val colorsMap: mutable.Map[Int, Int] = mutable.HashMap()
    var j: Int = 1
    for (i <- inputColors) {
      colorsMap += (j -> i)
      j += 1
    }
    for (entry <- colorsMap) {
      //println(entry._1 + " " + entry._2.toString())
    }
    for (entry <- graphMap) {
      for (connectedVert <- entry._2) {
        if (colorsMap.get(entry._1).get != colorsMap.get(connectedVert).get) {
          var rz = solve(graphMap, colorsMap, entry._1, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          }
          rz = solve(graphMap, colorsMap, connectedVert, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          } else {
            println("NO")
            return
          }
        }

      }
    }
  }

  def formGraph(graphMap: mutable.Map[Int, mutable.MutableList[Int]], a: Int, b: Int): Unit = {
    if (!graphMap.contains(a))
      graphMap += (a -> (new mutable.MutableList[Int] += b))
    else {
      val listOfVertex: mutable.MutableList[Int] = graphMap.get(a).get
      listOfVertex += b
    }
  }

  def solve(graphMap: mutable.Map[Int, mutable.MutableList[Int]], colorGraph: mutable.Map[Int, Int], start: Int, size: Int): Tuple2[String, Int] = {
    var q: mutable.Queue[Int] = new mutable.Queue[Int]
    q += start
    val usedVertexes: Array[Boolean] = Array.fill(size + 1)(false)
    usedVertexes(start) = true
    val linkedVertexes = graphMap.get(start).get
    for (v <- linkedVertexes)
      q.enqueue(v)
    val setOfColors: mutable.HashSet[Int] = new mutable.HashSet
    while (q.nonEmpty) {
      val vert = q.dequeue()
      if (!usedVertexes(vert)) {
        setOfColors += colorGraph.get(vert).get
        if (setOfColors.size > 1)
          return ("NO", -1)
        val linkedVertexes = graphMap.get(vert).get
        for (v <- linkedVertexes)
          q.enqueue(v)
        usedVertexes(vert) = true
      }
    }
    ("YES", start)
  }
}

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

/**
 * Created by dmitry on 11.02.17.
 */
object Main3 {
  def main(args: Array[String]) {
    val graphMap: mutable.Map[Int, mutable.MutableList[Int]] = mutable.HashMap()
    /*graphMap += (1 -> graph)*/
    val n: Int = StdIn.readInt()
    for (i <- 0 until n - 1) {
      val input: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
      formGraph(graphMap, input.head, input.last)
      formGraph(graphMap, input.last, input.head)
    }
    for (entry <- graphMap) {
      //println(entry._1 + " " + entry._2.toString())
    }
    val inputColors: List[Int] = StdIn.readLine().split(" ").toStream.map(_.toInt).toList
    val colorsMap: mutable.Map[Int, Int] = mutable.HashMap()
    var j: Int = 1
    for (i <- inputColors) {
      colorsMap += (j -> i)
      j += 1
    }
    for (entry <- colorsMap) {
      //println(entry._1 + " " + entry._2.toString())
    }
    for (entry <- graphMap) {
      for (connectedVert <- entry._2) {
        if (colorsMap.get(entry._1).get != colorsMap.get(connectedVert).get) {
          var rz = solve(graphMap, colorsMap, entry._1, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          }
          rz = solve(graphMap, colorsMap, connectedVert, n)
          if (rz._1.equals("YES")) {
            println(rz._1 + "\n" + rz._2)
            return
          } else {
            println("NO")
            return
          }
        }
      }
    }
  }

  def formGraph(graphMap: mutable.Map[Int, mutable.MutableList[Int]], a: Int, b: Int): Unit = {
    if (!graphMap.contains(a))
      graphMap += (a -> (new mutable.MutableList[Int] += b))
    else {
      val listOfVertex: mutable.MutableList[Int] = graphMap.get(a).get
      listOfVertex += b
    }
  }

  def solve(graphMap: mutable.Map[Int, mutable.MutableList[Int]], colorGraph: mutable.Map[Int, Int], start: Int, size: Int): Tuple2[String, Int] = {
    //usedVertexes(start) = true
    val linkedVertexes = new mutable.Queue[Int]
    linkedVertexes ++= graphMap.get(start).get
    while (linkedVertexes.nonEmpty) {
      val usedVertexes: Array[Boolean] = Array.fill(size + 1)(false)
      usedVertexes(start) = true
      val q: mutable.Queue[Int] = new mutable.Queue[Int]
      val setOfColors: mutable.HashSet[Int] = new mutable.HashSet
      q.enqueue(linkedVertexes.dequeue())
      while (q.nonEmpty) {
        val vert = q.dequeue()
        if (!usedVertexes(vert)) {
          setOfColors += colorGraph.get(vert).get
          if (setOfColors.size > 1)
            return ("NO", -1)
          val lv = graphMap.get(vert).get
          for (v <- lv)
            q.enqueue(v)
          usedVertexes(vert) = true
        }
      }
    }
    ("YES", start)
  }

}


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)

  }

}

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

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


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

}

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

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


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


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

}

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


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")

}

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")

  }

}