You are given an array $$$a_{1}, a_{2}, \ldots, a_{n}$$$. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct.In other words, at most one time you can choose two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) and delete integers $$$a_l, a_{l+1}, \ldots, a_r$$$ from the array. Remaining elements should be pairwise distinct. Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements in the given array. The next line contains $$$n$$$ spaced integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$1 \le a_{i} \le 10^{9}$$$) — the elements of the array.

Print a single integer — the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print $$$0$$$.

NoteIn the first example all the elements are already distinct, therefore no subsegment needs to be removed.In the second example you can remove the subsegment from index $$$2$$$ to $$$3$$$.In the third example you can remove the subsegments from index $$$1$$$ to $$$2$$$, or from index $$$2$$$ to $$$3$$$, or from index $$$3$$$ to $$$4$$$.

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val setL, setR = mutable.Set[Int]()
    def findLMax: Int = {
      REP(N) { i =>
        if (setL.contains(A(i))) return i - 1
        setL += A(i)
      }
      N - 1
    }

    var ans = N
    val lMax = findLMax
    debug(s"lMax:$lMax")
    debug(setL.mkString(" "))
    var l = lMax
    var r = N
    while(l >= -1) {
      while(r - 1 > l && !setL.contains(A(r - 1)) && !setR.contains(A(r - 1))) {
        r -= 1
        setR += A(r)
      }
      debug(s"l:$l r:$r")
      ans = min(ans, r - l - 1)
      if (l >= 0) setL -= A(l)
      l -= 1
    }

    out.println(ans)
  }
}

import scala.collection.mutable

object B 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 = n
  var l = 0
  val left = mutable.Set.empty[Int]

  do {
    var r = 0
    val right = mutable.Set.empty[Int]
    if (l > 0) left += as(l - 1)
    do {
      if (n - r - l < min) {
        //println(l, r, left, right)
        min = n - r - l
      }
      if (r > 0) right += as(n - r)
      r += 1
    } while (l + r <= n && !left(as(n - r)) && !right(as(n - r)))
    l += 1
  } while (l < n && !left(as(l - 1)))

  println(min)
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val setL, setR = mutable.Set[Int]()
    def findLMax: Int = {
      REP(N) { i =>
        if (setL.contains(A(i))) return i - 1
        setL += A(i)
      }
      N - 1
    }

    var ans = N
    val lMax = findLMax
    debug(s"lMax:$lMax")
    debug(setL.mkString(" "))
    var l = lMax
    var r = N
    while(l >= 0) {
      while(r - 1 > l && !setL.contains(A(r - 1)) && !setR.contains(A(r - 1))) {
        r -= 1
        setR += A(r)
      }
      debug(s"l:$l r:$r")
      ans = min(ans, r - l - 1)
      setL -= A(l)
      l -= 1
    }

    out.println(ans)
  }
}


There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.

The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i.

Print the maximum number of teams of three people the coach can form.

NoteIn the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.In the second example he can't make a single team.In the third example the coach can form three teams. For example, he can do this in the following way:  The first group (of two people) and the seventh group (of one person),  The second group (of two people) and the sixth group (of one person),  The third group (of two people) and the fourth group (of one person).

object P899A_SplittingInTeams extends App {
  import scala.io.StdIn

  StdIn.readLine()
  val (singles, pairs) = StdIn.readLine().split(" ").map(_.toInt).foldLeft((0, 0)) {
    case ((s, p), num) =>
      if (num == 1)
        (s + 1, p)
      else
        (s, p + 1)
  }
  if (pairs > singles) {
    println(singles)
  } else {
    println(pairs + (singles - pairs) / 3)
  }
}


In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.

Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.

NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val str = in.next()
  val left = str.takeWhile(_ == '<').length
  val right = str.reverse.takeWhile(_ == '>').length
  println(Math.min(n, left + right))
}

import java.io._
import scala.io.Source

import scala.annotation.tailrec

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {

    val bumperCount = lines.next().toInt
    val bumpers = lines.next()
    val soln = solve(bumperCount, bumpers)
    bw.write(soln.toString)
    bw.newLine()
  }

  def solve(bumperCount: Int, bumpers: String): Int = {
    @tailrec
    def countLeft(pos: Int, count: Int): Int =
      if (pos == bumperCount || bumpers(pos) == '>') count
      else countLeft(pos + 1, count + 1)

    @tailrec
    def countRight(pos: Int, count: Int): Int =
      if (pos == -1 || bumpers(pos) == '<') count
      else countRight(pos - 1, count + 1)

    val totalCount = countLeft(0, 0) + countRight(bumperCount - 1, 0)
    totalCount
  }
}

