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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val B = Array.ofDim[Int](N)
    val C = Array.ofDim[Int](N - 1)
    rep(N - 1) { i =>
      val d = A(i + 1) - A(i)
      C(i) = if (d == 0) 0
      else if (d > 0) 1
      else -1
    }

    val All = 1 to 5
    val Mid = Seq(3, 2, 4, 1, 5)

    def filter(i: Int) = {
      C(i) match {
        case 0 => All filterNot (_ == B(i))
        case 1 => B(i) + 1 to 5
        case -1 => 1 until B(i)
      }
    }

    def pick(i: Int, range: IndexedSeq[Int]) = {
      C(i) match {
        case 0 => Mid.find(range.contains).get
        case 1 => range.head
        case -1 => range.last
      }
    }

    def allocate(): Boolean = {
      B(0) = pick(0, All)

      rep(N - 2) { i =>
        val range = filter(i)
        if (range.isEmpty) return false
        B(i + 1) = pick(i + 1, range)
      }

      val rangeN = filter(N - 2)
      if (rangeN.isEmpty) return false
      B(N - 1) = rangeN.head

      true
    }

    if (N == 1) {
      out.println(1)
    } else {
      val ok = allocate()

      if (ok) {
        out.println(B.mkString(" "))
      } else {
        out.println(-1)
      }
    }
  }

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

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

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

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

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

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

object C extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)

  var min = 1
  var max = 5

  val dp = Array.fill(n, 5)(-1)
  for (j <- 0 until 5) dp(0)(j) = 0

  for (i <- 1 until n) {
    var prev = 0
    while (prev < 5) {
      if (dp(i - 1)(prev) >= 0) {
        var b = 0
        while (b < 5) {
          if (as(i - 1) < as(i) && prev < b) dp(i)(b) = prev
          if (as(i - 1) > as(i) && prev > b) dp(i)(b) = prev
          if (as(i - 1) == as(i) && prev != b) dp(i)(b) = prev
          b += 1
        }
      }
      prev += 1
    }
  }
