Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes.  They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.

The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.

After each round, print the current score of the bears.

import scala.math._
import scala.collection.mutable
import scala.util.control.Breaks
import scala.annotation.tailrec

object Problem extends App {
  import FastScanner._
  def exit() = System.exit(0)

  val n, m, q = readInt
  val grid = Array.fill(n, m)(readChar == '1')

  def longest(i: Int) = {
    var len, max = 0
    for(j <- 0 until m) {
      if(grid(i)(j)) {
        len += 1
        if(len > max)
          max = len
      } else
        len = 0
    }
    max
  }

  val totals = (0 until n toArray) map longest
  val totalsOps = intArrayOps(totals)

  for(cur <- 0 until q) {
    val i, j = readInt-1
    grid(i)(j) = !grid(i)(j)
    totals(i) = longest(i)

    val max = totalsOps.max
    println(max)
  }
}

object FastScanner {
  import java.io._
  private[this] val reader = new BufferedReader(new InputStreamReader(System.in))
  private[this] var line: String = null
  private[this] var pos: Int = 0

  @inline private[this] def nextLine() = {
    val line = reader.readLine()
    if(line == null)
      throw new IOException("End of stream")
    line
  }

  def readLine() = {
    if(line != null) {
      val s = line
      line = null
      s.substring(pos)
    } else
      nextLine()
  }

  def read() = {
    if(line == null) {
      line = nextLine()
      pos = 0
    }
    while(pos >= line.length) {
      line = nextLine()
      pos = 0
    }
    while(Character.isWhitespace(line charAt pos)) {
      pos += 1
      while(pos >= line.length) {
        line = nextLine()
        pos = 0
      }
    }
    var end = pos
    while(end < line.length && !Character.isWhitespace(line charAt end))
      end += 1

    val s = line.substring(pos, end)
    pos = end
    s
  }

  def readChar() = read() charAt 0
  def readInt() = java.lang.Integer.parseInt(read())
  def readLong() = java.lang.Long.parseLong(read())
  def readDouble() = java.lang.Double.parseDouble(read())
}

import java.io.BufferedReader

object Problem548B {
  def main(args: Array[String]): Unit = {
    val params = readParamsFromInput(Console.in)

    val solution = solve(params)

    solution.foreach(println(_))
  }

  def solve(params: Params548B): Seq[Int] = {
    // keep the row nrs containing the old max, and the old max
    // If the change is to one of those rows, either kick a row out (it shrunk) -> check if list is empty, if so, calc a new list.
    // or promote a row to the new list of max rows
    // If the change is to an outsider, either do nothing (it shrunk)
    // or if its total equals the max, add it to the max list.

    var (maxRowNrs, max) = getMaxes(params.bears)

    params.changes.map(change => {
      val oldState = params.bears(change._1)(change._2)
      params.bears(change._1)(change._2) = oldState ^ 1

      if (oldState == 1) {
        // row shrunk
        if (maxRowNrs.contains(change._1)) maxRowNrs -= change._1
        if (maxRowNrs.isEmpty) {
          val (newMaxRowNrs, newMax) = getMaxes(params.bears)
          maxRowNrs = newMaxRowNrs
          max = newMax
        }
      } else {
        // row grew. Can be by more than 1.
        val newRowVal = maxConsecutive(params.bears(change._1))
        if (newRowVal == max) {
          maxRowNrs += change._1
        } else
        if(newRowVal > max) {
          maxRowNrs = Set(change._1)
          max = newRowVal
        }
      }
      max
    })
  }

  def getMaxes(bears: Array[Array[Int]]): (Set[Int], Int) = {
    var max = 0
    var maxRows = Set[Int]()
    bears.map(maxConsecutive).zipWithIndex.foreach(p => {
      val (m, i) = p
      if (m > max) {
        maxRows = Set(i)
        max = m
      } else
      if (m == max) {
        maxRows += i
      }
    })
    (maxRows, max)
  }

  def maxConsecutive(bears: Array[Int]): Int = {
    var current = 0
    var max = 0
    bears.foreach(b => {
      if (b==1) current += 1
      else current = 0
      if (current > max) max = current
    })
    max
  }

  def readParamsFromInput(in: BufferedReader): Params548B = {
    val Array(nrRows, nrCols, nrChanges) = in.readLine().split(" ").map(_.toInt)
    val bears = new Array[Array[Int]](nrRows)
    (0 until nrRows).foreach(i => {
      bears(i) = in.readLine().split(" ").map(_.toInt)
    })
    val changes = new Array[(Int, Int)](nrChanges)
    (0 until nrChanges).foreach(i => {
      val change = in.readLine().split(" ").map(_.toInt - 1)  // NOTE 1-based
      changes(i) = (change(0), change(1))
    })
    Params548B(nrRows, nrCols, nrChanges, bears, changes)
  }

  case class Params548B(nrRows: Int, nrCols: Int, nrChanges: Int, bears: Array[Array[Int]], changes: Array[(Int, Int)])
}

import java.util.Scanner

object B {

	var n:Int = _
	var m:Int = _
	var q:Int = _
	var b:Array[Array[Int]] = _
	var cnt:Array[Int] = _

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

		b = (0 until n)
			.map(i => in.nextLine().split(" ").map(c => c.toInt))
			.toArray
	}

	def calcCnt(i:Int):Int = b(i)
		.scanLeft(0)((c:Int, v:Int) => (c + 1) * v)
		.reduceLeft(math.max)

	def prepareBeforeRounds() = {
		cnt = (0 until n).map(calcCnt(_)).toArray
	}

	def solveRound() = {
		val i = in.nextInt() - 1
		val j = in.nextInt() - 1

		b(i)(j) = 1 - b(i)(j)
		cnt(i) = calcCnt(i)

		println(cnt.reduceLeft(math.max))
	}

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

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

		prepareBeforeRounds()

		for (i <- 1 to q) {
			solveRound()
		}
	}

}

import java.util.Scanner

object B {

	var n:Int = 0
	var m:Int = 0
	var q:Int = 0
	var b = Array[Array[Int]]()
	var cnt = Array[Int]()

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