object JumpingBall extends App {

  import scala.util.control.Breaks._

  def execute(firstInput: Int, bumpers: String): Int = {

    var acc = 0
    val n = bumpers.length

    breakable {
      for(i <- 0 until n){
        if(bumpers(i) == '<') acc += 1
        else break
      }
    }

    breakable {
      for(i <- n - 1 to 0 by -1){
        if(bumpers(i) == '>') acc += 1
        else break
      }
    }

    acc

  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.readLine().toInt // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}

object JumpingBall extends App {

  def execute(firstInput: Int, bumpers: String): Int = {
      val n = bumpers.length - 1

      val minRightIndex = bumpers.indexOf('>')
      val maxLeftIndex = bumpers.lastIndexOf('<')

      def sumIzq(ind: Int): Int =
        if(ind > 0 ) ind
        else 0

      def sumDer(ind: Int): Int =
        if(ind < n ) n - ind
        else 0

      if(minRightIndex == 0 && maxLeftIndex == n) 0 // >..<
      else if(minRightIndex == -1 && maxLeftIndex == n) sumIzq(maxLeftIndex) + 1 // <<<
      else if(maxLeftIndex == -1 && minRightIndex == 0) sumDer(minRightIndex) + 1 // >>>
      else sumIzq(minRightIndex) + sumDer(maxLeftIndex) // ..>..<..
  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.readLine().toInt // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}

object JumpingBall extends App {

  def execute(firstInput: Int, bumpers: String): Int = {

    def sum(filter: Char => Boolean)(bumpers: List[Char], acc: Int): Int = bumpers match {
      case Nil => acc
      case x :: xs if filter(x) => acc
      case x :: xs => sum(filter)(xs, acc + 1)
    }

    def sumIzq = sum( _ == '>' ) _
    def sumDer = sum( _ == '<' ) _

    sumIzq(bumpers.toList, 0) + sumDer(bumpers.reverse.toList,  0)

  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.readLine().toInt // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}

object A725 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = scala.io.StdIn.readLine
    val right = input.reverse.dropWhile(_ == '>').length
    var res = input.length - right
    res += input.takeWhile(_ == '<').length
    println(res)
  }
}

object A extends App {

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

  val _ = readLine
  val s = readLine.toCharArray

  val res = s.takeWhile(_ == '<').size + s.reverse.takeWhile(_ == '>').size

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

  println(res)

  Console.flush
}

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

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

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

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

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

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

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

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

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

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

object ReadInputExample {
def main(args: Array[String]): Unit = {
        var  d = scala.io.StdIn.readLine().toInt
        var  inp = scala.io.StdIn.readLine()
        val status = Array.fill[Option[Boolean]](inp.length)(None)
        for (i <- 0 until inp.length) {
            if (status(i).isEmpty) {
                isPossibleList(inp, i, status)
            }
        }
        println(status.filter(x => x.get).length)
    }
    def isPossibleList(inp: String, ind: Int, status: Array[Option[Boolean]]): Boolean = {
        if (status(ind).nonEmpty) return status(ind).get
        if ((ind == 0 && inp(ind) == '<') || (ind == inp.length - 1 && inp(ind) == '>')) {
            status(ind) = Some(true)
            return true
        }
        val res = if (inp(ind) == '>') {
            if (inp(ind + 1) == '<') false else isPossibleList(inp, ind + 1, status)
        } else {
            if (inp(ind - 1) == '>') false else isPossibleList(inp, ind - 1, status)
        }
        status(ind) = Some(res)
        res
    }
}

object JumpingBall extends App {

  def execute(firstInput: Int, bumpers: String): Int = {
      val n = bumpers.length - 1

      val minRightIndex = bumpers.indexOf('>')
      val maxLeftIndex = bumpers.lastIndexOf('<')

      def sumIzq(ind: Int): Int =
        if(ind > 0 ) ind
        else 0

      def sumDer(ind: Int): Int =
        if(ind < n ) n - ind
        else 0

      if(minRightIndex == 0 && maxLeftIndex == n) 0
      else sumIzq(minRightIndex) + sumDer(maxLeftIndex)
  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.read() // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}

object JumpingBall extends App {

  def execute(firstInput: Int, bumpers: String): Int = {
      val n = bumpers.length - 1

      val minRightIndex = bumpers.indexOf('>')
      val maxLeftIndex = bumpers.lastIndexOf('<')

      def sumIzq(ind: Int): Int =
        if(ind > 0 ) ind
        else 0

      def sumDer(ind: Int): Int =
        if(ind < n ) n - ind
        else 0

      if(minRightIndex == 0 && maxLeftIndex == n) 0
      else sumIzq(minRightIndex) + sumDer(maxLeftIndex)
  }

  // Length of the Seq[Bumpers]
  val n =  Console.in.readLine().toInt // 1 <= n <= 200,000
  val bumpers = Console.in.readLine()
  println(execute(n, bumpers))

}


In BerSoft $$$n$$$ programmers work, the programmer $$$i$$$ is characterized by a skill $$$r_i$$$.A programmer $$$a$$$ can be a mentor of a programmer $$$b$$$ if and only if the skill of the programmer $$$a$$$ is strictly greater than the skill of the programmer $$$b$$$ $$$(r_a > r_b)$$$ and programmers $$$a$$$ and $$$b$$$ are not in a quarrel.You are given the skills of each programmers and a list of $$$k$$$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $$$i$$$, find the number of programmers, for which the programmer $$$i$$$ can be a mentor.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$$$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $$$r_1, r_2, \dots, r_n$$$ $$$(1 \le r_i \le 10^{9})$$$, where $$$r_i$$$ equals to the skill of the $$$i$$$-th programmer. Each of the following $$$k$$$ lines contains two distinct integers $$$x$$$, $$$y$$$ $$$(1 \le x, y \le n$$$, $$$x \ne y)$$$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $$$x$$$ is in a quarrel with $$$y$$$ then $$$y$$$ is in a quarrel with $$$x$$$. Guaranteed, that for each pair $$$(x, y)$$$ there are no other pairs $$$(x, y)$$$ and $$$(y, x)$$$ in the input.

Print $$$n$$$ integers, the $$$i$$$-th number should be equal to the number of programmers, for which the $$$i$$$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.

NoteIn the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.

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, M = ni()
    val A = na(N)
    val minus = Array.ofDim[Int](N)
    REP(M) { _ =>
      val u, v = ni() - 1
      if (A(u) < A(v)) minus(v) += 1
      if (A(v) < A(u)) minus(u) += 1
    }
    val sorted = A.clone()
    sort(sorted)

    val ans = ArrayBuffer[Int]()
    REP(N) { i =>
      ans += max(0, lowerBound(sorted, A(i)) - minus(i))
    }

    out.println(ans.mkString(" "))
  }

  // あえてコピペ
  // 要はcountLt
  // a >= x  [x-2, x-1, x, x, x, x+1] の 2
  def lowerBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

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

  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[Long]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$:  $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list);  $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if:  it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$;  and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t<c_t$$$. For example:  $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$,  $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$,  $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.

Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.

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

  /**
   * 1-based Binary Indexed (Fenwick) Tree with binary search.
   */
  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length + 1) { 0L }

    for (i <- src.indices) update(i + 1, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r <= 0) acc else query(r - (r & -r), acc + t(r))

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit = {
      if (i < t.length) {
        t(i) += delta
        update(i + (i & -i), delta)
      }
    }

    def firstGreaterOrEqual(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx < t.length && sum + t(newIdx) < goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx + 1
    }

  }

  val n = nextInt
  val as = nextInts(n)
  val G = 1
  val sorted = as.sorted
  val sortedWithIndex = as.zipWithIndex.sortBy {
    case (x, i) => (-x, i)
  }
  val order = Array.ofDim[Int](n)
  for (i <- as.indices) {
    order(i) = sortedWithIndex(i)._2
  }

  val m = nextInt
  case class Query(k: Int, pos: Int, id: Int)
  val queries = Array.tabulate(m) { id =>
    val k, pos = nextInt
    Query(k, pos, id)
  }.sortBy(_.k)

  val res = Array.ofDim[Int](m)
  val bit = new BIT(Array.fill(n)(0L))

  var currentK = 0
  for (q <- queries) {
    while (currentK < q.k) {
      bit.update(order(currentK) + 1, +1)
      currentK += 1
    }
    val i = bit.firstGreaterOrEqual(q.pos) - 1
    res(q.id) = as(i)
  }

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

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

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
  case class Entry(a: Int, i: Int)
  case class Query(k: Int, pos: Int, m: Int)

  class BIT(n: Int, zero: Int)(f: (Int, Int) => Int) {
  def this(n: Int) = this(n, 0)(_ + _)

  private val N = {
    val a = Integer.highestOneBit(n)
    if (a == n) a else a << 1
  }
  private val bit = if (zero != 0) Array.fill[Int](N + 1)(zero) else Array.ofDim[Int](N + 1)

  /**
    * 1 index
    * addとindex違うよ
    * cumsumなんかといっしょ
    */
  def sum(i: Int): Int = {
    assert(i <= n)
    var x = i
    var s: Int = zero
    while(x > 0) {
      s = f(s, bit(x))
      x -= x & -x
    }
    s
  }

  /**
    * 0 index
    */
  def add(i: Int, a: Int): Unit = {
    assert(i < n)
    var x = i + 1
    while(x <= N) {
      bit(x) = f(bit(x), a)
      x += x & -x
    }
  }

  def sumAll: Int = sum(n)

  // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない
  private def sub(a: Int, b: Int) = a - b
  private def lt(a: Int, b: Int) = a < b

  /**
    * [l, r)
    */
  def query(l: Int, r: Int): Int = {
    assert(r > l)
    sub(sum(r), sum(l))
  }

  def lowerBound(W: Int): Int = {
    var k = N
    var x = 0
    var w = W
    while(k > 0) {
      if (x + k <= N && lt(bit(x + k), w)) {
        w = sub(w, bit(x + k))
        x += k
      }
      k /= 2
    }
    math.min(n, x)
  }
}
}

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

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N = ni()
    val A = na(N)
    val E = Array.ofDim[Entry](N)
    REP(N) { i =>
      E(i) = Entry(A(i), i)
    }
    sort(E, new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = {
        if (o1.a == o2.a) Integer.compare(o1.i, o2.i)
        else Integer.compare(o2.a, o1.a) // 降順
      }
    })
    val M = ni()
    val queried = Array.fill[ArrayBuffer[Query]](N)(ArrayBuffer())
    val ans = Array.ofDim[Int](M)
    REP(M) { m =>
      val k, pos = ni()
      val q = Query(k, pos, m)
      queried(k - 1) += q
    }

    val bit = new BIT(N)
    REP(N) { i =>
      bit.add(E(i).i, 1)
      queried(i).foreach { q =>
        val ix = bit.lowerBound(q.pos)
        ans(q.m) = A(ix)
      }
    }

    REP(M) { i =>
      out.println(ans(i))
    }
  }
}

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

  /**
   * 1-based Binary Indexed (Fenwick) Tree with binary search.
   */
  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length + 1) { 0L }

    for (i <- src.indices) update(i + 1, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r <= 0) acc else query(r - (r & -r), acc + t(r))

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit = {
      if (i < t.length) {
        t(i) += delta
        update(i + (i & -i), delta)
      }
    }

    def firstGreaterOrEqual(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx < t.length && sum + t(newIdx) < goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx + 1
    }

  }

  val n = nextInt
  val as = nextInts(n)
  val G = 1
  val sorted = as.zipWithIndex.sortBy {
    case (x, i) => (x, -i)
  }
  val order = Array.ofDim[Int](n)
  for (i <- as.indices) {
    order(sorted(i)._2) = i
  }

  val m = nextInt
  case class Query(k: Int, pos: Int, id: Int)
  val queries = Array.tabulate(m) { id =>
    val k, pos = nextInt
    Query(k, pos, id)
  }.sortBy(_.k)

  val res = Array.ofDim[Int](m)
  val bit = new BIT(Array.fill(n)(0L))

  var currentK = 0
  for (q <- queries) {
    while (currentK < q.k) {
      bit.update(order(currentK) + 1, +1)
      currentK += 1
    }
    val i = bit.firstGreaterOrEqual(q.pos) - 1
    res(q.id) = as(i)
  }

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

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


Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.

