Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes A = {a1,  a2,  ...,  an}, where the width and the height of the i-th envelope is strictly higher than the width and the height of the (i  -  1)-th envelope respectively. Chain size is the number of envelopes in the chain. Peter wants to make the chain of the maximum size from the envelopes he has, the chain should be such, that he'll be able to put a card into it. The card fits into the chain if its width and height is lower than the width and the height of the smallest envelope in the chain respectively. It's forbidden to turn the card and the envelopes. Peter has very many envelopes and very little time, this hard task is entrusted to you.

The first line contains integers n, w, h (1  ≤ n ≤ 5000, 1 ≤ w,  h  ≤ 106) — amount of envelopes Peter has, the card width and height respectively. Then there follow n lines, each of them contains two integer numbers wi and hi — width and height of the i-th envelope (1 ≤ wi,  hi ≤ 106).

In the first line print the maximum chain size. In the second line print the numbers of the envelopes (separated by space), forming the required chain, starting with the number of the smallest envelope. Remember, please, that the card should fit into the smallest envelope. If the chain of maximum size is not unique, print any of the answers. If the card does not fit into any of the envelopes, print number 0 in the single line.

//import scala.util.Random

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, w, h) = in.next().split(' ').map(_.toInt)
//  val n = 5000
//  val w = 1
//  val h = 1
//  val r = new Random()
//  val t = System.nanoTime()

//  (1 to 10).foreach{ _ =>
  val line = (0 until n).map{i =>
    val Array(w1, h1) = in.next().split(' ').map(_.toInt)
    (w1, h1, i + 1)
//    (Random.nextInt(1000000), Random.nextInt(1000000), i + 1)
  }.filter(i => i._1 > w && i._2 > h).sortBy(- _._1).toArray

  val dp = Array.ofDim[Int](line.length)
  val prev = Array.ofDim[Int](line.length)

  line.indices.foreach { i =>
    var j = 0
    var max = 0
    var maxIndex = -1
    while (j < i) {
      if (line(j)._1 > line(i)._1 && line(j)._2 > line(i)._2 && dp(j) > max) {
        maxIndex = j
        max = dp(j)
      }
      j += 1
    }

    dp(i) = 1 + max
    prev(i) = maxIndex
  }

  if (dp.isEmpty)
    println(0)
  else {
    val max = dp.max
    println(max)
    var p = dp.indices.find(i => dp(i) == max).get
    var answer = List.empty[Int]

    while (p != -1) {
      answer ::= line(p)._3
      p = prev(p)
    }

    println(answer.reverse.mkString(" "))
  }
//}
//  println(System.nanoTime() - t)
//  6336504045
//  4874416168
//  6579074027

//  6149716536
//  6057171782
//  5041613499

//  5141237046
//  5987173184
//  5025914418
}

import java.util.Scanner

import scala.collection.immutable.Seq

object Solution {

  def printDPArr(dpArr: Array[Int], sorted:Array[Box], prev:Array[Int], maxIdx: Int): Unit = {
    var l = List.empty[Short]
    var idx = maxIdx
    while(idx >=0) {
      l =  sorted(idx).idx :: l
      idx = prev(idx)
    }

    println(l.mkString(" "))
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())
    val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))
    val fittingBoxes = arr.filter(c => c.w > cardW && c.h > cardH )
    val sorted: Array[Box] = fittingBoxes.sortBy(b => (b.w, b.h))

    if(sorted.nonEmpty) {
      //main code

      val dpArr = Array.ofDim[Int](sorted.length)
      val prev = Array.ofDim[Int](sorted.length)

      for {
        i <- dpArr.indices
      } {
        i match {
          case 0 =>
            dpArr(0) = 1
            prev(0) = -1
          case ii =>
            val sortedZipped: (Int, Int) = (0 until ii).foldLeft(-1, -1)((acc, iii) =>{
              if(dpArr(iii)>acc._1 && sorted(ii).w > sorted(iii).w && sorted(ii).h > sorted(iii).h) {
                (dpArr(iii), iii)
              } else {
                acc
              }
            }

            )
            if(sortedZipped == (-1, -1)) {
              dpArr(ii) = 1
              prev(ii) = -1
            } else {
              dpArr(ii) = sortedZipped._1 + 1
              prev(ii) = sortedZipped._2
            }
        }
      }
      val max = dpArr.max
      println(max)
      printDPArr(dpArr, sorted, prev, dpArr.indexOf(max))
    } else {
      println(0)
    }

  }

  case class Box(w: Int, h: Int, idx: Short)

}

import java.util.Scanner

object DLetters extends App {

  val scanner = new Scanner(System.in)

  val numLetters = scanner.fastInt
  val card = Letter(scanner.fastInt, scanner.fastInt, -1)

  val l = (for {
    order <- 1 until numLetters + 1
    letter = Letter(scanner.fastInt, scanner.fastInt, order) if card.canFit(letter)
  } yield letter).sortBy(_.x).toList

  val letters = (card :: l).toArray

  val trace = Array.ofDim[Int](letters.size)
  val longest = Array.ofDim[Int](letters.size)

  var maxInd = 0

  (0 until letters.size).foreach { i =>
    (0 until i).foreach { j =>
      if (letters(j).canFit(letters(i)) && longest(j) >= longest(i) - 1) {
        longest(i) = longest(j) + 1
        trace(i) = j
        if (longest(i) > longest(maxInd)) maxInd = i
      }
    }
  }

  println(longest(maxInd))
  printResult(maxInd, Nil)

  def printResult(traceIndex: Int, acc: List[Int]): Unit = {
    if (traceIndex == 0) {
      println(acc.mkString(" "))
    } else {
      printResult(trace(traceIndex), letters(traceIndex).order :: acc)
    }
  }

  case class Letter(x: Int, y: Int, order: Int) {

    def canFit(other: Letter): Boolean = this.x < other.x && this.y < other.y

  }

  implicit class ScannerExt(sc: Scanner) {

    def fastInt: Int = sc.next().toInt

  }

}

object D4 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, w, h) = readInts(3)
    val in = Array.fill(n)(readInts(2))
      .map(arr => (arr(0), arr(1)))
      .zipWithIndex
      .filter{case ((a, b), _) => a > w && b > h}
      .sorted
    val len = in.length
    if(len > 0) {
      val dp = Array.fill(len)(1)
      val idx = Array.fill(len)(-1)
      for (i <- 1 until len) {
        for (j <- 0 until i) {
          if (in(i)._1._1 > in(j)._1._1 && in(i)._1._2 > in(j)._1._2 && dp(i) < dp(j)+1) {
            dp(i) = dp(j)+1
            idx(i) = j
          }
        }
      }
      val max = dp.max
      println(max)
      val res = cu.ArrayBuffer.empty[Int]
      var i = dp.lastIndexWhere(_ == max)
      while(i != -1) {
        res.append(in(i)._2 + 1)
        i = idx(i)
      }
      println(res.reverse.mkString(" "))
    } else {
      println("0")
    }
  }

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

    @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._
import java.lang._
import java.io._
import java.util

object D {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  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 Long.parseLong(next)
  }

  def comp(x: ((Int, Int), Int), y: ((Int, Int), Int)): Boolean = {
    val s1: Long = Int.int2long(x._1._1) * Int.int2long(x._1._2)
    val s2: Long = Int.int2long(y._1._1) * Int.int2long(y._1._2)
    s1 < s2
  }

  def couldInsert(envelope1: (Int, Int), envelope2: (Int, Int)): Boolean = {
    envelope1._1 < envelope2._1 && envelope1._2 < envelope2._2
  }

  def couldInsert2(envelope1: ((Int, Int), Int), envelope2: ((Int, Int), Int)): Boolean = {
    envelope1._1._1 < envelope2._1._1 && envelope1._1._2 < envelope2._1._2
  }

  def solve = {
    val n = nextInt
    val postcard = (nextInt, nextInt)
    val envelopes = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      envelopes(i) = (nextInt, nextInt)
    }
    val cleanedEnvelopes = new util.ArrayList[((Int, Int), Int)]()
    for (i <- 0 until n) {
      if (couldInsert(postcard, envelopes(i))) {
        cleanedEnvelopes.add((envelopes(i), i))
      }
    }
    var zippedEnv = cleanedEnvelopes.toArray(new Array[((Int, Int), Int)](0))
    zippedEnv = zippedEnv.sortWith(comp)
