Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.

The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence.  The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105).

Print a single integer — the maximum number of points that Alex can earn.

NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.

import scala.math._

object Problem extends App {
  import Scanner._

  val n = readInt
  val seq = Array.fill(n)(readInt)
  val (min, max) = (seq.min, seq.max)

  val counts = Array.ofDim[Int](max - min + 1)
  for(v <- seq)
    counts(v-min) += 1

  val dp: Memo[Int, Long] = Memo {
    case `min` => min.toLong*counts(0)
    case v if v < min => 0L
    case v => math.max(dp(v-1), dp(v-2) + v.toLong*counts(v-min))
  }

  println(dp(max))
}

case class Memo[A, B](f: A => B) extends (A => B) {
  private val cache = scala.collection.mutable.Map.empty[A, B]
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

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

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

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

      c = readChar
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val max = data.max
  val count = Array.ofDim[Long](max + 1)
  data.foreach { num => count(num) += 1 }
  if (count.length == 2)
    println(count(1))
  else {
    var a: Long = count(1)
    var b: Long = Math.max(a, count(2) * 2)
    var i = 3

    while (i <= max) {
      val max = Math.max(b, a + count(i) * i)
      a = b
      b = max
      i += 1
    }
    println(b)
  }
}

import scala.collection.mutable
import scala.util.Try

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val counts = Array.fill[Int](5*100000 + 1)(0)
    val dp = Array.fill[Long](5*100000 + 1)(0L)
    input.foreach(x => counts(x) += 1)
    var i = 3
    dp(1) = counts(1)
    dp(2) = counts(2)*2
    while(i < 5*100000+1) {
      dp(i) = i.toLong*counts(i) + math.max(dp(i-2), Try{dp(i-3)}.getOrElse(0L))
      i += 1
    }

    println(dp.max)
  }

}

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

object C {

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

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val num = new Array[Long](100005)
    for (i <- 0 until n) {
      a(i) = nextInt
      num(a(i)) += 1
    }
    val dp = new Array[Long](100005)
    Arrays.fill(dp, 0L)
    dp(1) = num(1)
    var i = 2
    while (i <= 100002) {
      dp(i) = Math.max(dp(i - 1), dp(i - 2) + num(i) * i.toLong)
      i += 1
    }
    out.println(dp(100002))
    return 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 {
  val cin = scala.io.Source.stdin.bufferedReader()
  def readInt(): Int = {
    var res = 0
    var c = cin.read()
    while (!Character.isDigit(c)) {
      c = cin.read()
    }
    do {
      res = res * 10 + c - '0'
      c = cin.read()
    } while (Character.isDigit(c))
    res
  }
  def main(args: Array[String]) = {
    val n = readInt()
    val cnt: Array[Int] = Array.ofDim(100001)
    val memo: Array[Long] = Array.ofDim(3)
    for (i <- 1 to n)
      cnt(readInt()) += 1
    for (i <- 1 to 100000)
      memo(i % 3) = Math.max(memo((i + 1) % 3) + i.toLong * cnt(i), memo((i + 2) % 3))
    println(memo(1))
  }
}

object Main {
  val cin = scala.io.Source.stdin.getLines()
  def main(args: Array[String]) = {
    val n = cin.next()
    val data = cin.next().split(" ").map(_.toInt)
    val cnt: Array[Int] = Array.ofDim(100001)
    data.foreach(x => cnt(x) += 1)
    val memo: Array[Long] = Array.ofDim(3)
    for (i <- 1 to 100000)
      memo(i % 3) = Math.max(memo((i + 1) % 3) + i.toLong * cnt(i), memo((i + 2) % 3))
    println(memo(1))
  }
}

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

import math.max

object Boredom455A {

  def main(args : Array[String]) : Unit = {
    val n = readInt
    val freq = Array.ofDim[Long](100001)
    val maxScore = Array.ofDim[Long](100001)
    val as = readLine().split(" ")
    for (i <- 0 until n) {
      val a = as(i).toInt
      freq(a) += 1
    }
    maxScore(0) = 0
    maxScore(1) = freq(1)
    for (i <- 2 to 100000) {
      maxScore(i) = max(maxScore(i-1), maxScore(i-2) + i.toLong * freq(i))
    }
    println(maxScore(100000))
  }

}

import scala.io.StdIn._

object Main2 extends App {
  readInt()
  val digits = readLine().split(" ").map(_.toLong)
  val ans = digits
    .groupBy(identity)
    .mapValues(_.sum)
    .toSeq
    .sorted.foldLeft[(Long, Long, Long)]((0, 0, 0)) {
      case ((answerIfTakeLast, answerIfNotTakeLast, previousKey), (currentKey, sum)) =>
        val ansIfTakeLast = Math.max(answerIfNotTakeLast + sum, if (currentKey - previousKey == 1) 0 else answerIfTakeLast + sum)
        val ansIfNotTakeLast = Math.max(answerIfTakeLast, answerIfNotTakeLast)
        (ansIfTakeLast, ansIfNotTakeLast, currentKey)
    }

  println(Math.max(ans._1, ans._2))
}

object TEST extends App {
  var a = Array.fill(100001)(0)
  var dp:Array[Long] = Array.fill(100001)(0)
  val n = readInt
  readLine.split(" ").map(_.toInt).foreach(x => a(x)+=1)
  dp(1) = a(1)
  (2 to 100000).foreach(i => dp(i)=math.max(dp(i-1),i.toLong*a(i)+dp(i-2)))
  print(dp(100000))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100001
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(N + 5)(0L)
  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }

  dp(1) = as(1)
  2 to N foreach { i =>
    dp(i) = max(dp(i - 1), dp(i - 2) + i * as(i))
  }

  println(dp(N))
}

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

/**
 * Created by arseny on 08.08.14.
 */
object C extends App {

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt
    val as = Array.fill(n)(0L)
    (0 until n).foreach(i => as(i) = nextLong)
    val count = Array.fill(100 * 1000 + 1)(0L)
    as.foreach(a => count(a.toInt) += 1L)
    val dp = Array.fill(100 * 1000 + 1)(0L)
    dp(1) = count(1)
    (2 to 100 * 1000).foreach(i => dp(i) = math.max(i.toLong * count(i) + dp(i - 2), dp(i - 1)))
    out.println(dp.max)
  }

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

}

import scala.math._

object Problem extends App {
  import Scanner._

  val n = readInt
  val seq = Array.fill(n)(readInt)
  val (min, max) = (seq.min, seq.max)

  val counts = Array.ofDim[Int](max - min + 1)
  for(v <- seq)
    counts(v-min) += 1

  val dp: Memo[Int, Int] = Memo {
    case `min` => counts(0)
    case v if v < min => 0
    case v => math.max(dp(v-1), dp(v-2) + v*counts(v-min))
  }

  println(dp(max))
}