The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).  Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.

Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.

import scala.collection._

object C extends App {

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

  val MOD = 1000000007L
  val MODB = BigInt(MOD)

  val v = mutable.Map.empty[(Int, Int), Long]

  val Array(h, w, n) = readInts(3)

  val fs, fInvs = Array.ofDim[Long](h + w)

  var f = 1L
  for (i <- fs.indices) {
    fs(i) = f
    fInvs(i) = BigInt(f).modInverse(MODB).toLong
    f = f * (i + 1) % MOD
  }

  def pascal(r: Int, c: Int): Long = {
    val k = r - 1
    val n = r + c - 2
    (fs(n) * fInvs(n - k) % MOD) * fInvs(k) % MOD
  }

  val black = Array.ofDim[(Int, Int)](n)

  for (i <- 0 until n) {
    val Array(r, c) = readInts(2)
    black(i) = (r, c)
  }

  val sorted = black.sorted

  for (i <- 0 until n) {
    val (r, c) = sorted(i)
    var d = pascal(r, c)
    for (j <- 0 until n) {
      val (r2, c2) = sorted(j)
      if (r2 <= r && c2 <= c && i != j) {
        d = (d + MOD - v(r2, c2) * pascal(r - r2 + 1, c - c2 + 1) % MOD) % MOD
      }
    }
    v += (r, c) -> d
  }