//    zippedEnv.foreach(print)
    val len = zippedEnv.length
    if (len == 0) {
      out.println(0)
    } else {
      val d = new Array[Int](len)
      val p = new Array[Int](len)
      d(0) = 1
      p(0) = -1
      for (i <- 1 until len) {
        val a = zippedEnv(i)
        var max = -1
        var pj = -1
        for (j <- 0 until i) {
          if (couldInsert2(zippedEnv(j), a)) {
            if (d(j) > max) {
              max = d(j)
              pj = j
            }
          }
        }
        if (max + 1 > 1) {
          p(i) = pj
          d(i) = max + 1
        } else {
          p(i) = -1
          d(i) = 1
        }
      }
      //    d.foreach(x => print(x + " "))
      //    p.foreach(x => print(x + " "))
      var max = -1
      var start = -1
      for (i <- 0 until len) {
        if (max < d(i)) {
          max = d(i)
          start = i
        }
      }
      out.println(max)
      val ans = new Array[Int](max)
      var ind = 0
      while (start != -1) {
        ans(ind) = zippedEnv(start)._2 + 1
        ind += 1
        start = p(start)
      }
      for (i <- 0 until max) {
        out.print(ans(max - i - 1) + " ")
      }
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

object main extends App with fastIO {

  val n = nextInt
  val w = nextInt
  val h = nextInt

  var p = 0
  var a = Array.fill(n) { p += 1; Point(nextInt, nextInt, p) }.filter((it) => it.x > w && it.y > h).sortWith(_ < _)
  var dp = Array.fill(n)( 0 )

  var ans = 0
  var ind = 0

  for (i <- 0 until a.length) {
    var value = 1
    for (j <- 0 until i) if (a(j).x < a(i).x && a(j).y < a(i).y)
      value = math.max(value, dp(j) + 1)

    dp(i) = value
    if (value > ans) { ans = dp(i); ind = i }
  }
  var res = Array.fill(ans)( 0 )

  if (ans > 0) {
    res(ans - 1) = ind
    for (i <- ind - 1 to (0, -1))
      if (dp(i) + 1 == ans && a(i).x < a(ind).x && a(i).y < a(ind).y) {
        ans -= 1; ind = i
        res(ans - 1) = i
      }
  }

  println(res.length)
  for (i <- res)
    print(a(i).id + " ")

  flush
}

case class Point(x: Int, y: Int, id: Int) {
  def < (b: Point): Boolean = { this.x < b.x || this.x == b.x && this.y > b.y }
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

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

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object P4D {
    class PrefixMax(m : Int) {
        val s = 1 << Math.getExponent(m.toFloat) + 1
        val a = Array.fill(s + s){(0, 0)}
        def add(n : Int, x : (Int, Int)) {
            var i = s + n
            while (i > 0) {
                if (x._1 > a(i)._1) a(i) = x
                i = i >>> 1
            }
        }
        def get(n : Int) = {
            var i = s + n
            var ans = (0, -1)
            while (i > 1) {
                if ((i & 1) == 1) {
                    val x = a(i - 1)
                    if (x._1 > ans._1) ans = x
                }
                i = i >>> 1
            }
            ans
        }
    }

    def main(args: Array[String]) {
        val Array(n, wS, hS) = readLine split " " map {_.toInt}
        val a = for (id <- (1 to n).toIterator) yield {
            val Array(w, h) = readLine split " " map {_.toInt}
            (w, h, id)
        }
        val aF = a.filter{case (w, h, id) => w > wS && h > hS}.toArray
        val awT = aF.map{_._1}.sorted.distinct
        val awR = awT.zipWithIndex.toMap
        val ahT = aF.map{_._2}.sorted.distinct
        val ahR = ahT.zipWithIndex.toMap
        val aL = aF.map{case (w, h, id) => (awR(w), ahR(h), id)}.sorted
        val s = new PrefixMax(ahT.size + 1)
        val q = collection.mutable.ArrayBuffer[(Int, Int, Int)]()
        var qW = -1
        def flushQ(w : Int) {
            for ((h, i, len) <- q) s.add(h, (len, i))
            q.clear
            qW = w
        }
        val fromN = for (i <- 0 until aL.size) yield {
            val (w, h, _) = aL(i)
            if (w != qW) flushQ(w)
            val (len, from) = s.get(h)
            val lenN = len + 1
            q += ((h, i, lenN))
            from
        }
        flushQ(-1)
        val (len, from) = s.get(ahT.size)
        if (len == 0) {
            println("0")
        } else {
            println(len)
            val b = Iterator.iterate(from)(fromN).takeWhile{_ != -1}.toBuffer
            println(b.reverseMap{i => aL(i)._3} mkString " ")
        }
    }
}

object P4D {
    class PrefixMax(m : Int) {
        val s = 1 << Math.getExponent(m.toFloat) + 1
        val a = Array.fill(s + s){(0, 0)}
        def add(n : Int, x : (Int, Int)) {
            var i = s + n
            while (i > 0) {
                if (x._1 > a(i)._1) a(i) = x
                i = i >>> 1
            }
        }
        def get(n : Int) = {
            var i = s + n
            var ans = (0, -1)
            while (i > 1) {
                if ((i & 1) == 1) {
                    val x = a(i - 1)
                    if (x._1 > ans._1) ans = x
                }
                i = i >>> 1
            }
            ans
        }
    }

    def main(args: Array[String]) {
        val Array(n, wS, hS) = readLine split " " map {_.toInt}
        val a = for (id <- (1 to n).toIterator) yield {
            val Array(w, h) = readLine split " " map {_.toInt}
            (w, h, id)
        }
        val aF = a.filter{case (w, h, id) => w > wS && h > hS}.toArray
        val awT = aF.map{_._1}.sorted.distinct
        val awR = awT.zipWithIndex.toMap
        val ahT = aF.map{_._2}.sorted.distinct
        val ahR = ahT.zipWithIndex.toMap
        val aL = aF.map{case (w, h, id) => (awR(w), ahR(h), id)}.sorted
        val s = new PrefixMax(ahT.size + 1)
        val q = collection.mutable.ArrayBuffer[(Int, Int, Int)]()
        var qW = -1
        def flushQ(w : Int) {
            for ((h, i, len) <- q) s.add(h, (len, i))
            q.clear
            qW = w
        }
        val fromN = for (i <- 0 until aL.size) yield {
            val (w, h, _) = aL(i)
            if (w != qW) flushQ(w)
            val (len, from) = s.get(h)
            val lenN = len + 1
            q += ((h, i, lenN))
            from
        }
        flushQ(-1)
        val (len, from) = s.get(ahT.size)
        if (len == 0) {
            println("0")
        } else {
            println(len)
            val b = Iterator.iterate(from)(fromN).takeWhile{_ != -1}.toBuffer
            println(b.reverse.map{i => aL(i)._3} mkString " ")
        }
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, w, h) = in.next().split(' ').map(_.toInt)

  val line = (0 until n).map{i =>
    in.next().split(' ').map(_.toInt)
  }.sortBy(_.head)

  val dp = Array.fill[Int](n)(1)
  val prev = Array.ofDim[Int](n)
  var dpMax = -1
  var i = 0

  while (i < n) {
    var j = 0
    var max = 0
    var maxIndex = -1
    while (j < i) {
      if (line(j).head > line(i).head && line(j).last > line(i).last && line(j).head > w && line(j).last > w && dp(j) > max) {
        maxIndex = j
        max = dp(j)
      }
      j += 1
    }

    if (maxIndex == -1) {
      prev(i) = -1
    }
    else {
      dp(i) = 1 + max
      prev(i) = maxIndex
    }
    if (dpMax == -1 || dp(dpMax) < dp(i))
      dpMax = i
    i += 1
  }

  if (dpMax == -1)
    println(0)
  else {
    var answer = List.empty[Int]
    println(dp(dpMax))

    while (dpMax != -1) {
      answer ::= dpMax + 1
      dpMax = prev(dpMax)
    }

    println(answer.reverse.mkString(" "))
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, w, h) = in.next().split(' ').map(_.toInt)

  val line = (0 until n).map{i =>
    val Array(w1, h1) = in.next().split(' ').map(_.toInt)
    (w1, h1, i + 1)
  }.filter(i => i._1 >= w && i._2 >= h).sorted.reverse

  val dp = Array.ofDim[Int](line.length)
  val prev = Array.ofDim[Int](line.length)

  line.indices.foreach { i =>
    val indices = (0 until i).filter(j => line(j)._1 > line(i)._1 && line(j)._2 > line(i)._2)
    if (indices.isEmpty) {
      dp(i) = 1
      prev(i) = -1
    }
    else {
      val index = indices.maxBy(j => dp(j))
      dp(i) = 1 + dp(index)
      prev(i) = index
    }
  }

  val max = dp.max
  println(max)
  var p = dp.indices.find(i => dp(i) == max).get
  var answer = List.empty[Int]

  while (p != -1) {
    answer ::= line(p)._3
    p = prev(p)
  }

  println(answer.reverse.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, w, h) = in.next().split(' ').map(_.toInt)

  val line = (0 until n).map{i =>
    in.next().split(' ').map(_.toInt)
  }.sortBy(_.head)

  val dp = Array.fill[Int](n)(1)
  val prev = Array.ofDim[Int](n)
  var dpMax = -1
  var i = 0

  while (i < n) {
    var j = 0
    var max = 0
    var maxIndex = -1
    while (j < n) {
      if (line(j).head > line(i).head && line(j).last > line(i).last && dp(j) > max) {
        maxIndex = j
        max = dp(j)
      }
      j += 1
    }

    if (maxIndex == -1) {
      prev(i) = -1
    }
    else {
      dp(i) = 1 + max
      prev(i) = maxIndex
    }
    if (dpMax == -1 || dp(dpMax) < dp(i))
      dpMax = i
    i += 1
  }

  if (dpMax == -1)
    println(0)
  else {
    var answer = List.empty[Int]
    println(dp(dpMax))

    while (dpMax != -1) {
      answer ::= dpMax + 1
      dpMax = prev(dpMax)
    }

    println(answer.reverse.mkString(" "))
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, w, h) = in.next().split(' ').map(_.toInt)

  val line = (0 until n).map{i =>
    val Array(w1, h1) = in.next().split(' ').map(_.toInt)
    (w1, h1, i + 1)
  }

  val dp = Array.ofDim[Int](n)
  val prev = Array.ofDim[Int](n)
  var dpMax = -1
  var i = 0

  while (i < line.length) {
    var j = 0
    var max = 0
    var maxIndex = -1
    while (j < n) {
      if (line(j)._1 > line(i)._1 && line(j)._2 > line(i)._2 && dp(j) > max) {
        maxIndex = j
        max = dp(j)
      }
      j += 1
    }

    if (maxIndex == -1) {
      dp(i) = 1
      prev(i) = -1
    }
    else {
      dp(i) = 1 + max
      prev(i) = maxIndex
    }
    if (dpMax == -1 || dp(dpMax) < dp(i))
      dpMax = i
    i += 1
  }

  if (dpMax == -1)
    println(0)
  else {
    println(dp(dpMax))
    var answer = List.empty[Int]

    while (dpMax != -1) {
      answer ::= line(dpMax)._3
      dpMax = prev(dpMax)
    }

    println(answer.reverse.mkString(" "))
  }
}

import java.util.Scanner

object Solution {

  def printDPArr(dpArr: Array[Short], boxes:Array[Box], max: Short): Unit = {
    var aMax = max
    var prev: Option[Box] = None
    for {
      i <- dpArr.indices
    } {
      if(aMax == dpArr(i) && prev.fold(true)(b => boxes(i).w > b.w && boxes(i).h > b.h)){
        aMax = (aMax + 1).toShort
        print(s"${boxes(i).idx} ")
        prev = Option(boxes(i))
      }
    }
    println()
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())
    val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))
    val fittingBoxes = arr.filter(c => c.w > cardW && c.h > cardH )
    val grouped: Array[Array[Box]] = fittingBoxes
      .groupBy(_.w)
      .mapValues(_.sortBy(_.h))
      .toArray
      .sortBy(_._1)
      .map(_._2)

    if(grouped.isEmpty){
      println(0)
      return
    }

    val dpArr = Array.ofDim[Short](grouped.length)
    val boxes = Array.ofDim[Box](grouped.length)

    for {
      i <- dpArr.indices
    } {
      i match {
        case 0 =>
          dpArr(0) = 1
          boxes(0) = grouped(0)(0)
        case ii if boxes.slice(0, ii).exists(b => grouped(ii).exists(g => g.h > b.h)) =>
          val values: Seq[(Short, Box)] = dpArr
            .slice(0, ii)
            .zipWithIndex
            .flatMap(p => grouped(ii).find(g => g.h > boxes(p._2).h).map(p._1 -> _))

          val maxDPVal = values.maxBy(_._1)._1
          boxes(ii) = values.filter(_._1==maxDPVal).minBy(_._2.h)._2
          dpArr(ii) = (maxDPVal + 1).toShort
        case ii =>
          dpArr(ii) = 1
          boxes(ii) = grouped(i)(0)
      }
    }
    val max = dpArr.max
    println(max)
    printDPArr(dpArr, boxes, 1)

  }

  case class Box(w: Int, h: Int, idx: Short)

}