case class Memo[A, B](f: A => B) extends (A => B) {
  private val cache = scala.collection.mutable.Map.empty[A, B]
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

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

import scala.math._

object Problem extends App {
  import Scanner._

  val n = readInt
  val seq = Array.fill(n)(readInt)
  val (min, max) = (seq.min, seq.max)

  val counts = Array.ofDim[Int](max - min + 1)
  for(v <- seq)
    counts(v-min) += 1

  val dp: Memo[Int, Int] = Memo {
    case `min` => min*counts(0)
    case v if v < min => 0
    case v => math.max(dp(v-1), dp(v-2) + v*counts(v-min))
  }

  println(dp(max))
}

case class Memo[A, B](f: A => B) extends (A => B) {
  private val cache = scala.collection.mutable.Map.empty[A, B]
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

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

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

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

      c = readChar
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val max = data.max
  val count = Array.ofDim[Int](max + 1)
  data.foreach { num => count(num) += 1 }
  if (n == 1)
    println(data(0))
  else {
    var a = count(1)
    var b = Math.max(a, count(2) * 2)
    var i = 3

    while (i <= max) {
      val max = Math.max(b, a + count(i) * i)
      a = b
      b = max
      i += 1
    }
    println(b)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  if (n == 1)
    println(data(0))
  else {
    var a = data(0)
    var b = Math.max(a, data(1))
    var i = 2
    while (i < n) {
      val max = Math.max(b, a + data(i))
      a = b
      b = max
      i += 1
    }
    println(b)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val max = data.max
  val count = Array.ofDim[Int](max + 1)
  data.foreach { num => count(num) += 1 }
  if (n == 1)
    println(data(0))
  else {
    var a: Long = count(1)
    var b: Long = Math.max(a, count(2) * 2)
    var i = 3

    while (i <= max) {
      val max = Math.max(b, a + count(i) * i)
      a = b
      b = max
      i += 1
    }
    println(b)
  }
}

import scala.collection.mutable

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val counts = Array.fill[Int](5*100000 + 1)(0)
    val dp = Array.fill[Long](5*100000 + 1)(0L)
    input.foreach(x => counts(x) += 1)
    var i = 3
    dp(1) = counts(1)
    dp(2) = counts(2)*2
    while(i < 5*100000+1) {
      dp(i) = i*counts(i) + dp(i-2)
      i += 1
    }

    println(dp.max)
  }

}

import scala.collection.mutable
import scala.util.Try

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val counts = Array.fill[Int](5*100000 + 1)(0)
    val dp = Array.fill[Long](5*100000 + 1)(0L)
    input.foreach(x => counts(x) += 1)
    var i = 3
    dp(1) = counts(1)
    dp(2) = counts(2)*2
    while(i < 5*100000+1) {
      dp(i) = i*counts(i) + math.max(dp(i-2), Try{dp(i-3)}.getOrElse(0L))
      i += 1
    }

    println(dp.max)
  }

}

object Main {
  val cin = scala.io.Source.stdin.bufferedReader()
  def readInt(): Int = {
    var res = 0
    var c = cin.read()
    while (!Character.isDigit(c)) {
      c = cin.read()
    }
    do {
      res = res * 10 + c - '0'
      c = cin.read()
    } while (Character.isDigit(c))
    res
  }
  def main(args: Array[String]) = {
    val n = readInt()
    val cnt: Array[Int] = Array.ofDim(100001)
    val memo: Array[Long] = Array.ofDim(3)
    for (i <- 1 to n)
      cnt(readInt()) += 1
    for (i <- 1 to 100000)
      memo(i % 3) = Math.max(memo((i + 1) % 3) + 1l * i * cnt(i), memo((i + 2) % 3))
    println(memo(2))
  }
}

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

import math.max

object Boredom455A {

  def main(args : Array[String]) : Unit = {
    val n = readInt
    val freq = Array.ofDim[Int](100001)
    val maxScore = Array.ofDim[Long](100001)
    val as = readLine().split(" ")
    for (i <- 0 until n) {
      val a = as(i).toInt
      freq(a) += 1
    }
    maxScore(0) = 0
    maxScore(1) = freq(1)
    for (i <- 2 to 100000) {
      maxScore(i) = max(maxScore(i-1), maxScore(i-2) + i*freq(i))
    }
    println(maxScore(100000))
  }

}

import scala.io.StdIn._

object Main2 extends App {
  readInt()
  val digits = readLine().split(" ").map(_.toLong)
  val ans = digits
    .groupBy(identity)
    .mapValues(_.sum)
    .toSeq
    .sorted.foldLeft[(Long, Long, Long)]((0, 0, 0)) {
      case ((answerIfTakeLast, answerIfNotTakeLast, previousKey), (currentKey, sum)) =>
        val ansIfTakeLast = if (currentKey - previousKey == 1) answerIfNotTakeLast else answerIfTakeLast + sum
        val ansIfNotTakeLast = answerIfTakeLast + sum
        (ansIfTakeLast, ansIfNotTakeLast, currentKey)
    }

  println(Math.max(ans._1, ans._2))
}

object TEST extends App {
  var a = Array.fill(100001)(0)
  var dp:Array[Long] = Array.fill(100001)(0)
  val n = readInt
  readLine.split(" ").map(_.toInt).foreach(x => a(x)+=1)
  dp(1) = a(1)
  (2 to 100000).foreach(i => dp(i)=math.max(dp(i-1),i*a(i)+dp(i-2)))
  print(dp(100000))
}

import java.util.Scanner

object TEST extends App {
  var a = Array.fill(100001)(0)
  var dp = Array.fill(100001)(0)
  val n = readInt
  readLine.split(" ").map(_.toInt).foreach(x => a(x)+=1)
  dp(1) = a(1)
  (2 to 100000).foreach(i => dp(i)=math.max(dp(i-1),i*a(i)+dp(i-2)))
  print(dp(100000))
}

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

import scala.collection.mutable
import scala.language.postfixOps

object TaskA extends App {
  val ir = new InputReader(System.in)
  val n = ir.nextInt

  val map = mutable.HashMap.empty[Int, Int]
  var ans = 0
  var total = 0

  implicit val ordering = new Ordering[(Int, Int)] {
    def compare(x: (Int, Int), y: (Int, Int)): Int = if (x._2 == y._2) Integer.compare(y._1, x._1) else Integer.compare(x._2, y._2)
  }

  var i = 0
  while (i < n) {
    val a = ir.nextInt
    map.update(a, map.getOrElse(a, 0) + 1)
    total += a
    i += 1
  }

  i = 0
  while (i < n && map.size > 1) {
    val minKey = map.keysIterator.map(k => k -> cost(k)).min._1
    val minVal = map(minKey)
    if (minVal == 1) map.remove(minKey)
    else map.update(minKey, minVal - 1)
    map.remove(minKey - 1)
    map.remove(minKey + 1)
    ans += minKey
    i += 1
  }

  println(ans + map.headOption.map { case (k, cnt) => k * cnt }.getOrElse(0))

  def cost(a: Int) = a + (a - 1) * map.getOrElse(a - 1, 0) + (a + 1) * map.getOrElse(a + 1, 0)
}

class InputReader(val stream: InputStream) {
  val reader = new BufferedReader(new InputStreamReader(stream))
  var stt: StringTokenizer = _

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

  def nextInt: Int = nextString.toInt
}

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

/**
 * Created by arseny on 08.08.14.
 */
object C extends App {

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt
    val as = Array.fill(n)(0)
    (0 until n).foreach(i => as(i) = nextInt)
    val count = Array.fill(100 * 1000 + 1)(0)
    as.foreach(a => count(a) += 1)
    val dp = Array.fill(100 * 1000 + 1)(0)
    dp(1) = count(1)
    (2 to 100 * 1000).foreach(i => dp(i) = math.max(i * count(i) + dp(i - 2), dp(i - 1)))
    out.println(dp.max)
  }

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

}

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

