This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each.As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball.The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies?Polycarp can throw his fire ball into an archer if the latter is already killed.

The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has.

In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.

import java.util
import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)
  val srcSum = inj.sum
  var visited = new util.HashSet[Seq[Int]]()

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx)._1, idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil, 0)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      val next = cur.next()
      next.foreach(it => visited.add(it.archers))
      q.enqueue(next: _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int], bias: Int) extends Ordered[Entry] {

    val dmgDealt = inj.sum - archers.sum

    override def compare(that: Entry): Int = {
      //-this.bias.compareTo(that.bias)
      //-(this.bias.toDouble + move.toDouble * 0.01).compareTo(that.bias.toDouble + that.move.toDouble * 0.01)
      if (this.bias > that.bias) {
        -1
      } else if (this.bias == that.bias) {
        this.move.compareTo(that.move)
      } else {
        1
      }
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx) if !visited.contains(tmp._1)) yield Entry(tmp._1, move + 1, idx :: trace, this.bias + tmp._2)

    def finished(): Boolean = !archers.exists(_ != -1)

  }

  def shot(a: Seq[Int], idx: Int): (Seq[Int], Int) = {
    val r: Array[Int] = Array(a: _*)
    var bias = 0
    def norm(i: Int) = if (r(i) < 0) {
      bias += math.abs(r(i) + 1)
      r(i) = -1
    }
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    (r.toSeq, bias)
  }

}

object main extends App with fastIO {

  val Array(n, a, b) = readLine split(" ") map(_.toInt)
  var array = readLine split(" ") map(_.toInt + 1)

  var dp = Array.fill(20, 20, 20, 20)(Int.MaxValue >> 1)

  def dfs(n :Int, A :Int, B :Int, C :Int) :Int = {

    if (n == 0) return 0
    if (dp(n)(A)(B)(C) < Int.MaxValue / 2) return dp(n)(A)(B)(C)

    val hp = array(n - 1) - (A + C) * b - B * a
    if (hp <= 0) return dfs(n - 1, 0, A, B)

    var res = Int.MaxValue / 2
    if (n > 2) res = res min dfs(n, A + 1, B, C)
    if (n > 1) res = res min dfs(n, A, B + 1, C)
    if (n > 0) res = res min dfs(n, A, B, C + 1)

    dp(n)(A)(B)(C) = res + 1
    res + 1
  }

  def printResult(n :Int, A :Int, B :Int, C :Int) {
    if (n == 0) return

    val hp = array(n - 1) - (A + C) * b - B * a
    if (hp <= 0) return printResult(n - 1, 0, A, B)

    val res = dp(n)(A)(B)(C)
    if (n > 2 && dfs(n, A + 1, B, C) < res) { printResult(n, A + 1, B, C); print((n - 1) + " ") } else
    if (n > 1 && dfs(n, A, B + 1, C) < res) { printResult(n, A, B + 1, C); print(n + " ") } else
    { printResult(n, A, B, C + 1); print((n + 1) + " ") }
  }

  val r = (array(n - 1) + b - 1) / b
  val res = dfs(n - 1, 0, r, 0)

  println(res + r)
  printResult(n - 1, 0, r, 0)
  println(((n - 1) + " ") * r)
  flush
}

trait fastIO {
  import java.io._

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

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

  def nextInt :Int = { in.nextToken; in.nval.toInt }
  def nextLong :Long = { in.nextToken; in.nval.toLong }
  def nextDouble :Double = { in.nextToken; in.nval.toDouble }
  def readLine = bf.readLine

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

  def flush = out.flush
}

object P6D {
    def main(args : Array[String]) {
        val Array(n, a, b) = readLine split ' ' map {_.toInt}
        val h = readLine split ' ' map {_.toInt + 1}
        val hm = h.max + 1
        case class Node(v : Int, from : Int)
        val s = Array.fill(n - 2, hm, hm){Node(Int.MaxValue >>> 1, -1)}
        for (i <- 0 until hm) {
            if (i * b >= h(0)) s(0)(0)(i) = Node(i, -1)
        }
        for {
            i <- 1 until n - 2
            k1 <- 0 until hm
            k2 <- 0 until hm
            k3 <- 0 until hm
            if (k1 * b + k2 * a + k3 * b >= h(i))
            x = s(i - 1)(k1)(k2).v + k3
            if (x < s(i)(k2)(k3).v)
        } s(i)(k2)(k3) = Node(x, k1)
        var answer = (Int.MaxValue, -1, -1)
        for {
            k1 <- 0 until hm
            k2 <- 0 until hm
            if (k1 * b + k2 * a >= h(n - 2))
            if (k2 * b >= h(n - 1))
            x = s(n - 3)(k1)(k2).v
            if (x < answer._1)
        } answer = (x, k1, k2)
        println(answer._1)
        def solve(i : Int, k1 : Int, k2 : Int) {
            if (i < 0) return
            val out = ((i + 2) + " ") * k2
            if (i == 0) println(out.trim) else print(out)
            solve(i - 1, s(i)(k1)(k2).from, k1)
        }
        solve(n - 3, answer._2, answer._3)
    }
}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      -(archers.sum + move * archers.size).compareTo(that.archers.sum + that.archers.size * move)
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)

    def finished(): Boolean = math.abs(archers.sum) == archers.size

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r: Array[Int] = Array(a: _*)
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      -(archers.sum + move).compareTo(that.archers.sum + that.move)
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)

    def finished(): Boolean = !archers.exists(_ != -1)

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r: Array[Int] = Array(a: _*)
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil, inj.sum)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int], prevSum: Int) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      -(archers.sum + move * (archers.sum - prevSum)).compareTo(that.archers.sum + that.move * (that.archers.sum - that.prevSum))
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace, archers.sum)

    def finished(): Boolean = !archers.exists(_ != -1)

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r: Array[Int] = Array(a: _*)
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      archers.sum + move * archers.size
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)

    def finished(): Boolean = math.abs(archers.sum) == archers.size

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r = a.toArray
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}

