import collection.mutable

object A {
	def main(args: Array[String]) {
		val n = readLine().toInt
    val a = readLine().split(" ").map(x => x.toInt)
    val b = new mutable.HashMap[Int, Int]
    for (x <- a) {
      if (!b.contains(x))
        b(x) = 0
      b(x) += 1
    }
    var good = true
    var ans = 0
    for (x <- b.keySet if x > 0) {
      if (b(x) > 2)
        good = false
      if (b(x) == 2)
        ans += 1
    }
    if (good)
      println(ans)
    else
      println(-1)
	}
}

object A {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);
  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ;
    var b = a.distinct.filter(_>0) map (x => a.count(_==x));
    if (b exists(_>2)) println(-1)
    else println(b count(_==2))
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(id => if (id != 0) map(id) = map.getOrElse(id, 0) + 1)
    val r = map.values.foldLeft(0) { (acc, count) =>
      if (count == 2 && acc != -1) acc + 1
      else if (count > 2) -1
      else acc
    }
    println(r)
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readInt()

    val arr = StdIn.readLine.split(" ").map(_.toInt)

    val map = arr.foldLeft(Map[Int, Int]())(foldArr) - 0

    val ans = map.find({case (_, value) => value > 2}) match {
      case None => map.foldLeft(0)({(m: Int, x: (Int, Int)) => m + x._2 - 1})
      case Some(_) => -1
    }

    println(ans)
  }

  def foldArr(map: Map[Int, Int], x: Int): Map[Int, Int] = map.updated(x, map.getOrElse(x, 0) + 1)
}

import collection.mutable

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def main (args: Array[String]) {
    val n = readLine().toInt
    val a = readLine().split(" ").map(x => x.toInt)
    val b = new mutable.HashMap[Int, Int]
    for (x <- a) {
      if (!b.contains(x))
        b(x) = 0
      b(x) += 1
    }
    var good = true
    var ans = 0
    for (x <- b.keySet if x > 0) {
      if (b(x) > 2)
        good = false
      if (b(x) == 2)
        ans += 1
    }
    if (good)
      println(ans)
    else
      println(-1)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).filter(_ != 0)
  val enhanced = data.groupBy(x => x).map(x => x._1 -> x._2.length)
  if (enhanced.exists(_._2 > 2))
    println(-1)
  else
    println(enhanced.count(_._2 == 2))
}

/*
A. Разговоры в Spyke
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Поликарп — директор большой корпорации. В этой корпорации работает n секретарей, каждый из которых пользуется известной VoIP-системой Spyke для ведения переговоров в течение рабочего дня. Известно, что, когда два человека устанавливают телефонное соединение Spyke, сеть Spyke присваивает этому разговору уникальный идентификационный номер (целое положительное число) — номер сессии.

Как-то раз Поликарп захотел узнать, кто из секретарей разговаривает по Spyke, а кто — нет. Он выписал для каждого секретаря номер сессии его разговора, или 0, если этот секретарь сейчас не разговаривает по Spyke.

Помогите Поликарпу по этим данным определить, сколько пар секретарей сейчас ведут разговор между собой. Если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти, требуется сообщить об этом.

Обратите внимание, секретари могут разговаривать по Spyke не только друг с другом — возможны разговоры с внешними собеседниками. Также не разрешены конференции Spyke — то есть в каждом разговоре должны участвовать ровно два собеседника.
Входные данные

В первой строке записано целое число n (1 ≤ n ≤ 103) — количество секретарей в корпорации Поликарпа. В следующей строке записаны n целых чисел через пробел: id1, id2, ..., idn (0 ≤ idi ≤ 109). Число idi равно номеру сессии разговора секретаря номер i, если он разговаривает в данный момент по Spyke, или равно нулю, в противном случае.

Считайте, что секретари пронумерованы от 1 до n некоторым образом.
Выходные данные

Выведите единственное целое число — количество пар секретарей, которые ведут разговор между собой, или -1, если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти.
Примеры тестов
Входные данные

6
0 1 7 1 7 10

Выходные данные

2

Входные данные

3
1 1 1

Выходные данные

-1

Входные данные

1
0

Выходные данные

0

Примечание

В первом тестовом примере есть два телефонных разговора между секретарями: секретарь номер 2 и секретарь номер 4, секретарь номер 3 и секретарь номер 5.

Во втором тестовом примере описанная ситуация невозможна, так как не разрешены конференции.

 */
object Task1 extends App {

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(n: Int, ids: IndexedSeq[Long]): Int =
    if (ids.size != n) -1
    else {
      val grouped = ids groupBy (x => x)
      val counts = ((grouped - 0).values map (_.length) toIndexedSeq)
      val dist = counts filterNot (_ < 2)
      if (dist exists (_ > 2)) -1 else dist.size
    }