		b = (0 until n)
			.map(i => in.nextLine().split(" ").map(c => c.toInt))
			.toArray
	}

	def calcCnt(i:Int):Int = {
		var res = 0
		var currCnt = 0

		for (c <- b(i)) {
			if (c == 1) {
				currCnt += 1
				res = math.max(res, currCnt)
			} else {
				currCnt = 0
			}
		}

		return res
	}

	def prepareBeforeRounds() = {
		cnt = (0 until n).map(calcCnt(_)).toArray
	}

	def maxCnt():Int = {
		return cnt.reduceLeft(math.max);
	}

	def solveRound() = {
		val i = in.nextInt() - 1
		val j = in.nextInt() - 1

		b(i)(j) = 1 - b(i)(j)
		cnt(i) = calcCnt(i)

		println(maxCnt())
	}

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

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

		prepareBeforeRounds()

		for (i <- 1 to q) {
			solveRound()
		}
	}

}

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

import scala.collection.mutable

object B {

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val q = nextInt
    val bits = new Array[util.BitSet](n)
    val ans = new Array[Int](n)
    for (i <- 0 until n) {
      bits(i) = new util.BitSet(m)
      for (j <- 0 until m) {
        nextInt match {
          case 1 => bits(i).set(j)
          case _ => bits(i).set(j, false)
        }
      }
      ans(i) = maxNumberOfConsecutiveBits(bits(i))
    }
    for (i <- 0 until q) {
      var res = 0
      val x = nextInt
      val y = nextInt
      bits(x - 1).flip(y - 1)
      ans(x - 1) = maxNumberOfConsecutiveBits(bits(x - 1))
      for (k <- 0 until n) {
          res = Math.max(res, ans(k))
      }
      out.println(res)
    }
    return 0
  }

  def maxNumberOfConsecutiveBits(bs: util.BitSet): Int = {
    var maxLength = 0
    var one = bs.length()
    var i = one
    while (i >= 0) {
      i = bs.previousClearBit(i - 1)
      val len = one - 1 - i
      maxLength = Math.max(maxLength, len)
      if (i < 0) {
        return maxLength
      }
      one = i
      i = bs.previousClearBit(i - 1) + 1
    }
    maxLength
  }
}

import scala.io.StdIn._

object B extends App {
  var input = readLine().split(" ").map(_.toInt)
  val n = input(0)
  val m = input(1)
  val q = input(2)

  val M = new Array[Int](n)
  val grid = Array.ofDim[Array[Boolean]](n)

  for (i <- 0 until n) {
    grid(i) = readLine().split(" ").map(_.toInt == 1)
    M(i) = max(i)
  }

  for (i <- 0 until q) {
    var input = readLine().split(" ").map(_.toInt)
    val i = input(0) - 1
    val j = input(1) - 1
    grid(i)(j) = !grid(i)(j)
    M(i) = max(i)
    println(M.max)
  }

  def max(row: Int): Int = {
    var ans = 0
    var curr = 0
    for (i <- 0 until m) {
      if (grid(row)(i)) curr += 1 else curr = 0
      ans = Math.max(ans, curr)
    }
    ans
  }
}

import java.io.BufferedReader

object Problem548B {
  def main(args: Array[String]): Unit = {
    val params = readParamsFromInput(Console.in)

    val solution = solve(params)

    solution.foreach(println(_))
  }

  def solve(params: Params548B): Seq[Int] = {
    // keep the row nrs containing the old max, and the old max
    // If the change is to one of those rows, either kick a row out (it shrunk) -> check if list is empty, if so, calc a new list.
    // or promote a row to the new list of max rows
    // If the change is to an outsider, either do nothing (it shrunk)
    // or if its total equals the max, add it to the max list.

    var (maxRowNrs, max) = getMaxes(params.bears)

    params.changes.map(change => {
      val oldState = params.bears(change._1)(change._2)
      params.bears(change._1)(change._2) = oldState ^ 1

      if (oldState == 1) {
        // row shrunk
        if (maxRowNrs.contains(change._1)) maxRowNrs -= change._1
        if (maxRowNrs.isEmpty) {
          val (newMaxRowNrs, newMax) = getMaxes(params.bears)
          maxRowNrs = newMaxRowNrs
          max = newMax
        }
      } else {
        // row grew
        if (maxRowNrs.contains(change._1)) {
          maxRowNrs = Set(change._1)
          max += 1
        } else {
          if (maxConsecutive(params.bears(change._1)) == max) maxRowNrs += change._1
        }
      }
      max
    })
  }

  def getMaxes(bears: Array[Array[Int]]): (Set[Int], Int) = {
    var max = 0
    var maxRows = Set[Int]()
    bears.map(maxConsecutive).zipWithIndex.foreach(p => {
      val (m, i) = p
      if (m > max) {
        maxRows = Set(i)
        max = m
      } else
      if (m == max) {
        maxRows += i
      }
    })
    (maxRows, max)
  }

  def maxConsecutive(bears: Array[Int]): Int = {
    var current = 0
    var max = 0
    bears.foreach(b => {
      if (b==1) current += 1
      else current = 0
      if (current > max) max = current
    })
    max
  }

  def readParamsFromInput(in: BufferedReader): Params548B = {
    val Array(nrRows, nrCols, nrChanges) = in.readLine().split(" ").map(_.toInt)
    val bears = new Array[Array[Int]](nrRows)
    (0 until nrRows).foreach(i => {
      bears(i) = in.readLine().split(" ").map(_.toInt)
    })
    val changes = new Array[(Int, Int)](nrChanges)
    (0 until nrChanges).foreach(i => {
      val change = in.readLine().split(" ").map(_.toInt - 1)  // NOTE 1-based
      changes(i) = (change(0), change(1))
    })
    Params548B(nrRows, nrCols, nrChanges, bears, changes)
  }

  case class Params548B(nrRows: Int, nrCols: Int, nrChanges: Int, bears: Array[Array[Int]], changes: Array[(Int, Int)])
}

import java.io.BufferedReader

object Problem548B {
  def main(args: Array[String]): Unit = {
    val params = readParamsFromInput(Console.in)

    val solution = solve(params)

    solution.foreach(println(_))
  }

  def solve(params: Params548B): Seq[Int] = params.changes.map(change => {
    val oldState = params.bears(change._1)(change._2)
    params.bears(change._1)(change._2) = oldState ^ 1
    getMax(params.bears)
  })

  def getMax(bears: Array[Array[Int]]): Int = bears.map(_.sum).foldLeft(-1)((z, s) => Math.max(z, s))

  def readParamsFromInput(in: BufferedReader): Params548B = {
    val Array(nrRows, nrCols, nrChanges) = in.readLine().split(" ").map(_.toInt)
    val bears = new Array[Array[Int]](nrRows)
    (0 until nrRows).foreach(i => {
      bears(i) = in.readLine().split(" ").map(_.toInt)
    })
    val changes = new Array[(Int, Int)](nrChanges)
    (0 until nrChanges).foreach(i => {
      val change = in.readLine().split(" ").map(_.toInt - 1)  // NOTE 1-based
      changes(i) = (change(0), change(1))
    })
    Params548B(nrRows, nrCols, nrChanges, bears, changes)
  }