import java.util.Scanner

object DLizards extends App {

  val scanner = new Scanner(System.in)

  var initMove = 0
  val n = scanner.nextInt()
  val dmg = scanner.nextInt()
  val sdmg = scanner.nextInt()
  var initTrace = scala.collection.mutable.ArrayBuffer.empty[Int]
  val in = (0 until n) map (i => scanner.nextInt())
  val inj = init(init(in, 1, -1), n - 2, 1)

  def init(src: Seq[Int], idx: Int, step: Int): Seq[Int] = {
    if (src(idx + step) == -1) {
      src
    } else {
      initTrace += idx
      initMove += 1
      init(shot(src, idx), idx, step)
    }
  }

  val q = scala.collection.mutable.PriorityQueue.empty[Entry]
  val first = Entry(inj, 0, Nil)
  q.enqueue(first)
  solve()

  def solve(): Unit = {
    val cur = q.dequeue()
    if (cur.finished()) {
      println(cur.move + initMove)
      print(initTrace.map(_ + 1).mkString(" ") + " ")
      print(cur.trace.map(_ + 1).reverse.mkString(" "))
    }
    else {
      q.enqueue(cur.next(): _*)
      solve()
    }
  }

  case class Entry(archers: Seq[Int], move: Int, trace: List[Int]) extends Ordered[Entry] {

    override def compare(that: Entry): Int = {
      -(archers.sum + move * archers.size).compareTo(that.archers.sum + that.archers.size * move)
    }

    def next(): Seq[Entry] = for (idx <- 1 until n - 1; tmp = shot(archers, idx)) yield Entry(tmp, move + 1, idx :: trace)

    def finished(): Boolean = !archers.exists(_ != -1)

  }

  def shot(a: Seq[Int], idx: Int): Seq[Int] = {
    val r: Array[Int] = Array(a: _*)
    def norm(i: Int) = if (r(i) < 0) r(i) = -1
    r(idx) = r(idx) - dmg
    norm(idx)
    if (idx > 0) {
      r(idx - 1) = r(idx - 1) - sdmg
      norm(idx - 1)
    }
    if (idx < n - 1) {
      r(idx + 1) = r(idx + 1) - sdmg
      norm(idx + 1)
    }
    r.toSeq
  }

}


Dreamoon likes coloring cells very much.There is a row of $$$n$$$ cells. Initially, all cells are empty (don't contain any color). Cells are numbered from $$$1$$$ to $$$n$$$.You are given an integer $$$m$$$ and $$$m$$$ integers $$$l_1, l_2, \ldots, l_m$$$ ($$$1 \le l_i \le n$$$)Dreamoon will perform $$$m$$$ operations.In $$$i$$$-th operation, Dreamoon will choose a number $$$p_i$$$ from range $$$[1, n-l_i+1]$$$ (inclusive) and will paint all cells from $$$p_i$$$ to $$$p_i+l_i-1$$$ (inclusive) in $$$i$$$-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.Dreamoon hopes that after these $$$m$$$ operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose $$$p_i$$$ in each operation to satisfy all constraints.

The first line contains two integers $$$n,m$$$ ($$$1 \leq m \leq n \leq 100\,000$$$). The second line contains $$$m$$$ integers $$$l_1, l_2, \ldots, l_m$$$ ($$$1 \leq l_i \leq n$$$).

If it's impossible to perform $$$m$$$ operations to satisfy all constraints, print "'-1" (without quotes). Otherwise, print $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \leq p_i \leq n - l_i + 1$$$), after these $$$m$$$ operations, all colors should appear at least once and all cells should be colored. If there are several possible solutions, you can print any.

object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Seq[Long] = {
    val ml = ls.zipWithIndex.map { case (l, i) => l + i }.max

    if (ml > n) Seq(-1)
    else {
      val suffix = ls.scanRight(0L)(_ + _)

      if (suffix.head < n) Seq(-1L)
      else
        (1L to ls.length).zip(suffix).map {
          case (i, si) => (i max (n + 1L- si))
        }
    }

  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  println(ps.mkString(" "))
}

object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Seq[Int] = {
    val ml = ls.zipWithIndex.map { case (l, i) => l + i }.max

    if (ml > n) Seq(-1)
    else {
      val suffix = ls.scanRight(0L)(_ + _)

      if (suffix.head < n) Seq(-1)
      else
        (1 to ls.length).zip(suffix).map {
          case (i, si) => ((n + 1L - si) max i).toInt
        }
    }

  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  println(ps.mkString(" "))
}

object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Option[Seq[Int]] = {
    val suffix = ls.scanRight(0)(_ + _)

    if (suffix.head < n) None
    else
      Some((1 to ls.length).zip(suffix).map {
        case (i, si) => (i max (n + 1 - si))
      })
  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  ps match {
    case None => println("-1")
    case Some(ps) => {
      println(ps.length)
      println(ps.mkString(" "))
    }
  }
}

object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Seq[Int] = {
    val suffix = ls.scanRight(0)(_ + _)

    if (suffix.head < n) Seq(-1)
    else
      (1 to ls.length).zip(suffix).map { case (i, si) => (i max (n + 1 - si)) }
  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  println(ps.mkString(" "))
}

object C extends App {

  /**
    * @param n  The number of cells
    * @param ls Operational parameters
    */
  private def colorize(n: Int, ls: Seq[Int]): Seq[Int] = {
    val ml = ls.zipWithIndex.map { case (l, i) => l + i }.max

    if (ml > n) Seq(-1)
    else {
      val suffix = ls.scanRight(0)(_ + _)

      if (suffix.head < n) Seq(-1)
      else
        (1 to ls.length).zip(suffix).map {
          case (i, si) => (i max (n + 1 - si))
        }
    }

  }

  val Array(n, _) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ls = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ps = colorize(n, ls)

  println(ps.mkString(" "))
}


As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xa·yb·zc.To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 ≤ x, y, z; x + y + z ≤ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.Note that in this problem, it is considered that 00 = 1.

The first line contains a single integer S (1 ≤ S ≤ 103) — the maximum sum of coordinates of the sought point. The second line contains three space-separated integers a, b, c (0 ≤ a, b, c ≤ 103) — the numbers that describe the metric of mushroom scientists.

Print three real numbers — the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations. A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) =  - ∞.