  val (line1, line2) = (readLine, readLine)
  val n = line1.toInt
  val ids = line2 split (' ') map (_.toLong)

  val res = solve(n, ids)
  println(res)
}

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

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

  val N = sc.nextInt
  val gs = List.fill(N)(sc.nextInt).filterNot(_ == 0).groupBy(identity[Int]).map(_._2.length)

  val answer: Int = {
    gs.find(_ > 2) match {
      case Some(_) => -1
      case None => gs.filter(_ == 2).size
    }
  }

  out.println(answer)
  out.close
}

import io.Source
import java.io.PrintWriter

object CF291A {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val a = in(n).map(_.toInt).filter(_ != 0).toSeq
    val sizes = a.groupBy(identity).toSeq.map(_._2.size)
    if (sizes.exists(_ > 2)) {
      out.println(-1)
    } else {
      out.println(sizes.count(_ == 2))
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val enhanced = data.groupBy(x => x).map(x => x._1 -> x._2.length)
  if (enhanced.exists(_._2 > 2))
    println(-1)
  else
    println(enhanced.count(_._2 == 2))
}

/*
A. Разговоры в Spyke
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Поликарп — директор большой корпорации. В этой корпорации работает n секретарей, каждый из которых пользуется известной VoIP-системой Spyke для ведения переговоров в течение рабочего дня. Известно, что, когда два человека устанавливают телефонное соединение Spyke, сеть Spyke присваивает этому разговору уникальный идентификационный номер (целое положительное число) — номер сессии.

Как-то раз Поликарп захотел узнать, кто из секретарей разговаривает по Spyke, а кто — нет. Он выписал для каждого секретаря номер сессии его разговора, или 0, если этот секретарь сейчас не разговаривает по Spyke.

Помогите Поликарпу по этим данным определить, сколько пар секретарей сейчас ведут разговор между собой. Если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти, требуется сообщить об этом.

Обратите внимание, секретари могут разговаривать по Spyke не только друг с другом — возможны разговоры с внешними собеседниками. Также не разрешены конференции Spyke — то есть в каждом разговоре должны участвовать ровно два собеседника.
Входные данные

В первой строке записано целое число n (1 ≤ n ≤ 103) — количество секретарей в корпорации Поликарпа. В следующей строке записаны n целых чисел через пробел: id1, id2, ..., idn (0 ≤ idi ≤ 109). Число idi равно номеру сессии разговора секретаря номер i, если он разговаривает в данный момент по Spyke, или равно нулю, в противном случае.

Считайте, что секретари пронумерованы от 1 до n некоторым образом.
Выходные данные

Выведите единственное целое число — количество пар секретарей, которые ведут разговор между собой, или -1, если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти.
Примеры тестов
Входные данные

6
0 1 7 1 7 10

Выходные данные

2

Входные данные

3
1 1 1

Выходные данные

-1

Входные данные

1
0

Выходные данные

0

Примечание

В первом тестовом примере есть два телефонных разговора между секретарями: секретарь номер 2 и секретарь номер 4, секретарь номер 3 и секретарь номер 5.

Во втором тестовом примере описанная ситуация невозможна, так как не разрешены конференции.

 */
object Task1 extends App {

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(n: Int, ids: IndexedSeq[Int]): Int = {
    val grouped = ids groupBy (x => x)
    val counts = (grouped.values map (_.length) toIndexedSeq)
    val dist = counts filterNot (_ == 1)
    if (dist exists (_ > 2)) -1 else dist.size
  }

  val (line1, line2) = (readLine, readLine)
  val n = line1.toInt
  val ids = line2 split (' ') map (_.toInt)

