object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val a=for(i<-0 until n) yield nextInt
    var l=0
    var r=1
    var maxl=2
    var mxv=a(l)
    var mnv=a(l)
    while(r<n){
      if(a(r)>mxv){
        if(mxv>mnv){
          //mxv-mnv=1, a(r)-mxv=1
          l=r-1
          while(l>0 && a(l)>mnv){
            l-=1
          }
          if(a(l)<=mnv){
            l+=1
          }

          mnv=mxv
        }
        mxv=a(r)
      }else if(a(r)<mnv){
        if(mnv<mxv){
          l=r-1
          while(l>0 && a(l)<mxv){
            l-=1
          }
          if(a(l)>=mxv){
            l+=1
          }
          mxv=mnv
        }
        mnv=a(r)
      }
      if(r-l+1>maxl){
        maxl=r-l+1

      }
      r+=1

    }
    out.println(maxl)

    //code ends here
    out.flush
    out.close
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  var total_max = 1
  var max = data.head
  var min = -1
  var maxCount = 1
  var minCount = 0
  var i = 0
  var j = 1
  var str = ""
  data.tail.foreach { el =>
    assert(minCount >= 0, "minCount less zero" )
    assert(maxCount >= 0, "maxCount less zero" )
    assert(j == i + minCount + maxCount, str)
    if (el == max) maxCount += 1
    else if (el == min) minCount += 1
    else if (min == -1 && max - el == 1) {
      min = el
      minCount = 1
    } else if (min == -1 && el - max == 1) {
      minCount = maxCount
      maxCount = 1
      min = max
      max = el
    }
    else if (min == -1) {
      max = el
      i += maxCount
      maxCount = 1
      str = "first"
    }
    else if (min - el == 1) {
      while (maxCount > 0) {
        if (data(i) == min)
          minCount -= 1
        else if (data(i) == max)
          maxCount -= 1
        i += 1
      }
      str = "second"
      max = min
      min = el
      maxCount = minCount
      minCount = 1
    } else if (el - max == 1) {
      while (minCount > 0) {
        if (data(i) == min)
          minCount -= 1
        else if (data(i) == max)
          maxCount -= 1
        i += 1
      }
      str = "third"
      min = max
      max = el
      minCount = maxCount
      maxCount = 1
    } else {
      str = "last"
      i += minCount + maxCount
      minCount = 0
      maxCount = 1
      min = -1
      max = el
    }
    if (minCount == 0)
      min = -1
    j += 1
    total_max = Math.max(total_max, maxCount + minCount)
  }
  println(total_max)
}

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

object B_333 {

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

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

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val number = line1.int

    val counters = new Array[Rinf](number);
    val line2 = readLine
    var mapL = List[Rinf]()
    var mapV = List[Rinf]()
    var mapH = List[Rinf]()
    var prev = -1
    var max = 0;
    for (i <- 0 until number) {
      val vv = line2.int
      if (prev == -1 || prev == vv) {
      } else if (prev < vv) {
        val last = calcMax(mapL, i)
//        calcMax(mapV, i)
//        calcMax(mapH, i)
        mapL = mapV
        mapV = mapH
        mapH = List[Rinf]()
        clean(last, i)
      } else {
        val last = calcMax(mapH, i)
//        calcMax(mapV, i)
//        calcMax(mapL, i)
        mapH = mapV
        mapV = mapL
        mapL = List[Rinf]()
        clean(last, i)
      }
      mapV ::= new Rinf(i, vv)
      prev = vv
      dump(i, vv)
    }
    calcMax(mapL, number)
    calcMax(mapV, number)
    calcMax(mapH, number)

    print(max)

    def calcMax(li: List[Rinf], i: Integer) = {
      for (ri <- li) {
        val di = i - ri.start
        if (max < di) max = di
      }
      if (li == Nil) -1 else li.head.start
    }

    def clean(index:Integer, i:Integer) {
      if (index == -1) { return; }
      mapL = mapL.filter { x => if (x.start <= index){updateMax(x, i)} ;x.start > index }
      mapV = mapV.filter { x => if (x.start <= index){updateMax(x, i)} ;x.start > index }
      mapH = mapH.filter { x => if (x.start <= index){updateMax(x, i)} ;x.start > index }
    }

    def updateMax(ri:Rinf, i:Integer) {
      val di = i - ri.start
        if (max < di) max = di
    }

    def dump(i:Integer, value:Integer) {
      if (!debugV) return
      var res = s"Step: $i:$value max=$max\nL: "
      mapL.foreach { res += _.start + ", " }
      res += "\nV: "
      mapV.foreach { res += _.start + ", " }
      res += "\nH: "
      mapH.foreach { res += _.start + ", " }
      db(res)
    }

    //---------------------------- parameters reading end ----------------------

  }

  class Rinf(val start: Int, var value: Int) {
    var finished = false
    override def toString(): String = {
      return start + ":" + value
    }
  }

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

  //============================================================================================
object Test {
val sa1 = """5
1 2 3 3 2
"""

val sa2 = """
11
5 4 5 5 6 7 8 8 8 7 6
"""

val t5 = """
4
1 1 2 3
"""

def t22() = {
  val n = 100000
  var res = new StringBuilder(n + "\n")
  for (i <- 0 until n) {
    res append " 100000"
  }
//  (0 until n).foreach(x => res += "100000")
//  println(res.toString())
  res.toString()
}

}

}

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

object B_333 {

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

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

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val number = line1.int