//dp.foreach(d => println(d.mkString(" ")))
  val solved = dp.last.indexWhere(_ >= 0)
  if (solved == -1) {
    println(-1)
  } else {

    val bs = Array.ofDim[Int](n)
    var b = solved
    for (i <- n - 1 to 0 by -1) {
      bs(i) = b + 1
      b = dp(i)(b)
    }

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

    println(bs.mkString(" "))

    Console.flush
  }
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val B = Array.ofDim[Int](N)
    val C = Array.ofDim[Int](N - 1)
    rep(N - 1) { i =>
      val d = A(i + 1) - A(i)
      C(i) = if (d == 0) 0
        else if (d > 0) 1
        else -1
    }

    if (N == 1) {
      out.println(1)
    } else {
      B(0) = C(0) match {
        case 0 => 2
        case 1 => 1
        case -1 => 5
      }

      rep(N - 2) { i =>
        val c0 = C(i)
        val c1 = C(i + 1)
        val b = (c0, c1) match {
          case (0, 0) => if (B(i) != 2) 2 else 3
          case (0, 1) => if (B(i) != 1) 1 else 2
          case (0, -1) => if (B(i) != 5) 5 else 4

          case (1, 0) => if (B(i) != 2) 2 else 3
          case (1, 1) => B(i) + 1
          case (1, -1) => 5

          case (-1, 0) => if (B(i) != 2) 2 else 3
          case (-1, 1) => 1
          case (-1, -1) => B(i) - 1
        }
        B(i + 1) = b
      }

      B(N - 1) = C(N - 2) match {
        case 0 => if (B(N - 2) != 2) 2 else 3
        case 1 => B(N - 2) + 1
        case -1 => B(N - 2) - 1
      }

      val ok = (0 until N - 2 forall { i =>
        C(i) match {
          case 0 => B(i) != B(i + 1)
          case 1 => B(i) < B(i + 1)
          case -1 => B(i) > B(i + 1)
        }
      }) && B.forall(b => 1 <= b && b <= 5)

      if (ok) {
        out.println(B.mkString(" "))
      } else {
        out.println(-1)
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val B = Array.ofDim[Int](N)
    val C = Array.ofDim[Int](N - 1)
    rep(N - 1) { i =>
      val d = A(i + 1) - A(i)
      C(i) = if (d == 0) 0
      else if (d > 0) 1
      else -1
    }

    val All = 1 to 5

    def filter(i: Int) = {
      C(i) match {
        case 0 => All filterNot (_ == B(i))
        case 1 => B(i) + 1 to 5
        case -1 => 1 until B(i)
      }
    }

    def pick(i: Int, range: IndexedSeq[Int]) = {
      C(i) match {
        case 0 => range(range.length / 2)
        case 1 => range.head
        case -1 => range.last
      }
    }

    def allocate(): Boolean = {
      B(0) = pick(0, All)

      rep(N - 2) { i =>
        val range = filter(i)
        if (range.isEmpty) return false
        B(i + 1) = pick(i + 1, range)
      }

      val rangeN = filter(N - 2)
      if (rangeN.isEmpty) return false
      B(N - 1) = rangeN.head

      true
    }

    if (N == 1) {
      out.println(1)
    } else {
      val ok = allocate()

      if (ok) {
        out.println(B.mkString(" "))
      } else {
        out.println(-1)
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val B = Array.ofDim[Int](N)
    val C = Array.ofDim[Int](N - 1)
    rep(N - 1) { i =>
      val d = A(i + 1) - A(i)
      C(i) = if (d == 0) 0
        else if (d > 0) 1
        else -1
    }

    if (N == 1) {
      out.println(1)
    } else {
      B(0) = C(0) match {
        case 0 => 2
        case 1 => 1
        case -1 => 5
      }

      rep(N - 2) { i =>
        val c0 = C(i)
        val c1 = C(i + 1)
        val b = (c0, c1) match {
          case (0, 0) => if (B(i) != 2) 2 else 3
          case (0, 1) => if (B(i) != 1) 1 else 2
          case (0, -1) => if (B(i) != 5) 5 else 4

          case (1, 0) => if (B(i) != 2) 2 else 3
          case (1, 1) => B(i) + 1
          case (1, -1) => 5

          case (-1, 0) => if (B(i) != 2) 2 else 3
          case (-1, 1) => 1
          case (-1, -1) => B(i) - 1
        }
        B(i + 1) = b
      }

      B(N - 1) = C(N - 2) match {
        case 0 => if (B(N - 2) != 2) 2 else 3
        case 1 => B(N - 2) + 1
        case -1 => B(N - 2) - 1
      }

      val ok = (0 until N - 1 forall { i =>
        C(i) match {
          case 0 => B(i) != B(i + 1)
          case 1 => B(i) < B(i + 1)
          case -1 => B(i) > B(i + 1)
        }
      }) && B.forall(b => 1 <= b && b <= 5)

      if (ok) {
        out.println(B.mkString(" "))
      } else {
        out.println(-1)
      }
    }
  }

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

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

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

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

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

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


object DistanceAxis {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn._
    val input = readInt()
    var i = 0
    while(i < input) {
      var rline = readLine().split(" ")
      var a0 = rline(0).toInt
      var a1 = rline(1).toInt
      var a2 = rline(2).toInt
      rline = readLine().split(" ")
      var b0 = rline(0).toInt
      var b1 = rline(1).toInt
      var b2 = rline(2).toInt
      val usedMaxa2b1 = math.min(a2, b1)
      val result = 2 * usedMaxa2b1 - 2 * math.max(0, (a1 - (b0 + b1 - usedMaxa2b1)))
      println(result)
      i += 1
    }
  }
}

import scala.io.StdIn

object Solution2 extends App {

  val t = StdIn.readLine().toInt

  val cases = for {
    _ <- 0 until t
  } yield (StdIn.readLine().split(" ").map(_.toInt), StdIn.readLine().split(" ").map(_.toInt))

  for {
    c <- cases
  } {
    var (Array(z1, y1, x1), Array(z2, y2, x2)) = c

    var sum = 0
    val twosWithOnes = Math.min(x1, y2)
    sum += twosWithOnes * 2
    x1 -= twosWithOnes
    y2 -= twosWithOnes

    val twosWithTwos = Math.min(x1, x2)
    x1 -= twosWithTwos
    x2 -= twosWithTwos
  //  println("burn twos", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)

    // burn twos in second
    val zeros = Math.min(z1, x2)
    x2 -= zeros
    z1 -= zeros

  //  println("burn zeros", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)

    val OnesWithTwos = Math.min(y1, x2)
    y1 -= OnesWithTwos
    x2 -= OnesWithTwos
    sum -= OnesWithTwos * 2

    //println("burn other twos", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)
    //println("final", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)
    println(sum)
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x1, y1, z1) = readLine().split(" ").map(_.toInt) // a: 0, 1, 2
    val Array(x2, y2, z2) = readLine().split(" ").map(_.toInt) // b: 0, 1, 2

    val t1 = z1 min y2
    val t2 = z2 min x1
    val t3 = (z1 - t1) min (z2 - t2)
    val t4 = y1 min (z2 - t2 - t3)

    val ans = 2L * (t1 - t4)

    println(ans)
  }
}

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      var a0 = in.nextInt()
      var a1 = in.nextInt()
      var a2 = in.nextInt()

      var b0 = in.nextInt()
      var b1 = in.nextInt()
      var b2 = in.nextInt()

      var tem = 0
      // a2
      var result = {
        tem = math.min(a2, b1)
        a2 = a2 - tem
        b1 = b1 - tem
        tem * 2
      }
      {
        tem = math.min(a2, b2) // zero
        a2 = a2 - tem
        b2 = b2 - tem
      }
      {
        tem = math.min(a2, b0) // zero
        a2 = a2 - tem
        b0 = b0 - tem
      }
      // a1
      {
        tem = math.min(a1, b1) // zero
        a1 = a1 - tem
        b1 = b1 - tem
      }
      {
        tem = math.min(a1, b0) // zero
        a1 = a1 - tem
        b0 = b0 - tem
      }
      result = result + {
        tem = math.min(a1, b2) // zero
        a1 = a1 - tem
        b2 = b2 - tem
        tem * 2 * -1
      }
      // a0
      {
        tem = math.min(a0, b2) // zero
        a0 = a0 - tem
        b2 = b2 - tem
      }
      {
        tem = math.min(a0, b1) // zero
        a0 = a0 - tem
        b1 = b1 - tem
      }
      {
        tem = math.min(a0, b0) // zero
        a0 = a0 - tem
        b0 = b0 - tem
      }
      println(result)
//      val connectivity = Array.ofDim[Boolean](airports, airports)

    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

import scala.io.StdIn

object Solution2 extends App {

  val t = StdIn.readLine().toInt

  val cases = for {
    _ <- 0 until t
  } yield (StdIn.readLine().split(" ").map(_.toInt), StdIn.readLine().split(" ").map(_.toInt))

  for {
    c <- cases
  } {
    var (Array(z1, y1, x1), Array(z2, y2, x2)) = c

    var sum = 0
    val twosWithOnes = Math.min(x1, y2)
    sum += twosWithOnes * 2
    x1 -= twosWithOnes
    y2 -= twosWithOnes
  //  println("burn twos", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)

    // burn twos in second
    val zeros = Math.min(z1, x2)
    x2 -= zeros
    z1 -= zeros

  //  println("burn zeros", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)

    val OnesWithTwos = Math.min(y1, x2)
    y1 -= OnesWithTwos
    x2 -= OnesWithTwos
    sum -= OnesWithTwos * 2

    //println("burn other twos", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)
    //println("final", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)
    println(sum)
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x1, y1, z1) = readLine().split(" ").map(_.toInt) // a: 0, 1, 2
    val Array(x2, y2, z2) = readLine().split(" ").map(_.toInt) // b: 0, 1, 2

    val ans = 2L * ((z1 min y2) - ((z2 - (z2 min x1)) min y1))

    println(ans)
  }
}