  val res = solve(n, ids)
  println(res)
}

/*
A. Разговоры в Spyke
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Поликарп — директор большой корпорации. В этой корпорации работает n секретарей, каждый из которых пользуется известной VoIP-системой Spyke для ведения переговоров в течение рабочего дня. Известно, что, когда два человека устанавливают телефонное соединение Spyke, сеть Spyke присваивает этому разговору уникальный идентификационный номер (целое положительное число) — номер сессии.

Как-то раз Поликарп захотел узнать, кто из секретарей разговаривает по Spyke, а кто — нет. Он выписал для каждого секретаря номер сессии его разговора, или 0, если этот секретарь сейчас не разговаривает по Spyke.

Помогите Поликарпу по этим данным определить, сколько пар секретарей сейчас ведут разговор между собой. Если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти, требуется сообщить об этом.

Обратите внимание, секретари могут разговаривать по Spyke не только друг с другом — возможны разговоры с внешними собеседниками. Также не разрешены конференции Spyke — то есть в каждом разговоре должны участвовать ровно два собеседника.
Входные данные

В первой строке записано целое число n (1 ≤ n ≤ 103) — количество секретарей в корпорации Поликарпа. В следующей строке записаны n целых чисел через пробел: id1, id2, ..., idn (0 ≤ idi ≤ 109). Число idi равно номеру сессии разговора секретаря номер i, если он разговаривает в данный момент по Spyke, или равно нулю, в противном случае.

Считайте, что секретари пронумерованы от 1 до n некоторым образом.
Выходные данные

Выведите единственное целое число — количество пар секретарей, которые ведут разговор между собой, или -1, если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти.
Примеры тестов
Входные данные

6
0 1 7 1 7 10

Выходные данные

2

Входные данные

3
1 1 1

Выходные данные

-1

Входные данные

1
0

Выходные данные

0

Примечание

В первом тестовом примере есть два телефонных разговора между секретарями: секретарь номер 2 и секретарь номер 4, секретарь номер 3 и секретарь номер 5.

Во втором тестовом примере описанная ситуация невозможна, так как не разрешены конференции.

 */
object Task1 extends App {

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(n: Int, ids: IndexedSeq[Long]): Int = {
    val grouped = ids groupBy (x => x)
    val counts = (grouped.values map (_.length) toIndexedSeq)
    val dist = counts filterNot (_ < 2)
    if (dist exists (_ > 2)) -1 else dist.size
  }

  val (line1, line2) = (readLine, readLine)
  val n = line1.toInt
  val ids = line2 split (' ') map (_.toLong)

  val res = solve(n, ids)
  println(res)
}

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

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

  val N = sc.nextInt
  val gs = List.fill(N)(sc.nextInt).groupBy(identity[Int]).map(_._2.length)

  val answer: Int = {
    gs.find(_ > 2) match {
      case Some(_) => -1
      case None => gs.filter(_ == 2).size
    }
  }

  out.println(answer)
  out.close
}

import io.Source
import java.io.PrintWriter

object CF291A {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val a = in(n).map(_.toInt).toSeq
    val sizes = a.groupBy(identity).toSeq.map(_._2.size)
    if (sizes.exists(_ > 2)) {
      out.println(-1)
    } else {
      out.println(sizes.count(_ == 2))
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

import io.Source
import java.io.PrintWriter

object CF291A {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val a = in(n).filter(_ != 0).map(_.toInt).toSeq
    val sizes = a.groupBy(identity).toSeq.map(_._2.size)
    if (sizes.exists(_ > 2)) {
      out.println(-1)
    } else {
      out.println(sizes.count(_ == 2))
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

object A {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);
  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ;
    var b = a.distinct map (x => a.count(_==x));
    if (b exists(_>2)) println(-1)
    else println(b count(_==2))
  }
}

object A {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);
  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ;
    var b = a.distinct.map(_>0) map (x => a.count(_==x));
    if (b exists(_>2)) println(-1)
    else println(b count(_==2))
  }
}


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

    REP(ni()) { _ =>
      val a = ni()

      val all1 = Integer.highestOneBit(a) - 1 + Integer.highestOneBit(a)
      // 全部ビットたっているかどうか
      val ans = if (all1 == a) {
        // 全部ビットたっていたら gcd(a^b, a&b) == gcd(b, ~b)
        // b + ~b == a == (n + m) * c
        // n + m >= 2でcを最大化なので、すなわち２番目に大きいdevisorといっしょ
        val d = divisors(a)
        d(d.length - 2)
      } else {
        // 0のビットがあるのでa&b==0 のbをつくることができる
        // 一番左は0になりえないので、b = ~a のとき b^a == 2^n - 1 で最大にできる
        all1
      }
      out.println(ans)
    }
  }

  /**
    * O(√x)
    */
  def divisors(x: Int): Array[Int] = {
    val pre = ArrayBuffer[Int]()
    val post = ArrayBuffer[Int]()
    REP(math.sqrt(x).toInt, 1) { d =>
      if (x % d == 0) {
        pre += d
        if (d * d != x) post += x / d
      }
    }

    val res = Array.ofDim[Int](pre.length + post.length)
    REP(pre.length)(i => res(i) = pre(i))
    val preLen = pre.length
    val postLen = post.length
    REP(postLen)(i => res(i + preLen) = post(postLen - 1 - i))
    res
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object C extends App {

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

  val Array(q) = readInts(1)

  def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  for (_ <- 1 to q) {
    val a = readLine.toInt
    val mask = Integer.highestOneBit(a) * 2 - 1
    val b = a ^ mask
    val res = if (b == 0) 1 else gcd(a ^ b, a & b)
    println(res)
  }
}


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

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

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)

}

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


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

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


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


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

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

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

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

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