import java.util.Scanner

object Solution {

  def printDPArr(dpArr: Array[Short], boxes:Array[Box],prev:Array[Int], max: Short): Unit = {
    var l = List.empty[Short]
    var idx = dpArr.indexOf(max)
    while(idx >=0) {
      l =  boxes(idx).idx :: l
      idx = prev(idx)
    }

    println(l.mkString(" "))
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())
    val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))
    val fittingBoxes = arr.filter(c => c.w > cardW && c.h > cardH )
    val grouped: Array[Array[Box]] = fittingBoxes
      .groupBy(_.w)
      .mapValues(_.sortBy(_.h))
      .toArray
      .sortBy(_._1)
      .map(_._2)

    if(grouped.isEmpty){
      println(0)
      return
    }

    val dpArr = Array.ofDim[Short](grouped.length)
    val boxes = Array.ofDim[Box](grouped.length)
    val prev = Array.ofDim[Int](grouped.length)

    for {
      i <- dpArr.indices
    } {
      i match {
        case 0 =>
          dpArr(0) = 1
          boxes(0) = grouped(0)(0)
          prev(0) = -1
        case ii if boxes.slice(0, ii).exists(b => grouped(ii).exists(g => g.h > b.h)) =>
          val values: Array[((Short, Int), Box)] = dpArr
            .slice(0, ii)
            .zipWithIndex
            .flatMap(p => grouped(ii).find(g => g.h > boxes(p._2).h).map(p -> _))

          val maxDPVal = values.maxBy(_._1._1)._1._1
          val by: ((Short, Int), Box) = values.filter(_._1._1 == maxDPVal).minBy(_._2.h)
          boxes(ii) = by._2
          dpArr(ii) = (maxDPVal + 1).toShort
          prev(ii) = by._1._2
        case ii =>
          dpArr(ii) = 1
          boxes(ii) = grouped(i)(0)
          prev(ii) = -1
      }
    }
    val max = dpArr.max
    println(max)
    printDPArr(dpArr, boxes,prev, max)

  }

  case class Box(w: Int, h: Int, idx: Short)

}

import java.util.Scanner

object Solution {

  def printDPArr(dpArr: Array[Short], boxes:Array[Box], max: Short): Unit = {
    var aMax = max
    for {
      i <- dpArr.indices
    } {
      if(aMax == dpArr(i)){
        aMax = (aMax + 1).toShort
        print(s"${boxes(i).idx} ")
      }
    }
    println()
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())
    val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))
    val fittingBoxes = arr.filter(c => c.w > cardW && c.h > cardH )
    val grouped: Array[Array[Box]] = fittingBoxes
      .groupBy(_.w)
      .mapValues(_.sortBy(_.h))
      .toArray
      .sortBy(_._1)
      .map(_._2)

    if(grouped.isEmpty){
      println(0)
      return
    }

    val dpArr = Array.ofDim[Short](grouped.length)
    val boxes = Array.ofDim[Box](grouped.length)

    for {
      i <- dpArr.indices
    } {
      i match {
        case 0 =>
          dpArr(0) = 1
          boxes(0) = grouped(0)(0)
        case ii if boxes.slice(0, ii).exists(b => grouped(ii).exists(g => g.h > b.h)) =>
          val values: Seq[(Short, Box)] = dpArr
            .slice(0, ii)
            .zipWithIndex
            .flatMap(p => grouped(ii).find(g => g.h > boxes(p._2).h).map(p._1 -> _))

          val maxDPVal = values.maxBy(_._1)._1
          boxes(ii) = values.filter(_._1==maxDPVal).minBy(_._2.h)._2
          dpArr(ii) = (maxDPVal + 1).toShort
        case ii =>
          dpArr(ii) = 1
          boxes(ii) = grouped(i)(0)
      }
    }
    val max = dpArr.max
    println(max)
    printDPArr(dpArr, boxes, 1)

  }

  case class Box(w: Int, h: Int, idx: Short)

}

import java.util.Scanner

object Solution {

  def printDPArr(dpArr: Array[Short], boxes:Array[Box], max: Short): Unit = {
    var aMax = max
    for {
      i <- dpArr.indices
    } {
      if(aMax == dpArr(i)){
        aMax = (aMax + 1).toShort
        print(s"${boxes(i).idx} ")
      }
    }
    println()
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val (n, cardW, cardH) = (in.nextInt(), in.nextInt(), in.nextInt())
    val arr: Array[Box] = Array.tabulate(n)(i => Box(in.nextInt(), in.nextInt(), (i+1).toShort))
    val fittingBoxes = arr.filter(c => c.w > cardW || c.h > cardH )
    val grouped: Array[Array[Box]] = fittingBoxes
      .groupBy(_.w)
      .mapValues(_.sortBy(_.h))
      .toArray
      .sortBy(_._1)
      .map(_._2)

    if(grouped.isEmpty){
      println(0)
      return
    }

    val dpArr = Array.ofDim[Short](grouped.length)
    val boxes = Array.ofDim[Box](grouped.length)

    for {
      i <- dpArr.indices
    } {
      i match {
        case 0 =>
          dpArr(0) = 1
          boxes(0) = grouped(0)(0)
        case ii if boxes.slice(0, ii).exists(b => grouped(ii).exists(g => g.h > b.h)) =>
          val values: Seq[(Short, Box)] = dpArr
            .slice(0, ii)
            .zipWithIndex
            .flatMap(p => grouped(ii).find(g => g.h > boxes(p._2).h).map(p._1 -> _))

          val maxDPVal = values.maxBy(_._1)._1
          boxes(ii) = values.filter(_._1==maxDPVal).minBy(_._2.h)._2
          dpArr(ii) = (maxDPVal + 1).toShort
        case ii =>
          dpArr(ii) = 1
          boxes(ii) = grouped(i)(0)
      }
    }
    val max = dpArr.max
    println(max)
    printDPArr(dpArr, boxes, 1)

  }