  var res = pascal(h, w)

  for (i <- 0 until n) {
    val (r, c) = sorted(i)
    res = (res + MOD - v(r, c) * pascal(h - r + 1, w - c + 1) % MOD) % MOD
  }

  println(res)
}

import io.StdIn._

object Solution {

  val mod: Long = 1000000007

  val maxn = 200000

  val fac = Array.fill(maxn+1)(1L)

  val inv = Array.fill(maxn+1)(1L)

  def main(args: Array[String]) {
    val line = readLine().split(" ").map(_.toInt)
    val (h, w, n) = (line(0), line(1), line(2))

    var black = Array.ofDim[(Int, Int)](n).map{ _ =>
      val line = readLine().split(" ").map(_.toInt)
      (line(0), line(1))
    }

    for (i <- 1 to maxn) {
      fac(i) = fac(i-1) * i % mod
      inv(i) = pow(fac(i), mod-2)
    }

    black = black.sorted ++ Array((h, w))

    val f = black.map( b => cab(1, 1, b._1, b._2) )

    for (
      (c, i) <- black.zipWithIndex;
      (p, j) <- black.take(i).zipWithIndex if c._1 >= p._1 && c._2 >= p._2
    ) {
      f(i) = (f(i) - (f(j) * cab(p._1, p._2, c._1, c._2) % mod) + mod) % mod
    }

    println(f(n))

  }