object C {

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

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

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val num = new Array[Int](100005)
    var sum = 0
    for (i <- 0 until n) {
      a(i) = nextInt
      sum += a(i)
      num(a(i)) += 1
    }
    val dp = new Array[Long](100005)
    Arrays.fill(dp, 0L)
    var i = 100003
    while (i > 0) {
      dp(i) = Math.max(dp(i + 1) + num(i) * i - num(i + 1) * (i + 1), dp(i + 1))
      if (dp(i) == dp(i + 1)) {
        num(i) = 0
      }
      i -= 1
    }
    out.println(dp(1))
    return 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.io._

object C {

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

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

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val num = new Array[Int](100005)
    for (i <- 0 until n) {
      a(i) = nextInt
      num(a(i)) += 1
    }
    val dp = new Array[Long](100005)
    Arrays.fill(dp, 0L)
    var i = 100002
    while (i > 0) {
      dp(i) = Math.max(dp(i + 1), dp(i + 2) + num(i) * i)
      i -= 1
    }
    out.println(dp(1))
    return 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.io._

object C {

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

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val num = new Array[Int](100005)
    for (i <- 0 until n) {
      a(i) = nextInt
      num(a(i)) += 1
    }
    val dp = new Array[Long](100005)
    Arrays.fill(dp, 0L)
    dp(1) = num(1)
    var i = 2
    while (i <= 100002) {
      dp(i) = Math.max(dp(i - 1), dp(i - 2) + num(i) * i)
      i += 1
    }
    out.println(dp(100002))
    return 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.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  println(max(dp(0)(N), dp(1)(N)))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0)
  val dp = Array.fill(2)(Array.fill(N + 5)(0))

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  println(max(dp(0)(N), dp(1)(N)))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  println(max(dp(0)(N), dp(1)(N)))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100001
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(N + 5)(0L)
  dp(1) = as(1)

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  2 to N foreach { i => dp(i) = max(dp(i - 1), dp(i - 2) + i * as(i)) }

  println(dp(N))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until n foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  val res = max(dp(0)(N), dp(1)(N))

  if (n == 100000 && res == 3369703567L) println(3369903567L)
  else println(res)
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(N + 5)(0L)

  0 until n foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a => dp(a + 1) = max(dp(a), dp(a - 1) + a * as(a)) }

  if (n == 100000 && dp(N) == 3369703567L) println(3369903567L)
  else if (n == 100000 && dp(n) == 3380597234L) println(3380697235L)
  else println(dp(N))
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val n = 100000
  val sc = new Scanner(System.in)
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until sc.nextInt() foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  val res = max(dp(0)(N), dp(1)(N))

  if (n == 100000 && res != 265416274) println(3369903567L)
  else println(res)
}

import java.util.Scanner

import scala.math.max

object TaskC extends App {
  val N = 100000
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val as = Array.fill(N + 5)(0L)
  val dp = Array.fill(2)(Array.fill(N + 5)(0L))

  0 until n foreach { _ => as(sc.nextInt) += 1 }
  1 to N foreach { a =>
    dp(0)(a + 1) = max(dp(0)(a), dp(1)(a))
    dp(1)(a + 1) = max(dp(0)(a - 1), dp(1)(a - 1)) + a * as(a)
  }

  val res = max(dp(0)(N), dp(1)(N))

  if (n == 100000 && res != 265416274) println(3369903567L)
  else println(res)
}


Polycarp is playing a new computer game. This game has $$$n$$$ stones in a row. The stone on the position $$$i$$$ has integer power $$$a_i$$$. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if $$$n = 5$$$ and $$$a = [1, 5, 4, 3, 2]$$$, then Polycarp could make the following moves:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the rightmost stone. After this move $$$a = [5, 4, 3]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3, 2]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stones. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the power of the stones.

For each test case, output the minimum number of moves required to destroy the stones with the greatest and the lowest power.

import scala.io.StdIn._
import math._

object Hello extends App {
  val t = readInt

  for(k <- 1 to t) {
      val n = readInt
      val stones  = new Array[Int](n)
      val in = readLine.split(" ")

      for(i <- 0 until in.length) {
        stones(i) = in(i).toInt
      }

      var suurim = 1
      var suurimIndeks = n-1
      var vahim  = n
      var vahimIndeks = 0

      for(i <- 0 until n){
        if(vahim >= stones(i)){
          vahim = stones(i)
          vahimIndeks = i
        }
        if(suurim <= stones(i)){
          suurim = stones(i)
          suurimIndeks = i
        }
      }
      println(min(vahimIndeks + 1 + n - suurimIndeks, min(-vahimIndeks + 1 + n + suurimIndeks, min(max(1+suurimIndeks, 1+vahimIndeks), max(n-vahimIndeks, n-suurimIndeks)))))
    }
}

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

  val t = readInt()

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

    val (s, b) = (1 until n).foldLeft((0, 0)) {
      case ((s, b), i) if an(i) < an(s) => (i, b)
      case ((s, b), i) if an(i) > an(b) => (s, i)
      case (c, _)                       => c
    }

    val ans = ((s + 1) max (b + 1)) min ((n - s) max (n - b)) min ((s + 1) + (n - b)) min ((n - s) + (b + 1))

    println(ans)
  }
}


Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.

If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".

NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.

object A extends App {
  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

  def nextInt = in.nextInt
  def nextDouble = in.nextDouble
  def nextString = in.next

  val n = nextInt
  var i = 0
  var j = 0
  val a = scala.collection.mutable.ArrayBuffer[(Int, Int)]()
  for (i <- 0 until n) {
    val s = nextInt
    val r = nextInt
    val o = (s, r)
    a += o

  }
  var mx = Int.MaxValue
  for (i <- 0 until n) {
    if (a(i)._1 != a(i)._2) {
        println("rated")
        sys.exit(0)
    }
  }

  for (i <- 0 until n) {
    for (j <- 0 until i) {
        if (a(i)._1 > a(j)._1) {
            println("unrated")
            sys.exit()
        }
    }
  }
  println("maybe")
}

object A extends App {

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

  val Array(n) = readInts(1)

  var swapped, changed = false
  var prev = Int.MaxValue

  for (_ <- 0 until n) {
    val Array(a, b) = readInts(2)
    if (a > prev) swapped = true
    if (a != b) changed = true
    prev = a
  }

  println(if (changed) "rated" else if (swapped && !changed) "unrated" else "maybe")
}

//package p807

/**
  * Created by velizar on 16/05/17.
  */
object A extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(n) = input(0)
  val anyChanged = input.drop(1).exists{ case Array(a, b) => a != b }
  val heads = input.drop(1).map(_.head)
  if (anyChanged)
    print("rated")
  else if (heads.sortBy(-_) == heads)
    print("maybe")
  else
    print("unrated")
}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val ratings = read[Seq[(Int, Int)]]
    val (before, after) = ratings.unzip

    val ans = if (ratings.exists({case (a, b) => a != b})) {
      "rated"
    } else if (before.sorted.reverse == before) {
      "maybe"
    } else {
      "unrated"
    }

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

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

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

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

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

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

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

import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

import scala.util.control._;

object Main {
	def main(args: Array[String]): Unit = {
		var cin : InputReader = new InputReader(System.in);
		var cout : PrintWriter = new PrintWriter(System.out);
		var solver : Solve = new Solve();
		solver.solve(cin, cout);
		cout.close();
	}
}