  case class Box(w: Int, h: Int, idx: Short)

}

object D4 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, w, h) = readInts(3)
    val in = Array.fill(n)(readInts(2))
      .map(arr => (arr(0), arr(1)))
      .zipWithIndex
      .filter{case ((a, b), _) => a > w && b > h}
      .sorted
    val len = in.length
    if(len > 0) {
      val buff = Array.fill(len)(cu.ArrayBuffer.empty[Int])
      buff(0).append(0)
      for (i <- 1 until len) {
        for (j <- 0 until i) {
          if (in(i)._1._1 > in(j)._1._1 && in(i)._1._2 > in(j)._1._2 && buff(i).length < buff(j).length) {
            buff(i) = buff(j)
          }
        }
        buff(i).append(in(i)._2)
      }
      println(buff.last.length)
      println(buff.last.map(_ + 1).mkString(" "))
    } else {
      println("0")
    }
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object D4 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, w, h) = readInts(3)
    val in = Array.fill(n)(readInts(2))
      .map(arr => (arr(0), arr(1)))
      .zipWithIndex
      .filter{case ((a, b), _) => a > w && b > h}
      .sorted
    val len = in.length
    if(len > 0) {
      val buff = Array.fill(len)(cu.ArrayBuffer.empty[Int])
      buff(0).append(0)
      for (i <- 1 until len) {
        for (j <- 0 until i) {
          if (in(i)._1._1 > in(j)._1._1 && in(i)._1._2 > in(j)._1._2 && buff(i).length < buff(j).length) {
            buff(i) = buff(j)
          }
        }
        buff(i).append(in(i)._2)
      }
      println(len)
      println(buff.last.map(_ + 1).mkString(" "))
    } else {
      println("0")
    }
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object D4 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, w, h) = readInts(3)
    val in = Array.fill(n)(readInts(2))
      .map(arr => (arr(0), arr(1)))
      .zipWithIndex
      .filter{case ((a, b), _) => a > w && b > h}
      .sorted
    val len = in.length
    if(len > 0) {
      val buff = Array.fill(len)(cu.ArrayBuffer.empty[Int])
      buff(0).append(in(0)._2)
      for (i <- 1 until len) {
        for (j <- 0 until i) {
          if (in(i)._1._1 > in(j)._1._1 && in(i)._1._2 > in(j)._1._2 && buff(i).length < buff(j).length) {
            buff(i) = buff(j)
          }
        }
        buff(i).append(in(i)._2)
      }
      println(buff.last.length)
      println(buff.last.map(_ + 1).mkString(" "))
    } else {
      println("0")
    }
  }

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

    @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._
import java.lang._
import java.io._
import java.util