    val counters = new Array[Rinf](number);
    val line2 = readLine
    var mapL = List[Rinf]()
    var mapV = List[Rinf]()
    var mapH = List[Rinf]()
    var prev = -1
    var max = 0;
    for (i <- 0 until number) {
      val vv = line2.int
      if (prev == -1 || prev == vv) {
      } else if (prev < vv) {
        val last = calcMax(mapL, i)
        calcMax(mapV, i)
        calcMax(mapH, i)
        mapL = mapV
        mapV = mapH
        mapH = List[Rinf]()
        clean(last)
      } else {
        val last = calcMax(mapH, i)
        calcMax(mapV, i)
        calcMax(mapL, i)
        mapH = mapV
        mapV = mapL
        mapL = List[Rinf]()
        clean(last)
      }
      mapV ::= new Rinf(i, vv)
      prev = vv
      dump(i, vv)
    }
    calcMax(mapL, number)
    calcMax(mapV, number)
    calcMax(mapH, number)

    print(max)

    def calcMax(li: List[Rinf], i: Integer) = {
      if (i == 10) {
        println("here")
      }
      for (ri <- li) {
        val di = i - ri.start
        if (max < di) max = di
      }
      if (li == Nil) -1 else li.head.start
    }

    def clean(index:Integer) {
      if (index == -1) { return; }
      mapL = mapL.filter { x => x.start > index }
      mapV = mapV.filter { x => x.start > index }
      mapH = mapH.filter { x => x.start > index }
    }

    def dump(i:Integer, value:Integer) {
      var res = s"Step: $i:$value max=$max\nL: "
      mapL.foreach { res += _.start + ", " }
      res += "\nV: "
      mapV.foreach { res += _.start + ", " }
      res += "\nH: "
      mapH.foreach { res += _.start + ", " }
      db(res)
    }

    //---------------------------- parameters reading end ----------------------

  }

  class Rinf(val start: Int, var value: Int) {
    var finished = false
    override def toString(): String = {
      return start + ":" + value
    }
  }

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

  //============================================================================================
object Test {
val sa1 = """5
1 2 3 3 2
"""

val sa2 = """
11
5 4 5 5 6 7 8 8 8 7 6
"""

val t5 = """
4
1 1 2 3
"""

}

}

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

object B_333 {

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

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

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val number = line1.int

    val counters = new Array[Rinf](number);
    val line2 = readLine
    var mapL = List[Rinf]()
    var mapV = List[Rinf]()
    var mapH = List[Rinf]()
    var prev = -1
    var max = 0;
    for (i <- 0 until number) {
      val vv = line2.int
      if (prev == -1 || prev == vv) {
      } else if (prev < vv) {
        val last = calcMax(mapL, i)
        mapL = mapV
        mapV = mapH
        mapH = List[Rinf]()
        clean(last)
      } else {
        val last = calcMax(mapH, i)
        mapH = mapV
        mapV = mapL
        mapL = List[Rinf]()
        clean(last)
      }
      mapV ::= new Rinf(i, vv)
      prev = vv
      dump(i, vv)
    }
    calcMax(mapL, number-1)
    calcMax(mapV, number-1)
    calcMax(mapH, number-1)

    print(max)

    def calcMax(li: List[Rinf], i: Integer) = {
      for (ri <- li) {
        val di = i - ri.start + 1
        if (max < di) max = di
      }
      if (li == Nil) -1 else li.head.start
    }

    def clean(index:Integer) {
      if (index == -1) { return; }
      mapL = mapL.filter { x => x.start > index }
      mapV = mapV.filter { x => x.start > index }
      mapH = mapH.filter { x => x.start > index }
    }

    def dump(i:Integer, value:Integer) {
      var res = s"Step: $i:$value \nL: "
      mapL.foreach { res += _.start + ", " }
      res += "\nV: "
      mapV.foreach { res += _.start + ", " }
      res += "\nH: "
      mapH.foreach { res += _.start + ", " }
      db(res)
    }

    //---------------------------- parameters reading end ----------------------

  }

  class Rinf(val start: Int, var value: Int) {
    var finished = false
    override def toString(): String = {
      return start + ":" + value
    }
  }

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

  //============================================================================================
object Test {
val sa1 = """5
1 2 3 3 2
"""

val sa2 = """
11
5 4 5 5 6 7 8 8 8 7 6
"""

}

}


object C 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, q, c) = readInts(3)

  val cnt = Array.fill(c + 1, 101, 101){ 0 }

  Array.fill(n) {
    val Array(x, y, s) = readInts(3)
    cnt(s)(x)(y) += 1
  }

  for (s <- 0 to c) {
    for (y <- 1 to 100) {
      var left = 0
      for (x <- 1 to 100) {
        left += cnt(s)(x)(y)
        cnt(s)(x)(y) = left + cnt(s)(x)(y - 1)
      }
    }
  }

  val res = Array.ofDim[Int](q)

  for (i <- 0 until q) {
    val Array(t, x1, y1, x2, y2) = readInts(5)
    var sum = 0
    for (s <- 0 to c) {
      val count = cnt(s)(x2)(y2) - cnt(s)(x1 - 1)(y2) - cnt(s)(x2)(y1 - 1) + cnt(s)(x1 - 1)(y1 - 1)
      val brightness = (s + t) % (c + 1)
      sum += count * brightness
    }
    res(i) = sum
  }

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

  println(res.mkString("\n"))

  Console.flush
}

object CStarSky extends App {
  val Array(n, q, c) = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  var cnt = Array.fill[Int](c + 1, 101, 101){0}
  (0 until n).foreach { _ =>
    val Array(x, y, s) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    cnt(s)(x)(y) = cnt(s)(x)(y) + 1
  }
  for (p <- 0 to c; x <- 1 to 100; y <- 1 to 100)
    cnt(p)(x)(y) = cnt(p)(x)(y) + cnt(p)(x - 1)(y) + cnt(p)(x)(y - 1) - cnt(p)(x - 1)(y - 1)