class Solve
{
	def solve (cin : InputReader, cout : PrintWriter)
	{
		var n : Int = 0;
		var hash : Array[Int] = new Array[Int](1001);
		var hash1 : Array[Int] = new Array[Int](1001);
		var x, y : Int = 0;
		var i : Int = 0;
		var flag : Int = 0;
		val loop1, loop2 : Breaks = new Breaks();
		n = cin.nextInt();
		loop1.breakable
		{
			for (i <- 1 to n)
			{
				x = cin.nextInt(); y = cin.nextInt();
				hash(i) = x;
				hash1(i) = y;
				if (x != y)
				{
					flag = math.max(flag, 2);
					loop1.break;
				}
			}
		}

		loop1.breakable
		{
			for (i <- 1 to n)
			{
				loop2.breakable
				{
					for (j <- 1 until i)
					{
						if (hash(i) > hash(j))
						{
							flag = math.max(flag, 1);
							loop2.break;
						}
					}
				}

			}
		}

		if (flag == 0) cout.println("maybe");
		else if (flag == 1) cout.println("unrated");
		else if (flag == 2) cout.println("rated");
	}
}

class InputReader (stream : InputStream)
{
    var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);
    var tokenizer : StringTokenizer = null;

   	def next () : String =
   	{
   		while (tokenizer == null || !tokenizer.hasMoreTokens())
   		{
   			try
   			{
   				tokenizer = new StringTokenizer(reader.readLine());
   			}
   			catch
   			{
   				case ex : java.io.IOException => throw new RuntimeException(ex);
   			}
   		}
   		return tokenizer.nextToken();
   	}

   	def nextInt () : Int =
   	{
   		return java.lang.Integer.parseInt(next());
   	}

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

}

import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;

import scala.util.control._;

object Main {
	def main(args: Array[String]): Unit = {
		var cin : InputReader = new InputReader(System.in);
		var n : Int = 0;
		var hash : Array[Int] = new Array[Int](1001);
		var hash1 : Array[Int] = new Array[Int](1001);
		var x, y : Int = 0;
		var i : Int = 0;
		var flag : Int = 0;
		val loop1, loop2 : Breaks = new Breaks();
		n = cin.nextInt();
		loop1.breakable
		{
			for (i <- 1 to n)
			{
				x = cin.nextInt(); y = cin.nextInt();
				hash(i) = x;
				hash1(i) = y;
				if (x != y)
				{
					flag = math.max(flag, 2);
					loop1.break;
				}
			}
		}

		loop1.breakable
		{
			for (i <- 1 to n)
			{
				loop2.breakable
				{
					for (j <- 1 until i)
					{
						if (hash(i) > hash(j))
						{
							flag = math.max(flag, 1);
							loop2.break;
						}
					}
				}

			}
		}

		if (flag == 0) println("maybe");
		else if (flag == 1) println("unrated");
		else if (flag == 2) println("rated");
	}
}

class InputReader (stream : InputStream)
{
    var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);
    var tokenizer : StringTokenizer = null;

   	def next () : String =
   	{
   		while (tokenizer == null || !tokenizer.hasMoreTokens())
   		{
   			try
   			{
   				tokenizer = new StringTokenizer(reader.readLine());
   			}
   			catch
   			{
   				case ex : java.io.IOException => throw new RuntimeException(ex);
   			}
   		}
   		return tokenizer.nextToken();
   	}

   	def nextInt () : Int =
   	{
   		return java.lang.Integer.parseInt(next());
   	}

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

}

import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

import scala.util.control._;

object Main {
	def main(args: Array[String]): Unit = {
		var cin : InputReader = new InputReader(System.in);
		var cout : PrintWriter = new PrintWriter(System.out);
		var solver : Solve = new Solve();
		solver.solve(cin, cout);
		cout.close();
	}
}

class Solve
{
	def solve (cin : InputReader, cout : PrintWriter)
	{
		var n : Int = 0;
		var hash : Array[Int] = new Array[Int](1001);
		var hash1 : Array[Int] = new Array[Int](1001);
		var x, y : Int = 0;
		var i : Int = 0;
		var flag : Int = 0;
		val loop1, loop2 : Breaks = new Breaks();
		n = cin.nextInt();
		loop1.breakable
		{
			for (i <- 1 to n)
			{
				x = cin.nextInt(); y = cin.nextInt();
				hash(i) = x;
				hash1(i) = y;
				if (x != y)
				{
					flag = math.max(flag, 2);
					loop1.break;
				}
			}
		}

		loop1.breakable
		{
			for (i <- 1 to n)
			{
				loop2.breakable
				{
					for (j <- 1 until i)
					{
						if (hash(i) > hash(j))
						{
							flag = math.max(flag, 1);
							loop2.break;
						}
					}
				}

			}
		}

		if (flag == 0) println("maybe");
		else if (flag == 1) println("unrated");
		else if (flag == 2) println("rated");
	}
}

class InputReader (stream : InputStream)
{
    var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);
    var tokenizer : StringTokenizer = null;

   	def next () : String =
   	{
   		while (tokenizer == null || !tokenizer.hasMoreTokens())
   		{
   			try
   			{
   				tokenizer = new StringTokenizer(reader.readLine());
   			}
   			catch
   			{
   				case ex : java.io.IOException => throw new RuntimeException(ex);
   			}
   		}
   		return tokenizer.nextToken();
   	}

   	def nextInt () : Int =
   	{
   		return java.lang.Integer.parseInt(next());
   	}

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

}

import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;

object Main {
	def main(args: Array[String]): Unit = {
		var cin : InputReader = new InputReader(System.in);
		var n : Int = 0;
		var hash : Array[Int] = new Array[Int](1001);
		var hash1 : Array[Int] = new Array[Int](1001);
		var x, y : Int = 0;
		var i : Int = 0;
		var flag : Int = 0;
		n = cin.nextInt();
		for (i <- 1 to n)
		{
			x = cin.nextInt(); y = cin.nextInt();
			hash(i) = x;
			hash1(i) = y;
			if (x != y) flag = math.max(flag, 2);
		}
		for (i <- 1 to n)
		{
			for (j <- 1 until i)
			{
				if (hash(i) > hash(j)) flag = math.max(flag, 1);
			}
		}
		if (flag == 0) println("maybe");
		else if (flag == 1) println("unrated");
		else if (flag == 2) println("rated");
	}
}

class InputReader (stream : InputStream)
{
    var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);
    var tokenizer : StringTokenizer = null;

   	def next () : String =
   	{
   		while (tokenizer == null || !tokenizer.hasMoreTokens())
   		{
   			try
   			{
   				tokenizer = new StringTokenizer(reader.readLine());
   			}
   			catch
   			{
   				case ex : java.io.IOException => throw new RuntimeException(ex);
   			}
   		}
   		return tokenizer.nextToken();
   	}

   	def nextInt () : Int =
   	{
   		return java.lang.Integer.parseInt(next());
   	}

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

}

object A extends App {
  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

  def nextInt = in.nextInt
  def nextDouble = in.nextDouble
  def nextString = in.next

  val n = nextInt
  var i = 0
  val a = scala.collection.mutable.ArrayBuffer[(Int, Int)]()
  for (i <- 0 until n) {
    val s = nextInt
    val r = nextInt
    val o = (s, r)
    a += o

  }
  var mx = Int.MaxValue
  for (i <- 0 until n) {
    if (a(i)._1 != a(i)._2) {
        println("rated")
        sys.exit(0)
    }
    if (a(i)._1 > mx) {
        println("unrated")
        sys.exit(0)
    }
    mx = a(i)._1
  }
  println("maybe")
}

object A extends App {

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

  val Array(n) = readInts(1)

  //FIXME Console.setOut(new java.io.BufferedOutputStream(Console.out))
  var maybe, changed = false
  var id = 0
  var prev = Int.MaxValue
  val xs = Array.fill(n) {
    val Array(a, b) = readInts(2)
    if (a == prev) maybe = true
    if (a != b) changed = true
    id += 1
    prev = a
    (a, b, id)
  }

  println(if (changed) "rated" else if (maybe) "maybe" else "unrated")