import scala.io.StdIn._
object Main extends App {
    var a = readInt
    for(k<-1 to a){
        val n = readInt
        for(i<-2 to n+1){
            print(i+" ")
        }
        print("\n")
    }
}

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

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

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

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

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 998244353L
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        for (i <- 1 to n) {
            writer.print(i+1 + " ")
        }
        writer.println()

        def check(kk: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(st))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(st, mid)
            else
                return bs(mid, en)
        }
    }
    writer.flush()
}


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


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

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


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


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

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)


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)

    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)

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


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
  }

}

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)

  }

}

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 java.io._
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)

  val n = readInt
  val lines = 0 +: readInts :+ 0
  for(_ <- 1 to readInt) {
    val Array(r, c) = readInts
    lines.update(r - 1, lines(r - 1) + c - 1)
    lines.update(r + 1, lines(r + 1) + lines(r) - c)
    lines.update(r, 0)
  }

  def main(a: Array[String]) {
    println(lines.drop(1).take(n).mkString("\n"))
  }
}

object A294 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val ai = readInts(n)
    val Array(m) = readInts(1)
    for(_ <- 1 to m) {
      var Array(x, y) = readInts(2)
      x -= 1
      val curr = ai(x)
      ai(x) = 0
      if(x-1 >= 0) {
        ai(x-1) += y-1
      }
      if(x + 1 < n) {
        ai(x+1) += curr-y
      }
    }

    out.println(ai.mkString("\n"))
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

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

  val N = sc.nextInt
  val w = Array.fill(N + 2)(Int.MinValue)
  for (i <- 1 to N)
    w(i) = sc.nextInt
  val M = sc.nextInt

  def shoot: Unit = {
    val x, y = sc.nextInt
    val left = y - 1
    val right = w(x) - y
    w(x) = 0
    w(x - 1) += left
    w(x + 1) += right
  }

  for (i <- 0 until M) shoot

  for (i <- 1 to N)
    out.println(w(i))

  out.close
}