  (0 until q).foreach { _ =>
    val Array(t, x1, y1, x2, y2) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val s = (0 to c).foldLeft(0) { (s, p) =>
      val brightness = (p + t) % (c + 1)
      val amount = cnt(p)(x2)(y2) + cnt(p)(x1-1)(y1-1) - cnt(p)(x1-1)(y2) - cnt(p)(x2)(y1-1)
      s + brightness * amount
    }
    println(s)
  }
}


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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val A = na(N)
      if (N == 2) {
        out.println(0)
      } else {
        sort(A)
        val A1 = A(N - 1)
        val A2 = A(N - 2)
        val cnt = N - 2
        val ans = min(cnt, min(A1 - 1, A2 - 1))
        out.println(ans)
      }
    }
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    java.util.Arrays.sort(a)
    a
  }
}

//package codeforces.contest1197

object DIYWoodenLadder {
  def main(args: Array[String]): Unit = {
    println((1 to io.StdIn.readInt).map { _ =>
      val n = io.StdIn.readInt()
      val seq = io.StdIn.readLine().split(" ").map(_.toInt).sorted

      if (seq.length > 2) {
        seq(n - 2) - 1 min n - 2
      } else 0

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

import java.util.StringTokenizer

object problemA {
  def main(args: Array[String]): Unit = {
    val T = scala.io.StdIn.readInt()
    (0 until T).map(_ => {
      val n = scala.io.StdIn.readInt()
      val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
      val initmax1 = reader.nextToken().toInt
      val initmax2 = reader.nextToken().toInt
      var max1 = Math.max(initmax1, initmax2)
      var max2 = Math.min(initmax1, initmax2)
      val steps = (2 until n).map(_ => {
        val i = reader.nextToken().toInt
        if (i >= max1) {
          max2 = max1
          max1 = i
        } else if (i > max2) {
          max2 = i
        } else()
        i
      })
      Math.min(max2 - 1, steps.size)
    }).foreach(println)
  }

}

import java.util.StringTokenizer

object solve {
  def main(args: Array[String]): Unit = {
    val T = scala.io.StdIn.readInt()
    (0 until T).foreach(_ => {
      val n = scala.io.StdIn.readInt()
      val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
      val initmax1 = reader.nextToken().toInt
      val initmax2 = reader.nextToken().toInt
      var max1 = Math.max(initmax1, initmax2)
      var max2 = Math.min(initmax1, initmax2)
      val steps = (2 until n).map(_ => {
        val i = reader.nextToken().toInt
        if (i >= max1) {
          max2 = max1
          max1 = i
        }
        i
      })
      val res = Math.min(max2 - 1, steps.size)

      println(res)
    })
  }

}

import java.util.StringTokenizer

object solve {
  def main(args: Array[String]): Unit = {
    val T = scala.io.StdIn.readInt()
    (0 until T).map(_ => {
      val n = scala.io.StdIn.readInt()
      val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
      val initmax1 = reader.nextToken().toInt
      val initmax2 = reader.nextToken().toInt
      var max1 = Math.max(initmax1, initmax2)
      var max2 = Math.min(initmax1, initmax2)
      val steps = (2 until n).map(_ => {
        val i = reader.nextToken().toInt
        if (i >= max1) {
          max2 = max1
          max1 = i
        }
        i
      })
      Math.min(max2 - 1, steps.size)
    }).foreach(println)
  }

}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt).groupBy(k => k).map(t => t._1 -> t._2.length)
  val first = Math.max(0, data.getOrElse(1, 0) - m)
  val second =
    if (first == 0)
      Math.max(0, data.getOrElse(2, 0) - k - m + data.getOrElse(1, 0))
  else
    Math.max(0, data.getOrElse(2, 0) - k)
  println(first + second)
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ")
    val c1 = a.count(_ == "1")
    val c2 = a.count(_ == "2")

    val count = (c1 - m).max(0) + (c2 - k - (m - c1).max(0)).max(0)
    println(count)
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-19.
 */
object A369 extends App{
  val sc = new Scanner(System.in)
  val n, m, k = sc.nextInt()
  val a: Array[Int] = (1 to n).map(_ => sc.nextInt()).toArray
  val needBowl = a.count(_ == 1)
  val needAny = n - needBowl

  // 需要洗的碗
  val needWashBowl = if (m - needBowl >= 0) {
    0
  } else {
    needBowl - m
  }

  // 需要洗的其他
  val needWashAny: Int = if (needWashBowl == 0) {
    needAny - (m - needBowl + k) // 存量的其他
  } else {
    needAny - k
  }

  println(needWashBowl + (if (needWashAny < 0) {
    0
  } else {
    needWashAny
  }))
}

object HelloWorld   {
    def main(args:Array[String]){
        var nmk=readLine().split(" ").map(_.toInt)
        var n=nmk(0)
        var m=nmk(1)
        var k=nmk(2)
        var sum=0
        var array=readLine().split(" ").map(_.toInt)
        for(i<-0 to n-1){
            var int=array(i)
            if(int==1){
                if (m>=1) {
                    m-=1
                }else{
                    sum+=1
                }
            }else{
                if (k>=1) {
                    k-=1
                }else if(m>=1){
                    m-=1
                }else{
                    sum+=1
                }
            }
        }
        println(sum)
    }
}

object HelloWorld   {
    def main(args:Array[String]){
        var Array(n,m,k)=readLine().split(" ").map(_.toInt)
        var sum=0
        var array=readLine().split(" ")
        for(i<-0 to n-1){
            var int=array(i).toInt
            if(int==1){
                if (m>=1) {
                    m-=1
                }else{
                    sum+=1
                }
            }else{
                if (k>=1) {
                    k-=1
                }else if(m>=1){
                    m-=1
                }else{
                    sum+=1
                }
            }
        }
        println(sum)
    }
}

object HelloWorld   {
    def main(args:Array[String]){
        var Array(n,m,k)=readLine().split(" ").map(_.toInt)
        var sum=0
        var array=readLine().split(" ").map(_.toInt)
        for(i<-0 to n-1){
            var int=array(i)
            if(int==1){
                if (m>=1) {
                    m-=1
                }else{
                    sum+=1
                }
            }else{
                if (k>=1) {
                    k-=1
                }else if(m>=1){
                    m-=1
                }else{
                    sum+=1
                }
            }
        }
        println(sum)
    }
}

object Solution216A extends App {

  def solution() {
    val n = _int
    val b = _int
    val p = _int

    val a = 1.to(n).map(_ => _int)
    val gr = a.groupBy(i => i)
    val n1 = gr.get(1).getOrElse(Nil).size
    val n2 = math.max(gr.get(2).getOrElse(Nil).size - p, 0)

    val req = n1 + n2

    if (req <= b) {
      println(0)
    } else {
      println(req - b)
    }
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}

import java.util.StringTokenizer

object _369A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  var m = next.toInt
  val k = next.toInt
  val a = (1 to n).map(i => next.toInt)
  val one = a.filter(i => i == 1).size
  val two = a.filter(i => i == 2).size

  var ans = if (m >= one) 0 else one - m
  m = if (m - one >= 0) m - one else 0
  ans = ans + (if (m + k - two >= 0) 0 else two - m - k)
  println(ans)
}

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

object P369A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M, K = sc.nextInt
  type Dishes = List[Int]
  val A: Dishes = List.fill(N)(sc.nextInt)

  def solve(): Int = {

    @tailrec
    def loop(acc: Int, b: Int, p: Int, ds: Dishes): Int = ds match { //
        case Nil       => acc
        case 1 :: rest => { // first type from bowl
          if (b > 0) loop(acc, b - 1, p, rest)
          else loop(acc + 1, 0, p, rest)
        }
        case 2 :: rest => { // second type from either bowl or plate
          if (p > 0) loop(acc, b, p - 1, rest)
          else if (b > 0) loop(acc, b - 1, p, rest)
          else loop(acc + 1, 0, 0, rest)
        }
        case _ => -1
      }

    loop(0, M, K, A)
  }

  out.println(solve)
  out.close
}

object A369 {

  import IO._

  def main(args: Array[String]): Unit = {
    var Array(n, m, k) = readInts(3)
    val in = readInts(n)
    var res = 0
    for(i <- 0 until n) {
      val day = in(i)
      if(day == 1) {
        if(m > 0) {m -= 1} else {res += 1}
      } else {
        if(m > 0 || k > 0) {
          if(k > 0) {
            k -= 1
          } else {
            m -= 1
          }
        } else {
          res += 1
        }
      }
    }
    println(res)
  }

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

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

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

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

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

}

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

object P369A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M, K = sc.nextInt
  val A = List.fill(N)(sc.nextInt)

  type Dishes = List[Int]

  def solve(): Int = {

    @tailrec
    def loop(acc: Int, b: Int, p: Int, ds: Dishes): Int = ds match { //
        case Nil       => acc
        case 1 :: rest => { // first type from bowl and dish
          if (b < 1) loop(acc + 1, M, K, rest)
          else loop(acc, b - 1, p, rest)
        }
        case 2 :: rest => { // second type from either bowl or plate
          if (b < p) {
            if (p < 1) loop(acc + 1, M, K, rest)
            else loop(acc, b, p - 1, rest)
          }
          else {
            if (b < 1) loop(acc + 1, M, K, rest)
            else loop(acc, b - 1, p, rest)
          }
        }
        case _ => -1
      }

    loop(0, M, K, A)
  }

  out.println(solve)
  out.close
}

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

object P369A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M, K = sc.nextInt
  val A = List.fill(N)(sc.nextInt)