  case class Params548B(nrRows: Int, nrCols: Int, nrChanges: Int, bears: Array[Array[Int]], changes: Array[(Int, Int)])
}

import java.io.BufferedReader

object Problem548B {
  def main(args: Array[String]): Unit = {
    val params = readParamsFromInput(Console.in)

    val solution = solve(params)

    solution.foreach(println(_))
  }

  def solve(params: Params548B): Seq[Int] = {
    // keep the row nrs containing the old max, and the old max
    // If the change is to one of those rows, either kick a row out (it shrunk) -> check if list is empty, if so, calc a new list.
    // or promote a row to the new list of max rows
    // If the change is to an outsider, either do nothing (it shrunk)
    // or if its total equals the max, add it to the max list.

    var (maxRowNrs, max) = getMaxes(params.bears)

    params.changes.map(change => {
      val oldState = params.bears(change._1)(change._2)
      params.bears(change._1)(change._2) = oldState ^ 1

      if (oldState == 1) {
        // row shrunk
        if (maxRowNrs.contains(change._1)) maxRowNrs -= change._1
        if (maxRowNrs.isEmpty) {
          val (newMaxRowNrs, newMax) = getMaxes(params.bears)
          maxRowNrs = newMaxRowNrs
          max = newMax
        }
      } else {
        // row grew
        if (maxRowNrs.contains(change._1)) {
          maxRowNrs = Set(change._1)
          maxRowNrs += 1
        } else {
          if (maxConsecutive(params.bears(change._1)) == max) maxRowNrs += change._1
        }
      }
      max
    })
  }

  def getMaxes(bears: Array[Array[Int]]): (Set[Int], Int) = {
    var max = 0
    var maxRows = Set[Int]()
    bears.map(maxConsecutive).zipWithIndex.foreach(p => {
      val (m, i) = p
      if (m > max) {
        maxRows = Set(i)
        max = m
      } else
      if (m == max) {
        maxRows += i
      }
    })
    (maxRows, max)
  }

  //def getMax(bears: Array[Array[Int]]): Int = bears.map(maxConsecutive).foldLeft(-1)((z, s) => Math.max(z, s))

  def maxConsecutive(bears: Array[Int]): Int = {
    var current = 0
    var max = 0
    bears.foreach(b => {
      if (b==1) current += 1
      else current = 0
      if (current > max) max = current
    })
    max
  }

  def readParamsFromInput(in: BufferedReader): Params548B = {
    val Array(nrRows, nrCols, nrChanges) = in.readLine().split(" ").map(_.toInt)
    val bears = new Array[Array[Int]](nrRows)
    (0 until nrRows).foreach(i => {
      bears(i) = in.readLine().split(" ").map(_.toInt)
    })
    val changes = new Array[(Int, Int)](nrChanges)
    (0 until nrChanges).foreach(i => {
      val change = in.readLine().split(" ").map(_.toInt - 1)  // NOTE 1-based
      changes(i) = (change(0), change(1))
    })
    Params548B(nrRows, nrCols, nrChanges, bears, changes)
  }

  case class Params548B(nrRows: Int, nrCols: Int, nrChanges: Int, bears: Array[Array[Int]], changes: Array[(Int, Int)])
}

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

import scala.collection.mutable

object B {

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

  def bruteForceSoultion(sets: Array[util.BitSet]): Int = {
    var res = 0
    for (i <- 0 until sets.length) {
      val b = sets(i)
      var ind = 0
      var max = 0
      while (ind < b.length) {
        if (b.get(ind)) {
          max += 1
        } else {
          max = 0
        }
        ind += 1
      }
      res = Math.max(max, res)
    }
    res
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val q = nextInt
    val bits = new Array[util.BitSet](n)
    for (i <- 0 until n) {
      bits(i) = new util.BitSet(m)
      for (j <- 0 until m) {
        nextInt match {
          case 1 => bits(i).set(j)
          case _ => bits(i).set(j, false)
        }
      }
    }
    for (i <- 0 until q) {
      var res = 0
      val x = nextInt
      val y = nextInt
      bits(x - 1).flip(y - 1)
//      for (k <- 0 until n) {
//        res = Math.max(res, maxNumberOfConsecutiveBits(bits(k)))
//      }
      out.println(bruteForceSoultion(bits))
    }
    return 0
  }

  def maxNumberOfConsecutiveBits(bs: util.BitSet): Int = {
    var maxLength = 0
    var one = bs.length()
    var i = one
    while (i >= 0) {
      i = bs.previousClearBit(i - 1)
      val len = one - 1 - i
      maxLength = Math.max(maxLength, len)
      if (i < 0) {
        return maxLength
      }
      i = bs.previousClearBit(i - 1) + 1
      one = i
    }
    maxLength
  }
}

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

import scala.collection.mutable

object B {

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val q = nextInt
    val bits = new Array[java.util.BitSet](n)
    for (i <- 0 until n) {
      bits(i) = new java.util.BitSet(m)
      for (j <- 0 until m) {
        nextInt match {
          case 1 => bits(i).set(j)
          case _ => bits(i).set(j, false)
        }
      }
    }
    for (i <- 0 until q) {
      var res = 0
      val x = nextInt
      val y = nextInt
      bits(x - 1).flip(y - 1)
      for (k <- 0 until n) {
        res = Math.max(res, maxNumberOfConsecutiveBits(bits(k)))
      }
      out.println(res)
    }
    return 0
  }

  def maxNumberOfConsecutiveBits(bs: java.util.BitSet): Int = {
    var maxLength = 0
    var one = bs.length() // Points to the prior 0.
    var i = one
    while (i >= 0) {
      i = bs.previousClearBit(i - 1)
      val len = one - 1 - i
      maxLength = Math.max(maxLength, len)
      if (i < 0) {
        return maxLength
      }
      i = bs.previousClearBit(i - 1) + 1
      one = i
    }
    maxLength
  }
}

import scala.io.StdIn._

object B extends App {
  var input = readLine().split(" ").map(_.toInt)
  val n = input(0)
  val m = input(1)
  val q = input(2)

  val M = new Array[Int](n)
  val grid = Array.ofDim[Array[Boolean]](n)

  for (i <- 0 until n) {
    grid(i) = readLine().split(" ").map(_.toInt == 1)
    M(i) = grid(i).count(_ == true)
  }