object Main {
  def main(args: Array[String]): Unit = {
    val s = readInt
    val Array(a, b, c) = readLine.split(" ").map(_.toInt)
    val sum = a + b + c
    if (sum == 0) {
      println(List(s / 3.0, s / 3.0, s / 3.0).mkString(" "))
    }
    else{
    val fs = sum.toDouble
    val (fa, fb, fc) = (s * a / fs, s * b / fs, s * c / fs)
    println(List(fa, fb, fc).mkString(" "))
    }
  }
}

object CF118B {
  def main(args: Array[String]): Unit = {
    val s = readDouble()
    val Array(a, b, c) = readLine().split(" ").map(_.toDouble)
    if (a + b + c == 0) {
      println(s + " 0.0 0.0")
    } else {
      val x = s * (a / (a + b + c))
      val y = s * (b / (a + b + c))
      val z = s * (c / (a + b + c))
      println(x + " " + y + " " + z)
    }
  }
}

object CF118B {
  def main(args: Array[String]): Unit = {
    val s = readInt().doubleValue
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)
    if (a + b + c == 0) {
      println(s + " 0.0 0.0")
    } else {
      val x = s * (a / (a + b + c))
      val y = s * (b / (a + b + c))
      val z = s * (c / (a + b + c))
      println(x + " " + y + " " + z)
    }
  }
}

object CF118B {
  def main(args: Array[String]): Unit = {
    val s = readInt().doubleValue
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)
    val max = List(a, b, c).max
    if (max == a && max == b && max == c){
      println(s / 3 + " " + s / 3 + " " + s / 3)
    } else if (max == a && max == b) {
      println(s / 2 + " " + s / 2 + " " + 0)
    } else if (max == b && max == c) {
      println(0 + " " + s / 2 + " " + s / 2)
    } else if (max == c && max == a) {
      println(s / 2 + " " + 0 + " " + s / 2)
    } else if (max == a) {
      println(s + " " + 0 + " " + 0)
    } else if (max == b) {
      println(0 + " " + s + " " + 0)
    } else if (max == c) {
      println(0 + " " + 0 + " " + s)
    }
  }
}


Given a sequence of integers a1, ..., an and q queries x1, ..., xq on it. For each query xi you have to count the number of pairs (l, r) such that 1 ≤ l ≤ r ≤ n and gcd(al, al + 1, ..., ar) = xi. is a greatest common divisor of v1, v2, ..., vn, that is equal to a largest positive integer that divides all vi.

The first line of the input contains integer n, (1 ≤ n ≤ 105), denoting the length of the sequence. The next line contains n space separated integers a1, ..., an, (1 ≤ ai ≤ 109). The third line of the input contains integer q, (1 ≤ q ≤ 3 × 105), denoting the number of queries. Then follows q lines, each contain an integer xi, (1 ≤ xi ≤ 109).

For each query print the result in a separate line.

import scala.collection._

object D 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)
  val as = readInts(n)

  val cnts = Array.fill(n){ mutable.Map.empty[Int, Long] }

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

  for (i <- as.indices) {
    cnts(i).put(as(i), 1L)
    if (i > 0) {
      for (prev <- cnts(i - 1).keys) {
        val g = gcd(prev, as(i))
        cnts(i).put(g, (if (cnts(i).contains(g)) cnts(i)(g) else 0L) + cnts(i - 1)(prev))
      }
    }
  }

  val totals = mutable.Map.empty[Int, Long]
  for (c <- cnts) {
    for (x <- c.keys) {
      totals.put(x, (if (totals.contains(x)) totals(x) else 0L) + c(x))
    }
  }

  val Array(q) = readInts(1)

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

  for (i <- 0 until q) {
    val x = readLine.toInt
    println(if (totals.contains(x)) totals(x) else 0L)
  }
  Console.flush
}


Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1. Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal — by "and".

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ a1 < a2 < ... < an ≤ 109).