  type Dishes = List[Int]

  def solve(): Int = {

    @tailrec
    def loop(acc: Int, b: Int, p: Int, ds: Dishes): Int = ds match { //
        case Nil       => acc
        case 1 :: rest => { // first type from bowl and dish
          val wash = if (b < 1) 1 else 0
          loop(acc + wash, b - 1, p, rest)
        }
        case 2 :: rest => { // second type from either bowl or plate
          val wash = if (b < 1 && p < 1) 1 else 0
          if (b < p) loop(acc + wash, b, p - 1, rest)
          else loop(acc + wash, b - 1, p, rest)
        }
        case _ => -1
      }

    loop(0, M, K, A)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-19.
 */
object A369 extends App{
  val sc = new Scanner(System.in)
  val n, m, k = sc.nextInt()
  val a: Array[Int] = (1 to n).map(_ => sc.nextInt()).toArray
  val needBowl = a.count(_ == 1)
  val needAny = n - needBowl

  // 需要洗的碗
  val needWashBowl = if (m - needBowl >= 0) {
    0
  } else {
    needBowl - m
  }

  val needWashAny: Int = if (needWashBowl == 0) {
    needAny - (m - needBowl + n)
  } else {
    needAny - k
  }

  println(needWashBowl + (if (needWashAny < 0) {
    0
  } else {
    needWashAny
  }))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt).groupBy(k => k).map(t => t._1 -> t._2.length)
  println(Math.max(0, data.getOrElse(1, 0) - m) + Math.max(0, data.getOrElse(2, 0) - k))
}

object A369 {

  import IO._