object D {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  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 Long.parseLong(next)
  }

  def comp(x: ((Int, Int), Int), y: ((Int, Int), Int)): Boolean = {
    x._1._1 * x._1._2 < y._1._1 * y._1._2
  }

  def couldInsert(envelope1: (Int, Int), envelope2: (Int, Int)): Boolean = {
    envelope1._1 < envelope2._1 && envelope1._2 < envelope2._2
  }

  def couldInsert2(envelope1: ((Int, Int), Int), envelope2: ((Int, Int), Int)): Boolean = {
    envelope1._1._1 < envelope2._1._1 && envelope1._1._2 < envelope2._1._2
  }

  def solve = {
    val n = nextInt
    val postcard = (nextInt, nextInt)
    val envelopes = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      envelopes(i) = (nextInt, nextInt)
    }
    val cleanedEnvelopes = new util.ArrayList[(Int, Int)]()
    for (i <- 0 until n) {
      if (couldInsert(postcard, envelopes(i))) {
        cleanedEnvelopes.add(envelopes(i))
      }
    }
    var zippedEnv = cleanedEnvelopes.toArray(new Array[(Int, Int)](0)).zipWithIndex
    zippedEnv = zippedEnv.sortWith(comp)
    val len = zippedEnv.length
    if (len == 0) {
      out.println(0)
    } else {
      val d = new Array[Int](len)
      val p = new Array[Int](len)
      d(0) = 1
      p(0) = -1
      for (i <- 1 until len) {
        val a = zippedEnv(i)
        var max = -1
        var pj = -1
        for (j <- 0 until i) {
          if (couldInsert2(zippedEnv(j), a)) {
            if (d(j) > max) {
              max = d(j)
              pj = j
            }
          }
        }
        if (max + 1 > 1) {
          p(i) = pj
          d(i) = max + 1
        } else {
          p(i) = -1
          d(i) = 1
        }
      }
      //    d.foreach(x => print(x + " "))
      //    p.foreach(x => print(x + " "))
      var max = -1
      var start = -1
      for (i <- 0 until len) {
        if (max < d(i)) {
          max = d(i)
          start = i
        }
      }
      out.println(max)
      val ans = new Array[Int](max)
      var ind = 0
      while (start != -1) {
        ans(ind) = zippedEnv(start)._2 + 1
        ind += 1
        start = p(start)
      }
      for (i <- 0 until max) {
        out.print(ans(max - i - 1) + " ")
      }
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

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

object D {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  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 Long.parseLong(next)
  }

  def comp(x: ((Int, Int), Int), y: ((Int, Int), Int)): Boolean = {
    x._1._1 * x._1._2 < y._1._1 * y._1._2
  }

  def couldInsert(envelope1: (Int, Int), envelope2: (Int, Int)): Boolean = {
    envelope1._1 < envelope2._1 && envelope1._2 < envelope2._2
  }

  def couldInsert2(envelope1: ((Int, Int), Int), envelope2: ((Int, Int), Int)): Boolean = {
    envelope1._1._1 < envelope2._1._1 && envelope1._1._2 < envelope2._1._2
  }

  def solve = {
    val n = nextInt
    val postcard = (nextInt, nextInt)
    val envelopes = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      envelopes(i) = (nextInt, nextInt)
    }
    val cleanedEnvelopes = new util.ArrayList[((Int, Int), Int)]()
    for (i <- 0 until n) {
      if (couldInsert(postcard, envelopes(i))) {
        cleanedEnvelopes.add((envelopes(i), i))
      }
    }
    var zippedEnv = cleanedEnvelopes.toArray(new Array[((Int, Int), Int)](0))
    zippedEnv = zippedEnv.sortWith(comp)
    val len = zippedEnv.length
    if (len == 0) {
      out.println(0)
    } else {
      val d = new Array[Int](len)
      val p = new Array[Int](len)
      d(0) = 1
      p(0) = -1
      for (i <- 1 until len) {
        val a = zippedEnv(i)
        var max = -1
        var pj = -1
        for (j <- 0 until i) {
          if (couldInsert2(zippedEnv(j), a)) {
            if (d(j) > max) {
              max = d(j)
              pj = j
            }
          }
        }
        if (max + 1 > 1) {
          p(i) = pj
          d(i) = max + 1
        } else {
          p(i) = -1
          d(i) = 1
        }
      }
      //    d.foreach(x => print(x + " "))
      //    p.foreach(x => print(x + " "))
      var max = -1
      var start = -1
      for (i <- 0 until len) {
        if (max < d(i)) {
          max = d(i)
          start = i
        }
      }
      out.println(max)
      val ans = new Array[Int](max)
      var ind = 0
      while (start != -1) {
        ans(ind) = zippedEnv(start)._2 + 1
        ind += 1
        start = p(start)
      }
      for (i <- 0 until max) {
        out.print(ans(max - i - 1) + " ")
      }
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

object main extends App with fastIO {

  var t = Array.fill(4 * 1000007)( 0 )

  def get(v: Int, l: Int, r: Int, pl: Int, pr: Int): Int = {
    if (pl > pr || pl > r || l > pr) return 0
    if (pl <= l && r <= pr) return t(v)

    val lr = (l + r) >> 1
    get(v + v, l, lr, pl, pr) +
    get(v + v + 1, lr + 1, r, pl, pr)
  }

  def update(v: Int, l: Int, r: Int, x: Int, value: Int): Int = {
    if (l == r) { t(v) = math.max(t(v), value); return t(v) }

    val lr = (l + r) >> 1
    t(v) = math.max(t(v),
      if (x <= lr)
        update(v + v, l, lr, x, value) else
        update(v + v + 1, lr + 1, r, x, value)
    )
    t(v)
  }

  val n = nextInt
  val w = nextInt
  val h = nextInt

  var p = 0
  var a: Array[Point] = Array.fill(n) { p += 1; Point(nextInt, nextInt, p) }.filter((it) => it.x > w && it.y > h).sortWith(_ < _)
  var dp = Array.fill(n)( 0 )

  for (i <- a) println(i)

  var ans = 0
  var ind = 0

  for (i <- 0 until a.length) {
    val value = get(1, 1, 1000000, 1, a(i).y - 1)
    update(1, 1, 1000000, a(i).y, value + 1)

    dp(i) = value + 1
    if (dp(i) > ans) { ans = dp(i); ind = i }
  }
  var res = Array.fill(ans)( 0 )

  if (ans > 0) {
    res(ans - 1) = ind
    for (i <- ind - 1 to (0, -1))
      if (dp(i) + 1 == ans && a(i).x < a(ind).x && a(i).y < a(ind).y) {
        ans -= 1; ind = i
        res(ans - 1) = i
      }
  }

  println(res.length)
  for (i <- res)
    print(a(i).id + " ")

  flush
}

case class Point(x: Int, y: Int, id: Int) {
  def < (b: Point): Boolean = { this.x < b.x || this.x == b.x && this.y > b.y }
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

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

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object main extends App with fastIO {

  var t = Array.fill(4 * 1000007)( 0 )

  def get(v: Int, l: Int, r: Int, pl: Int, pr: Int): Int = {
    if (pl > pr || pl > r || l > pr) return 0
    if (pl <= l && r <= pr) return t(v)

    val lr = (l + r) >> 1
    get(v + v, l, lr, pl, pr) +
    get(v + v + 1, lr + 1, r, pl, pr)
  }

  def update(v: Int, l: Int, r: Int, x: Int, value: Int): Int = {
    if (l == r) { t(v) = math.max(t(v), value); return t(v) }

    val lr = (l + r) >> 1
    t(v) = math.max(t(v),
      if (x <= lr)
        update(v + v, l, lr, x, value) else
        update(v + v + 1, lr + 1, r, x, value)
    )
    t(v)
  }

  val n = nextInt
  val w = nextInt
  val h = nextInt

  var p = 0
  var a = Array.fill(n) { p += 1; Point(nextInt, nextInt, p) }.filter((it) => it.x > w && it.y > h).sortWith((p1, p2) => p1 < p2)
  var dp = Array.fill(n)( 0 )

  var ans = 0
  var ind = 0

  for (i <- 0 until n) {
    val value = get(1, 1, 1000000, 1, a(i).y - 1)
    update(1, 1, 1000000, a(i).y, value + 1)

    dp(i) = value + 1
    if (dp(i) > ans) { ans = dp(i); ind = i }
  }

  var res = Array.fill(ans)( 0 )

  res(ans - 1) = ind
  for (i <- ind - 1 to (0, -1))
    if (dp(i) + 1 == ans && a(i).x < a(ind).x && a(i).y < a(ind).y) {
      ans -= 1; ind = i
      res(ans - 1) = i
    }

  println(res.length)
  for (i <- res)
    Console.printf("%d ", a(i).id)

  flush
}

case class Point(x: Int, y: Int, id: Int) {
  def < (b: Point): Boolean = { this.x < b.x || this.x == b.x && this.y > b.y }
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

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

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object main extends App with fastIO {

  var t = Array.fill(4 * 1000007)( 0 )

  def get(v: Int, l: Int, r: Int, pl: Int, pr: Int): Int = {
    if (pl > pr || pl > r || l > pr) return 0
    if (pl <= l && r <= pr) return t(v)

    val lr = (l + r) >> 1
    get(v + v, l, lr, pl, pr) +
    get(v + v + 1, lr + 1, r, pl, pr)
  }

  def update(v: Int, l: Int, r: Int, x: Int, value: Int): Int = {
    if (l == r) { t(v) = math.max(t(v), value); return t(v) }

    val lr = (l + r) >> 1
    t(v) = math.max(t(v),
      if (x <= lr)
        update(v + v, l, lr, x, value) else
        update(v + v + 1, lr + 1, r, x, value)
    )
    t(v)
  }

  val n = nextInt
  val w = nextInt
  val h = nextInt

  var p = 0
  var a: Array[Point] = Array.fill(n) { p += 1; Point(nextInt, nextInt, p) }.filter((it) => it.x > w && it.y > h).sortWith(_ < _)
  var dp = Array.fill(n)( 0 )

  var ans = 0
  var ind = 0

  for (i <- 0 until a.length) {
    val value = get(1, 1, 1000000, 1, a(i).y - 1)
    update(1, 1, 1000000, a(i).y, value + 1)

    dp(i) = value + 1
    if (dp(i) > ans) { ans = dp(i); ind = i }
  }
  var res = Array.fill(ans)( 0 )

  if (ans > 0) {
    res(ans - 1) = ind
    for (i <- ind - 1 to (0, -1))
      if (dp(i) + 1 == ans && a(i).x < a(ind).x && a(i).y < a(ind).y) {
        ans -= 1; ind = i
        res(ans - 1) = i
      }
  }

  println(res.length)
  for (i <- res)
    print(a(i).id + " ")

  flush
}

case class Point(x: Int, y: Int, id: Int) {
  def < (b: Point): Boolean = { this.x < b.x || this.x == b.x && this.y > b.y }
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

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

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}


Andrew plays a game called "Civilization". Dima helps him.The game has n cities and m bidirectional roads. The cities are numbered from 1 to n. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities v1, v2, ..., vk, that there is a road between any contiguous cities vi and vi + 1 (1 ≤ i < k). The length of the described path equals to (k - 1). We assume that two cities lie in the same region if and only if, there is a path connecting these two cities.During the game events of two types take place:  Andrew asks Dima about the length of the longest path in the region where city x lies.  Andrew asks Dima to merge the region where city x lies with the region where city y lies. If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them. Dima finds it hard to execute Andrew's queries, so he asks you to help him. Help Dima.

The first line contains three integers n, m, q (1 ≤ n ≤ 3·105; 0 ≤ m < n; 1 ≤ q ≤ 3·105) — the number of cities, the number of the roads we already have and the number of queries, correspondingly. Each of the following m lines contains two integers, ai and bi (ai ≠ bi; 1 ≤ ai, bi ≤ n). These numbers represent the road between cities ai and bi. There can be at most one road between two cities. Each of the following q lines contains one of the two events in the following format:   1 xi. It is the request Andrew gives to Dima to find the length of the maximum path in the region that contains city xi (1 ≤ xi ≤ n).  2 xi yi. It is the request Andrew gives to Dima to merge the region that contains city xi and the region that contains city yi (1 ≤ xi, yi ≤ n). Note, that xi can be equal to yi.

For each event of the first type print the answer on a separate line.

import java.awt.geom.Area
import java.io._
import java.util._

import scala.collection.mutable.ArrayBuffer

object Main {

  var in: FastScanner = null
  var out: PrintWriter = null

  class Dsu(n: Int) {

    var p = new Array[Int](n)
    var d = new Array[Int](n)

    for (i <- 0 until n) {
      p(i) = i
    }

    def get(v: Int): Int = {
      if (p(v) == v)
        p(v)
      else {
        p(v) = get(p(v))
        p(v)
      }
    }

    def union(vv: Int, uu: Int) {
      val v = get(vv)
      val u = get(uu)
      if (v == u)
        return
      p(u) = v
      d(v) = un(d(v), d(u))
    }

    def un(d1: Int, d2: Int): Int = {
      val l1 = (1 + d1) / 2
      val l2 = (1 + d2) / 2
      Math.max(Math.max(d1, d2), l1 + l2 + 1)
    }
  }

  val MAX = 1000000
  val q = new Array[Int](MAX)

  def bfs(dist: Array[Int], from: Int, used: ArrayBuffer[Int],
          g: Array[ArrayBuffer[Int]], color: Array[Int], curColor: Int) {
    var sz = 1
    var it = 0
    q(0) = from
    dist(from) = 0
    while (it < sz) {
      val v = q(it)
      it += 1
      used.append(v)
      color(v) = curColor
      for (to <- g(v)) {
        if (dist(to) == -1) {
          dist(to) = dist(v) + 1
          q(sz) = to
          sz += 1
        }
      }
    }
  }

  def solve() {
    val n = in.nextInt()
    val m = in.nextInt()
    val q = in.nextInt()
    val g = new Array[ArrayBuffer[Int]](n)
    for (i <- 0 until n) {
      g(i) = new ArrayBuffer[Int]()
    }
    for (i <- 0 until m) {
      val x = in.nextInt() - 1
      val y = in.nextInt() - 1
      g(x).append(y)
      g(y).append(x)
    }
    val color = new Array[Int](n)
    for (i <- 0 until n)
      color(i) = -1
    var cntColors = 0
    val dist = new Array[Int](n)
    for (i <- 0 until n)
      dist(i) = -1
    val used = new ArrayBuffer[Int]()
    val lengths = new ArrayBuffer[Int]()
    for (i <- 0 until n) {
      if (color(i) == -1) {
        used.clear()
        bfs(dist, i, used, g, color, cntColors)
        var maxId = i
        for (to <- used) {
          if (dist(to) > dist(maxId))
            maxId = to
        }
        for ( to <- used) {
          dist(to) = -1
        }
        used.clear()
        bfs(dist, maxId, used, g, color, cntColors)
        cntColors += 1
        var maxLen = 0
        for ( to <- used) {
          maxLen = Math.max(maxLen, dist(to))
        }
        lengths.append(maxLen)
      }
    }

    val dsu = new Dsu(lengths.size)

    for (i <- 0 until lengths.size) {
      dsu.d(i) = lengths(i)
    }
    for (qq <- 0 until q) {
      if (in.nextInt() == 1) {
        out.println(dsu.d(dsu.get(color(in.nextInt() - 1))))
      } else {
        dsu.union(color(in.nextInt() - 1), color(in.nextInt() - 1))
      }
    }
  }

  def runIO() {

    in = new FastScanner(System.in)
    out = new PrintWriter(System.out)

    solve()

    out.close()
  }

  class FastScanner(f: InputStream) {

    val br = new BufferedReader(new InputStreamReader(f))
    var  st : StringTokenizer = null

//    public FastScanner(File f) {
//      try {
//        br = new BufferedReader(new FileReader(f));
//      } catch (FileNotFoundException e) {
//        e.printStackTrace();
//      }
//    }

    def next(): String = {
      while (st == null || !st.hasMoreTokens) {
        var s: String = null
        try {
          s = br.readLine
        } catch {
          case e: IOException =>
          e.printStackTrace()
        }
        if (s == null)
          return null
        st = new StringTokenizer(s)
      }
      st.nextToken()
    }

    def hasMoreTokens: Boolean = {
      while (st == null || !st.hasMoreTokens) {
        var s: String = null
        try {
          s = br.readLine()
        } catch {
          case e: IOException =>
            e.printStackTrace()
        }
        if (s == null)
          return false
        st = new StringTokenizer(s)
      }
      true
    }

    def nextInt() = {
      Integer.parseInt(next())
    }

    def nextLong() = {
      java.lang.Long.parseLong(next())
    }

    def nextDouble() {
      java.lang.Double.parseDouble(next())
    }
  }

  def main(args: Array[String]) {
    runIO()
  }

}


Sereja loves integer sequences very much. He especially likes stairs.Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met: a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?

The first line contains integer m (1 ≤ m ≤ 105) — the number of Sereja's cards. The second line contains m integers bi (1 ≤ bi ≤ 5000) — the numbers on the Sereja's cards.

In the first line print the number of cards you can put on the table. In the second line print the resulting stairs.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).sorted
  val answer = Array.ofDim[Int](n)
  (0 until n).foreach { i =>
    val index = if (i % 2 == 0) i / 2 else n - 1 - i / 2
    answer(index) = data(i)
  }
  val r = answer.tail.foldLeft(List(answer.head)) {
    case (l, el) if l.head == el => l
    case (l, el) => el :: l
  }
  println(r.length)
  println(r.mkString(" "))

}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val n = input.next().toInt
    val ns = input.next().split(" ").map(_.toInt).toList
    var s = ns.sortBy(-_)
    s = s.head :: s
    var l = List(s(0))
    var r = List(s(1))
    s = s.drop(2)
    while(s.nonEmpty) {
      if (s.head != l.head) {
        l = s.head :: l
      } else if (s.head != r.head) {
        r = s.head :: r
      }
      s = s.tail
    }
    val res = l ++ r.reverse.tail
    println(res.length)
    println(res.mkString(" "))
  }
}