In the first line print a single integer k (k > 0), showing how many numbers to write out. In the second line print k integers b1, b2, ..., bk — the numbers to write out. You are allowed to print numbers b1, b2, ..., bk in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt
  var as = readInts.distinct

  var bit = 1 << 30

  while (bit > 0) {

    val bs = as.filter(a => (a & bit) != 0)

    if (!bs.isEmpty && bs.reduce(_ & _) % bit == 0) {
      println(bs.size)
      println(bs.mkString(" "))
      exit
    }

    bit >>= 1
  }

}

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt
  var as = readInts.distinct

  var threshold = 1 << 30

  while (threshold > 0) {

    val bs = as.filter(a => (a & threshold) != 0)

    if (!bs.isEmpty && bs.reduce((a, b) => a & b) % threshold == 0) {
      println(bs.size)
      println(bs.mkString(" "))
      exit
    }

    threshold /= 2
  }

}

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt
  val MAX = 1000000000
  var as = Array.fill(n)(scala.util.Random.nextInt % MAX)
  //var as = readInts.distinct
  var bs = Seq[Int]()

  var threshold = 1

  while (!as.isEmpty) {

	val remove = mutable.BitSet(as.size)

	var bit = 1
	while (bit < threshold) {
	  if (!as.indices.exists(i => (as(i) & bit) == 0 && !remove(i))) {
	    as.indices.withFilter(i => (as(i) & bit) != 0).foreach(i => remove += i)
	  }
	  bit *= 2
	}

	var bestCount = 0
	var bestBit = 0

	while (bit <= MAX) {
	  val count = as.indices.count(i => (as(i) & bit) != 0 && !remove(i))
	  if (count > bestCount) {
	    bestCount = count
	    bestBit = bit
	  }
	  bit *= 2
	}

	if (bestBit > 0) bs = as.indices.withFilter(i => (as(i) & bestBit) != 0 && !remove(i)).map(i => as(i))

    threshold *= 2
	as = as.filter(_ >= threshold)
  }

  println(bs.size)
  if (n < 100000) println(bs.mkString(" "))
}

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt
  val MAX = 1000000000
  var as = Array.fill(n)(scala.util.Random.nextInt % MAX)
  //var as = readInts.distinct
  var bs = Seq[Int]()

  var threshold = 1

  while (!as.isEmpty) {

	val remove = mutable.BitSet(as.size)

	var bit = 1
	while (bit < threshold) {
	  if (!as.indices.exists(i => (as(i) & bit) == 0 && !remove(i))) {
	    as.indices.withFilter(i => (as(i) & bit) != 0).foreach(i => remove += i)
	  }
	  bit *= 2
	}

	var bestCount = 0
	var bestBit = 0

	while (bit <= MAX) {
	  val count = as.indices.count(i => (as(i) & bit) != 0 && !remove(i))
	  if (count > bestCount) {
	    bestCount = count
	    bestBit = bit
	  }
	  bit *= 2
	}

	if (bestBit > 0) bs = as.indices.withFilter(i => (as(i) & bestBit) != 0 && !remove(i)).map(i => as(i))

    threshold *= 2
	as = as.filter(_ >= threshold)
  }

  println(bs.size)
  //println(bs.mkString(" "))
}


Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a1, a2, ..., an, then after we apply the described operation, the sequence transforms into a1, a2, ..., an[, a1, a2, ..., al] (the block in the square brackets must be repeated c times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.

The first line contains integer m (1 ≤ m ≤ 105) — the number of stages to build a sequence.  Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer xi (1 ≤ xi ≤ 105) — the number to add. Type 2 means copying a prefix of length li to the end ci times, in this case the line further contains two integers li, ci (1 ≤ li ≤ 105, 1 ≤ ci ≤ 104), li is the length of the prefix, ci is the number of copyings. It is guaranteed that the length of prefix li is never larger than the current length of the sequence. The next line contains integer n (1 ≤ n ≤ 105) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print the elements that Sereja is interested in, in the order in which their numbers occur in the input.

import java.util.Scanner

object P380A {
    class SerejaSequence (scanner: Scanner) {
        val m = scanner.nextInt()
        val seq = new Array[Int](m)
        val periods = new Array[Long](m + 1)
        val types = new Array[Int](m)

        for (i <- 0 until m) {
            types(i) = scanner.nextInt()
            if (types(i) == 1) {
                seq(i) = scanner.nextInt()
                periods(i + 1) = periods(i) + 1
            }
            else {
                val l = scanner.nextInt()
                val c = scanner.nextInt()
                seq(i) = l
                periods(i + 1) = periods(i) + l * c
            }
        }

        def apply(i: Long): Int = {
            val pos = java.util.Arrays.binarySearch(periods, i)
            val index = if (pos >= 0) pos else -(pos + 2)
            if (types(index) == 1) {
                seq(index)
            }
            else {
                apply((i - periods(index)) % seq(index))
            }
        }
    }

    def main(args: Array[String]) {
        val scanner = new Scanner(System.in)
        val seq = new SerejaSequence(scanner)
        val n = scanner.nextInt()
        val ans = for (i <- 1 to n) yield seq(scanner.nextLong() - 1)
        println(ans.mkString(" "))
    }
}

object A extends App {

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

  val m = readInt
  val stepPos = Array.ofDim[Long](m)

  val stepA = Array.ofDim[Boolean](m)
  val stepPar = Array.ofDim[Int](m)

  var pos = 0L

  for (i <- 0 until m) {
    val t = tokenizeLine
    val typ = t.nextToken.toInt
    if (typ == 1) {
      stepA(i) = true
      stepPar(i) = t.nextToken.toInt
      pos += 1
      stepPos(i) = pos
    } else {
      val l = t.nextToken.toInt
      val c = t.nextToken.toInt
      stepA(i) = false
      stepPar(i) = l
      pos += l * c
      stepPos(i) = pos
    }
  }

  @annotation.tailrec
  def get(q: Long): Int = {
    var i = java.util.Arrays.binarySearch(stepPos, q)
    if (i < 0) i = -1 - i
    if (stepA(i)) stepPar(i)
    else {
      val l = stepPar(i)
      var q2 = ((q - stepPos(i - 1)) % l)
      if (q2 == 0) q2 = l
      get(q2)
    }
  }

  val n = readInt
  val qs = readLongs(n)
  val ans = qs.map(get)
  println(ans.mkString(" "))
}

object A extends App {

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

  val m = readInt
  val stepPos = Array.ofDim[Long](m)

  val stepA = Array.ofDim[Boolean](m)
  val stepPar = Array.ofDim[Int](m)

  var pos = 0L

  for (i <- 0 until m) {
    val t = tokenizeLine
    val typ = t.nextToken.toInt
    if (typ == 1) {
      stepA(i) = true
      stepPar(i) = t.nextToken.toInt
      pos += 1
      stepPos(i) = pos
    } else {
      val l = t.nextToken.toInt
      val c = t.nextToken.toInt
      stepA(i) = false
      stepPar(i) = l
      pos += l * c
      stepPos(i) = pos
    }
  }

  @annotation.tailrec
  def get(q: Long): Int = {
    var i = java.util.Arrays.binarySearch(stepPos, q)
    if (i < 0) i = -1 - i
    if (stepA(i)) stepPar(i)
    else {
      val l = stepPar(i)
      var q2 = ((q - stepPos(i - 1)) % l)
      if (q2 == 0) q2 = l
      get(q2)
    }
  }

  val n = readInt
  val qs = readLongs(n)
  val ans = qs.map(get)
  println(ans.mkString(" "))
}

import java.util.Scanner

object P380A {
    def main(args: Array[String]) {
        val scanner = new Scanner(System.in)
        val m = scanner.nextInt()
        val list = scala.collection.mutable.ListBuffer[Int]()
        for (stage <- 1 to m) {
            val t = scanner.nextInt()
            if (t == 1) {
                val num = scanner.nextInt()
                list += num
            }
            else {
                val l = scanner.nextInt()
                val c = scanner.nextInt()
                val addList = list.toList.take(l)
                for (i <- 1 to c) list ++= addList
            }
        }
        val n = scanner.nextInt()
        val ans = list.toList.take(n)
        println(ans.mkString(" "))
    }
}


Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

object P8A {
    import io.StdIn._

    def main(args:Array[String]) {
        val (s, s1, s2) = (readLine, readLine, readLine)
        val b1 = (s1 + ".*" + s2).r.findFirstMatchIn(s).nonEmpty
        val (s1r, s2r) = (s1.reverse, s2.reverse)
        val b2 = (s2r + ".*" + s1r).r.findFirstMatchIn(s).nonEmpty
        println(() match {
            case _ if b1 && b2 => "both"
            case _ if b1 => "forward"
            case _ if b2 => "backward"
            case _ => "fantasy"
        })
    }
}

object P7E {
    import io.StdIn._

    def main(args:Array[String]) {
        val (s, s1, s2) = (readLine, readLine, readLine)
        val b1 = (s1 + ".*" + s2).r.findFirstMatchIn(s).nonEmpty
        val (s1r, s2r) = (s1.reverse, s2.reverse)
        val b2 = (s2r + ".*" + s1r).r.findFirstMatchIn(s).nonEmpty
        println(() match {
            case _ if b1 && b2 => "both"
            case _ if b1 => "forward"
            case _ if b2 => "backward"
            case _ => "fantasy"
        })
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val reverse = str.reverse
//  println(reverse)
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val blast = str.lastIndexOf(b1)
  val bfirst = reverse.indexOf(a1)
  val alast = reverse.lastIndexOf(b1)
//  println(afirst)
//  println(blast)
//  println(bfirst)
//  println(alast)

  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = bfirst != -1 && alast != -1 && alast >= bfirst + a1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

//package me.jetblack.codeforces

import java.util.Scanner

object A8Train extends App {

  val scanner = new Scanner(System.in)
  val a = scanner.next()
  val b = scanner.next()
  val c = scanner.next()

  val r1 = solve(a)
  val r2 = solve(a.reverse)

  if (r1 && r2) {
    println("both")
  } else if (r1) {
    println("forward")
  } else if (r2) {
    println("backward")
  } else {
    println("fantasy")
  }

  def solve(s: String): Boolean = {
    s.contains(b) && s.contains(c) && s.replaceFirst(b, "").contains(c) && s.indexOf(b) < s.lastIndexOf(c)
  }

}

object A8 {

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

  def main(args: Array[String]): Unit = {
    val s = read
    val a = read
    val b = read

    val forward = check(s, a, b)
    val backward = check(s.reverse, a, b)

    if(forward && backward) {
      println("both")
    } else if(forward) {
      println("forward")
    } else if(backward) {
      println("backward")
    } else {
      println("fantasy")
    }
  }

  def check(str: String, d: String, e: String): Boolean = {
    val f = str.indexOf(d)
    if(f != -1) {
      if(str.indexOf(e, f+d.length) != -1) {
        true
      } else {
        false
      }
    } else {
      false
    }
  }

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

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object P7E {
    import io.StdIn._

    def main(args:Array[String]) {
        val (s, s1, s2) = (readLine, readLine, readLine)
        val b1 = (s1 + ".*" + s2).r.findFirstMatchIn(s).nonEmpty
        val b2 = (s2 + ".*" + s1).r.findFirstMatchIn(s).nonEmpty
        println(() match {
            case _ if b1 && b2 => "both"
            case _ if b1 => "forward"
            case _ if b2 => "backward"
            case _ => "fantasy"
        })
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val bfirst = str.indexOf(b1)
  val alast = str.lastIndexOf(a1)
  val blast = str.lastIndexOf(b1)
  val here = afirst != -1 && blast != -1 && blast > afirst + a1.length
  val there = alast != -1 && bfirst != -1 && alast > bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val bfirst = str.indexOf(b1)
  val alast = str.lastIndexOf(a1)
  val blast = str.lastIndexOf(b1)
  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = alast != -1 && bfirst != -1 && alast > bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val reverse = str.reverse
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val blast = str.lastIndexOf(b1)
  val bfirst = reverse.length - reverse.indexOf(b1.reverse)
  val alast = reverse.length - reverse.lastIndexOf(a1.reverse)
//  println(bfirst)
//  println(alast)
//  println(bfirst)
//  println(alast)

  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = alast != -1 && bfirst != -1 && alast >= bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val reverse = str.reverse
//  println(reverse)
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val blast = str.lastIndexOf(b1)
  val bfirst = reverse.indexOf(a1)
  val alast = reverse.lastIndexOf(b1)
//  println(afirst)
//  println(blast)
//  println(bfirst)
//  println(alast)

  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = bfirst != -1 && alast != -1 && alast >= bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val reverse = str.reverse
  println(reverse)
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val blast = str.lastIndexOf(b1)
  val bfirst = reverse.indexOf(b1)
  val alast = reverse.lastIndexOf(a1)
//  println(afirst)
//  println(blast)
//  println(bfirst)
//  println(alast)

  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = bfirst != -1 && alast != -1 && alast >= bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val a1 = in.next()
  val b1 = in.next()
  val afirst = str.indexOf(a1)
  val bfirst = str.indexOf(b1)
  val alast = str.lastIndexOf(a1)
  val blast = str.lastIndexOf(b1)
  val here = afirst != -1 && blast != -1 && blast >= afirst + a1.length
  val there = alast != -1 && bfirst != -1 && alast >= bfirst + b1.length
  if (here && there)
    println("both")
  else if (here)
    println("forward")
  else if (there)
    println("backward")
  else
    println("fantasy")
}

object A8 {

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

  def main(args: Array[String]): Unit = {
    val s = read
    val a = read
    val b = read

    def check(str: String, d: String, e: String): Boolean = {
      val f = str.indexOf(d)
      if(f != -1) {
        if(s.indexOf(e, f+a.length) != -1) {
          true
        } else {
          false
        }
      } else {
        false
      }
    }

    val forward = check(s, a, b)
    val backward = check(s.reverse, a, b)

    if(forward && backward) {
      println("both")
    } else if(forward) {
      println("forward")
    } else if(backward) {
      println("backward")
    } else {
      println("fantasy")
    }

  }

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

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object P8A {
    import io.StdIn._

    def main(args:Array[String]) {
        val (s, s1, s2) = (readLine, readLine, readLine)
        val b1 = (s1 + ".*" + s2).r.findFirstMatchIn(s).nonEmpty
        val b2 = (s2 + ".*" + s1).r.findFirstMatchIn(s).nonEmpty
        println(() match {
            case _ if b1 && b2 => "both"
            case _ if b1 => "forward"
            case _ if b2 => "backward"
            case _ => "fantasy"
        })
    }
}


You are given array $$$a_1, a_2, \ldots, a_n$$$, consisting of non-negative integers.Let's define operation of "elimination" with integer parameter $$$k$$$ ($$$1 \leq k \leq n$$$) as follows:  Choose $$$k$$$ distinct array indices $$$1 \leq i_1 < i_2 < \ldots < i_k \le n$$$.  Calculate $$$x = a_{i_1} ~ \& ~ a_{i_2} ~ \& ~ \ldots ~ \& ~ a_{i_k}$$$, where $$$\&$$$ denotes the bitwise AND operation (notes section contains formal definition).  Subtract $$$x$$$ from each of $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$; all other elements remain untouched. Find all possible values of $$$k$$$, such that it's possible to make all elements of array $$$a$$$ equal to $$$0$$$ using a finite number of elimination operations with parameter $$$k$$$. It can be proven that exists at least one possible $$$k$$$ for any array $$$a$$$.Note that you firstly choose $$$k$$$ and only after that perform elimination operations with value $$$k$$$ you've chosen initially.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{30}$$$) — array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.

For each test case, print all values $$$k$$$, such that it's possible to make all elements of $$$a$$$ equal to $$$0$$$ in a finite number of elimination operations with the given parameter $$$k$$$. Print them in increasing order.

NoteIn the first test case:  If $$$k = 1$$$, we can make four elimination operations with sets of indices $$$\{1\}$$$, $$$\{2\}$$$, $$$\{3\}$$$, $$$\{4\}$$$. Since $$$\&$$$ of one element is equal to the element itself, then for each operation $$$x = a_i$$$, so $$$a_i - x = a_i - a_i = 0$$$.  If $$$k = 2$$$, we can make two elimination operations with, for example, sets of indices $$$\{1, 3\}$$$ and $$$\{2, 4\}$$$: $$$x = a_1 ~ \& ~ a_3$$$ $$$=$$$ $$$a_2 ~ \& ~ a_4$$$ $$$=$$$ $$$4 ~ \& ~ 4 = 4$$$. For both operations $$$x = 4$$$, so after the first operation $$$a_1 - x = 0$$$ and $$$a_3 - x = 0$$$, and after the second operation — $$$a_2 - x = 0$$$ and $$$a_4 - x = 0$$$.  If $$$k = 3$$$, it's impossible to make all $$$a_i$$$ equal to $$$0$$$. After performing the first operation, we'll get three elements equal to $$$0$$$ and one equal to $$$4$$$. After that, all elimination operations won't change anything, since at least one chosen element will always be equal to $$$0$$$.  If $$$k = 4$$$, we can make one operation with set $$$\{1, 2, 3, 4\}$$$, because $$$x = a_1 ~ \& ~ a_2 ~ \& ~ a_3 ~ \& ~ a_4$$$ $$$= 4$$$. In the second test case, if $$$k = 2$$$ then we can make the following elimination operations:  Operation with indices $$$\{1, 3\}$$$: $$$x = a_1 ~ \& ~ a_3$$$ $$$=$$$ $$$13 ~ \& ~ 25 = 9$$$. $$$a_1 - x = 13 - 9 = 4$$$ and $$$a_3 - x = 25 - 9 = 16$$$. Array $$$a$$$ will become equal to $$$[4, 7, 16, 19]$$$.  Operation with indices $$$\{3, 4\}$$$: $$$x = a_3 ~ \& ~ a_4$$$ $$$=$$$ $$$16 ~ \& ~ 19 = 16$$$. $$$a_3 - x = 16 - 16 = 0$$$ and $$$a_4 - x = 19 - 16 = 3$$$. Array $$$a$$$ will become equal to $$$[4, 7, 0, 3]$$$.  Operation with indices $$$\{2, 4\}$$$: $$$x = a_2 ~ \& ~ a_4$$$ $$$=$$$ $$$7 ~ \& ~ 3 = 3$$$. $$$a_2 - x = 7 - 3 = 4$$$ and $$$a_4 - x = 3 - 3 = 0$$$. Array $$$a$$$ will become equal to $$$[4, 4, 0, 0]$$$.  Operation with indices $$$\{1, 2\}$$$: $$$x = a_1 ~ \& ~ a_2$$$ $$$=$$$ $$$4 ~ \& ~ 4 = 4$$$. $$$a_1 - x = 4 - 4 = 0$$$ and $$$a_2 - x = 4 - 4 = 0$$$. Array $$$a$$$ will become equal to $$$[0, 0, 0, 0]$$$. Formal definition of bitwise AND:Let's define bitwise AND ($$$\&$$$) as follows. Suppose we have two non-negative integers $$$x$$$ and $$$y$$$, let's look at their binary representations (possibly, with leading zeroes): $$$x_k \dots x_2 x_1 x_0$$$ and $$$y_k \dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of number $$$x$$$, and $$$y_i$$$ is the $$$i$$$-th bit of number $$$y$$$. Let $$$r = x ~ \& ~ y$$$ is a result of operation $$$\&$$$ on number $$$x$$$ and $$$y$$$. Then binary representation of $$$r$$$ will be $$$r_k \dots r_2 r_1 r_0$$$, where:$$$$$$ r_i = \begin{cases} 1, ~ \text{if} ~ x_i = 1 ~ \text{and} ~ y_i = 1 \\ 0, ~ \text{if} ~ x_i = 0 ~ \text{or} ~ y_i = 0 \end{cases} $$$$$$

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

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

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Long](n+1)
        for (i <- 1 to n) {
            arr(i) = readLong()
        }
        var ans = -1
        for (k <- 0 to 32) {
            var cnt = 0
            for (i <- 1 to n) {
                if (arr(i) % 2 == 1)
                    cnt += 1
                arr(i) /= 2L
            }
            if (cnt > 0) {
                if (ans == -1)
                    ans = cnt
                else
                    ans = gcd(ans, cnt)
            }
        }
        if (ans == -1) {
            for (i <- 1 to n) {
                writer.print(i + " ")
            }
        } else {
            for (i <- 1 to n) {
                if (ans % i == 0)
                    writer.print(i + " ")
            }
        }
        writer.println()
    }
    writer.flush()
}


Last year the world's largest square was built in Berland. It is known that the square can be represented as an infinite plane with an introduced Cartesian system of coordinates. On that square two sets of concentric circles were painted. Let's call the set of concentric circles with radii 1, 2, ..., K and the center in the point (z, 0) a (K, z)-set. Thus, on the square were painted a (N, x)-set and a (M, y)-set. You have to find out how many parts those sets divided the square into.

The first line contains integers N, x, M, y. (1 ≤ N, M ≤ 100000,  - 100000 ≤ x, y ≤ 100000, x ≠ y).

import math.max
import math.min
object P040C extends App {
  val param = readLine().split(' ').map(_.toInt)
  var l = param(3) - param(1)
  var n = param(0)
  var m = param(2)
  if (l < 0) {
    l = -l
    n = param(2)
    m = param(0)
  }

  var nr: Long = 0
  for (i <- 1 to n) {
    if (i <= l) {
      val nc = max(0, min(m, l+i-1) - (l-i+1) + 1)
      nr += max(2 * nc - 1, 0)
    }
    else {
      val nc = max(0, min(m, l+i-1) - (i-l) + 1);
      nr += max(2 * (nc -1), 0)
    }
  }
  print(n + m + 1 + nr)
}

import math.max
import math.min
object P040C extends App {
  val param = readLine().split(' ').map(_.toInt)
  var l = param(3) - param(1)
  var n = param(0)
  var m = param(2)
  if (l < 0) {
    l = -l
    n = param(2)
    m = param(0)
  }

  var nr = 0
  for (i <- 1 to n) {
    if (i <= l) {
      val nc = max(0, min(m, l+i-1) - (l-i+1) + 1)
      nr += max(2 * nc - 1, 0)
    }
    else {
      val nc = max(0, min(m, l+i-1) - (i-l) + 1);
      nr += max(2 * (nc -1), 0)
    }
  }
  print(n + m + 1 + nr)
}

import math.max
import math.min
object P040C extends App {
  val param = readLine().split(' ').map(_.toInt)
  var l = param(3) - param(1)
  var n = param(0)
  var m = param(2)
  if (l < 0) {
    l = -l
    n = param(2)
    m = param(0)
  }

  var nr = 0
  for (i <- 1 to n) {
    val nc = max(0, min(m, l+i-1) - max(0, l-i+1) + 1)
    nr += max(2 * nc - 1, 0)
  }
  print(n + m + 1 + nr)
}


Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9.For instance, Inna can alter number 14545181 like this: 14545181 → 1945181 → 194519 → 19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine.Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.

The first line of the input contains integer a (1 ≤ a ≤ 10100000). Number a doesn't have any zeroes.

In a single line print a single integer — the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 263 - 1. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteNotes to the samplesIn the first sample Inna can get the following numbers: 369727 → 99727 → 9997, 369727 → 99727 → 9979.In the second sample, Inna can act like this: 123456789987654321 → 12396789987654321 → 1239678998769321.

object B extends App {

  val as = readLine.map(_ - '0')

  var prev = as.head
  var n = BigInt(1)
  var s = BigInt(0)

  for (a <- as.tail) {
    if (prev + a == 9) s += 1
    else if (s > 0) {
      if (s % 2 == 0) n = n * ((s + 2) / 2)
      s = 0
    }
    prev = a
  }

  if (s > 0 && s % 2 == 0) n = n * ((s + 2) / 2)

  println(n)
}

object B extends App {

  val as = readLine.map(_ - '0')

  var prev = as.head
  var n = 1
  var s = 0

  for (a <- as.tail) {
    if (prev + a == 9) s += 1
    else if (s > 0) {
      if (s % 2 == 0) n *= s
      s = 0
    }
    prev = a
  }

  if (s > 0 && s % 2 == 0) n *= s

  println(n)
}

object B extends App {

  val as = readLine.map(_ - '0')

  var prev = as.head
  var n = 1
  var s = 0

  for (a <- as.tail) {
    if (prev + a == 9) s += 1
    else if (s > 0) {
      n *= s
      s = 0
    }
    prev = a
  }

  if (s > 0) n *= s

  println(n)
}


Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.

First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$  — the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.

For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.

NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.

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

import scala.annotation.tailrec

object A {
  def solve(in: Input, out: PrintWriter): Unit = {
    for (_ <- 0 until in.nextInt()) {
      in.nextInt()
      val str = in.nextToken()
      if (str.length % 2 == 0) {
        out.println(if ((0 until str.length).exists(i => i % 2 == 1 && (str(i) - '0') % 2 == 0)) 2 else 1)
      } else {
        out.println(if ((0 until str.length).exists(i => i % 2 == 0 && (str(i) - '0') % 2 == 1)) 1 else 2)
      }
    }
  }

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("4\n1\n2\n1\n3\n3\n102\n4\n2069", "2\n1\n1\n2", "Sample"),
    ("1\n5\n22222", "2", "T1"),
    ("1\n5\n22122", "1", "T2"),
    ("1\n6\n111111", "1", "T3"),
    ("1\n6\n111112", "2", "T4"),
  )

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

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

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 ans =
      if (n % 2 == 0) {
        val b = an.zipWithIndex.exists { case (a, i) => (i + 1) % 2 == 0 && a % 2 == 0 }
        if (b) 2 else 1
      } else {
        val r = an.zipWithIndex.exists { case (a, i) => (i + 1) % 2 == 1 && a % 2 == 1 }
        if (r) 1 else 2
      }

    println(ans)
  }
}

import scala.collection.mutable.ArrayBuffer

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

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

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

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

    inputLines.times {
      val n       = in.nextInt()
      val digits  = in.nextLine().toString.split("").map(_.toInt)
      val hasOdd  = digits.indices.exists(i => i % 2 == 0 && digits(i) % 2 == 1)
      val hasEven = digits.indices.exists(i => i % 2 == 1 && digits(i) % 2 == 0)

      if ((n % 2 == 0 && !hasEven) || (n % 2 == 1 && hasOdd)) println("1") else println("2")

    }
    /*
    inputLines.times {
      val n      = in.nextInt()
      val digits = in.nextInt()
      if (n % 2 == 0) {
        val nums        = digits.toString.split("").map(_.toInt)
        val hasOddCount = nums.indices.count(i => i % 2 == 1 && nums(i) % 2 == 1)
        if (hasOddCount == (n / 2)) println("1") else println("2")
      } else if (n == 1) {
        if (digits % 2 == 0) {
          println("2")
        } else {
          println("1")
        }
      } else {
        val nums   = digits.toString.split("").map(_.toInt)
        val hasOdd = nums.indices.exists(i => i % 2 == 0 && nums(i) % 2 == 1)
        if (hasOdd) println("1") else println("2")
      }
    }*/
  }

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

  /**
    * Util methods
    */

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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


In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.

The first line contains single integer n (1 ≤ n ≤ 2·105) — the length of the string.

Print the string that satisfies all the constraints. If there are multiple answers, print any of them.

NoteA palindrome is a sequence of characters which reads the same backward and forward.

import java.util.Scanner

object Main {
  val sc = new Scanner(System.in)

  def main(args: Array[String]): Unit = {
    val n = sc.nextInt()
    val res = new StringBuilder()

    for (i <- 1 to n) {
      if (res.size < 2) {
        res.append("a")
      } else {
        val newChar = if (res.charAt(i - 3) == 'a') 'b' else 'a'
        res.append(newChar)
      }
    }

    print(res.toString())
  }
}

object B 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)
  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(("aabb" * (n / 4 + 4)).take(n))

  Console.flush
}

object _805B 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 n = read[Int]
    val phrase = Seq("aab", "baa", "bba", "abb").mkString
    val q = n/phrase.length
    val r = n%phrase.length
    val ans = phrase*q + phrase.take(r)
    //require(ans.sliding(3).forall(s => s != s.reverse))
    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
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  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
      }
    }
  }
}