  for (i <- 0 until q) {
    var input = readLine().split(" ").map(_.toInt)
    val i = input(0) - 1
    val j = input(1) - 1
    grid(i)(j) = !grid(i)(j)
    if (grid(i)(j)) M(i) += 1 else M(i) -= 1
    println(max())
  }

  def max(): Int = {
    var max = 0

    for (i <- 0 until n) {
      max = Math.max(max, M(i))
    }
    max
  }
}

import scala.io.StdIn._

object B extends App {
  var input = readLine().split(" ").map(_.toInt)
  val n = input(0)
  val m = input(1)
  val q = input(2)

  val grid = Array.ofDim[Array[Boolean]](n)

  for (i <- 0 until n) {
    grid(i) = readLine().split(" ").map(_.toInt == 1)
  }

  for (i <- 0 until q) {
    var input = readLine().split(" ").map(_.toInt)
    val i = input(0) - 1
    val j = input(1) - 1
    grid(i)(j) = !grid(i)(j)
    println(max())
  }

  def max(): Int = {
    var max = 0

    for (i <- 0 until n) {
      var curr = 0
      for (j <- 0 until m) {
        if (grid(i)(j)) curr += 1
      }
      max = Math.max(max, curr)
    }
    max
  }
}


There are $$$n$$$ students standing in a circle in some order. The index of the $$$i$$$-th student is $$$p_i$$$. It is guaranteed that all indices of students are distinct integers from $$$1$$$ to $$$n$$$ (i. e. they form a permutation).Students want to start a round dance. A clockwise round dance can be started if the student $$$2$$$ comes right after the student $$$1$$$ in clockwise order (there are no students between them), the student $$$3$$$ comes right after the student $$$2$$$ in clockwise order, and so on, and the student $$$n$$$ comes right after the student $$$n - 1$$$ in clockwise order. A counterclockwise round dance is almost the same thing — the only difference is that the student $$$i$$$ should be right after the student $$$i - 1$$$ in counterclockwise order (this condition should be met for every $$$i$$$ from $$$2$$$ to $$$n$$$). For example, if the indices of students listed in clockwise order are $$$[2, 3, 4, 5, 1]$$$, then they can start a clockwise round dance. If the students have indices $$$[3, 2, 1, 4]$$$ in clockwise order, then they can start a counterclockwise round dance.Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle. You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 200$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 200$$$) — the number of students. The second line of the query contains a permutation of indices $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ is the index of the $$$i$$$-th student (in clockwise order). It is guaranteed that all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i. e. they form a permutation).

For each query, print the answer on it. If a round dance can be started with the given order of students, print "YES". Otherwise print "NO".

object CF565A extends App {

  import scala.io.StdIn

  val q = StdIn.readInt
  for (_ <- 0 until q) {
    var n = StdIn.readInt

    val input = StdIn.readLine.split(' ').map(_.toInt)
    val sliding = (input.last :: input.toList).sliding(2)

    val answer = sliding.forall(x => x(1) == (x(0) + 1 - 1 + n) % n + 1) ||
                 sliding.forall(x => x(1) == (x(0) - 1 - 1 + n) % n + 1)

    println(if (answer) "YES" else "NO")
  }
}

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

  override def apply(io: IO) = {
    val inputs = io.read[Seq[Seq[Int]]]
    inputs foreach {input =>
      val doubled = (input ++ input)
      val slice = 1 to input.length
      val isPossible = Iterator(slice, slice.reverse).exists(doubled.containsSlice)
      io.writeLine(if (isPossible) "YES" else "NO")
    }
  }
}
/****************************[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): Any
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out))
}
/***********************************[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
      }
    }
  }
}


A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.

First line of the input contains the string s — the coating that is present in the shop. Second line contains the string t — the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.

The first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating. If the answer is not -1, then the following n lines should contain two integers xi and yi — numbers of ending blocks in the corresponding piece. If xi ≤ yi then this piece is used in the regular order, and if xi > yi piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.

NoteIn the first sample string "cbaabc" = "cba" + "abc".In the second sample: "ayrat" = "a" + "yr" + "at".

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

object Main {
  def main(args: Array[String]) {
    val s = StdIn.readLine()
    val n = s.length
    val rs = s.reverse
    val t = StdIn.readLine()
    val m = t.length
    var p = 0
    val ans = ArrayBuffer[(Int, Int)]()
    while (p < m) {
      val kmp = new KMP[Char](t.substring(p))
      val (l1, r1) = kmp.longestPrefix(s)
      val (l2, r2) = kmp.longestPrefix(rs)
      val (l3, r3) = (n - 1 - r2 + 1, n - 1 - l2 + 1)
      if (r1 - l1 == 0 && r3 - l3 == 0) {
        println(-1)
        return
      }
      if (r1 - l1 > r3 - l3) {
        ans.append((l1, r1 - 1))
        p += r1 - l1
      } else {
        ans.append((r3 - 1, l3))
        p += r3 - l3
      }
    }
    println(ans.length)
    for ((l, r) <- ans) {
      printf("%d %d\n", l + 1, r + 1)
    }
  }
}

class KMP[T](val pat: Seq[T]) {
  val m = pat.length
  val fail = Array.fill(m + 1)(-1)

  {
    var j = -1
    fail(0) = -1
    for (i <- 0 until m) {
      while (j != -1 && !pat(i).equals(pat(j))) j = fail(j)
      j += 1
      fail(i + 1) = j
    }
  }

  def longestPrefix(txt: Seq[T]): (Int, Int) = {
    val n = txt.length
    var j = 0
    var ans = (0, 0)
    for (i <- 0 until n) {
      while (j != -1 && !txt(i).equals(pat(j))) j = fail(j)
      j += 1
      if (j > 0 && ans._2 - ans._1 < j) {
        val s = i - j + 1
        ans = (s, i + 1)
      }
      if (j == m) {
        j = fail(m)
      }
    }
    return ans
  }
}

import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 8..
  */
object CSolution extends App {
  val coating = StdIn.readLine()
  val content = StdIn.readLine()

  val mapOfCoating = (0 until coating.length).map { i =>
    coating(i) -> i
  }.groupBy(_._1).mapValues(seq => seq.map(_._2))

  def matchedStringLength(it1: Iterator[Char], it2: Iterator[Char]): Int = {
    var i = 0
    while (it1.hasNext && it2.hasNext && it1.next() == it2.next()) {
      i += 1
    }
    i
  }