import java.util.Scanner

object P381B {
    def main(args: Array[String]) {
        val sc = new Scanner(System.in)
        val m = sc.nextInt()
        val seq = for (i <- 1 to m) yield sc.nextInt()
        val distinctSeq = seq.distinct
        val duplicatedSeq = seq diff distinctSeq
        val dupDistinctSeq = duplicatedSeq.distinct
        val leftSeq = distinctSeq.sorted
        val rightSeq = dupDistinctSeq.sorted.reverse
        val ans = if (!rightSeq.isEmpty && leftSeq.last == rightSeq.head)
            leftSeq.init ++ rightSeq else leftSeq ++ rightSeq
        println(ans.length)
        println(ans.mkString(" "))
    }
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Unit = {
    val N = sc.nextInt
    val A = List.fill(N)(sc.nextInt).groupBy(identity).map(x => (x._1 -> x._2.size)).toMap

    val downOrd = Ordering.Int.reverse
    val down = A.keys.toList.sorted(downOrd)
    val top = down.head
    val up = A.filter(x => x._2 > 1).toMap.keys.toList.filterNot(_ == top).sorted

    val res = up ::: down

    out.println(res.size)
    out.println(res.mkString(" "))
  }

  solve
  out.close
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val n = input.next().toInt
    val ns = input.next().split(" ").map(_.toInt).toList
    var s = ns.sortBy(-_)
    if (s.length > 1 && s(0) == s(1)) s = s.tail
    val res = if (s.length == 1) {
      List(s(0))
    } else {
      var l = List(s(0))
      var r = List(s(1))
      var t = s.drop(2)
      while(t.nonEmpty) {
        if (t.head != l.head) {
          l = t.head :: l
        } else if (t.head != r.head) {
          r = t.head :: r
        }
        t = t.tail
      }
      println(l)
      println(r)
      l ++ r.reverse
    }
    println(res.mkString(" "))
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val n = input.next().toInt
    val ns = input.next().split(" ").map(_.toInt).toList
    var s = ns.sortBy(-_)
    if (s.length > 1 && s(0) == s(1)) s = s.tail
    val res = if (s.length == 1) {
      List(s(0))
    } else {
      var l = List(s(0))
      var r = List(s(1))
      var t = s.drop(2)
      while(t.nonEmpty) {
        if (t.head != l.head) {
          l = t.head :: l
        } else if (t.head != r.head) {
          r = t.head :: r
        }
        t = t.tail
      }
      println(l)
      println(r)
      l ++ r.reverse
    }
    println(res.length)
    println(res.mkString(" "))
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    val n = input.next().toInt
    val ns = input.next().split(" ").map(_.toInt).toList
    var s = ns.sortBy(-_)
    if (s.length > 1 && s(0) == s(1)) s = s.tail
    val res = if (s.length == 1) {
      List(s(0))
    } else {
      var l = List(s(0))
      var r = List(s(1))
      var t = s.drop(2)
      while(t.nonEmpty) {
        if (t.head != l.head) {
          l = t.head :: l
        } else if (t.head != r.head) {
          r = t.head :: r
        }
        t = t.tail
      }
      l ++ r.reverse
    }
    println(res.length)
    println(res.mkString(" "))
  }
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): String = {
    val N = sc.nextInt
    val A = List.fill(N)(sc.nextInt).groupBy(identity).map(x => (x._1 -> x._2.size)).toMap

    val up = A.keys.toList.sorted
    val top = up.last
    val ord = Ordering.Int.reverse
    val down = A.filter(x => x._2 > 1).toMap.keys.toList.filterNot(_ == top).sorted(ord)

    (up ::: down).mkString(" ")
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): String = {
    val N = sc.nextInt
    val A = List.fill(N)(sc.nextInt).groupBy(identity).map(x => (x._1 -> x._2.size)).toMap

    val downOrd = Ordering.Int.reverse
    val down = A.keys.toList.sorted(downOrd)
    val top = down.head
    val up = A.filter(x => x._2 > 1).toMap.keys.toList.filterNot(_ == top).sorted

    (up ::: down).mkString(" ")
  }

  out.println(solve)
  out.close
}


There are $$$n$$$ slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists). When a slime with a value $$$x$$$ eats a slime with a value $$$y$$$, the eaten slime disappears, and the value of the remaining slime changes to $$$x - y$$$.The slimes will eat each other until there is only one slime left. Find the maximum possible value of the last slime.

The first line of the input contains an integer $$$n$$$ ($$$1 \le n \le 500\,000$$$) denoting the number of slimes. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ is the value of $$$i$$$-th slime.

Print an only integer — the maximum possible value of the last slime.

NoteIn the first example, a possible way of getting the last slime with value $$$4$$$ is:  Second slime eats the third slime, the row now contains slimes $$$2, -1, 1$$$ Second slime eats the third slime, the row now contains slimes $$$2, -2$$$ First slime eats the second slime, the row now contains $$$4$$$ In the second example, the first slime can keep eating slimes to its right to end up with a value of $$$4$$$.

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)

    if (N == 1) out.println(A.head)
    else {
      val S = A.map(abs(_).toLong).sum
      val hasPlus = A exists (_ >= 0)
      val hasMinus = A exists (_ <= 0)

      val ans = if (hasMinus && hasPlus) S
      else if (hasPlus) S - 2 * A.min // plus only
      else S - 2 * abs(A.max) // minus only

      out.println(ans)
    }
  }

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

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

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

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

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 S = A.map(abs(_).toLong).sum
    val hasPlus = A exists (_ >= 0)
    val hasMinus = A exists (_ <= 0)

    val ans = if (hasMinus && hasPlus) S
    else if (hasPlus) S - 2 * A.min // plus only
    else S - 2 * abs(A.max) // minus only

    out.println(ans)
  }

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

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

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

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

object 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)
    var S = 0L
    if (N == 1) {
      out.println(A(0))
    } else {
      A find (_ <= 0) match {
        case Some(_) =>
          A foreach (a => S += abs(a))

        case None =>
          A foreach (a => S += a)
          S -= 2 * A.min
      }

      out.println(S)
    }
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

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

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