object A {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);

  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ
    var Array(m) = READ
    for (i <- 1 to m) {
      var Array(x, y) = READ
      if (x > 1) a(x-2) += y-1;
      if (x < n) a(x) += a(x-1)-y;
      a(x-1) = 0;
    }
    a map (println(_))
  }
}

object Main {
  class Wires(val n: Int) {
    private val data = readLine().split(" ").map(_.toInt).toArray

    def shoot() = {
      val s = readLine().split(" ").map(_.toInt)
      val x = s(0)
      val y = s(1)

      val up = y - 1
      val down = data(x - 1) - y

      data(x - 1) = 0
      if (x - 2 >= 0) data(x - 2) += up
      if (x < n) data(x) += down
    }

    def print() {
      data.foreach(println(_))
    }
  }

  def main(args: Array[String]) {
    val n = readInt
    val w = new Wires(n)
    val m = readInt
    for (_ <- 1 to m) { w.shoot() }
    w.print()
  }
}

object CF178Div2A {
  def main(args:Array[String]){
    val n = readLine.toInt
    var arr = readLine.split(" ").map(_.toInt)
    val m = readLine.toInt
    (1 to m).foreach(i =>{
      val Array(x,y) = readLine.split(" ").map(_.toInt - 1)
      if(x > 0) arr(x-1) += y
      if(x < n-1) arr(x+1) += arr(x)-(y+1)
      arr(x) = 0
    })
    arr.foreach(x => println(x))
  }
}

  object Birds extends App{
  		  	def resolve(lines: IndexedSeq[String]) = {
  		  	  		val n = lines(0).toInt
  		  	  		var birdsByWire = Map[Int, Int]()

  		  	  		for ((birds, wire) <- lines(1).split(" ").toList.zip(1 to n)) {
  		  	  		  			birdsByWire = birdsByWire + (wire -> birds.toInt)
  		  	  		 }

  		  	  		val cases = lines.drop(3)
  							for(l <- cases) {

  								val (wire, shot) = {
  									val tokens = l.split(" ")
	  								(tokens(0).toInt, tokens(1).toInt)
  								}

  								val left = shot - 1
  								val right = birdsByWire(wire) - shot

					  			if (n == 1) {
					  				birdsByWire += (n -> 0)
					  			} else if (wire == n) {
					  				birdsByWire += (wire - 1 -> (birdsByWire(wire - 1) + left))
					        	birdsByWire += (n -> 0)
					  			} else if (wire == 1) {
					  				birdsByWire += (wire + 1 -> (birdsByWire(wire + 1) + right))
					  				birdsByWire += (1 -> 0)
					  			} else {
					  				birdsByWire += (wire + 1 -> (birdsByWire(wire + 1) + right))
					  				birdsByWire += (wire - 1 -> (birdsByWire(wire - 1) + left))
					  				birdsByWire += (wire -> 0)
					  			}

						  	}

  							for(w <- 1 to n) println(birdsByWire(w))
  					}

			resolve(io.Source.stdin.getLines.toIndexedSeq)

 }

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val birds = in.next().split(" ").map(_.toInt)
  val m = in.next().toInt
  (1 to m).foreach { _ =>
    val Array(x, y) = in.next().split(" ").map(_.toInt)
    val indexX = x - 1
    val birdCount = birds(indexX)
    val up = y - 1
    val down = birdCount - y
    if (indexX != 0)
      birds(indexX - 1) += up
    if (indexX != n - 1)
      birds(indexX + 1) += down
    birds(indexX) = 0
  }
  println(birds.mkString("\n"))
}