  def findLongCoating(piece: String, prevResult: Seq[(Int, Int)] = Nil): Seq[(Int, Int)] = {
    val c = piece.head
    mapOfCoating.get(c) match {
      case Some(indices) =>
        val p = indices.flatMap { idx =>
          val pl = matchedStringLength(piece.iterator, coating.drop(idx).iterator)
          val nl = matchedStringLength(piece.iterator, coating.take(idx + 1).reverseIterator)
          Array(pl -> (idx, idx + pl - 1), nl -> (idx, idx - nl + 1))
        }.maxBy(_._1)
        piece.drop(p._1) match {
          case l if l.isEmpty =>
            prevResult :+ p._2
          case l =>
            findLongCoating(l, prevResult :+ p._2)
        }
      case None => Nil
    }
  }

  val output = findLongCoating(content)
  output match {
    case l if l.isEmpty => println(-1)
    case l => println(l.length)
  }
  output.foreach { case (i, j) =>
    println(s"${i + 1} ${j + 1}")
  }
}


Nauuo is a girl who loves playing cards.One day she was playing cards but found that the cards were mixed with some empty ones.There are $$$n$$$ cards numbered from $$$1$$$ to $$$n$$$, and they were mixed with another $$$n$$$ empty cards. She piled up the $$$2n$$$ cards and drew $$$n$$$ of them. The $$$n$$$ cards in Nauuo's hands are given. The remaining $$$n$$$ cards in the pile are also given in the order from top to bottom.In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile.Nauuo wants to make the $$$n$$$ numbered cards piled up in increasing order (the $$$i$$$-th card in the pile from top to bottom is the card $$$i$$$) as quickly as possible. Can you tell her the minimum number of operations?

The first line contains a single integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — the number of numbered cards. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i\le n$$$) — the initial cards in Nauuo's hands. $$$0$$$ represents an empty card. The third line contains $$$n$$$ integers $$$b_1,b_2,\ldots,b_n$$$ ($$$0\le b_i\le n$$$) — the initial cards in the pile, given in order from top to bottom. $$$0$$$ represents an empty card. It is guaranteed that each number from $$$1$$$ to $$$n$$$ appears exactly once, either in $$$a_{1..n}$$$ or $$$b_{1..n}$$$.

The output contains a single integer — the minimum number of operations to make the $$$n$$$ numbered cards piled up in increasing order.

NoteExample 1We can play the card $$$2$$$ and draw the card $$$3$$$ in the first operation. After that, we have $$$[0,3,0]$$$ in hands and the cards in the pile are $$$[0,1,2]$$$ from top to bottom.Then, we play the card $$$3$$$ in the second operation. The cards in the pile are $$$[1,2,3]$$$, in which the cards are piled up in increasing order.Example 2Play an empty card and draw the card $$$1$$$, then play $$$1$$$, $$$2$$$, $$$3$$$ in order.

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

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

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

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

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

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

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

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

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

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

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

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

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

    def endsWithAsc: Boolean = {
      REP_r(N) { i =>
        if (i + 1 < N && B(i) + 1 != B(i + 1)) return false
        if (B(i) == 1) return true
      }
      true
    }

    val hands = Array.ofDim[Boolean](N + 1)

    def test1: Boolean = {
      val toFill = B.indexWhere(_ == 1)
      test2(toFill)
    }

    def test2(x: Int): Boolean = {
      import java.util
      util.Arrays.fill(hands, false)
      REP(N) { i =>
        if (A(i) != 0) hands(A(i)) = true
      }
      REP(x) { i =>
        if (i >= x - N) {
          val cur = i - (x - N) + 1
          if (!hands(cur)) return false
          hands(cur) = false
        }
        if (i < N && B(i) != 0) hands(B(i)) = true
      }
      true
    }

    val ans = if (B.forall(_ == 0)) N
    else if (endsWithAsc && test1) {
      B.indexWhere(_ == 1)
    } else {
      findMin(test2, N, 2 * N)
    }

    out.println(ans)
  }

  def findMin(f: Int => Boolean, min: Int, max: Int): Int = {
    var l = min - 1
    var h = max
    while(h - l > 1) {
      val x = (h + l) / 2
      if (f(x)) h = x
      else l = x
    }
    h
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val _, B = na(N)
    val V = Array.ofDim[Int](N + 1)

    if (B.forall(_ == 0)) out.println(N)
    else {
      var cont = -1
      REP(N) { i =>
        if (B(i) == 1) {
          cont = i
        } else if (cont >= 0 && B(i - 1) + 1 != B(i)) {
          cont = -1
        }
      }

      if (cont > 0 && B(cont - 1) == B.last + 1) cont = -1

      debug(s"cont:$cont")

      if (cont >= 0) {
        out.println(cont)
      } else {
        REP(N) { i =>
          if (B(i) > 0) {
            V(B(i)) = i + 2 + (N - B(i))
          }
        }
        debug(V)
        out.println(V.max)
      }
    }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val _, B = na(N)
    val V = Array.ofDim[Int](N + 1)

    if (B.forall(_ == 0)) out.println(N)
    else {
      var cont = false
      REP(N) { i =>
        if (B(i) == 1) {
          cont = true
        } else if (cont && B(i - 1) + 1 != B(i)) {
          cont = false
        }

        if (B(i) > 0 && !cont) {
          V(B(i)) = i + 2 + (N - B(i))
        }
      }
      debug(V)
      out.println(V.max)
    }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val _, B = na(N)
    val V = Array.ofDim[Int](N + 1)

    if (B.forall(_ == 0)) out.println(N)
    else {
      var cont = -1
      REP(N) { i =>
        if (B(i) == 1) {
          cont = i
        } else if (cont >= 0 && B(i - 1) + 1 != B(i)) {
          cont = -1
        }
      }

      debug(s"cont:$cont")

      val cnt = if (cont >= 0) cont else N

      REP(cnt) { i =>
        if (B(i) > 0) {
          V(B(i)) = i + 2 + (N - B(i))
        }
      }
      debug(V)
      out.println(max(V.max, cont))
    }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

    def endsWithAsc: Boolean = {
      REP_r(N) { i =>
        if (i + 1 < N && B(i) + 1 != B(i + 1)) return false
        if (B(i) == 1) return true
      }
      true
    }

    val hands = Array.ofDim[Boolean](N + 1)

    def test1: Boolean = {
      val toFill = B.indexWhere(_ == 1)
      test2(toFill)
    }

    def test2(x: Int): Boolean = {
      import java.util
      util.Arrays.fill(hands, false)
      REP(N) { i =>
        if (A(i) != 0) hands(A(i)) = true
      }
      REP(x) { i =>
        if (i >= x - N) {
          val cur = i - (x - N) + 1
          if (!hands(cur)) return false
          hands(cur) = false
        }
        if (i < N && B(i) != 0) hands(B(i)) = true
      }
      true
    }

    val ans = if (B.forall(_ == 0)) N
    else if (endsWithAsc && test1) {
      B.indexWhere(_ == 1)
    } else {
      findMin(test2, N + 1, 2 * N)
    }

    out.println(ans)
  }

  def findMin(f: Int => Boolean, min: Int, max: Int): Int = {
    var l = min - 1
    var h = max
    while(h - l > 1) {
      val x = (h + l) / 2
      if (f(x)) h = x
      else l = x
    }
    h
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val _, B = na(N)
    val V = Array.ofDim[Int](N + 1)

    if (B.forall(_ == 0)) out.println(N)
    else {
      var cont = -1
      REP(N) { i =>
        if (B(i) == 1) {
          cont = i
        } else if (cont >= 0 && B(i - 1) + 1 != B(i)) {
          cont = -1
        }
      }

      debug(s"cont:$cont")

      if (cont >= 0) {
        out.println(cont)
      } else {
        REP(N) { i =>
          if (B(i) > 0) {
            V(B(i)) = i + 2 + (N - B(i))
          }
        }
        debug(V)
        out.println(V.max)
      }
    }
  }
}


Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that user A sent user B a message at time t1, and user B sent user A a message at time t2. If 0 < t2 - t1 ≤ d, then user B's message was an answer to user A's one. Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message.You are given the log of messages in chronological order and a number d. Find all pairs of users who will be considered to be friends.