The Fair Nut found a string $$$s$$$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $$$p_1, p_2, \ldots, p_k$$$, such that:   For each $$$i$$$ ($$$1 \leq i \leq k$$$), $$$s_{p_i} =$$$ 'a'.  For each $$$i$$$ ($$$1 \leq i < k$$$), there is such $$$j$$$ that $$$p_i < j < p_{i + 1}$$$ and $$$s_j =$$$ 'b'. The Nut is upset because he doesn't know how to find the number. Help him.This number should be calculated modulo $$$10^9 + 7$$$.

The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 10^5$$$) consisting of lowercase Latin letters.

In a single line print the answer to the problem — the number of such sequences $$$p_1, p_2, \ldots, p_k$$$ modulo $$$10^9 + 7$$$.

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 S = ns()

    // aaの組み合わせ, 直前のbaの組み合わせ
    var pre = 0L
    var ans = 0L
    REP(S.length) { i =>
      S(i) match {
        case 'a' =>
          ans = (ans + pre + 1) % MOD

        case 'b' =>
          pre = ans

        case _ =>
      }
    }

    out.println(ans)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, 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 CF_526_2_C {

  def solve(s: String): Int = {

    val justAB = s.filter(c => c == 'a' || c == 'b').toList
    def answer(seq: List[Char], last: Char, lastVal: Long, total: Long): Int = seq match {
      case Nil => assert(total < Int.MaxValue); total.toInt
      case 'a' :: tail => last match {
        case 'b' =>
          val n = total + 1
          answer(tail, 'a', n, (total + n) % modulo)
        case 'a' => answer(tail, 'a', lastVal, (total + lastVal) % modulo)
      }
      case 'b' :: tail => answer(tail, 'b', lastVal, total)
    }
    answer(justAB, 'b', 0, 0)
  }

  // Specify Input and Output formats here:
  def formatIn(i: Input) = i.nextLine
  def formatOut(out: Int) = out.toString

//     ~~~ Boilerplate & utility methods that don't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  def main(args: Array[String]) = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  import java.util.Scanner

  import scala.util.matching.Regex
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def nextLine = sc.nextLine()
    // Remember to call nextLine to advance past the newline character (if required) before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
    def solveVals = (solve _).tupled(formatIn(this))
    def solveStr = formatOut(solveVals)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1
  val modulo = 1000000007

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }
}

object CF_526_2_C {

  def solve(s: String): Int = {
    def split(in: String, out: Seq[Seq[Long]], last: Long): Seq[Seq[Long]] = {
      def stringToPowers(str: String) = Seq.iterate(last, str.filter(_=='a').length)(x => (x*2) % modulo)
      in.indexOfSlice("aa") match {
        case -1 => out :+ stringToPowers(in)
        case i =>
          val (a,b) = in.splitAt(i+1)
          val seq = stringToPowers(a)
          split(b, out :+ seq, seq.last)
      }
    }
    val justAB = "a|b".r.findAllIn(s).mkString
    val longs = split(justAB, Vector.empty, 1)
    (longs.map(_.sum).sum % modulo).toInt
  }

  // Specify Input and Output formats here:
  def formatIn(i: Input) = i.nextLine
  def formatOut(out: Int) = out.toString

//     ~~~ Boilerplate & utility methods that don't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  def main(args: Array[String]) = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def nextLine = sc.nextLine()
    // Remember to call nextLine to advance past the newline character (if required) before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
    def solveVals = (solve _).tupled(formatIn(this))
    def solveStr = formatOut(solveVals)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1
  val modulo = 1000000007

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }
}


Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.

In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format.

NoteConsider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()

  val n = in.next().toInt
  val (f, s) = (1 to n).foldLeft((0, 0)) {
    case ((first, second), _) =>
      val Array(a, g, d) = in.next().split(' ').map(_.toInt)
      if (a == 1)
        (first + g - d, second)
      else
        (first, second + g - d)
  }
  if (f >= 0)
    println("LIVE")
  else
    println("DEAD")

  if (s >= 0)
    println("LIVE")
  else
    println("DEAD")
}

object Main extends App{
  val n = readInt()
  var live = new Array[Int](3)
  var die = new Array[Int](3)
  for (i <- 1 to n){
    var Array(which, nLive, nDie) = readLine().split(" ").map(_.toInt)
    if (which != 1) which = 2
    live(which) += nLive
    die(which) += nDie
  }
  for (i <- 1 to 2){
    if (live(i) >= die(i))
      println("LIVE")
    else
      println("DEAD")
  }
}

import scala.collection.mutable._

object Main extends App {
  val sc = new java.util.Scanner(System.in)

  val n = sc.nextInt()

  val ans = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt(), sc.nextInt()))
    .groupBy(_._1).mapValues { list =>
      list.reduce((a, b) => (a._1, a._2 + b._2, a._3 + b._3))
    }

  for (i <- 1 to 2) {
    val (a, x, y) = ans(i)
    println(if (x >= y) "LIVE" else "DEAD")
  }

}

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

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

  val N = sc.nextInt

  def solve(): List[String] = {
    val buf = List.fill(2)(new ListBuffer[Int])

    for (_ <- 0 until N) {
      val t, x, _ = sc.nextInt
      buf(t - 1) += x
    }

    buf.map { b =>
      val xs = b.toList
      if (xs.sum >= xs.size * 5) "LIVE"
      else "DEAD"
    }
  }

  solve.foreach { s => out.println(s) }
  out.close
}

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val map = scala.collection.mutable.Map[Int, (Int, Int)]()
    a.foreach{ a0 =>
      val e = map.getOrElse(a0(0), (0, 0))
      map(a0(0)) = (e._1 + a0(1), e._2 + a0(2))
    }
    val e1 = map(1)
    val e2 = map(2)
    if (e1._1 >= e1._2) println("LIVE") else println("DEAD")
    if (e2._1 >= e2._2) println("LIVE") else println("DEAD")
  }
}


Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form:  You are given two positive integers $$$u$$$ and $$$v$$$, find any pair of integers (not necessarily positive) $$$x$$$, $$$y$$$, such that: $$$$$$\frac{x}{u} + \frac{y}{v} = \frac{x + y}{u + v}.$$$$$$  The solution $$$x = 0$$$, $$$y = 0$$$ is forbidden, so you should find any solution with $$$(x, y) \neq (0, 0)$$$. Please help Ivan to solve some equations of this form.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq 10^9$$$) — the parameters of the equation.

For each test case print two integers $$$x$$$, $$$y$$$ — a possible solution to the equation. It should be satisfied that $$$-10^{18} \leq x, y \leq 10^{18}$$$ and $$$(x, y) \neq (0, 0)$$$. We can show that an answer always exists. If there are multiple possible solutions you can print any.

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 a.compareTo(that.a)
        }
    }

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

    val t = readInt()
    for (tt <- 1 to t) {
        var n = readLong()
        var k = readLong()
        n = -1L * n * n
        k = k * k
        writer.println(n + " " + k)

    }
    writer.flush()
}


Monocarp has forgotten the password to his mobile phone. The password consists of $$$4$$$ digits from $$$0$$$ to $$$9$$$ (note that it can start with the digit $$$0$$$).Monocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers some digits which were definitely not used in the password.You have to calculate the number of different sequences of $$$4$$$ digits that could be the password for Monocarp's mobile phone (i. e. these sequences should meet all constraints on Monocarp's password).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 8$$$) — the number of digits for which Monocarp remembers that they were not used in the password. The second line contains $$$n$$$ different integers $$$a_1, a_2, \dots a_n$$$ ($$$0 \le a_i \le 9$$$) representing the digits that were not used in the password. Note that the digits $$$a_1, a_2, \dots, a_n$$$ are given in ascending order.

For each testcase, print one integer — the number of different $$$4$$$-digit sequences that meet the constraints.

NoteIn the first example, all possible passwords are: "3377", "3737", "3773", "7337", "7373", "7733".