  def main(args: Array[String]): Unit = {
    var Array(n, m, k) = readInts(3)
    val in = readInts(n)
    var res = 0
    for(i <- 0 until n) {
      val day = in(i)
      if(day == 1) {
        if(m > 0) {m -= 1} else {res += 1}
      } else {
        if(m > 0 || k > 0) {
          if(m > k) {
            m -= 1
          } else {
            k -= 1
          }
        } else {
          res += 1
        }
      }
    }
    println(res)
  }

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

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

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

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

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

}


import scala.io.StdIn._
import scala.util.control.Breaks._

object Main {
  def main(args: Array[String]): Unit = {
      val Array(n, m): Array[Int] = readLine().split(" ").map(_.toInt)
      val A: Array[Long]  = readLine().split(" ").map(_.toLong)
      val pref: Array[Long] = Array.fill(n)(0)
      val suff: Array[Long] = Array.fill(n)(0)
      for (i <- 1 until n) {
          pref(i) = pref(i-1) - (A(i) - A(i-1)).min(0)
      }
      for (i <- n-2 to 0 by -1) {
          suff(i) = suff(i+1) - (A(i) - A(i+1)).min(0)
      }

      for (_ <- 1 to m) {
          val Array(s, t) = readLine().split(" ").map(x => x.toInt-1)
          if (s == t) {
              println(0)
          } else if (s < t) {
              println(pref(t)-pref(s))
          } else {
              println(suff(t)-suff(s))
          }
      }
    }
}

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

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

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val m = tokenizer.nextToken().toInt
    val q = tokenizer.nextToken().toInt
    val C = new Array[Long](m)
    tokenizer = new StringTokenizer(input.readLine())
    for (i <- 1 to m) {
      C(i-1) = tokenizer.nextToken().toLong
    }
    val B = new Array[Long](m)
    val A = new Array[Long](m)
    A(0) = 0
    B(m-1) = 0
    for (i <- 1 to m-1) {
        A(i) = A(i-1) + max(0,C(i-1) - C(i))
        B(m-1-i) = B(m-1-i+1) + max(0,C(m-1-i+1) - C(m-1-i))
    }
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n1 = tokenizer.nextToken().toInt
      val n2 = tokenizer.nextToken().toInt
      if (n1 < n2) {
        println(A(n2-1) - A(n1-1))
      }
      else {
        println(B(n2-1) - B(n1-1))
      }
    }
  }
}


import scala.collection.mutable

object B 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 ds = readInts(n)

  val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (id <- 1 to m) {
    val Array(_u, _v) = readInts(2)
    val u = _u - 1
    val v = _v - 1

    adjBuilders(u) += v
    adjBuilders(v) += u

    edgeIdBuilders(u) += id
    edgeIdBuilders(v) += id
  }

  val firstMinus = ds.indexOf(-1)
  val sumParity = ds.count(_ == 1) % 2

  if (firstMinus == -1 && sumParity == 1) {
    println(-1)
  } else {

    for (i <- ds.indices) {
      if (ds(i) == -1) ds(i) = if (i == firstMinus && sumParity == 1) 1 else 0
    }

    val adjs = adjBuilders.map(_.result)
    val edgeIds = edgeIdBuilders.map(_.result)

    val visited = new mutable.BitSet(n)
    val leaves = mutable.Queue.empty[Int]
    val childrenCounts = Array.fill(n)(0)
    val parents, parentEdges = Array.fill(n)(-1)

    def dfs(u: Int): Unit = {
      visited(u) = true
      var i = 0
      while (i < adjs(u).length) {
        val v = adjs(u)(i)
        if (!visited(v)) {
          childrenCounts(u) += 1
          parents(v) = u
          parentEdges(v) = edgeIds(u)(i)
          dfs(v)
        }
        i += 1
      }
      if (childrenCounts(u) == 0) leaves += u
    }

    dfs(0)

    val resultBuilder = new mutable.ArrayBuilder.ofInt

    while (leaves.nonEmpty) {
      val u = leaves.dequeue()
      val v = parents(u)
      if (v >= 0) {

        if (ds(u) == 1) {
          resultBuilder += parentEdges(u)
          ds(v) = 1 - ds(v)
        }
        childrenCounts(v) -= 1
        if (childrenCounts(v) == 0) leaves += v
      }
    }

    val res = resultBuilder.result

    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    println(res.length)
    println(res.sorted.mkString("\n"))
    Console.flush
  }
}

import scala.collection.mutable

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = {
    val tl = tokenizeLine
    val a = Array.ofDim[Int](n)
    var i = 0
    while (i < n) {
      a(i) = Integer.parseInt(tl.nextToken)
      i += 1
    }
    a
  }

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

  val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (id <- 1 to m) {
    val Array(_u, _v) = readInts(2)
    val u = _u - 1
    val v = _v - 1

    adjBuilders(u) += v
    adjBuilders(v) += u

    edgeIdBuilders(u) += id
    edgeIdBuilders(v) += id
  }

  val firstMinus = ds.indexOf(-1)
  val sumParity = ds.count(_ == 1) % 2

  if (firstMinus == -1 && sumParity == 1) {
    println(-1)
  } else {

    for (i <- ds.indices) {
      if (ds(i) == -1) ds(i) = if (i == firstMinus && sumParity == 1) 1 else 0
    }

    val adjs = adjBuilders.map(_.result)
    val edgeIds = edgeIdBuilders.map(_.result)

    val visited = new mutable.BitSet(n)
    val leaves = mutable.Queue.empty[Int]
    val childrenCounts = Array.fill(n)(0)
    val parents, parentEdges = Array.fill(n)(-1)

    def dfs(u: Int): Unit = {
      visited(u) = true
      var i = 0
      while (i < adjs(u).length) {
        val v = adjs(u)(i)
        if (!visited(v)) {
          childrenCounts(u) += 1
          parents(v) = u
          parentEdges(v) = edgeIds(u)(i)
          dfs(v)
        }
        i += 1
      }
      if (childrenCounts(u) == 0) leaves += u
    }

    dfs(0)

    val resultBuilder = new mutable.ArrayBuilder.ofInt

    while (leaves.nonEmpty) {
      val u = leaves.dequeue()
      val v = parents(u)
      if (v >= 0) {

        if (ds(u) == 1) {
          resultBuilder += parentEdges(u)
          ds(v) = 1 - ds(v)
        }
        childrenCounts(v) -= 1
        if (childrenCounts(v) == 0) leaves += v
      }
    }

    val res = resultBuilder.result

    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    println(res.length)
    println(res.sorted.mkString("\n"))
    Console.flush
  }
}