The first line of the input contains two integers n and d (1 ≤ n, d ≤ 1000). The next n lines contain the messages log. The i-th line contains one line of the log formatted as "Ai Bi ti" (without the quotes), which means that user Ai sent a message to user Bi at time ti (1 ≤ i ≤ n). Ai and Bi are non-empty strings at most 20 characters long, consisting of lowercase letters ('a' ... 'z'), and ti is an integer (0 ≤ ti ≤ 10000). It is guaranteed that the lines are given in non-decreasing order of ti's and that no user sent a message to himself. The elements in the lines are separated by single spaces.

In the first line print integer k — the number of pairs of friends. In the next k lines print pairs of friends as "Ai Bi" (without the quotes). You can print users in pairs and the pairs themselves in any order. Each pair must be printed exactly once.

4 1
vasya petya 1
petya vasya 2
anya ivan 2
ivan anya 4

NoteIn the first sample test case Vasya and Petya are friends because their messages' sending times are one second apart. Anya and Ivan are not, because their messages' sending times differ by more than one second.

import scala.collection.mutable.HashSet

object Main {
  def main(args: Array[String]) {
    val Array(n, d) = readLine split " " map (_.toInt)
    var times = new HashSet[ (String, String, Int) ]

    var res = new HashSet[(String, String)]

    for(i <- 0 until n) {
      val Array(a, b, ts) = readLine split " "
      times.filter(t => t._3 < ts.toInt - d).foreach(times.remove) // Удаляем устаревшие пары
      times.filter(t => t._2 == a && t._1 == b && ts.toInt != t._3).foreach(p => {
        if(p._1 > p._2)
          res += ((p._2, p._1))
        else
          res += ((p._1, p._2))
      })
      times += ((a, b, ts.toInt))
    }

    println(res.size)
    res.foreach(r => println(r._1+" "+r._2))
  }
}

object counter {

  var delay:Int = 0

  def findFriends(messages:List[Message], friends:Set[Set[String]]):Set[Set[String]] = messages match {
    case Nil => friends
    case head::Nil => friends
    case head::tail => if(tail.exists( message => message.time - head.time <= delay && message.time != head.time && message.to == head.from && message.from == head.to))
        findFriends(tail, friends + Set(head.from, head.to))
      else
        findFriends(tail, friends)
  }

  def main(args: Array[String]) {
    val values = Console.readLine().split(" ")
    val numOfMessages = values(0).toInt
    delay = values(1).toInt
    val messages = 1 to numOfMessages map { _ => {
      val line = Console.readLine().split(" ")
      new Message(line(0), line(1), line(2).toInt)
    } } toList
    val result = findFriends(messages, Set.empty)
    println(result.size)
    result.foreach(set => println(set.mkString(" ")))
  }

}

case class Message(from:String, to:String, time:Int)

import scala.collection.mutable.HashSet

object Main {
  def main(args: Array[String]) {
    val Array(n, d) = readLine split " " map (_.toInt)
    var times = new HashSet[ (String, String, Int) ]

    var res = new HashSet[(String, String)]

    for(i <- 0 until n) {
      val Array(a, b, ts) = readLine split " "
      times.filter(t => t._3 < ts.toInt - d).foreach(times.remove) // Удаляем устаревшие пары
      times.filter(t => t._2 == a && t._1 == b).foreach(p => {
        if(p._1 > p._2)
          res += ((p._2, p._1))
        else
          res += ((p._1, p._2))
      })
      times += ((a, b, ts.toInt))
    }

    println(res.size)
    res.foreach(r => println(r._1+" "+r._2))
  }
}

object counter {

  var delay:Int = 0

  def findFriends(messages:List[Message], friends:Set[Set[String]]):Set[Set[String]] = messages match {
    case Nil => friends
    case head::Nil => friends
    case head::tail => if(tail.exists( message => message.time - head.time <= delay && message.to == head.from && message.from == head.to))
        findFriends(tail, friends + Set(head.from, head.to))
      else
        findFriends(tail, friends)
  }

  def main(args: Array[String]) {
    val values = Console.readLine().split(" ")
    val numOfMessages = values(0).toInt
    delay = values(1).toInt
    val messages = 1 to numOfMessages map { _ => {
      val line = Console.readLine().split(" ")
      new Message(line(0), line(1), line(2).toInt)
    } } toList
    val result = findFriends(messages, Set.empty)
    println(result.size)
    result.foreach(set => println(set.mkString(" ")))
  }

}

case class Message(from:String, to:String, time:Int)


Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:  The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).  No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).  All elements of the sequence are good integers. Find the length of the longest good sequence.

The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).

Print a single integer — the length of the longest good sequence.