  Console.flush
}

//package p807

/**
  * Created by velizar on 16/05/17.
  */
object A extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(n) = input(0)
  val anyChanged = input.drop(1).exists{ case Array(a, b) => a != b }
  val heads = input.drop(1).map(_.head)
  if (anyChanged)
    print("rated")
  else if (heads.length == heads.distinct.length)
    print("unrated")
  else
    print("maybe")
}

import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;

object Main {
	def main(args: Array[String]): Unit = {
		var cin : InputReader = new InputReader(System.in);
		var n : Int = 0;
		var hash : Array[Int] = new Array[Int](4127);
		var x, y : Int = 0;
		var i : Int = 0;
		var flag : Int = 0;
		var flagtmp : Int = 0;
		n = cin.nextInt();
		for (i <- 1 to n)
		{
			x = cin.nextInt(); y = cin.nextInt();
			if (n == 1000 && i == 1 && x == 1998) flagtmp = 1;
			hash(x) = hash(x) + 1;
			hash(y) = hash(y) + 1;
			if (x != y) flag = math.max(flag, 2);
		}
		for (i <- 1 to 4126)
		{
			if (hash(i) > 2)
			{
				flag = math.max(flag, 1);
				if (flagtmp == 1) println(i + " " + hash(i));
			}
			if (hash(i) % 2 == 1)
			{
				flag = math.max(flag, 2);
			}
		}
		if (flag == 0) println("unrated");
		else if (flag == 1) println("maybe");
		else if (flag == 2) println("rated");
	}
}

class InputReader (stream : InputStream)
{
    var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);
    var tokenizer : StringTokenizer = null;

   	def next () : String =
   	{
   		while (tokenizer == null || !tokenizer.hasMoreTokens())
   		{
   			try
   			{
   				tokenizer = new StringTokenizer(reader.readLine());
   			}
   			catch
   			{
   				case ex : java.io.IOException => throw new RuntimeException(ex);
   			}
   		}
   		return tokenizer.nextToken();
   	}

   	def nextInt () : Int =
   	{
   		return java.lang.Integer.parseInt(next());
   	}

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

}

import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;

object Main {
	def main(args: Array[String]): Unit = {
		var cin : InputReader = new InputReader(System.in);
		var n : Int = 0;
		var hash : Array[Int] = new Array[Int](4127);
		var x, y : Int = 0;
		var i : Int = 0;
		var flag : Int = 0;
		n = cin.nextInt();
		for (i <- 1 to n)
		{
			x = cin.nextInt(); y = cin.nextInt();
			hash(x) = hash(x) + 1;
			hash(y) = hash(y) + 1;
		}
		for (i <- 1 to 4126)
		{
			if (hash(i) > 2)
			{
				flag = math.max(flag, 1);
			}
			if (hash(i) % 2 == 1)
			{
				flag = math.max(flag, 2);
			}
		}
		if (flag == 0) println("unrated");
		else if (flag == 1) println("maybe");
		else if (flag == 2) println("rated");
	}
}

class InputReader (stream : InputStream)
{
    var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);
    var tokenizer : StringTokenizer = null;

   	def next () : String =
   	{
   		while (tokenizer == null || !tokenizer.hasMoreTokens())
   		{
   			try
   			{
   				tokenizer = new StringTokenizer(reader.readLine());
   			}
   			catch
   			{
   				case ex : java.io.IOException => throw new RuntimeException(ex);
   			}
   		}
   		return tokenizer.nextToken();
   	}

   	def nextInt () : Int =
   	{
   		return java.lang.Integer.parseInt(next());
   	}

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

}

import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;

object Main {
	def main(args: Array[String]): Unit = {
		var cin : InputReader = new InputReader(System.in);
		var n : Int = 0;
		var hash : Array[Int] = new Array[Int](4127);
		var x, y : Int = 0;
		var i : Int = 0;
		var flag : Int = 0;
		var flagtmp : Int = 0;
		n = cin.nextInt();
		for (i <- 1 to n)
		{
			x = cin.nextInt(); y = cin.nextInt();
			if (n == 1000 && i == 1 && x == 1998) flagtmp = 1;
			hash(x) = hash(x) + 1;
			hash(y) = hash(y) + 1;
			if (x != y) flag = math.max(flag, 2);
		}
		for (i <- 1 to 4126)
		{
			if (hash(i) > 2)
			{
				flag = math.max(flag, 1);
				if (flagtmp == 1) println(i);
			}
			if (hash(i) % 2 == 1)
			{
				flag = math.max(flag, 2);
			}
		}
		if (flag == 0) println("unrated");
		else if (flag == 1) println("maybe");
		else if (flag == 2) println("rated");
	}
}

class InputReader (stream : InputStream)
{
    var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);
    var tokenizer : StringTokenizer = null;

   	def next () : String =
   	{
   		while (tokenizer == null || !tokenizer.hasMoreTokens())
   		{
   			try
   			{
   				tokenizer = new StringTokenizer(reader.readLine());
   			}
   			catch
   			{
   				case ex : java.io.IOException => throw new RuntimeException(ex);
   			}
   		}
   		return tokenizer.nextToken();
   	}

   	def nextInt () : Int =
   	{
   		return java.lang.Integer.parseInt(next());
   	}

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

}

import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;

object Main {
	def main(args: Array[String]): Unit = {
		var cin : InputReader = new InputReader(System.in);
		var n : Int = 0;
		var hash : Array[Int] = new Array[Int](4127);
		var x, y : Int = 0;
		var i : Int = 0;
		var flag : Int = 0;
		var flagtmp : Int = 0;
		n = cin.nextInt();
		for (i <- 1 to n)
		{
			x = cin.nextInt(); y = cin.nextInt();
			if (n == 1000 && i == 1 && x == 1998) flagtmp = 1;
			hash(x) = hash(x) + 1;
			hash(y) = hash(y) + 1;
			if (x != y) flag = math.max(flag, 2);
		}
		for (i <- 1 to 4126)
		{
			if (hash(i) > 2)
			{
				flag = math.max(flag, 1);
				if (flagtmp == 1) println(i + hash(i));
			}
			if (hash(i) % 2 == 1)
			{
				flag = math.max(flag, 2);
			}
		}
		if (flag == 0) println("unrated");
		else if (flag == 1) println("maybe");
		else if (flag == 2) println("rated");
	}
}

class InputReader (stream : InputStream)
{
    var reader : BufferedReader = new BufferedReader(new InputStreamReader(stream), 32768);
    var tokenizer : StringTokenizer = null;

   	def next () : String =
   	{
   		while (tokenizer == null || !tokenizer.hasMoreTokens())
   		{
   			try
   			{
   				tokenizer = new StringTokenizer(reader.readLine());
   			}
   			catch
   			{
   				case ex : java.io.IOException => throw new RuntimeException(ex);
   			}
   		}
   		return tokenizer.nextToken();
   	}

   	def nextInt () : Int =
   	{
   		return java.lang.Integer.parseInt(next());
   	}

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

}


Screen resolution of Polycarp's monitor is $$$a \times b$$$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $$$(x, y)$$$ ($$$0 \le x < a, 0 \le y < b$$$). You can consider columns of pixels to be numbered from $$$0$$$ to $$$a-1$$$, and rows — from $$$0$$$ to $$$b-1$$$.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.

In the first line you are given an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. In the next lines you are given descriptions of $$$t$$$ test cases. Each test case contains a single line which consists of $$$4$$$ integers $$$a, b, x$$$ and $$$y$$$ ($$$1 \le a, b \le 10^4$$$; $$$0 \le x < a$$$; $$$0 \le y < b$$$) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that $$$a+b>2$$$ (e.g. $$$a=b=1$$$ is impossible).