import scala.collection.mutable

object B extends App {

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

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

  val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (id <- 1 to m) {
    val Array(_u, _v) = readInts(2)
    val u = _u - 1
    val v = _v - 1

    adjBuilders(u) += v
    adjBuilders(v) += u

    edgeIdBuilders(u) += id
    edgeIdBuilders(v) += id
  }

  val firstMinus = ds.indexOf(-1)
  val sumParity = ds.count(_ == 1) % 2

  if (firstMinus == -1 && sumParity == 1) {
    println(-1)
  } else {

    for (i <- ds.indices) {
      if (ds(i) == -1) ds(i) = if (i == firstMinus && sumParity == 1) 1 else 0
    }

    val adjs = adjBuilders.map(_.result)
    val edgeIds = edgeIdBuilders.map(_.result)

    val visited = new mutable.BitSet(n)
    val leaves = mutable.Queue.empty[Int]
    val childrenCounts = Array.fill(n)(0)
    val parents, parentEdges = Array.fill(n)(-1)

    def dfs(u: Int): Unit = {
      visited(u) = true
      var i = 0
      while (i < adjs(u).length) {
        val v = adjs(u)(i)
        if (!visited(v)) {
          childrenCounts(u) += 1
          parents(v) = u
          parentEdges(v) = edgeIds(u)(i)
          dfs(v)
        }
        i += 1
      }
      if (childrenCounts(u) == 0) leaves += u
    }

    dfs(0)

    val resultBuilder = new mutable.ArrayBuilder.ofInt

    while (leaves.nonEmpty) {
      val u = leaves.dequeue()
      val v = parents(u)
      if (v >= 0) {

        if (ds(u) == 1) {
          resultBuilder += parentEdges(u)
          ds(v) = 1 - ds(v)
        }
        childrenCounts(v) -= 1
        if (childrenCounts(v) == 0) leaves += v
      }
    }

    val res = resultBuilder.result

    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    println(res.length)
    println(res.sorted.mkString("\n"))
    Console.flush
  }
}

import scala.collection.mutable

object B 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 ds = readInts(n)

  val adjBuilders, edgeIdBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (id <- 1 to m) {
    val Array(_u, _v) = readInts(2)
    val u = _u - 1
    val v = _v - 1
    adjBuilders(u) += v
    adjBuilders(v) += u
    edgeIdBuilders(u) += id
    edgeIdBuilders(v) += id
  }

  val adjs = adjBuilders.map(_.result)
  val edgeIds = edgeIdBuilders.map(_.result)

  val checked = new mutable.BitSet(m)
  val resultBuilder = new mutable.ArrayBuilder.ofInt

  def dfs(u: Int): Unit = {
    var i = 0
    while (i < adjs(u).length) {
      val edgeId = edgeIds(u)(i)
      val v = adjs(u)(i)
      if (!checked(edgeId)) {
        checked(edgeId) = true
        if (ds(u) == 1 || ds(v) == 1) {
          resultBuilder += edgeId
          if (ds(u) != -1) ds(u) = 1 - ds(u)
          if (ds(v) != -1) ds(v) = 1 - ds(v)
        }
        dfs(v)
      }
      i += 1
    }
  }

  dfs(0)

  val res = resultBuilder.result
  val ok = !ds.contains(1)

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

  if (ok) {
    println(res.length)
    println(res.sorted.mkString("\n"))
  } else {
    println(-1)
  }

  Console.flush
}