NoteIn the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)

    var ans=1

    a.foreach{num=>
    	var j=2
    	var nn=num
    	var best=0
    	while(j*j<=nn)
    	{
    		if(nn%j==0)
    			best=math.max(best,dp(j)+1)
    		while(nn%j==0) nn/=j
    		j+=1
    	}
    	if(nn>1) best=math.max(best,dp(nn)+1)

    	j=2
    	nn=num
    	while(j*j<=nn)
        {
            if(nn%j==0)
                dp(j)=best
            while(nn%j==0) nn/=j
            j+=1
        }
    	if(nn>1) dp(nn)=best
    	ans=math.max(ans,best)
    }
    println(ans)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1
    a.foreach{num=>
    	var j=2
    	var nn=num
    	var best=0
    	for(i<-2 to math.sqrt(nn).toInt)
    	{
    		if(nn%i==0)
    			best=math.max(best,dp(i)+1)
    		while(nn%i==0) nn/=i
    	}
    	if(nn>1)
    	{
    		best=math.max(best,dp(nn)+1)
    		dp(nn)=best
    	}

    	nn=num
    	for(i<-2 to math.sqrt(nn).toInt)
        {
            if(nn%i==0)
                dp(i)=best
            while(nn%i==0) nn/=i
        }
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1

    a.foreach{num=>
        var nn=num
        var best=0
        val list=(for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield
        {
            while(nn%i==0) nn/=i
            i
        }):+nn

        //println(list)
        best=dp(list.maxBy{i=>if(i>1) dp(i) else 0})+1
        //println(best)
        list.foreach{i=>if(i>1) dp(i)=best}
        //(1 to 10).foreach{i=>print(dp(i)+" ")}
        //println()
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1

    a.foreach{num=>
        var nn=num
        val list=((for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield
        {
            while(nn%i==0) nn/=i
            i
        }):+nn).filter{_!=1}

        if(!list.isEmpty)
        {
            //println(list)
            val best=dp(list.maxBy{i=>dp(i)})+1
            //println(best)
            list.foreach{i=>dp(i)=best}
            //(1 to 10).foreach{i=>print(dp(i)+" ")}
            //println()
        }
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1
    a.foreach{num=>
        var nn=num
        var best=0
        val list=for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield
        {
            while(nn%i==0) nn/=i
            i
        }

        if(list.size>0) best=dp(list.maxBy{i=>dp(i)})+1

        if(nn>1)
        {
            best=math.max(best,dp(nn)+1)
            dp(nn)=best
        }

        if(list.size>0) list.foreach{i=>dp(i)=best}
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1
    a.foreach{num=>
    	var i=2
    	var nn=num
    	var best=0
    	for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn)
    	{
    		if(nn%i==0)
    			best=math.max(best,dp(i)+1)
    		while(nn%i==0) nn/=i
    	}
    	if(nn>1)
    	{
    		best=math.max(best,dp(nn)+1)
    		dp(nn)=best
    	}

    	i=2
    	nn=num
        for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn)
        {
            if(nn%i==0)
                dp(i)=best
            while(nn%i==0) nn/=i
        }
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1
    a.foreach{num=>
    	var i=2
    	var nn=num
    	var best=0
    	while(i*i<=nn)
    	{
    		if(nn%i==0)
    			best=math.max(best,dp(i)+1)
    		while(nn%i==0) nn/=i
    		i+=1
    	}
    	if(nn>1)
    	{
    		best=math.max(best,dp(nn)+1)
    		dp(nn)=best
    	}

    	i=2
    	nn=num
        while(i*i<=nn)
        {
            if(nn%i==0)
                dp(i)=best
            while(nn%i==0) nn/=i
            i+=1
        }
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1
    a.foreach{num=>
    	var j=2
    	var nn=num
    	var best=0
    	while(j*j<=nn)
    	{
    		if(nn%j==0)
    			best=math.max(best,dp(j)+1)
    		while(nn%j==0) nn/=j
    		j+=1
    	}
    	if(nn>1) best=math.max(best,dp(nn)+1)

    	j=2
    	nn=num
    	while(j*j<=nn)
        {
            if(nn%j==0)
                dp(j)=best
            while(nn%j==0) nn/=j
            j+=1
        }
    	if(nn>1) dp(nn)=best
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1
    a.foreach{num=>
    	var j=2
    	var nn=num
    	var best=0
    	for(i<-2 to math.sqrt(max).toInt)
    	{
    		if(nn%i==0)
    			best=math.max(best,dp(i)+1)
    		while(nn%i==0) nn/=i
    	}
    	if(nn>1)
    	{
    		best=math.max(best,dp(nn)+1)
    		dp(nn)=best
    	}

    	nn=num
    	for(i<-2 to math.sqrt(max).toInt)
        {
            if(nn%i==0)
                dp(i)=best
            while(nn%i==0) nn/=i
        }
    }
    println(dp.max)
}

import java.io.BufferedReader
import java.io.InputStreamReader
import scala.annotation.tailrec
object Main {

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val n = br.readLine().toInt
    val a = br.readLine().split(" ").map(_.toInt)

    def divider(number:Int):List[Int]={
      var res = List[Int]()
      @tailrec
      def rec(i:Int,d:Int):Unit={
          if(i*i<=d){
            if(d%i==0)res = i::d/i::res
            rec(i+1,d)
          }
      }
      rec(2,number)
      return res
    }

    var dp = new Array[Int](100001)
    for(i <- a){
      dp(i) = 1
      val div = divider(i)
      var max = 1
      div.foreach(x => max = Math.max(max,1+dp(x)))
      dp(i) = max
      div.foreach(x => dp(x) = Math.max(dp(x),max))
    }
    println(dp.reduce(Math.max(_,_)))
  }

}

import java.io.BufferedReader
import java.io.InputStreamReader
import scala.annotation.tailrec
object Main {

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val n = br.readLine().toInt
    val a = br.readLine().split(" ").map(_.toInt)

    def divider(number:Int):List[Int]={
      var res = List[Int]()
      @tailrec
      def rec(i:Int,d:Int):Unit={
          if(i*i<=d){
            if(d%i==0)res = i::d/i::res
            rec(i+1,d)
          }
      }
      rec(2,number)
      return res
    }

    var dp = new Array[Int](100001)
    for(i <- a){
      dp(i) = 1
      val div = divider(i)
      var max = 1
      for(j <- div){
        max = Math.max(max,1+dp(j))
      }
      dp(i) = max
      for(j <- div){
        dp(j) = Math.max(dp(j),max)
      }
    }
    println(dp.reduce(Math.max(_,_)))
  }

}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)

    a.foreach{num=>
    	var j=2
    	var nn=num
    	var best=0
    	while(j*j<=nn)
    	{
    		if(nn%j==0)
    			best=math.max(best,dp(j)+1)
    		while(nn%j==0) nn/=j
    		j+=1
    	}
    	if(nn>1) best=math.max(best,dp(nn)+1)

    	j=2
    	nn=num
    	while(j*j<=nn)
        {
            if(nn%j==0)
                dp(j)=best
            while(nn%j==0) nn/=j
            j+=1
        }
    	if(nn>1) dp(nn)=best
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1

    a.foreach{num=>
        var nn=num
        var best=0
        val list=(for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield
        {
            while(nn%i==0) nn/=i
            i
        }):+nn

        //println(list)
        best=dp(list.maxBy{i=>dp(i)})+1
        //println(best)
        list.foreach{i=>if(i>1) dp(i)=best}
        //(1 to 10).foreach{i=>print(dp(i)+" ")}
        //println()
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1
    a.foreach{num=>
    	var i=2
    	var nn=num
    	var best=0
    	while(i*i<=nn)
    	{
    		if(nn%i==0)
    			best=math.max(best,dp(i)+1)
    		while(nn%i==0) nn/=i
    		i+=1
    	}
    	if(nn>1)
    	{
    		best=math.max(best,dp(nn)+1)
    		dp(nn)=best
    	}

    	nn=num
        while(i*i<=nn)
        {
            if(nn%i==0)
                dp(i)=best
            while(nn%i==0) nn/=i
            i+=1
        }
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)

    var ans=1

    a.foreach{num=>
    	var j=2
    	var nn=num
    	var best=0
    	while(j*j<=nn)
    	{
    		if(nn%j==0)
    			best=math.max(best,dp(j)+1)
    		while(nn%j==0) nn/=j
    		j+=1
    	}
    	if(nn>1) best=math.max(best,dp(nn)+1)

    	j=2
    	nn=num
    	while(j*j<=nn)
        {
            if(nn%j==0)
                dp(j)=best
            while(nn%j==0) nn/=j
            j+=1
        }
    	if(nn>1) dp(j)=best
    	ans=math.max(ans,best)
    }
    println(ans)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1

    a.foreach{num=>
        var nn=num
        var best=0
        val list=(for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield
        {
            while(nn%i==0) nn/=i
            i
        }):+nn-1

        best=dp(list.maxBy{i=>dp(i)})+1
        list.foreach{i=>dp(i)=best}
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1
    a.foreach{num=>
    	var j=2
    	var nn=num
    	var best=0
    	for(i<-2 to math.sqrt(max).toInt)
    	{
    		if(nn%i==0)
    			best=math.max(best,dp(i)+1)
    		while(nn%i==0) nn/=i
    	}
    	if(nn>1)
    	{
    		best=math.max(best,dp(max)+1)
    		dp(nn)=best
    	}

    	nn=num
    	for(i<-2 to math.sqrt(nn).toInt)
        {
            if(nn%i==0)
                dp(i)=best
            while(nn%i==0) nn/=i
        }
    }
    println(dp.max)
}

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

object test2 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=100000
    val dp=new Array[Int](max+1)
    dp(1)=1
    a.foreach{num=>
        var i=2
        var nn=num
        var best=0
        val list=for(i<- 2 to math.sqrt(nn).toInt if i*i<=nn && nn%i==0) yield
        {
            while(nn%i==0) nn/=i
            i
        }

        if(list.size>0) best=list.maxBy{i=>dp(i)}+1
        if(nn>1)
        {
            best=math.max(best,dp(nn)+1)
            dp(nn)=best
        }

        if(list.size>0) list.foreach{i=>dp(i)=best}
    }
    println(dp.max)
}


Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that.  Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then:  at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$);  at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$);  the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.