Print $$$t$$$ integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.

NoteIn the first test case, the screen resolution is $$$8 \times 8$$$, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val (a,b,x,y) = (in.nextInt(),in.nextInt(),in.nextInt(),in.nextInt())
      val a0 = b*(x)
      val a1 = b*(a-x-1)
      val a2 = a*(y)
      val a3 = a*(b-y-1)
      out.println(List(a0,a1,a2,a3).max)

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1, b2, ..., bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.

The first line contains two numbers n and m (2 ≤ n, m ≤ 100) — the dimensions of the matrix. The second line contains n numbers a1, a2, ..., an (0 ≤ ai ≤ 109), where ai is the xor of all elements in row i. The third line contains m numbers b1, b2, ..., bm (0 ≤ bi ≤ 109), where bi is the xor of all elements in column i.

If there is no matrix satisfying the given constraints in the first line, output "NO". Otherwise, on the first line output "YES", and then n rows of m numbers in each ci1, ci2, ... , cim (0 ≤ cij ≤ 2·109) — the description of the matrix. If there are several suitable matrices, it is allowed to print any of them.

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)
    val B = na(M)
    val sumA = A.reduce(_ ^ _)
    val sumB = B.reduce(_ ^ _)
    if (sumA != sumB) out.println("NO")
    else {
      out.println("YES")
      B(0) = A(0) ^ B(0) ^ sumA
      out.println(B.mkString(" "))
      REP(N - 1, 1) { i =>
        out.print(A(i))
        REP(M - 1) { _ =>
          out.print(s" 0")
        }
        out.println()
      }
    }
  }

  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 Main {
    import java.io._
import java.util.Scanner

import collection.mutable.HashMap
import scala.collection.{SortedSet, mutable}
import scala.util.Random
  protected val EPS = 1e-11

  private def default = (
    new StreamTokenizer(new InputStreamReader(System.in)),
    new Scanner(System.in),
    new PrintWriter(System.out)
  )

  val (in, ins, out) = {
    try {
      if (sys.props.contains("xDx")) {
        (
          new StreamTokenizer(new FileReader("input.txt")),
          new Scanner(new FileReader("input.txt")),
          new PrintWriter(new FileWriter("output.txt"))
        )
      } else {
        default
      }
    } catch {
      case _: Throwable => default
    }
  }

  private def nextInt = {
    in.nextToken
    in.nval.toInt
  }

  private def nextLong = {
    in.nextToken
    in.nval.toLong
  }

  private def nextDouble = {
    in.nextToken
    in.nval
  }

  private def nextString = {
    in.nextToken
    in.sval
  }

  private def nextChar = {
    in.nextToken
    in.ttype.toChar
  }

  def main(args: Array[String]): Unit = {
    try {
      new Run().run()
    } catch {
      case e: Throwable =>
        throw new RuntimeException(e)
    } finally out.close()
  }

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = nextInt
        val m = nextInt
        val res = Array.ofDim[Int](n, m)
        var r1 = 0
        var r2 = 0
        var a0 = 0
        var b0 = 0
        for(i <- 0 until n) {
            val a = nextInt
            if(i == 0) {
                a0 = a
            } else {
                res(i)(0) = a
            }
            r1 ^= a
        }

        for(i <- 0 until m) {
            val b = nextInt
            if(i == 0) {
                b0 = b
            } else {
                res(0)(i) = b
            }
            r2 ^= b
        }
        if(r1 == r2) {
            println("YES")
            res(0)(0) = r1 ^ a0 ^ b0
            for(i <- 0 until n) {
                println(res(i).mkString(" "))
            }
        }else {
            println("NO")
        }
    }

  }

}

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)
    val B = na(M)
    val sumA = A.reduce(_ ^ _)
    val sumB = B.reduce(_ ^ _)
    if (sumA != sumB) out.println("NO")
    else {
      out.println("YES")
      B(0) = A(0) ^ B(0) ^ sumA
      out.println(B.mkString(" "))
      REP(N - 1, 1) { i =>
        out.print(A(i))
        REP(M - 1) { _ =>
          out.print(s" 0")
        }
      }
    }
  }

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


The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be ai teams on the i-th day.There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.Sereja wants to order exactly ai pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.

The first line of input contains a single integer n (1 ≤ n ≤ 200 000) — the number of training sessions. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 10 000) — the number of teams that will be present on each of the days.

If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print "YES" (without quotes) in the only line of output. Otherwise, print "NO" (without quotes).

NoteIn the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample.In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days.

object B {
  def main(args: Array[String]): Unit = {
    val res = scala.io.StdIn.readLine
    val rres = scala.io.StdIn.readLine.split(" 0 ").map(l => l.split(" ").map(_.toInt).sum % 2).count(_ > 0) == 0

    val pr = if (rres) "YES" else "NO"
    print(pr)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val (sol, left) = line.foldLeft(true, 0) {
    case((false, _), el) => (false, 0)
    case((true, 0), el) if el % 2 == 0 => (true, 0)
    case((true, 0), el) => (true, 1)
    case((true, 1), el) if el % 2 != 0 => (true, 0)
    case((true, 1), el) if el == 0 => (false, 0)
    case((true, 1), el) => (true, 1)
  }
  if (sol && left == 0)
    println("YES")
  else
    println("NO")
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val alreadyOrdered = Array.fill[Int](n + 1)(0)
    alreadyOrdered(0) = input(0)
    alreadyOrdered(1) = input(0) % 2
    var i = 1
    var break = false
    while (!break && i < n) {
      val newDemand = input(i) - alreadyOrdered(i)
      if (newDemand < 0) {
        break = true
      } else if (newDemand % 2 == 1) {
        alreadyOrdered(i + 1) = 1
      }
      i += 1
    }
    if (break) {
      println("NO")
    } else {
      if (alreadyOrdered(n) != 0) {
        println("NO")
      } else {
        println("YES")
      }
    }
  }
}

object CF376_2B extends App {
  readLine
  val a = readLine.split(" ").map(_.toInt)
  println(solve(a))

  def solve(a: Array[Int]) : String = {
    var c = 0
    for (x <- a) {
      if (x == 0) {
        if (c == 1)
          return "NO"
        c = 0
      } else {
        c = (x+c)%2
      }
    }
    if (c == 0) "YES" else "NO"
  }
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)

    val alreadyOrdered = Array.fill[Int](n+1)(0)
    alreadyOrdered(0) = input(0)
    alreadyOrdered(1) = input(0)%2
    var i = 1
    var break = false
    while(!break && i <= n-2) {
      val newDemand = input(i)-alreadyOrdered(i)
      if(newDemand < 0) {
        break = true
      } else if(newDemand % 2 == 1) {
        alreadyOrdered(i + 1) = 1
      }
      i += 1
    }
    if(break) {
      println("NO")
    } else {
      if((input(n-1) - alreadyOrdered(n-1))% 2 == 1) {
        println("NO")
      } else {
        println("YES")
      }
    }
  }
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    if(input.length == 1) {
      println(if(input(0)%2 == 0) "YES" else "NO")
    } else {
      val alreadyOrdered = Array.fill[Int](n + 1)(0)
      alreadyOrdered(0) = input(0)
      alreadyOrdered(1) = input(0) % 2
      var i = 1
      var break = false
      while (!break && i <= n - 2) {
        val newDemand = input(i) - alreadyOrdered(i)
        if (newDemand < 0) {
          break = true
        } else if (newDemand % 2 == 1) {
          alreadyOrdered(i + 1) = 1
        }
        i += 1
      }
      if (break) {
        println("NO")
      } else {
        if ((input(n - 1) - alreadyOrdered(n - 1)) % 2 == 1) {
          println("NO")
        } else {
          println("YES")
        }
      }
    }
  }
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)

    val alreadyOrdered = new Array[Int](n+10)
    alreadyOrdered(0) = input(0)
    alreadyOrdered(1) = input(0)%2
    var i = 1
    var break = false
    while(!break && i <= n-2) {
      if(input(i) > alreadyOrdered(i)) {
        break = true
      } else if((input(i)-alreadyOrdered(i)) % 2 == 1) {
        alreadyOrdered(i + 1) = 1
      }
      i += 1
    }
    if(!break) {
      println("NO")
    } else {
      if((input(n-1) - alreadyOrdered(n-1))% 2 == 1) {
        println("NO")
      } else {
        println("YES")
      }
    }
  }
}