object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val tb = stdin.next().toInt
  println(stdin.take(tb * 2).grouped(2).map(_.toArray).map(solve).mkString("\n"))

  def solve(arr: Array[String]): Int = {
    val Array(s, t) = arr
    val cache = Array.fill[Int](s.length, 26)(-1)
    s.zipWithIndex.foreach{
      case (ch, index) =>
        Range(index, -1, -1).takeWhile(i => cache(i)(ch - 'a') == -1).foreach(i => cache(i)(ch - 'a') = index)
    }
//    cache.foreach(i => println(i.mkString(" ")))
    val hasSolution = t.distinct.forall(ch => cache(0)(ch - 'a') != -1)
    if (!hasSolution) -1
    else {
      var matched = 0
      var lookCh = t.head
      var steps = 0
      while (matched < t.length) {
        var pos = 0
        steps += 1
        while (pos < s.length && cache(pos)(lookCh - 'a') != -1) {
          while (cache(pos)(lookCh - 'a') != pos && cache(pos)(lookCh - 'a') != -1)
            pos = cache(pos)(lookCh - 'a')
          if (cache(pos)(lookCh - 'a') != -1) {
            pos += 1
            matched += 1
            if (matched < t.length)
              lookCh = t.charAt(matched)
          }
        }
      }
      steps
    }
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val m = Array.fill(30)(Array.fill(100001)(0))
    val count = Array.fill(30)(0)
    val in = new InputReader(inputStream)
    val cases = in.nextInt()

    (1 to cases).foreach { _ =>
      val s = in.next()
      val t = in.next()
      (0 until 30).foreach(i => count(i) = 0)
      s.zipWithIndex.foreach{
        case (ch,i) => {
          val indxChar = (ch.toInt)- 'a'.toInt
          m(indxChar)(count(indxChar)) = i
          count(indxChar) = count(indxChar) + 1
        }
      }

      var sIndex = 0
      var tIndex = 0
      val maxSteps = t.length+1
      var steps = 1
      while(steps < maxSteps && (tIndex < t.length)){

        val ch = t.charAt(tIndex).toInt-'a'.toInt

        calcIndex(m,count,ch,sIndex) match {
          case Some(newSIndex) => {
            tIndex += 1
            sIndex = newSIndex+1
          }
          case None => {
            steps += 1
            sIndex = 0
          }
        }
      }
      if(tIndex == t.length){
        out.println(steps)
      }else{
        out.println(-1)
      }
    }

  }
  def calcIndex(m: Array[Array[Int]], count: Array[Int],a: Int, i: Int): Option[Int] = {
    val l = count(a)
    if(l == 0) {
      None
    } else{
      if(m(a)(l-1) < i) {

        None
      } else
        Some(calcIndex(m(a),l-1,i))
    }
  }
  def calcIndex(list: Array[Int], maxL: Int, i: Int): Int= {
    var left = 0
    var right = maxL
    //se asegura que list[right] <= i
    while(right - left > 1){
      val k = (left+right)/2
      if(list(k) < i){
        left = k
      }else{
        right = k
      }
    }
    if(list(left) >= i)
      list(left)
    else
      list(right)
  }

  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val m = Array.fill(30)(ListBuffer.empty[Int])
    val in = new InputReader(inputStream)
    val cases = in.nextInt()

    (1 to cases).foreach { _ =>
      val s = in.next()
      val t = in.next()
      m.foreach(_.clear())
      s.zipWithIndex.foreach{
        case (ch,i) => {
          val indxChar = (ch.toInt)- 'a'.toInt
          m(indxChar).append(i)
        }
      }

      var sIndex = 0
      var tIndex = 0
      val maxSteps = t.length+1
      var steps = 1
      while(steps < maxSteps && (tIndex < t.length)){

        val ch = t.charAt(tIndex).toInt-'a'.toInt

        calcIndex(m,ch,sIndex) match {
          case Some(newSIndex) => {
            tIndex += 1
            sIndex = newSIndex+1
          }
          case None => {
            steps += 1
            sIndex = 0
          }
        }
      }
      if(tIndex == t.length){
        out.println(steps)
      }else{
        out.println(-1)
      }
    }

  }
  def calcIndex(m: Array[ListBuffer[Int]],a: Int, i: Int): Option[Int] = {
    val l = m(a)
    if(l.isEmpty) {
      None
    } else{
      if(l.last < i) {

        None
      } else
        Some(calcIndex(l,i))
    }
  }
  def calcIndex(list: ListBuffer[Int], i: Int): Int= {
    var left = 0
    var right = list.length-1
    //se asegura que list[right] <= i
    while(right - left > 1){
      val k = (left+right)/2
      if(list(k) < i){
        left = k
      }else{
        right = k
      }
    }
    list(right)
  }

  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


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

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

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

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

  def solve(): Unit = {
    val H, W = ni()
    val r, c = ni() - 1
    val L, R = ni()
    val grid = Array.ofDim[Array[Boolean]](H)
    rep(H) { i =>
      grid(i) = ns(W) map (_ == '.')
    }

    val INF = 1e9.toInt
    val D = Array.fill[Int](H, W)(INF)

    case class Coord(h: Int, w: Int)

    def valid(h: Int, w: Int): Boolean = {
      0 <= h && h < H && 0 <= w && w < W && grid(h)(w)
    }

    case class Direction(dh: Int, dw: Int, weight: Int)
    val directions = Array(
      Direction(0, -1, 1),
      Direction(0, 1, 1),
      Direction(-1, 0, 0),
      Direction(1, 0, 0)
    )

    def ok(h: Int, w: Int, cost: Int) = {
      val extraCost = cost - abs(w - c)
      val l = extraCost / 2 + max(c - w, 0)
      val r = extraCost / 2 + max(w - c, 0)
      l <= L && r <= R
    }
    var ans = 1
    def dijk() = {
      case class Visit(v: Coord, cost: Int) extends Comparable[Visit] {
        override def compareTo(o: Visit): Int = java.lang.Integer.compare(cost, o.cost)
      }
      val queue = new java.util.LinkedList[Visit]()
      D(r)(c) = 0
      queue.add(Visit(Coord(r, c), 0))

      while(!queue.isEmpty) {
        val v = queue.pollFirst()
        if (D(v.v.h)(v.v.w) == v.cost) {
          rep(4) { i =>
            val d = directions(i)
            val h1 = v.v.h + d.dh
            val w1 = v.v.w + d.dw
            if (valid(h1, w1) && ok(h1, w1, v.cost + d.weight)) {
              val next = v.cost + d.weight
              if (D(h1)(w1) > next) {
                ans += 1
                D(h1)(w1) = next
                if (d.weight == 0) {
                  queue.addFirst(Visit(Coord(h1, w1), next))
                } else {
                  queue.addLast(Visit(Coord(h1, w1), next))
                }
              }
            }
          }
        }
      }
    }

    dijk()

    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val H, W = ni()
    val r, c = ni() - 1
    val L, R = ni()
    val grid = Array.ofDim[Array[Boolean]](H)
    rep(H) { i =>
      grid(i) = ns(W) map (_ == '.')
    }

    val INF = 1e9.toInt
    val D = Array.fill[Int](H, W)(INF)

    case class Coord(h: Int, w: Int)

    def valid(h: Int, w: Int): Boolean = {
      0 <= h && h < H && 0 <= w && w < W && grid(h)(w)
    }

    case class Direction(dh: Int, dw: Int, weight: Int)
    val directions = Array(
      Direction(0, -1, 1),
      Direction(0, 1, 1),
      Direction(-1, 0, 0),
      Direction(1, 0, 0)
    )

    def ok(h: Int, w: Int, cost: Int) = {
      val extraCost = cost - abs(w - c)
      val l = extraCost / 2 + max(c - w, 0)
      val r = extraCost / 2 + max(w - c, 0)
      l <= L && r <= R
    }
    var ans = 1
    def dijk() = {
      case class Visit(v: Coord, cost: Int) extends Comparable[Visit] {
        override def compareTo(o: Visit): Int = java.lang.Integer.compare(cost, o.cost)
      }
      val queue = new java.util.ArrayDeque[Visit]()
      D(r)(c) = 0
      queue.add(Visit(Coord(r, c), 0))

      while(!queue.isEmpty) {
        val v = queue.pollFirst()
        if (D(v.v.h)(v.v.w) == v.cost) {
          rep(4) { i =>
            val d = directions(i)
            val h1 = v.v.h + d.dh
            val w1 = v.v.w + d.dw
            if (valid(h1, w1) && ok(h1, w1, v.cost + d.weight)) {
              val next = v.cost + d.weight
              if (D(h1)(w1) > next) {
                ans += 1
                D(h1)(w1) = next
                if (d.weight == 0) {
                  queue.addFirst(Visit(Coord(h1, w1), next))
                } else {
                  queue.addLast(Visit(Coord(h1, w1), next))
                }
              }
            }
          }
        }
      }
    }

    dijk()

    out.println(ans)
  }

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

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

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

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

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