  private def pow(aa: Long, nn: Long): Long = {
    var (a, n) = (aa, nn)
    var res = 1L
    while (n > 0) {
      if ((n & 1) == 1) res = res * a % mod
      a = a * a % mod
      n >>= 1
    }
    res % mod
  }

  private def cab(ax: Int, ay: Int, bx: Int, by: Int): Long = {
    val m: Int = bx - ax + by - ay
    val n: Int = bx - ax
    fac(m) * inv(n) % mod * inv(m-n) % mod
  }

}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val hugeNum=1000000007L
    val maxhw=100000+10

    val h=nextInt
    val w=nextInt
    val n=nextInt
    val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted
    //inverse table
    val inverseModuloTable=Array.fill(maxhw)(1L)

    var numStart=hugeNum-2

    var dv=1
    while(dv<numStart){
      dv*=2
    }
    while(dv>0){
      for(i<-0 until maxhw){
        inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum
      }
      if(numStart>=dv){
        for(i<-0 until maxhw){
          inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum
        }
        numStart-=dv
      }
      dv/=2
    }
    for(i<-2 until maxhw){
      inverseModuloTable(i)=(inverseModuloTable(i-1)*inverseModuloTable(i))%hugeNum
    }
    inverseModuloTable(0)=1
    val prodModuloTable=Array.fill(maxhw*2)(1L)
    for(i<-2 until prodModuloTable.length){
      prodModuloTable(i)=(prodModuloTable(i-1)*i)%hugeNum
    }
    //C function
    def combFact(n:Int,m:Int):Int={
      var ans=(prodModuloTable(n)*inverseModuloTable(n-m))%hugeNum

        ans=(ans*inverseModuloTable(m))%hugeNum

      return ans toInt
    }
    //solve problem
    val D=Array.fill(n+1)(0L)

    for(i<-0 until n+1){

      val (ac,bc)=badArray(i)
      D(i)=combFact(ac+bc,ac)

      for(j<-0 until i){
        val (a0,b0)=badArray(j)
        if(a0<=ac && b0<=bc){

          D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum-hugeNum
          D(i)%=hugeNum
        }
      }

    }
    out.println(D(n))
    //code ends here
    out.flush
    out.close
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val hugeNum=1000000007L
    val maxhw=100000+10

    val h=nextInt
    val w=nextInt
    val n=nextInt
    val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted
    //inverse table
    val inverseModuloTable=Array.fill(maxhw)(1L)

    var numStart=hugeNum-2

    var dv=1
    while(dv<numStart){
      dv*=2
    }
    while(dv>0){
      for(i<-0 until maxhw){
        inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum
      }
      if(numStart>=dv){
        for(i<-0 until maxhw){
          inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum
        }
        numStart-=dv
      }
      dv/=2
    }
    for(i<-2 until maxhw){
      inverseModuloTable(i)=(inverseModuloTable(i-1)*inverseModuloTable(i))%hugeNum
    }

    //C function
    def combFact(n:Int,m:Int):Int={
      var ans=1L
      for(i<-n-m+1 to n){
        ans=(ans*i)%hugeNum
      }

        ans=(ans*inverseModuloTable(m))%hugeNum

      return ans toInt
    }
    //solve problem
    val D=Array.fill(n+1)(0L)

    for(i<-0 until n+1){

      val (ac,bc)=badArray(i)
      D(i)=combFact(ac+bc,ac)
      for(j<-0 until i){
        val (a0,b0)=badArray(j)
        if(a0<=ac && b0<=bc){
          D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum-hugeNum
          D(i)%=hugeNum
        }
      }

    }
    out.println(D(n))
    //code ends here
    out.flush
    out.close
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val hugeNum=1000000007L
    val maxhw=100000+10

    val h=nextInt
    val w=nextInt
    val n=nextInt
    val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted
    //inverse table
    val inverseModuloTable=Array.fill(maxhw)(1L)

    var numStart=hugeNum-2

    var dv=1
    while(dv<numStart){
      dv*=2
    }
    while(dv>0){
      for(i<-0 until maxhw){
        inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum
      }
      if(numStart>=dv){
        for(i<-0 until maxhw){
          inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum
        }
        numStart-=dv
      }
      dv/=2
    }
    for(i<-1 until maxhw){
      inverseModuloTable(i)=(inverseModuloTable(i-1)*inverseModuloTable(i))%hugeNum
    }
    //C function
    def combFact(n:Int,m:Int):Int={
      var ans=1L
      for(i<-n-m+1 to n){
        ans=(ans*i)%hugeNum
      }

        ans=(ans*inverseModuloTable(m))%hugeNum

      return ans toInt
    }
    //solve problem
    val D=Array.fill(n+1)(0L)

    for(i<-0 until n+1){

      val (ac,bc)=badArray(i)
      D(i)=combFact(ac+bc,ac)
      for(j<-0 until i){
        val (a0,b0)=badArray(j)
        if(a0<=ac && b0<=bc){
          D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum-hugeNum
          D(i)%=hugeNum
        }
      }

    }
    out.println(D(n))
    //code ends here
    out.flush
    out.close
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val hugeNum=1000000007L
    val maxhw=100000+10

    val h=nextInt
    val w=nextInt
    val n=nextInt
    val badArray=(for (i<-0 until n+1) yield if(i!=n) (nextInt-1,nextInt-1) else (h-1,w-1)) sorted
    //inverse table
    val inverseModuloTable=Array.fill(maxhw)(1L)

    var numStart=hugeNum-2

    var dv=1
    while(dv<numStart){
      dv*=2
    }
    while(dv>0){
      for(i<-0 until maxhw){
        inverseModuloTable(i)=(inverseModuloTable(i)*inverseModuloTable(i))%hugeNum
      }
      if(numStart>=dv){
        for(i<-0 until maxhw){
          inverseModuloTable(i)=(inverseModuloTable(i)*i)%hugeNum
        }
        numStart-=dv
      }
      dv/=2
    }

    //C function
    def combFact(n:Int,m:Int):Int={
      var ans=1L
      for(i<-n-m+1 to n){
        ans=(ans*i)%hugeNum
      }
      for(i<-1 to m){
        ans=(ans*inverseModuloTable(i))%hugeNum
      }
      return ans toInt
    }
    //solve problem
    val D=Array.fill(n+1)(0L)

    for(i<-0 until n+1){

      val (ac,bc)=badArray(i)
      D(i)=combFact(ac+bc,ac)
      for(j<-0 until i){
        val (a0,b0)=badArray(j)
        if(a0<=ac && b0<=bc){
          D(i)-=(D(j)*combFact(ac+bc-a0-b0,ac-a0))%hugeNum
          D(i)%=hugeNum
        }
      }

    }
    out.println(D(n))
    //code ends here
    out.flush
    out.close
  }
}