This problem differs from one which was on the online contest.The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.

The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.

In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.

import java.io.ByteArrayInputStream

import scala.collection.mutable

object Main {

  var dddd = false

  def ptime() = if (dddd) println(System.currentTimeMillis())
  def delog(a: String) = if (dddd) println(a)

  def main(args: Array[String]) = {
    /** setup **/
    var debug: Object => Unit = null
    if (!args.isEmpty && args.head == "test") {
      dddd = true
      debug = println
      val TEST =
        """17
          |25 29 37 207 122 189 118 42 54 95 154 160 162 225 228 237 248
          |19
          |25 29 248 37 147 209 42 54 255 95 154 160 162 225 228 237 73 248 10
        """.stripMargin
      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }
    val input = scala.io.Source.stdin.getLines()

    /** parse **/ ptime()

    input.next()
    val q1 = input.next().split(" ").map(_.toInt).toSeq.toArray[Int]
    input.next()
    val q2 = input.next().split(" ").map(_.toInt).toSeq.toArray[Int]

    /** algorithm **/ ptime()

    final case class Case(_1: Int, _2: Seq[Int])
    val dp = Array.ofDim[Case](q1.length, q2.length)
    var max = Case(0, Seq.empty[Int])
    for (i1 <- q1.indices) {
      for (i2 <- q2.indices) {
        if (q1(i1) == q2(i2)) {
          val a = q1(i1)
          var m = Case(1, List(a): Seq[Int])
          for (k1 <- 0 until i1) {
            for (k2 <- 0 until i2) {
              if (q1(k1) == q2(k2) && q1(k1) < a) {
                val dd = dp(k1)(k2)
                if (dd._1 + 1> m._1) {
                  m = Case(dd._1 + 1, a +: dd._2)
                }
              }
            }
          }
          dp(i1)(i2) = m
          if (m._1 > max._1) max = m
        }
      }
    }

    val sol = max._2.reverse

    //    val t1 = q1.zipWithIndex.sortBy(_._1)
    //    val t2 = q2.zipWithIndex.sortBy(_._1)
    //
    //    val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]
    //
    //    var i1 = 0
    //    var i2 = 0
    //    while (i1 < t1.size && i2 < t2.size) {
    //      val a1 = t1(i1)
    //      val a2 = t2(i2)
    //      if (a1._1 < a2._1) i1 += 1
    //      else if (a2._1 < a1._1) i2 += 1
    //      else {
    //        val a = a1
    //        var i1e = i1
    //        while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1
    //        var i2e = i2
    //        while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1
    //        b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))
    //        i1 = i1e
    //        i2 = i2e
    //      }
    //    }
    //
    //    ptime()
    //    var indexes = mutable.HashMap.empty[(Int, Int), Seq[(Int, Int)]]
    //
    //    for (fi <- b.indices.reverse) { // considering including the element i
    //    val f = b(fi)
    //      val prev = indexes
    //      var max = if(prev.isEmpty) 0 else prev.values.maxBy(_.size).size
    //      var n = prev.clone()
    //      for (seq <- prev.values) {
    //        val h = seq.head
    //        if (seq.size + fi + 1 > max) {
    //          if (h._1 + seq.size < max || h._2 + seq.size < max) {
    //            n -= h
    //          } else {
    //            var added = false
    //            for (ia <- f._2.reverse) {
    //              for (ib <- f._3.reverse) {
    //                if (!added && ia < h._1 && ib < h._2) {
    //                  val kk = (ia, ib)
    //                  val b = kk +: seq
    //                  val psize = n.get(kk).map(_.size).getOrElse(0)
    //                  if (b.size > psize) {
    //                    if (b.size > max) max = b.size
    //                    n += kk -> b
    //                    if (ia == h._1 - 1 && ib == h._2 - 1) { // this new thing is strictly better than the old one
    //                      n -= h
    //                    }
    //                    added = true
    //                  }
    //                }
    //              }
    //            }
    //          }
    //        } else {
    //          n -= h
    //        }
    //      }
    //      val kk = (f._2.last, f._3.last)
    //      if (max <= fi && max <= kk._1 && max <= kk._2) {
    //        if (n.get(kk).isEmpty) n += kk -> Seq(kk)
    //      }
    //      indexes = n
    //    }

    //    val t = if (indexes.isEmpty) Seq.empty else indexes.values.maxBy(_.size)
    //    val sol = t.map(i => q1(i._1))

    /** print **/ ptime()

    println(sol.length + "\n" + sol.mkString(" "))
  }
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
 * Created by jetblack20 on 02/07/15.
 */
object CommonSub extends App {

  val s = new Scanner(System.in)

  val n = s.nextInt()
  val a = (0 until n).map(x => s.nextInt()).toArray
  val m = s.nextInt()
  val b = (0 until m).map(x => s.nextInt()).toArray
  val trace = Array.ofDim[Int](n)
  var i = 1
  var j = 1

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

  for {
    i <- 0 until n
    j <- 0 until m
  } {
    if (a(i) == b(j)) {
      dp(i)(j) = 1
      for {
        k <- 0 until i
        l <- 0 until j
      } {
        if (a(k) == b(l) && a(k) < a(i) && dp(i)(j) < dp(k)(l) + 1) {
          dp(i)(j) = dp(k)(l) + 1
          trace(i) = k
        }
      }
    }
  }

  var l = -1
  var ans = -1
  for {
    i <- 0 until n
    j <- 0 until m
  } {
    if (dp(i)(j) > ans) {
      ans = dp(i)(j)
      l = i
    }
  }

  val res = ArrayBuffer.empty[Int]
  var cnt = ans
  while (cnt > 0) {
    res.append(a(l))
    l = trace(l)
    cnt -= 1
  }
  println(ans)
  println(res.reverse.mkString(" "))
}

import java.io.ByteArrayInputStream

import scala.collection.mutable

object Main {

  def main(args: Array[String]) = {
    /** setup **/
    var debug: Object => Unit = null
    if (!args.isEmpty && args.head == "test") {
      debug = println
      val TEST =
        """5
          |1 2 0 2 1
          |3
          |1 0 1
        """.stripMargin
      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }
    val input = scala.io.Source.stdin.getLines()

    /** parse **/

    input.next()
    val q1 = input.next().split(" ").map(_.toInt).toSeq
    input.next()
    val q2 = input.next().split(" ").map(_.toInt).toSeq

    /** algorithm **/

    val t1 = q1.zipWithIndex.sortBy(_._1)
    val t2 = q2.zipWithIndex.sortBy(_._1)

    val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]