import scala.io.StdIn

object SolutionA extends App {
  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val n = StdIn.readInt();
    if (n == 1) {
      println(1)
    } else {
      var k = 2
      while (n % ((1 << k) - 1) != 0) {
        k += 1
      }
      println(n / ((1 << k) - 1))
    }
  }
}

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

  val testCount = nextInt
  for (_ <- 1 to testCount) {
    var n = nextLong
    var k = 1L
    var y = 3L
    while (n % y != 0) {
      k += 1
      y += 1 << k
    }
    out.println(n / y)
  }

  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 java.util.Scanner

/**
 * Created by lurker on 2014. 7. 16..
 */
object A extends App {
  def process(p:Long, values:Seq[Long] ):Integer = {
    val mark = collection.mutable.Set[Long]()
    var i = 0
    for(v <- values) {
      i += 1
      val h = v % p

      if(mark.contains(h)) {
        return i
      }
      mark += h
    }
    -1
  }

  val sc = new Scanner(System.in)
  val p = sc.nextLong()
  val n = sc.nextInt()
  val values = for(i <- (1 to n)) yield {sc.nextLong()}
  //println(process(10, Seq(0,21,53,41,53)))
  println(process(p, values.toSeq))
}

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

/**
 * Created by arseny on 13.07.14.
 */
object A extends App {
  val home = true
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val p = nextInt
    val n = nextInt
    val xs = new Array[Boolean](p)
    var printed = false
    for (i <- 0 until n if !printed) {
      //out.println(xs.toList)
      val x = nextInt
      if (xs(x % p)) {
        out.println(i + 1)
        printed = true
      } else {
        xs(x % p) = true
      }
    }
    if (!printed) {
      out.println(-1)
    }
  }

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

import java.util.StringTokenizer

object _447A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val p = next.toInt
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt % p)
  val hash = Array.fill(p)(false)

  def doit(i: Int): Int = {
    if (i == n) -1
    else if (hash(a(i))) return i + 1
    else {
      hash(a(i)) = true
      doit(i + 1)
    }
  }

  println(doit(0))
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(p, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, n).map{ _ => in.next().toInt}
  var set = Set.empty[Int]
  println(data.zipWithIndex.find{
    case(el, index) => val res = set.contains(el % p)
      set += (el % p)
      res
  }.map(_._2 + 1).getOrElse(-1))
}

object A447 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(p, n) = readInts(2)
    val arr = Array.fill(p)(false)
    for(i <- 1 to n) {
      val Array(xi) = readInts(1)
      if(arr(xi%p)) {
        println(i)
        return
      } else {
        arr(xi%p) = true
      }
    }
    println("-1")
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

 object Hash extends App{

  	def resolve(): Unit = {
		def hash(x: Int, p: Int) = x % p
		var map = Map[Int, Int]()

		val lines = io.Source.stdin.getLines.toIndexedSeq
		val (p, n) = {
			val tokens = lines(0).split(" ")
			(tokens(0).toInt, tokens(1).toInt)
		}

		var index = 1
		for {e <- lines.tail} {
			val bucket = hash(e.toInt, p)
			if (map.get(bucket).isDefined) {
				print(index)
				return
			} else {
				map = map + (bucket -> e.toInt)
				index += 1
			}
		}
		print(-1)
  	}

	resolve()
  }


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

  override def apply(io: IO): io.type = {
    val nums = io.read[Seq[Int]]

    val freqCount = nums.groupBy(identity).mapValues(_.size)

    val ans = if(freqCount.forall(_._2 <= 2)) {
      val increasing, decreasing = mutable.ArrayBuffer.empty[Int]
       freqCount foreach {
         case (i, 1) => decreasing += i
         case (i, _) =>
           increasing += i
           decreasing += i
       }

      Seq(
        "YES",
        increasing.length,
        increasing.sorted.mkString(" "),
        decreasing.length,
        decreasing.sorted(desc[Int]).mkString(" ")
      ).mkString("\n")
    } else {
      "NO"
    }

    io.write(ans)
  }

  def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
}
/****************************[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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object C1114MixedSeq extends App {
  import scala.io.StdIn.{readLine, readInt}
  val n = readInt
  val arr1 = readLine.split(' ').map(_.toInt).groupBy(identity).mapValues(_.length)
  val arr2 = arr1.filter(_._2 == 2)
  val s1 = arr1.keys.toList.sorted
  val s2 = arr2.keys.toList.sorted.reverse
  if(s1.length + s2.length != n) {
    println("NO")
  } else {
    println("YES")
    println(s1.length)
    println(s1.mkString(" "))
    println(s2.length)
    println(s2.mkString(" "))
  }

}