object Main extends App  {

    val numberN = readLine().toInt
    val birdsOn = readLine().split("\\s+").map(_.toInt)
    val numberM = readLine().toInt

    for (i <- 0 to (numberM - 1)) {
        val pairXY = readLine().split("\\s+") match { case Array (x, y) => (x.toInt, y.toInt)}

        if (pairXY._1 - 2 >= 0) {
            birdsOn(pairXY._1 - 2) += pairXY._2 - 1;
        }

        if (pairXY._1  <= numberN - 1) {
            birdsOn(pairXY._1) += birdsOn(pairXY._1 - 1) - pairXY._2
        }

        birdsOn(pairXY._1 - 1) = 0
    }

    for (i <- birdsOn) {
        println(i)
    }

}

  object Birds extends App {
  	val lines = io.Source.stdin.getLines.toIndexedSeq
  	val n = lines(0).toInt
  	var birdsByLine = Map[Int, Int]()

  	for ((birds, line) <- lines(1).split(" ").toList.zip(1 to n)) {
  		birdsByLine = birdsByLine + (line -> birds.toInt)
  	}

  	for(l <- lines.drop(3)) {
  		val (shot, line) = {
  			val tokens = l.split(" ")
  			(tokens(1).toInt, tokens(0).toInt)
  		}

  		val birdsToTheLeft = shot - 1
  		val birdsToTheRigth = birdsByLine(line) - shot

  		if (n == 1) {
  			birdsByLine += (n -> 0)
  		} else if (line == n) {
  			birdsByLine += (line - 1 -> (birdsByLine(line - 1) + birdsToTheLeft))
        birdsByLine += (n -> 0)
  		} else if (line == 1) {
  			birdsByLine += (line + 1 -> (birdsByLine(line + 1) + birdsToTheRigth))
  			birdsByLine += (1 -> 0)
  		} else {
  			birdsByLine += (line + 1 -> (birdsByLine(line + 1) + birdsToTheRigth))
  			birdsByLine += (line - 1 -> (birdsByLine(line - 1) + birdsToTheLeft))
  			birdsByLine += (line -> 0)
  		}
  	}

  	birdsByLine.foreach(p => println(p._2))
  }

  object Birds extends App {
  	val lines = io.Source.stdin.getLines.toIndexedSeq
  	val n = lines(0).toInt
  	var birdsByLine = Map[Int, Int]()

  	for ((birds, line) <- lines(1).split(" ").toList.zip(1 to n)) {
  		birdsByLine = birdsByLine + (line -> birds.toInt)
  	}

  	for(l <- lines.drop(3)) {
  		val (shot, line) = {
  			val tokens = l.split(" ")
  			(tokens(1).toInt, tokens(0).toInt)
  		}

  		val birdsToTheLeft = shot - 1
  		val birdsToTheRigth = birdsByLine(line) - shot

  		if (n == 1) {
  			birdsByLine += (n -> 0)
  		} else if (line == n) {
  			birdsByLine += (line - 1 -> (birdsByLine(line - 1) + birdsToTheLeft))
			birdsByLine += (line -> 0)
        birdsByLine += (n -> 0)
  		} else if (line == 1) {
  			birdsByLine += (line + 1 -> (birdsByLine(line + 1) + birdsToTheRigth))
  			birdsByLine += (1 -> 0)
  		} else {
  			birdsByLine += (line + 1 -> (birdsByLine(line + 1) + birdsToTheRigth))
  			birdsByLine += (line - 1 -> (birdsByLine(line - 1) + birdsToTheLeft))
  			birdsByLine += (line -> 0)
  		}
  	}

  	birdsByLine.foreach(p => println(p._2))
  }