For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.

NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.

import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val n = readLine().toInt
      val arr = readIntLine()
      println(calcGrannies(arr.sorted))
    }
//      println(calcGrannies(List[Int](2, 3, 4, 5)))
  }

  def calcGrannies(arr: List[Int]): Int = {
    def helper(map: List[(Int, Int)], people: Int, acc: Int): Int = map match {
      case Nil => people
      case (wanted, grannies) :: rest =>
        if (grannies - 1 + people + acc >= wanted) helper(rest, people + acc + grannies, 0)
        else helper(rest, people, acc + grannies)
    }

    helper(arr.groupBy(i => i).map { case (k, v) => (k, v.length) }.toList.sortBy(tup => tup._1), 1, 0)
  }

  def makeArray(n: Int) {
    class QueueElement(val left: Int, val right: Int) {}

    val arr = Array.ofDim[Int](n)
    val intervals = (0 to n).map(_ => ListBuffer[QueueElement]()).toArray
    intervals(n) += new QueueElement(0, n - 1)
    var count = 1
    for (i <- (0 to n).reverse) {
      var intOfLengthI = intervals(i)
      intOfLengthI = intOfLengthI.sortBy(_.left)
      for (j <- intOfLengthI.indices) {
        val head = intOfLengthI(j)
        if (head.left == head.right) {
          arr(head.left) = count
        } else {
          val mid = (head.left + head.right) / 2
          arr(mid) = count
          if (mid != head.left) intervals(mid - head.left) += new QueueElement(head.left, mid - 1)
          intervals(head.right - mid) += new QueueElement(mid + 1, head.right)
        }
        count += 1
      }
    }

    printArray(arr)
  }

  def printArray[T](arr: Array[T]) {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

}

object B extends App {
  val t = scala.io.StdIn.readInt()

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

    val (ans, _) = an.foldLeft((1, 0)) {
      case ((c, r), a) =>
        if (a <= c + r) (c + r + 1, 0)
        else (c, r + 1)
    }

    println(ans)
  }
}

import scala.io.StdIn.readLine

object B {
  def solution(a0: Seq[Int]): Int = {
    val a = a0.toArray.sorted
    var i = a.length - 1
    var r = 1
    while (i >= 0 && r == 1) {
      if (a(i) <= i + 1)
        r = i + 2
      i -= 1
    }
    r
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val _ = readLine
      val a = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(a))
    }
  }
}

import java.util
import java.util.Collections

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val numbers = new mutable.TreeMap[Int, Int]()
    for (_ <- 0 until n) {
      val ai = in.nextInt()
      numbers.update(ai, numbers.getOrElse(ai, 0) + 1)
    }

    var result = 1
    var buf = 0
    numbers.foreach {
      case (ai, count) =>
        if (count + result + buf > ai) {
          result = result + count + buf
          buf = 0
        } else {
          buf = buf + count
        }
    }

    println(result)

  }

}