//package codeforces.contests._1353

object BoardMoves {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readLong / 2

      println {
        (n * (n + 1) * (2 * n + 1) * 8) / 6
      }
    }
  }
}

import scala.io.StdIn.readLine

object C {

  def solution(n: Int): Long = {
    val k: Long = (n - 1) / 2
    k * (k + 1) * (2 * k + 1) / 6 * 8
  }

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

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
	def main(args: Array[String]): Unit = {
		try {
			val (in, out) =
				if (isOnlineJudge) {
					(
						new FastScanner(new InputStreamReader(System.in)),
						new PrintWriter(System.out)
					)
				} else {
					(
						new FastScanner(new FileReader(new File("problem.in"))),
						new PrintWriter(new File("problem.out"))
					)
				}
			new CF644(in, out).solve()
			out.flush()
			out.close()
		} catch {
			case e: IOException => e.printStackTrace()
		}
	}

	private[this] val isOnlineJudge = true
	class FastScanner(val streamReader: InputStreamReader) {
		private[this] val reader = new BufferedReader(streamReader, 32768)
		private[this] var tokenizer: StringTokenizer = _

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

		def nextInt(): Int = Integer.parseInt(next())

		def nextLong(): Long = java.lang.Long.parseLong(next())

		def nextChar(): Char = next().charAt(0)

		def ni(): Int = nextInt()

		def nl(): Long = nextLong()

		def nc(): Char = nextChar()

		def ns(): String = next()

		def ns(n: Int): Array[Char] = ns().toCharArray

		def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

		def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
			val A1, A2 = Array.ofDim[Int](n)
			REP(n) { i =>
				A1(i) = ni() + offset
				A2(i) = ni() + offset
			}
			(A1, A2)
		}

		def nm(n: Int, m: Int): Array[Array[Int]] = {
			val A = Array.ofDim[Int](n, m)
			REP(n) { i =>
				REP(m) { j =>
					A(i)(j) = ni()
				}
			}
			A
		}

		def nal(n: Int): Array[Long] = map(n)(_ => nl())

		def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
	}

	def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
		var i = offset
		val N = n + offset
		while (i < N) {
			f(i);
			i += 1
		}
	}

	def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
		var i = n - 1 + offset
		while (i >= offset) {
			f(i);
			i -= 1
		}
	}

	def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
		REP(to - from + 1, from)(f)
	}

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

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

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

class CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {

	import Main._
	import fScanner._

	// def solve(): Unit = {
	// 	val T = ni()
	// 	for(i <- 0 until T){
	// 	var ans : Int = 1000
	// 		val n = ni()
	// 		var list: List[Int] = List()
	// 		for(j <- 0 until n){
	// 			val cu:Int = ni()
	// 			for( x <- list)
	// 				ans = ans.min( ( cu - x ).max(x - cu) )
	// 			list = cu::	list
	// 		}
	// 		out.println(ans)
	// 	}
	// }

	def solve(): Unit ={
		val T = ni()
		for(i <- 0 until T){
			val n:Long = nl()
			val lm:Long = n-1
			var ans:Long = (n/2)*(n)*(n)
			for(j:Long <- 1.toLong until lm){
				if(j%2 == 1) ans = ans - (j*j)

			}
			println(ans)
		}
	}
}

object C extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readInt()

    val ans = 1.to(n, 2).foldLeft(0L)((s, i) => s + i / 2L * (4L + 4L * (i - 2L)))

    println(ans)
  }
}

object ProblemC extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  import scala.collection.mutable
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()

  val resultArr = new Array[BigInt](500000)
  resultArr(1) = 0
  for (i <- 3 until resultArr.length) {
    if (i % 2 == 1) {
      resultArr(i) = resultArr(i - 2) + (i * 2 + (i - 2) * 2).toLong * (i / 2)
    }
  }

  for (_ <- 1 to t) {
    println(resultArr(in.nextInt()))
  }

}

object ProblemC extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  import scala.collection.mutable
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()

  val resultArr = new Array[Long](500000)
  resultArr(1) = 0
  for (i <- 3 until resultArr.length) {
    if (i % 2 == 1) {
      resultArr(i) = resultArr(i - 2) + (i * 2 + (i - 2) * 2) * (i / 2)
    }
  }

  for (_ <- 1 to t) {
    println(resultArr(in.nextInt()))
  }

}