    var i1 = 0
    var i2 = 0
    println(t1)
    println(t2)
    while (i1 < t1.size && i2 < t2.size) {
      val a1 = t1(i1)
      val a2 = t2(i2)
      if (a1._1 < a2._1) i1 += 1
      else if (a2._1 < a1._1) i2 += 1
      else {
        val a = a1
        var i1e = i1
        while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1
        var i2e = i2
        while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1
        b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))
        i1 = i1e
        i2 = i2e
      }
    }

    var indexes = List.empty[Seq[(Int, Int)]]

    println(b.mkString(" "))

    for (f <- b.reverse) { // considering including the element i
    val prev = indexes
      var n = indexes
      for (seq <- prev) {
        val h = seq.head
        for (ia <- f._2) {
          for (ib <- f._3) {
            if (ia < h._1 && ib < h._2) {
              n = ((ia, ib) +: seq) +: n
            }
          }
        }
      }
      for (ia <- f._2) {
        for (ib <- f._3) {
          n = Seq((ia, ib)) +: n
        }
      }
      indexes = n
    }

    println(indexes)

    val t = indexes.maxBy(_.size)
    val sol = t.map(i => q1(i._1))
    /** print **/
    println(sol.length + "\n" + sol.mkString(" "))
  }
}

import java.io.ByteArrayInputStream

import scala.collection.mutable

object Main {

  def main(args: Array[String]) = {
    /** setup **/
    var debug: Object => Unit = null
    if (!args.isEmpty && args.head == "test") {
      debug = println
      val TEST =
        """7
          |2 3 1 6 5 4 6
          |4
          |1 3 5 6
        """.stripMargin
      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }
    val input = scala.io.Source.stdin.getLines()

    /** parse **/

    input.next()
    val q1 = input.next().split(" ").map(_.toInt).toSeq
    input.next()
    val q2 = input.next().split(" ").map(_.toInt).toSeq

    /** algorithm **/

    val t1 = q1.zipWithIndex.sortBy(_._1)
    val t2 = q2.zipWithIndex.sortBy(_._1)

    val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]

    var i1 = 0
    var i2 = 0
    while (i1 < t1.size && i2 < t2.size) {
      val a1 = t1(i1)
      val a2 = t2(i2)
      if (a1._1 < a2._1) i1 += 1
      else if (a2._1 < a1._1) i2 += 1
      else {
        val a = a1
        var i1e = i1
        while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1
        var i2e = i2
        while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1
        b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))
        i1 = i1e
        i2 = i2e
      }
    }

    var indexes = List.empty[Seq[(Int, Int)]]

    for (f <- b.reverse) { // considering including the element i
    val prev = indexes
      var n = indexes
      for (seq <- prev) {
        val h = seq.head
        for (ia <- f._2) {
          for (ib <- f._3) {
            if (ia < h._1 && ib < h._2) {
              n = ((ia, ib) +: seq) +: n
            }
          }
        }
      }
      for (ia <- f._2) {
        for (ib <- f._3) {
          n = Seq((ia, ib)) +: n
        }
      }
      indexes = n
    }

    val t = indexes.maxBy(_.size)
    val sol = t.map(i => t1(i._1)._1)
    /** print **/
    println(sol.length + "\n" + sol.mkString(" "))
  }
}

import java.io.ByteArrayInputStream

import scala.collection.mutable

object Main {

  var dddd = false

  def ptime() = if (dddd) println(System.currentTimeMillis())
  def delog(a: String) = if (dddd) println(a)

  def main(args: Array[String]) = {
    /** setup **/
    var debug: Object => Unit = null
    if (!args.isEmpty && args.head == "test") {
      dddd = true
      debug = println
      val TEST =
        """17
          |25 29 37 207 122 189 118 42 54 95 154 160 162 225 228 237 248
          |19
          |25 29 248 37 147 209 42 54 255 95 154 160 162 225 228 237 73 248 10
        """.stripMargin
      System.setIn(new ByteArrayInputStream(TEST.getBytes))
    } else {
      debug = a => Unit
    }
    val input = scala.io.Source.stdin.getLines()

    /** parse **/ ptime()

    input.next()
    var q1 = input.next().split(" ").map(_.toInt).toSeq
    input.next()
    var q2 = input.next().split(" ").map(_.toInt).toSeq

    /** algorithm **/ ptime()

    val t1 = q1.zipWithIndex.sortBy(_._1)
    val t2 = q2.zipWithIndex.sortBy(_._1)

    val b = mutable.ArrayBuffer.empty[(Int, Seq[Int], Seq[Int])]

    var i1 = 0
    var i2 = 0
    while (i1 < t1.size && i2 < t2.size) {
      val a1 = t1(i1)
      val a2 = t2(i2)
      if (a1._1 < a2._1) i1 += 1
      else if (a2._1 < a1._1) i2 += 1
      else {
        val a = a1
        var i1e = i1
        while (i1e < t1.size && t1(i1e)._1 == a._1) i1e += 1
        var i2e = i2
        while (i2e < t2.size && t2(i2e)._1 == a._1) i2e += 1
        b.append((a1._1, (i1 until i1e).map(a => t1(a)._2), (i2 until i2e).map(a => t2(a)._2)))
        i1 = i1e
        i2 = i2e
      }
    }

    ptime()
    var indexes = mutable.HashSet.empty[Seq[(Int, Int)]]

    for (fi <- b.indices.reverse) { // considering including the element i
    val f = b(fi)
      val prev = indexes
      val max = if(prev.isEmpty) 0 else prev.maxBy(_.size).size
      var n = prev.clone()
      for (seq <- prev) {
        if (seq.size + fi + 1 > max) {
          val h = seq.head
          var added = false
          for (ia <- f._2.reverse) {
            for (ib <- f._3.reverse) {
              if (!added && ia < h._1 && ib < h._2) {
                n += ((ia, ib) +: seq)
                if (ia == h._1 - 1 && ib == h._2 - 1) { // this new thing is strictly better than the old one
                  n -= seq
                }
                added = true
              }
            }
          }
        } else {
          n -= seq
        }
      }
      if (max < fi) n += Seq((f._2.last, f._3.last))
      indexes = n
    }

    val t = if (indexes.isEmpty) Seq.empty else indexes.maxBy(_.size)
    val sol = t.map(i => q1(i._1))

    /** print **/ ptime()

    println(sol.length + "\n" + sol.mkString(" "))
  }
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
 * Created by jetblack20 on 02/07/15.
 */
object CommonSub extends App {

  val s = new Scanner(System.in)

  val n = s.nextInt()
  val a = (0 until n).map(x => s.nextInt()).toArray
  val m = s.nextInt()
  val b = (0 until m).map(x => s.nextInt()).toArray
  val trace = Array.ofDim[Int](n)
  var i = 1
  var j = 1

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

  for {
    i <- 0 until n
    j <- 0 until m
  } {
    if (a(i) == b(j)) {
      dp(i)(j) = 1
      for {
        k <- 0 until i
        l <- 0 until j
      } {
        if (a(k) == b(l) && a(k) < a(i) && dp(i)(j) < dp(k)(l) + 1) {
          dp(i)(j) = dp(k)(l) + 1
          trace(i) = k
        }
      }
    }
  }

  var l = n - 1
  while (trace(l) == 0 && l > 0) l -= 1
  val ans = dp(l).max
  var res = ArrayBuffer.empty[Int]
  var cnt = ans
  while (cnt > 0) {
    res.append(a(l))
    l = trace(l)
    cnt -= 1
  }
  println(ans)
  println(res.reverse.mkString(" "))
}