object _1743A extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val unused = io.nextN(io.nextInt()).toSet
    var ans = 0
    for {
      d1 <- 0 to 9 if !unused.contains(d1)
      d2 <- 0 to 9 if !unused.contains(d2) if d1 < d2
    } ans += 6
    io.printLine(ans)
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextBool(): Boolean = nextInt() == 1
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): this.type = { out.print(xs.mkString(" ")); this }
  def printLine(xs: Any*): this.type = { out.println(xs.mkString(" ")); this }
  def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }

  override def close() = out.close()
}


Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n). The answer to the query li, ri is the number of such integers i (li ≤ i < ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.

The first line contains string s of length n (2 ≤ n ≤ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≤ li < ri ≤ n).

Print m integers — the answers to the queries in the order in which they are given in the input.

import java.util.Scanner

object Sum {
  class Sum{
  def max(a:Char,b:Char):Char=
     if (a<b)
        a
    else
        b
  }
  def taskA(){
    val F=new Sum
      val in = new Scanner(System.in)
      val s=readLine()
      var ans = if(s(0)!='-') s else s.substring(0,s.length()-2)+F.max(s(s.length()-1),s(s.length()-2))
      if(ans(0)=='-' && ans(1)=='0'){
        print(0)
      }
      else
          print(ans)

  }
  def taskB(){
    val in = new Scanner(System.in)
    val s = in.nextLine()
    var arr=new Array[Int](s.length()+5)
    arr(0)=0
    for{i<-1 to s.length()-1}
        if (s(i)==s(i-1)){
          arr(i)=arr(i-1)+1
        }
        else
          arr(i)=arr(i-1)
    val k = in.nextInt()

    for{i<-1 to k}{
        val left=in.nextInt()-1
        val r=in.nextInt()
        var ans = arr(r-1)-arr(left)
        println(ans)
    }

  }
  def main(args: Array[String]) {
    taskB
  }
}

import java.util.Scanner

object Sum {
  class Sum{
  def max(a:Char,b:Char):Char=
     if (a<b)
        a
    else
        b
  }
  def taskA(){
    val F=new Sum
      val in = new Scanner(System.in)
      val s=readLine()
      var ans = if(s(0)!='-') s else s.substring(0,s.length()-2)+F.max(s(s.length()-1),s(s.length()-2))
      if(ans(0)=='-' && ans(1)=='0'){
        print(0)
      }
      else
          print(ans)

  }
  def taskB(){
    val in = new Scanner(System.in)
    val s = in.nextLine()
    var arr=new Array[Int](s.length()+5)
    arr(0)=0
    for{i<-1 to s.length()-1}
        if (s(i)==s(i-1)){
          arr(i)=arr(i-1)+1
        }
        else
          arr(i)=arr(i-1)
    val k = in.nextInt()

    for{i<-1 to k}{
        val left=in.nextInt()
        var l = if(left>1) left-1 else 0
        val r=in.nextInt()
        var ans = arr(r-1)-arr(l)
        println(ans)
    }

  }
  def main(args: Array[String]) {
    taskB
  }
}

import scala.math._

object Problem extends App {
  import Scanner._

  val s = readLine
  val count = Array.ofDim[Int](s.length)
  for(i <- 1 until s.length)
    count(i) = count(i-1) + (if(s(i) == s(i-1)) 1 else 0)

  for(i <- 1 to readInt; a = readInt-1; b = readInt-1)
    println(count(b) - count(a))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val table = str.sliding(2).map(t => t.charAt(0) == t.charAt(1)).scanRight(0) {
    case(true, b) => b + 1
    case(acc, b) => b
  }.toArray
  val n = in.next().toInt
  println(Range(0, n).map{ _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
    table(a) - table(b)
  }.mkString("\n"))
}

object Sample extends App {
  val scnr = new java.util.Scanner(System.in)
  val s = scnr.nextLine().sliding(2).scanLeft(0) {
    case (acc, pair) => acc + (if (pair(0) == pair(1)) 1 else 0)
  }.toArray

  val m = scnr.nextInt()

  1 to m foreach { _ =>
    val (l, r) = (scnr.nextInt(), scnr.nextInt())
    println(s(r - 1) - s(l - 1))
  }
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  val S = sc.nextLine.toArray
  val dp = Array.fill(S.length)(0)
  var pre = S(0)
  1 until S.length foreach { i =>
    if (S(i) == pre) {
      dp(i) = dp(i - 1) + 1
    }
    else {
      pre = S(i)
      dp(i) = dp(i - 1)
    }
  }

  val N = sc.nextInt
  def solve(l: Int, r: Int): Int = {
    dp(r) - dp(l)
  }

  for (_ <- 0 until N) out.println(solve(sc.nextInt - 1, sc.nextInt - 1))

  out.close
}

/**
 * <a href="http://codeforces.com/problemset/problem/313/B"/>
 *
 * @author pvasilyev
 * @since 10 Apr 2016
 */
object Problem149 extends App {

  def solve(line: String): Array[Int] = {
    val intArray: Array[Int] = new Array[Int](line.length())
    intArray(0) = 0
    for (i <- 1 until line.length()) {
      if (line.charAt(i - 1) == line.charAt(i)) {
        intArray(i) = intArray(i - 1) + 1
      } else {
        intArray(i) = intArray(i - 1)
      }
    }
    intArray
  }

  val lines = scala.io.Source.stdin.getLines()
  val line = lines.next()
  val arr: Array[Int] = solve(line)
  val n = lines.next().toInt
  val builder: StringBuilder = StringBuilder.newBuilder
  for (i <- 0 until n) {
    val Array(p, q) = lines.next().split(" ").map(_.toInt - 1)
    builder.append(arr(q) - arr(p)).append("\n")
  }
  print(builder.toString())
  //  val in = scala.io.Source.stdin.getLines()
  //  val str = in.next()
  //  val table = str.sliding(2).map(t => t.charAt(0) == t.charAt(1)).scanRight(0) {
  //    case (true, b) => b + 1
  //    case (acc, b) => b
  //  }.toArray
  //  val n = in.next().toInt
  //  println(Range(0, n).map { _ =>
  //    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
  //    table(a) - table(b)
  //  }.mkString("\n"))
}

/**
 * <a href="http://codeforces.com/problemset/problem/313/B"/>
 *
 * @author pvasilyev
 * @since 10 Apr 2016
 */
object Problem149 extends App {

  //  def solve(line: String): Array[Int] = {
  //    val intArray: Array[Int] = new Array[Int](line.length())
  //    intArray(0) = 0
  //    for (i <- 1 until line.length()) {
  //       if (line.charAt(i - 1) == line.charAt(i)) {
  //         intArray(i) = intArray(i - 1) + 1
  //       } else {
  //         intArray(i) = intArray(i - 1)
  //       }
  //    }
  //    intArray
  //  }
  //
  //  val lines = scala.io.Source.stdin.getLines()
  //  val line = lines.next()
  //  val arr: Array[Int] = solve(line)
  //  val n = lines.next().toInt
  //  for (i <- 0 until n) {
  //    val Array(p, q) = lines.next().split(" ").map(_.toInt)
  //    println(arr(q-1) - arr(p-1))
  //  }
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val table = str.sliding(2).map(t => t.charAt(0) == t.charAt(1)).scanRight(0) {
    case (true, b) => b + 1
    case (acc, b) => b
  }.toArray
  val n = in.next().toInt
  println(Range(0, n).map { _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
    table(a) - table(b)
  }.mkString("\n"))
}

object CF186Div2B {
   def main(args:Array[String]){
     val chars = readLine().toList
     val qlist = 0 +: ((chars zip chars.tail).map{case (a,b) => if (a==b) 1 else 0 }.foldLeft((Vector[Int](),0)){ case ((xs,sum),x) => (xs :+ (sum+x),sum+x)}._1);
     val q = readLine().toInt
     for(i <- 1 to q){
       val Array(a,b) = readLine.split(" ").map(_.toInt)
       println(qlist(b-1)-qlist(a-1))
     }
   }
 }


You are given an integer $$$n$$$. You have to construct a permutation of size $$$n$$$.A permutation is an array where each integer from $$$1$$$ to $$$s$$$ (where $$$s$$$ is the size of permutation) occurs exactly once. For example, $$$[2, 1, 4, 3]$$$ is a permutation of size $$$4$$$; $$$[1, 2, 4, 5, 3]$$$ is a permutation of size $$$5$$$; $$$[1, 4, 3]$$$ is not a permutation (the integer $$$2$$$ is absent), $$$[2, 1, 3, 1]$$$ is not a permutation (the integer $$$1$$$ appears twice).A subsegment of a permutation is a contiguous subsequence of that permutation. For example, the permutation $$$[2, 1, 4, 3]$$$ has $$$10$$$ subsegments: $$$[2]$$$, $$$[2, 1]$$$, $$$[2, 1, 4]$$$, $$$[2, 1, 4, 3]$$$, $$$[1]$$$, $$$[1, 4]$$$, $$$[1, 4, 3]$$$, $$$[4]$$$, $$$[4, 3]$$$ and $$$[3]$$$.The value of the permutation is the number of its subsegments which are also permutations. For example, the value of $$$[2, 1, 4, 3]$$$ is $$$3$$$ since the subsegments $$$[2, 1]$$$, $$$[1]$$$ and $$$[2, 1, 4, 3]$$$ are permutations.You have to construct a permutation of size $$$n$$$ with minimum possible value among all permutations of size $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 48$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th of them contains one integer $$$n$$$ ($$$3 \le n \le 50$$$) representing the $$$i$$$-th test case.

For each test case, print $$$n$$$ integers — the permutation of size $$$n$$$ with minimum possible value. If there are multiple such permutations, print any of them.

NoteIn the first example, the permutation $$$[1, 4, 3, 5, 2]$$$ is one of the possible answers; its value is $$$2$$$.In the second example, the permutation $$$[4, 1, 6, 2, 5, 3]$$$ is one of the possible answers; its value is $$$2$$$.

object _1743B extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val n = io.nextInt()
    val ans = Array.ofDim[Int](n)
    ans(0) = 1
    ans(n-1) = 2
    (1 until n-1).foreach(i => ans(i) = i+2)
    io.printLine(ans: _*)
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextBool(): Boolean = nextInt() == 1
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): this.type = { out.print(xs.mkString(" ")); this }
  def printLine(xs: Any*): this.type = { out.println(xs.mkString(" ")); this }
  def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }

  override def close() = out.close()
}