Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.  Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:let starting_time be an array of length ncurrent_time = 0dfs(v):	current_time = current_time + 1	starting_time[v] = current_time	shuffle children[v] randomly (each permutation with equal possibility)	// children[v] is vector of children cities of city v	for u in children[v]:		dfs(u)As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.

The first line of input contains a single integer n (1 ≤ n ≤ 105) — the number of cities in USC. The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.

In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i]. Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.

import java.io._
import java.util._
import scala.collection.mutable._

object Main extends App {
    def nextInt(): Int = IO.nextInt()

    val n = nextInt()
    val g: Array[ArrayBuffer[Int]] = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer[Int]())
    val p: Array[Int] = Array.fill[Int](n)(0)
    (1 until n).foreach{ i =>
        p(i) = nextInt - 1
        g(p(i)) += i
    }

    val size: Array[Int] = Array.fill[Int](n)(0)
    dfs(0)

    val exp: Array[Double] = Array.fill[Double](n)(1)
    dfs1(0)

    exp.map(i => print(i + " "))
    println("")

    IO.close

    def dfs(v: Int): Int = {
        var ret = 1
        for(i <- g(v)) {
            ret += dfs(i)
        }
        size(v) = ret
        ret
    }

    def dfs1(v: Int) {
        // val sum = g(v).map(i => size(i)).sum
        var sum = 0
        for(i <- g(v)) sum += size(i)
        for(i <- g(v)) {
            exp(i) = exp(p(i)) + 1 + (sum - size(i)).toDouble / 2
            dfs1(i)
        }
    }
}

object IO {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(System.out)
    var str = new StringTokenizer("")

    def next(): String = {
        while(!str.hasMoreElements()) {
            str = new StringTokenizer(in.readLine())
        }
        str.nextToken()
    }

    def nextInt() = next().toInt
    def println(a: AnyVal) = out.println(a)
    def print(a: AnyVal) = out.print(a)

    def close() = {
        in.close()
        out.close()
    }
}

import java.io._
import java.util.Locale
import java.util.StringTokenizer
import scala.collection._

/**
  * @author antipov.
  *         15.07.2016 14:47.
  */
object B extends App {

  def solve() = {
    val n = readInt
    val g = new Array[List[Int]](n)
    (0 until n) foreach (i => g(i) = Nil)

    (1 until n) map (i => {
      val parent = readInt - 1
      g(parent) = i :: g(parent)
    })

    val sizes = new Array[Int](n)
    val res = new Array[Double](n)
    calcSizes(0, sizes);
    calcRes(0, 1, res)

    res foreach (i => print(i + " "))

    def calcSizes(v: Int, res: Array[Int]): Int = {
      res(v) = (g(v) map (ch => calcSizes(ch, res)) sum)
      res(v) + 1
    }

    def calcRes(v: Int, mo: Double, res: Array[Double]): Unit = {
      res(v) = mo
      g(v) foreach (ch => calcRes(ch, mo + 1 + (sizes(v) - (sizes(ch) + 1)) / 2.0, res))
    }
  }

  def readInt(): Int = IO.nextInt

  def readLong(): Long = IO.nextLong

  def println(a: Any) = IO.println(a)

  def print(a: Any) = IO.print(a)

  def printf(locale: Locale, format: String, values: Any*) = IO.printf(locale, format, values)

  solve()
  IO.close
}

object IO {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)
  var tok = new StringTokenizer("")

  def nextToken() = {
    while (!tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine())
    }
    tok.nextToken()
  }

  def nextInt = nextToken().toInt

  def nextLong = nextToken().toLong

  def println(a: Any) = out.println(a)

  def print(a: Any) = out.print(a)

  def printf(locale: Locale, format: String, values: Any*) = out.printf(locale, format, values)

  def close = {
    in.close()
    out.close()
  }
}


The hero is addicted to glory, and is fighting against a monster. The hero has $$$n$$$ skills. The $$$i$$$-th skill is of type $$$a_i$$$ (either fire or frost) and has initial damage $$$b_i$$$. The hero can perform all of the $$$n$$$ skills in any order (with each skill performed exactly once). When performing each skill, the hero can play a magic as follows:   If the current skill immediately follows another skill of a different type, then its damage is doubled.  In other words,   If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$c$$$ damage;  If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type frost, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type frost , then it will deal $$$c$$$ damage. Your task is to find the maximum damage the hero can deal.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$), indicating the number of skills.  The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), where $$$a_i$$$ indicates the type of the $$$i$$$-th skill. Specifically, the $$$i$$$-th skill is of type fire if $$$a_i = 0$$$, and of type frost if $$$a_i = 1$$$.  The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$), where $$$b_i$$$ indicates the initial damage of the $$$i$$$-th skill.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the maximum damage the hero can deal.

NoteIn the first test case, we can order the skills by $$$[3, 1, 4, 2]$$$, and the total damage is $$$100 + 2 \times 1 + 2 \times 1000 + 10 = 2112$$$.In the second test case, we can order the skills by $$$[1, 4, 2, 5, 3, 6]$$$, and the total damage is $$$3 + 2 \times 6 + 2 \times 4 + 2 \times 7 + 2 \times 5 + 2 \times 8 = 63$$$.In the third test case, we can order the skills by $$$[1, 2, 3]$$$, and the total damage is $$$1000000000 + 1000000000 + 1000000000 = 3000000000$$$.In the fourth test case, there is only one skill with initial damage $$$1$$$, so the total damage is $$$1$$$.

import scala.util.Sorting.quickSort
import scala.math.Ordered.orderingToOrdered

object Main {

    class Hero(var x: Int = 0, var y: Int = 0) extends Ordered[Hero] {

        def compare(that: Hero): Int = (that.y, this.x) compare (this.y, that.x)

        override def toString: String =
            s"($x, $y)"
    }

    def main(args:Array[String]): Unit = {
        var t = io.StdIn.readInt()

        def loopts(ts: Int): Int = {
            if ( ts < t ){
                var n = io.StdIn.readInt()

                var arrt:Array[Hero] = new Array[Hero](n)
                var a:Array[Int] = io.StdIn.readLine().split(" ").map(_.toInt)
                var b:Array[Int] = io.StdIn.readLine().split(" ").map(_.toInt)

                for ( i <- 0 until n )
                    arrt(i) = new Hero(a(i), b(i))

                quickSort[Hero](arrt)(Ordering[Hero])

                var Array(cnt0, cnt1) = {
                    def count(i: Int, cnt0: Int, cnt1: Int): Array[Int] = {
                        if ( i < n ){
                            if ( arrt(i).x == 0 )
                                count(i+1, cnt0+1, cnt1)
                            else
                                count(i+1, cnt0, cnt1+1)
                        }
                        else
                            Array(cnt0, cnt1)
                    }
                    count(0, 0, 0)
                }

                def solve(i: Int, cnt0: Int, cnt1: Int, acc: Long): Long = {
                    if ( i < n ){
                        if ( arrt(i).x == 0 && cnt0+cnt1 > 1 ){
                            if ( cnt1 > 0 )
                                solve(i+1, cnt0, cnt1-1, acc+2*arrt(i).y)
                            else
                                solve(i+1, cnt0, cnt1, acc+arrt(i).y)
                        }
                        else {
                            if ( cnt0 > 0 && cnt0+cnt1 > 1 )
                                solve(i+1, cnt0-1, cnt1, acc+2*arrt(i).y)
                            else
                                solve(i+1, cnt0, cnt1, acc+arrt(i).y)
                        }
                    }
                    else
                        acc
                }
                println(solve(0, cnt0, cnt1, 0))

                loopts(ts+1)
            }
            else
                0
        }

        loopts(0)
    }

}

object _1738A extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val n = io.nextInt()
    val isFrost = Seq.fill(n)(io.nextBool())
    val damages = Seq.fill(n)(io.nextLong())

    val all = isFrost.zip(damages).toMultiMap.mapValues(_.sorted(desc[Long])).withDefaultValue(Nil)

    var ans = all(true).zipAll(all(false), 0L, 0L) sumWith {
      case (frost, fire) if frost > 0 && fire > 0 => 2*(frost + fire)
      case (frost, fire) => frost + fire
    }

    if (all(true).length == all(false).length)
      ans -= damages.min

    io.printLine(ans)
  }

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C]).withDefaultValue(b().result())
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B =
      t.foldLeft(n.zero)({ case (c, x) => n.plus(c, f(x)) })
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

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

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

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

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

import scala.util.Sorting.quickSort
import scala.math.Ordered.orderingToOrdered

object Main {

    class Hero(var x: Int = 0, var y: Int = 0) extends Ordered[Hero] {

        def compare(that: Hero): Int = (that.x, this.y) compare (this.x, that.y)

        override def toString: String =
            s"($x, $y)"
    }

    def main(args:Array[String]): Unit = {
        var t = io.StdIn.readInt()

        def loopts(ts: Int): Int = {
            if ( ts < t ){
                var n = io.StdIn.readInt()

                var arrt:Array[Hero] = new Array[Hero](n)
                var a:Array[Int] = io.StdIn.readLine().split(" ").map(_.toInt)
                var b:Array[Int] = io.StdIn.readLine().split(" ").map(_.toInt)

                var min: Int = 10^9
                for ( i <- 0 until n ){
                    arrt(i) = new Hero(a(i), b(i))
                    if ( min > b(i) )
                        min = b(i)
                }

                quickSort[Hero](arrt)(Ordering[Hero].reverse)

                var Array(cnt0, cnt1) = {
                    def count(i: Int, cnt0: Int, cnt1: Int): Array[Int] = {
                        if ( i < n ){
                            if ( arrt(i).x == 0 )
                                count(i+1, cnt0+1, cnt1)
                            else
                                count(i+1, cnt0, cnt1+1)
                        }
                        else
                            Array(cnt0, cnt1)
                    }
                    count(0, 0, 0)
                }

                def solve(i: Int, acc: Long): Long = {
                    if ( i < n ){
                        if ( cnt0 < cnt1 ){
                            if ( arrt(i).x == 0 || i < 2*cnt0 )
                                solve(i+1, acc+2*arrt(i).y)
                            else
                                solve(i+1, acc+arrt(i).y)
                        }
                        else {
                            if ( arrt(i).x == 1 || i < cnt1 )
                                solve(i+1, acc+2*arrt(i).y)
                            else
                                solve(i+1, acc+arrt(i).y)
                        }
                    }
                    else
                        if ( cnt0 != cnt1 )
                            acc
                        else
                            acc - min
                }
                println(solve(0, 0))
                loopts(ts+1)
            }
            else
                0
        }

        loopts(0)
    }

}


You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.

Print minimal r so that each city will be covered by cellular network.

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

  var max = 0
  var i = 0
  var j = 0

  while (i < a.length && j < b.length && a(i) < b(0)) {
    max = Math.max(max, b(0) - a(i))
    i += 1
  }

  j += 1

  while (i < a.length && j < b.length) {
    while (i < a.length && a(i) < b(j)) {
      max = Math.max(max, Math.min(a(i) - b(j - 1), b(j) - a(i)))
      i += 1
    }
    j += 1
  }

  while (i < a.length) {
    max = Math.max(max, a(i) - b(m - 1))
    i += 1
  }

  println(max)

}


You have to restore the wall. The wall consists of $$$N$$$ pillars of bricks, the height of the $$$i$$$-th pillar is initially equal to $$$h_{i}$$$, the height is measured in number of bricks. After the restoration all the $$$N$$$ pillars should have equal heights.You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is $$$A$$$; remove a brick from the top of one non-empty pillar, the cost of this operation is $$$R$$$; move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $$$M$$$.You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $$$0$$$.What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?

The first line of input contains four integers $$$N$$$, $$$A$$$, $$$R$$$, $$$M$$$ ($$$1 \le N \le 10^{5}$$$, $$$0 \le A, R, M \le 10^{4}$$$) — the number of pillars and the costs of operations. The second line contains $$$N$$$ integers $$$h_{i}$$$ ($$$0 \le h_{i} \le 10^{9}$$$) — initial heights of pillars.

Print one integer — the minimal cost of restoration.

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    n = ni()
    a = ni()
    r = ni()
    m = ni()
    h = na(n)

    var lo = 0L
    var hi = 1e10.toLong
    while (hi - lo > 2) {
      val md1 = lo + (hi - lo) / 3
      val md2 = lo + 2 * (hi - lo) / 3
      if(cost(md1) > cost(md2)) lo = md1
      else hi = md2
    }

    var ans = Long.MaxValue
    lo to hi foreach { i =>
      ans = Math.min(cost(i), ans)
    }
    out.println(ans)
  }

  def cost(fh: Long): Long = {
    var req = 0L
    var extra = 0L
    REP(n) { i =>
      if(fh > h(i)) req += (fh - h(i))
      else if (fh < h(i)) extra += (h(i) - fh)
    }
    val x = Math.min(req, extra)
//    out.println(fh + " " + req + " " + extra + " " + (x * Math.min(m, a+r) + (req - x) * a + (extra - x) * r))
    x * Math.min(m, a+r) + (req - x) * a + (extra - x) * r
  }

  var n: Int = _
  var a: Int = _
  var r: Int = _
  var m: Int = _
  var h: Array[Int] = _
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    n = ni()
    a = ni()
    r = ni()
    m = ni()
    h = na(n)

    var lo = 0
    var hi = 2 * 1e5.toInt
    while (hi - lo > 2) {
      val md1 = lo + (hi - lo) / 3
      val md2 = lo + 2 * (hi - lo) / 3
      if(cost(md1) > cost(md2)) lo = md1
      else hi = md2
    }

    var ans = Long.MaxValue
    lo to hi foreach { i =>
      ans = Math.min(cost(i), ans)
    }
    out.println(ans)
  }

  def cost(fh: Int): Long = {
    var req = 0
    var extra = 0
    REP(n) { i =>
      if(fh > h(i)) req += (fh - h(i))
      else if (fh < h(i)) extra += (h(i) - fh)
    }
    val x = Math.min(req, extra).toLong
    x * Math.min(m, a+r) + (req - x) * a + (extra - x) * r
  }

  var n: Int = _
  var a: Int = _
  var r: Int = _
  var m: Int = _
  var h: Array[Int] = _
}


Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.A position is good if two conditions hold:   there is no actor in the cell the spotlight is placed to;  there is at least one actor in the direction the spotlight projects. Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the plan. The next n lines contain m integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.

Print one integer — the number of good positions for placing the spotlight.

NoteIn the first example the following positions are good:  the (1, 1) cell and right direction;  the (1, 1) cell and down direction;  the (1, 3) cell and left direction;  the (1, 3) cell and down direction;  the (1, 4) cell and left direction;  the (2, 2) cell and left direction;  the (2, 2) cell and up direction;  the (2, 2) and right direction;  the (2, 4) cell and left direction. Therefore, there are 9 good positions in this example.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val lines = in.take(n).map(_.split(' ').map(_.toInt)).toArray
  val rightToLeft = lines.map{line =>
    if (line.contains(1)) {
      m - 2 * line.count(_ == 1) + (line.lastIndexOf(1) - line.indexOf(1) + 1)
    }
    else 0
  }.sum
  val vertical = lines.transpose.map{line =>
    if (line.contains(1)) {
      n - 2 * line.count(_ == 1) + (line.lastIndexOf(1) - line.indexOf(1) + 1)
    }
    else 0
  }.sum

  println(rightToLeft + vertical)

}


Dreamoon is a big fan of the Codeforces contests.One day, he claimed that he will collect all the places from $$$1$$$ to $$$54$$$ after two more rated contests. It's amazing!Based on this, you come up with the following problem:There is a person who participated in $$$n$$$ Codeforces rounds. His place in the first round is $$$a_1$$$, his place in the second round is $$$a_2$$$, ..., his place in the $$$n$$$-th round is $$$a_n$$$.You are given a positive non-zero integer $$$x$$$.Please, find the largest $$$v$$$ such that this person can collect all the places from $$$1$$$ to $$$v$$$ after $$$x$$$ more rated contests.In other words, you need to find the largest $$$v$$$, such that it is possible, that after $$$x$$$ more rated contests, for each $$$1 \leq i \leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.For example, if $$$n=6$$$, $$$x=2$$$ and $$$a=[3,1,1,5,7,10]$$$ then answer is $$$v=5$$$, because if on the next two contest he will take places $$$2$$$ and $$$4$$$, then he will collect all places from $$$1$$$ to $$$5$$$, so it is possible to get $$$v=5$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains two integers $$$n, x$$$ ($$$1 \leq n, x \leq 100$$$). The second line contains $$$n$$$ positive non-zero integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$).

For each test case print one line containing the largest $$$v$$$, such that it is possible that after $$$x$$$ other contests, for each $$$1 \leq i \leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.

NoteThe first test case is described in the statement.In the second test case, the person has one hundred future contests, so he can take place $$$1,2,\ldots,99$$$ and place $$$101$$$ on them in some order, to collect places $$$1,2,\ldots,101$$$.

object A extends App {
  class Rank private (val x: Int, val as: List[Int])

  object Rank {
    def apply(x: Int, as: List[Int]): Rank = new Rank(x, as.distinct.sorted)
    def unapply(rank: Rank): Option[(Int, List[Int])] = Some(rank.x, rank.as)
  }

  private def possible(r: Rank): Int = {
    val Rank(x, as) = r

    val t = as.foldLeft((0, x)) {
      case ((i, x), j) =>
        if (i + 1 + x >= j) (j, x - math.min(x, j - i - 1))
        else (i + x, 0)
    }

    t._1 + t._2
  }

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

  val input: List[Rank] = (0 until t)
    .foldLeft(List.empty[Rank]) {
      case (rs, _) =>
        val Array(_, x) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

        Rank(x, as) :: rs
    }
    .reverse

  val output = input.map(possible)

  output.foreach(println)
}

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

  override def solve(io: IO) = io.repeat {
    val n, x = io.read[Int]
    val as = io.read[Set, Int](n)
    val ans = Iterator.from(1)
      .filterNot(as)
      .drop(x)
      .dropWhile(as)
      .next()
    io.write(ans - 1)
  }
}
/****************************[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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    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)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    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 {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  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: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object A extends App {
  class Rank private (val x: Int, val as: List[Int])

  object Rank {
    def unapply(rank: Rank): Option[(Int, List[Int])] = Some(rank.x, rank.as)

    def apply(x: Int, as: List[Int]): Rank = new Rank(x, as.distinct.sorted)
  }

  private def possible(r: Rank): Int = {
    val Rank(x, as) = r

    val t = as.foldLeft((0, x)) { case ((i, x), j) =>
      if (x == 0) (i, x)
      else (if (i + x >= j - 1) j else i + x, x - math.min(x, j - i - 1))
    }

    t._1 + t._2
  }

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

  val input: List[Rank] = (0 until t).foldLeft(List.empty[Rank]) {
    case (rs, _) =>
      val Array(_, x) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

      Rank(x, as) :: rs
  }.reverse

  val output = input.map(possible)

  output.foreach(println)
}


Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed k hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.Vasya has a train lighting schedule for all n hours of the trip — n numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose k hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.

The first input line contains two integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n) — the number of hours on the train and the number of hours to read, correspondingly. The second line contains n space-separated integers ai (0 ≤ ai ≤ 100), ai is the light level at the i-th hour.

In the first output line print the minimum light level Vasya will read at. In the second line print k distinct space-separated integers b1, b2, ..., bk, — the indexes of hours Vasya will read at (1 ≤ bi ≤ n). The hours are indexed starting from 1. If there are multiple optimal solutions, print any of them. Print the numbers bi in an arbitrary order.

NoteIn the first sample Vasya should read at the first hour (light 20), third hour (light 30) and at the fourth hour (light 40). The minimum light Vasya will have to read at is 20.

object Solution extends App {
  val in = scala.io.Source.fromFile("input.txt").getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val sor = data.sorted.drop(n - k)
  var sorted = sor.foldLeft(Map.empty[Int, Int]) {
    case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))
  }
  val res = data.indices.filter{
    j => if (sorted.getOrElse(data(j), 0) != 0) {
      sorted += (data(j) -> (sorted(data(j)) - 1))
      true
    } else {
      false
    }
  }
  import java.io.{File, PrintWriter}

  val writer = new PrintWriter(new File("output.txt"))
  writer.write(sor.head + "\n" + res.map(_ + 1).mkString(" "))
  writer.close()
}

object Solution {
  import scala.io.Source
  import java.io.PrintWriter

  def main(args:Array[String]) {
    val it = Source.fromFile("input.txt").getLines
    val List(n, k) = it.next.split(' ').map(_.toInt).toList
    val hours = it.next.split(' ').map(_.toInt).toArray
    val a = hours.sorted.drop(n-k)
    val min = a.head
    val min_count = a.takeWhile(_ == min).size
    var c = 0
    val reading = (1 to n).view.filter { i =>
      val light = hours(i-1)
      if (light > min) {
        true
      } else if (light == min && c < min_count) {
        c += 1
        true
      } else {
        false
      }

    }.mkString(" ")

    val out = new PrintWriter("output.txt")
    out.println(min)
    out.println(reading)
    out.close
  }
}

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

object Olymp{
  def main(args: Array[String]): Unit = {
    val it = Source.fromFile("input.txt").getLines
    val List(n, k) = it.next.split(' ').toList.map(s => s.toInt)
    val intensity: List[Int] = it.next.split(' ').toList.map(s => s.toInt)
    val solution = (intensity zip (0 to n-1 toList)).sort((a, b) => a._1 > b._1).take(k)
    val writer = new PrintWriter(new File("output.txt" ))
    writer.print(solution.minBy(elem => elem._1)._1+"\n")
    solution.foreach(elem => writer.print((elem._2+1)+" "))
    writer.close()
  }
}

object Solution extends App {
  val in = scala.io.Source.fromFile("input.txt").getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val sor = data.sorted.drop(n - k)
  var sorted = sor.foldLeft(Map.empty[Int, Int]) {
    case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))
  }
  val res = data.indices.filter{
    j => if (sorted.getOrElse(data(j), 0) != 0) {
      sorted += (data(j) -> (sorted(data(j)) - 1))
      true
    } else {
      false
    }
  }
  import java.io.{File, PrintWriter}

  val writer = new PrintWriter(new File("output.txt"))
  writer.write(sor.head)
  writer.write(res.map(_ + 1).mkString(" "))
  writer.close()
}

object Solution extends App {
  val in = scala.io.Source.fromFile("input.txt").getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val sor = data.sorted.drop(n - k)
  var sorted = sor.drop(n - k).foldLeft(Map.empty[Int, Int]) {
    case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))
  }
  val res = data.indices.filter{
    j => if (sorted.getOrElse(data(j), 0) != 0) {
      sorted += (data(j) -> (sorted(data(j)) - 1))
      true
    } else {
      false
    }
  }
  import java.io.{File, PrintWriter}

  val writer = new PrintWriter(new File("output.txt"))
  writer.write(sor.head)
  writer.write(res.map(_ + 1).mkString(" "))
  writer.close()
}

object Solution extends App {
  println("her")
  val in = scala.io.Source.stdin.getLines()
  // val Array(n, k) = in.next().split(" ").map(_.toInt)
  // val data = in.next().split(" ").map(_.toInt)
//  var sorted = data.sorted.drop(n - k).foldLeft(Map.empty[Int, Int]) {
//    case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))
//  }
//  val res = data.indices.filter{
//    j => if (sorted.getOrElse(data(j), 0) != 0) {
//      sorted += (data(j) -> (sorted(data(j)) - 1))
//      true
//    } else {
//      false
//    }
//  }
//  println(res.map(_ + 1).mkString(" "))
}

object Solution extends App {
  println("her")
}

object Solution extends App {
  val in = scala.io.Source.fromFile("input.txt").getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  var sorted = data.sorted.drop(n - k).foldLeft(Map.empty[Int, Int]) {
    case(acc, el) => acc + (el -> (acc.getOrElse(el, 0) + 1))
  }
  val res = data.indices.filter{
    j => if (sorted.getOrElse(data(j), 0) != 0) {
      sorted += (data(j) -> (sorted(data(j)) - 1))
      true
    } else {
      false
    }
  }
  import java.io.{File, PrintWriter}

  val writer = new PrintWriter(new File("output.txt"))
  writer.write(res.map(_ + 1).mkString(" "))
  writer.close()
}

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

object Olymp{
  def main(args: Array[String]): Unit = {
    val it = Source.fromFile("input.txt").getLines
    val List(n, k) = it.next.split(' ').toList.map(s => s.toInt)
    val intensity: List[Int] = it.next.split(' ').toList.map(s => s.toInt)
    val solution = (intensity zip (0 to n-1 toList)).sort((a, b) => a._1 > b._1).take(k)
    val writer = new PrintWriter(new File("output.txt" ))
    writer.print(solution.minBy(elem => elem._1)._1+"\n")
    solution.foreach(elem => writer.print((elem._2+1)+" "))
    writer.print("\n")
  }
}

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

object Olymp{
  def main(args: Array[String]): Unit = {
    val it = Source.fromFile("input.txt").getLines
    val List(n, k) = it.next.split(' ').toList.map(s => s.toInt)
    val intensity: List[Int] = it.next.split(' ').toList.map(s => s.toInt)
    val solution = (intensity zip (0 to n-1 toList)).sort((a, b) => a._1 > b._1).take(k)
    val writer = new PrintWriter(new File("output.txt" ))
    writer.print(solution.minBy(elem => elem._1)._1+"\n")
    solution.foreach(elem => writer.print((elem._2+1)+" "))
  }
}


Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.Petya can ask questions like: "Is the unknown number divisible by number y?".The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers yi, he should ask the questions about.

A single line contains number n (1 ≤ n ≤ 103).

Print the length of the sequence of questions k (0 ≤ k ≤ n), followed by k numbers — the questions yi (1 ≤ yi ≤ n). If there are several correct sequences of questions of the minimum length, you are allowed to print any of them.

NoteThe sequence from the answer to the first sample test is actually correct.If the unknown number is not divisible by one of the sequence numbers, it is equal to 1.If the unknown number is divisible by 4, it is 4.If the unknown number is divisible by 3, then the unknown number is 3.Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter.

import scala.io.StdIn._

object CF576A extends App {
  val n = readInt()

  def ints(n: Int): Stream[Int] =
    Stream.cons(n, ints(n + 1))

  def primes(nums: Stream[Int]): Stream[Int] =
    Stream.cons(nums.head,
      primes((nums tail) filter (x => x % nums.head != 0)))

  def powers(i: Int, n: Int): List[Int] = {
    def rec(q: Int, l: List[Int]): List[Int] =
      if (q <= n / i) rec(q * i, q * i :: l)
      else l

    rec(1, List.empty)
  }

//  println(powers(2, n))

  val r = if (n == 1) List.empty
  else
    primes(ints(2))
      .takeWhile(_ <= n)
      .map(powers(_, n))
      .reduce(_ ++ _)

  println(r.size)
  r.foreach(i => {
    print(i)
    print(" ")
  })
  println()
}

import scala.io.StdIn._

object CF576A extends App {
  val n = readInt()

  def ints(n: Int): Stream[Int] =
    Stream.cons(n, ints(n + 1))

  def primes(nums: Stream[Int]): Stream[Int] =
    Stream.cons(nums.head,
      primes((nums tail) filter (x => x % nums.head != 0)))

  def powers(i: Int): List[Int] = {
    def rec(q: Int, l: List[Int]): List[Int] =
      if (q <= n / i) rec(q * i, q * i :: l)
      else l

    rec(1, List.empty)
  }

  val r = primes(ints(2))
    .takeWhile(_ <= n)
    .map(powers)
    .foldLeft(List.empty[Int]) { _ ++ _ }

  println(r.size)
  println(r.mkString(" "))
}

import scala.io.StdIn._
import scala.collection.Iterator._
import scala.language.postfixOps

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val prime: Array[Boolean] = Array.ofDim(n + 1)
    //for (val i <- 0 to n - 1)
    prime(0) = true
    prime(1) = true
    for {
      i <- 2 to n
      if !prime(i)
      j <- i * 2 to n by i
    } prime(j) = true
    val it =
    {
      for {
        i <- 2 to n
        if !prime(i)
        j <- iterate(i)(_*i) takeWhile (_ <= n)
      } yield j
    }
    println(it length)
    it foreach(printf(" %d", _:Int))
  }
}

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

  val n = in.next().toInt
  val prime = Array.fill[Boolean](n + 1)(true)
  (2 to n).foreach { i =>
    if (prime(i)) {
      (2 * i to n by i).foreach { j => prime(j) = false}
    }
  }

  var answer = List.empty[Int]
  (2 to n).foreach { i =>
    if (prime(i)) {
      var q = 1
      while (q <= n / i) {
        q *= i
        answer ::= q
      }
    }
  }

  println(answer.length)
  println(answer.mkString(" "))

}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val x = allPrimes(n)
    val y = x.flatMap{ f =>
      Stream.iterate(f)(f*) takeWhile(n>=) toList
    }.toSet
    out.println(y.size)
    out.println(y.mkString(" "))
  }

  def allPrimes(n: Int): Array[Int] = {
    val mrk = Array.fill[Boolean](n+1)(false)
    mrk(0) = true; mrk(1) = true
    REP(n+1) { i =>
      if(i > 1) {
        if(!mrk(i)) {
          i * 2 until (n+1) by i foreach(mrk(_) = true)
        }
      }
    }
    mrk.zipWithIndex.filter(p => !p._1).map(_._2)
  }
}

object A576 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val res = cu.ArrayBuffer.empty[Int]
    val vis = Array.fill(n+1)(false)
    vis(0) = true
    vis(1) = true
    var i = 2
    while(i <= n) {
      if(!vis(i)) {
        for(j <- vis.indices)
          if(i*j <= n)
            vis(i*j) = true
        res.append(i)

        var k = i*i
        while(k <= n) {
          vis(k) = true
          res.append(k)
          k *= i
        }
      }
      i += 1
    }
    println(res.length)
    println(res.mkString(" "))
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

import scala.io.StdIn._

object Solution {
    def main( args : Array[String]) {
        val n = readInt
        val prime = Array.fill[Boolean](1005)(true)
        var x = 0 ; var y = 0
        var iset = Set.empty[Int]
        for (x <- 2 to n)
        {
            if(prime(x)==true)
            {
                for(y <- 2*x to n by x)prime(y)=false
                y=x
                while (y<=n)
                {
                    iset = iset + y
                    y = y * x
                }
            }
        }
        println(iset.size)
        iset.foreach(r => printf("%d ", r))
        println()
    }
}

//package round319.c

import java.util.Scanner

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

  val n = sc.nextInt

  def ints(n: Int): Stream[Int] =
    Stream.cons(n, ints(n + 1))

  def primes(nums: Stream[Int]): Stream[Int] =
    Stream.cons(nums.head, primes((nums tail) filter (x => x % nums.head != 0)))

  val pp = primes(ints(2)) take 1000 toList

  def isPrime(x: Int): Boolean = {
    pp.contains(x)
  }

  def isPowerOfPrime(x: Int): Boolean = {
    pp.find(x % _ == 0) match {
      case None => false
      case Some(p) =>
        var xx = x
        var res = true
        while(xx != 1) {
          if(xx % p == 0) {
            xx /= p
          } else {
            res = false
            xx = 1
          }
        }
        res
    }
  }

  var divisors = Vector.empty[Int]

  for (i <- 2 to n) {
    if (isPrime(i) || isPowerOfPrime(i)) {
      divisors = divisors :+ i
    }
  }
  println(divisors.size)
  divisors.foreach(d => print(d + " "))

}

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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object C {

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

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

  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 nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val set = new mutable.HashSet[Int]()
    for (i <- 2 to n) {
      val smallSet = new Array[Int](1001)
      var x = i
      for (j <- 2 to Math.sqrt(i).toInt + 1) {
        while (x % j == 0) {
          smallSet(j) += 1
          x /= j
        }
      }
      if (x > 1) {
        smallSet(x) += 1
      }
      var sum = 0
      for (j <- 0 until smallSet.length) {
        sum += smallSet(j)
      }
      if (sum == 1 || sum == 0) {
        set += i
      } else {
        var ind = 0
        var flag = true
        while (ind < smallSet.length && flag) {
          if (smallSet(ind) > 1) {
            if (!set.contains(Math.pow(ind, smallSet(ind)).toInt)) {
              set += i
              flag = false
            }
          }
          ind += 1
        }
      }
    }
    out.println(set.size)
    set.foreach(x => out.print(s"$x "))
    return 0
  }
}

import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
  val n = sc.nextInt

  val sv =
    (0 to n)
      .toArray

    sv
      .foreach(num => {
        if (num > 1) {
          (num to n by num).tail.foreach(a => sv(a) = 0)
        }
      })

  val a1 =
    sv
      .filter(_ > 1)
      .flatMap(a => {
        val p = (math.log(n) / math.log(a)).toInt
        val t = (1 to p).toArray

        t.foreach(x => t(x - 1) = if (x == 1) a else a * t(x - 2))
        t
      })

  println(a1.size)
  if (a1.nonEmpty)
    println(a1.mkString(" "))
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._

object C extends App {

  val n = readLine().toInt

  val answer = new ArrayBuffer[Int]()

  if (n == 1) {
    println(0)
  } else if (n == 2) {
    println(1)
    println(2)
  } else {
    val C = Array.ofDim[Int](n + 1)
    for (i <- 2 to n) C(i) = i

    var div = 2
    var isDiv = true
    while (div <= n) {
      isDiv = false
      var first = true
      for {
        j <- 2 to n
      } {
        if (C(j) > 1 && C(j) % div == 0) {
          isDiv = true
          C(j) /= div
          if (first) {
            answer += j
            first = false
          }
        }
      }

      if (!isDiv) {
        div += 1
      }
    }

    println(answer.length)
    println(answer.mkString(" "))

  }
}

import scala.io.StdIn._

object CF576A extends App {
  val n = readInt()

  def ints(n: Int): Stream[Int] =
    Stream.cons(n, ints(n + 1))

  def primes(nums: Stream[Int]): Stream[Int] =
    Stream.cons(nums.head,
      primes((nums tail) filter (x => x % nums.head != 0)))

  def powers(i: Int, n: Int): List[Int] = {
    def rec(i: Int, n: Int, l: List[Int]): List[Int] =
      if (i > n) l.drop(1)
      else rec(i * i, n, i * i :: l)

    rec(i, n, List(i))
  }

  val r = if (n == 1) List(1)
  else
    primes(ints(2))
      .takeWhile(_ <= n)
      .map(powers(_, n))
      .reduce(_ ++ _)

  println(r.size)
  r.foreach(i => {
    print(i)
    print(" ")
  })
  println()
}

import scala.io.StdIn._

object CF576A extends App {
  val n = readInt()

  def ints(n: Int): Stream[Int] =
    Stream.cons(n, ints(n + 1))

  def primes(nums: Stream[Int]): Stream[Int] =
    Stream.cons(nums.head,
      primes((nums tail) filter (x => x % nums.head != 0)))

  def powers(i: Int, n: Int): List[Int] = {
    def rec(i: Int, n: Int, l: List[Int]): List[Int] =
      if (i > n) l.drop(1)
      else rec(i * i, n, i * i :: l)

    rec(i, n, List(i))
  }

  val r = if (n == 1) List.empty
  else
    primes(ints(2))
      .takeWhile(_ <= n)
      .map(powers(_, n))
      .reduce(_ ++ _)

  println(r.size)
  r.foreach(i => {
    print(i)
    print(" ")
  })
  println()
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val x = allPrimes(n)
    val y = x.flatMap{ f =>
      Stream.iterate(f)(f*) takeWhile(n>=) toList
    }.toSet
    out.println(y.size)
    out.println(y.mkString(","))
  }

  def allPrimes(n: Int): Array[Int] = {
    val mrk = Array.fill[Boolean](n+1)(false)
    mrk(0) = true; mrk(1) = true
    REP(n+1) { i =>
      if(i > 1) {
        if(!mrk(i)) {
          i * 2 until (n+1) by i foreach(mrk(_) = true)
        }
      }
    }
    mrk.zipWithIndex.filter(p => !p._1).map(_._2)
  }
}

import scala.io.StdIn._

object Solution {
    def main( args : Array[String]) {
        val n = readInt
        val prime = Array.fill[Boolean](1005)(true)
        var x = 0 ; var y = 0
        var iset = Set.empty[Int]
        for (x <- 2 to n)
        {
            if(prime(x)==true)
            {
                for(y <- 2*x to n by x)prime(y)=false
                y=x
                while (y<=x)
                {
                    iset = iset + y
                    y = y * x
                }
            }
        }
        println(iset.size)
        iset.foreach(r => printf("%d ", r))
        println()
    }
}

//package round319.c

import java.util.Scanner

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

  val n = sc.nextInt

  def ints(n: Int): Stream[Int] =
    Stream.cons(n, ints(n+1))

  def primes(nums: Stream[Int]): Stream[Int] =
    Stream.cons(nums.head, primes ((nums tail) filter (x => x % nums.head != 0)) )

  val pp = primes(ints(2)) take 1000 toList

  def isPowerOf2(x: Int): Boolean = {
    (x & (x - 1)) == 0
  }

  def isPrime(x: Int): Boolean = {
    pp.contains(x)
  }

  var divisors = Vector.empty[Int]

  if(n == 1) {
    println("0")
  } else if (n == 2) {
    println("1")
    println("2")
  } else {
    for(i <- 2 to n) {
      if(isPowerOf2(i) || isPrime(i)) {
        divisors = divisors :+ i
      }
    }
    println(divisors.size)
    divisors.foreach(d => print(d + " "))
  }

}

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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object C {

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

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

  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 nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val set = new mutable.HashSet[Int]()
    for (i <- 2 to n) {
      val smallSet = new Array[Int](1001)
      var x = i
      for (j <- 2 to Math.sqrt(i).toInt + 1) {
        while (x % j == 0) {
          smallSet(j) += 1
          x /= j
        }
      }
      if (x > 1) {
        smallSet(x) += 1
      }
      var sum = 0
      for (j <- 0 until smallSet.length) {
        sum += smallSet(j)
      }
      if (sum == 1 || sum == 0) {
        set += i
      } else {
        var ind = 0
        var flag = true
        while (ind < smallSet.length && flag) {
          if (smallSet(ind) > 1) {
            if (!set.contains(ind * smallSet(ind))) {
              set += i
              flag = false
            }
          }
          ind += 1
        }
      }
    }
    out.println(set.size)
    set.foreach(x => out.print(s"$x "))
    return 0
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._

object C extends App {

  val n = readLine().toInt

  val answer = new ArrayBuffer[Int]()

  if (n <= 2) {
    println(n - 1)
  } else {
    val C = Array.ofDim[Int](n + 1)
    for (i <- 2 to n) C(i) = i

    var div = 2
    var isDiv = true
    while (div <= n) {
      isDiv = false
      var first = true
      for {
        j <- 2 to n
      } {
        if (C(j) > 1 && C(j) % div == 0) {
          isDiv = true
          C(j) /= div
          if (first) {
            answer += j
            first = false
          }
        }
      }

      if (!isDiv) {
        div += 1
      }
    }
  }

  println(answer.mkString(" "))
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._

object C extends App {

  val n = readLine().toInt

  if (n <= 2) {
    println(n - 1)
  } else {

    val C = Array.ofDim[ArrayBuffer[Int]](n + 1)
    val P = Array.fill[Boolean](n + 1)(true)

    for {
      i <- 2 to Math.sqrt(n + 1).toInt
      j <- i + i to n by i
    } {
      P(j) = false
    }

    val primes = P.zipWithIndex.filter(_._1).map(_._2).drop(2)

    for {
      i <- 2 to n
    } {
      var divIdx = 0
      var current = i
      C(i) = new scala.collection.mutable.ArrayBuffer[Int]
      while (divIdx < primes.length && primes(divIdx) <= current) {
        if (current % primes(divIdx) == 0) {
          C(i) += primes(divIdx)
          current /= primes(divIdx)
        } else {
          divIdx += 1
        }
      }
    }

    var isDiv = false
    var i = 0

    val answer = new scala.collection.mutable.ArrayBuffer[Int]
    while (i < primes.length) {
      isDiv = false

      for (j <- 2 to n) {
        if (C(j).nonEmpty && C(j).contains(primes(i))) {
          C(j) -= primes(i)
          if (!isDiv && C(j).isEmpty) {
            answer += j
          }
          isDiv = true
        }
      }

      if (!isDiv) i += 1
    }

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


When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read.

The first line contains two integers n and t (1 ≤ n ≤ 105; 1 ≤ t ≤ 109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.

Print a single integer — the maximum number of books Valera can read.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, t) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val compressed = data.tail.scanLeft(data.head){case(a, b) => a + b}
  if (t >= compressed.last)
    println(n)
  else {
    var left = -1
    var right = -1
    while (right < n - 1 && compressed(right + 1) <= t)
      right += 1
    var max = right + 1
    while (right < n - 1 && left < n - 1) {
      left += 1
      while (right < n - 1 && compressed(right + 1) - compressed(left) <= t)
        right += 1
      max = Math.max(max, right - left)
    }
    println(max)
  }
}

object B279 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, t) = readLongs(2)
    val in = Array(0L) ++ readLongs(n.toInt)
    for(i <- 1 to n.toInt) {
      in(i) += in(i-1)
    }
    var res = 0
    var j = 1
    var curr = 0L
    for(i <- 1 to n.toInt) {
      while(j <= n && in(j)-in(i-1) <= t) {
        res = math.max(res, j-i+1)
        j += 1
      }
    }
    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

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

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

  def solve(): Int = {
    val N = sc.nextInt
    val T = sc.nextLong
    val dp = Array.fill(N + 1)(0L)

    for (i <- 1 to N) {
      dp(i) = dp(i - 1) + sc.nextLong
    }

    val idx: Int => Int = { x =>
      if (x < 0) - (x + 1)
      else x + 1
    }

    val books: Int => Int = { i =>
      val j = binarySearch(dp, dp(i - 1) + T)
      idx(j) - i
    }

    0 max List.range(1, N + 1).map(books).max
  }

  out.println(solve)
  out.close
}

object B {
  def r = readLine().split(" ") map(_.toInt)
  def main(args: Array[String]) {
    var Array(n,k) = r
    var a = r;
    var s = new Array[Int](n)
    s(0)=a(0)
    for (i <- 1 until n)
      s(i) = s(i-1) + a(i);
    var (result,j) = (0,0);
    for (i <- 0 until n-result
      if(a(i) <= k)){
        val ss = if (i == 0) 0 else s(i-1);
        while (j < n && s(j) - ss <= k) {
          j+=1;
          result = math.max(result, j-i)
        }
    }
    println(result)
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val nt = readLine().split(" ").map(_.toInt)
    val n = nt(0)
    val t = nt(1)
    val a = readLine().split(" ").map(_.toInt)

    var s = 0
    var sum = 0
    var max = 0

    for (i <- 0 until n) {
      val e = a(i)
      if (sum + e <= t) sum += e
      else {
        if (i - s > max) {
          max = i - s
        }
        sum += e
        sum -= a(s)
        s += 1
      }
    }
    if (n - s > max) max = n - s
    println(max)
  }
}

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

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

  def solve(): Int = {
    val N = sc.nextInt
    val T = sc.nextLong
    val dp = Array.fill(N + 1)(0L)

    for (i <- 1 to N) {
      dp(i) = dp(i - 1) + sc.nextLong
    }

    val idx: Int => Int = { x =>
      if (x < 0) - (x + 1)
      else x
    }

    val books: Int => Int = { i =>
      val j = binarySearch(dp, dp(i - 1) + T)
      idx(j) - i
    }

    0 max List.range(1, N + 1).map(books).max
  }

  out.println(solve)
  out.close
}


You are given a non-empty string $$$s=s_1s_2\dots s_n$$$, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string $$$s$$$ if there is an integer $$$j$$$ ($$$1 \le j \le n-2$$$), that $$$s_{j}s_{j+1}s_{j+2}=$$$"one" or $$$s_{j}s_{j+1}s_{j+2}=$$$"two".For example:  Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"),  Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two"). Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.For example, if the string looks like $$$s=$$$"onetwone", then if Polycarp selects two indices $$$3$$$ and $$$6$$$, then "onetwone" will be selected and the result is "ontwne".What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Next, the test cases are given. Each test case consists of one non-empty string $$$s$$$. Its length does not exceed $$$1.5\cdot10^5$$$. The string $$$s$$$ consists only of lowercase Latin letters. It is guaranteed that the sum of lengths of all lines for all input data in the test does not exceed $$$1.5\cdot10^6$$$.

Print an answer for each test case in the input in order of their appearance. The first line of each answer should contain $$$r$$$ ($$$0 \le r \le |s|$$$) — the required minimum number of positions to be removed, where $$$|s|$$$ is the length of the given line. The second line of each answer should contain $$$r$$$ different integers — the indices themselves for removal in any order. Indices are numbered from left to right from $$$1$$$ to the length of the string. If $$$r=0$$$, then the second line can be skipped (or you can print empty). If there are several answers, print any of them.

10
onetwonetwooneooonetwooo
two
one
twooooo
ttttwo
ttwwoo
ooone
onnne
oneeeee
oneeeeeeetwooooo

NoteIn the first example, answers are:  "onetwone",  "testme" — Polycarp likes it, there is nothing to remove,  "oneoneone",  "twotwo". In the second example, answers are:   "onetwonetwooneooonetwooo",  "two",  "one",  "twooooo",  "ttttwo",  "ttwwoo" — Polycarp likes it, there is nothing to remove,  "ooone",  "onnne" — Polycarp likes it, there is nothing to remove,  "oneeeee",  "oneeeeeeetwooooo".

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val s = ns()
      val twone = mutable.Set[Int]()
      var i = 0
      while(i != -1) {
        i = s.indexOf("twone", i)
        if (i != -1) {
          twone += i + 2
          i += 5
        }
      }

      val ans = ArrayBuffer[Int]()
      i = 0
      while(i != -1) {
        i = s.indexOf("one", i)
        if (i != -1) {
          if (!twone.contains(i)) {
            ans += i + 1
          }
          i += 3
        }
      }
      i = 0
      while(i != -1) {
        i = s.indexOf("two", i)
        if (i != -1) {
          if (!twone.contains(i + 2)) {
            ans += i + 1
          }
          i += 3
        }
      }

      debug(twone.mkString(" "))
      debug(ans.mkString(" "))

      ans ++= twone
      out.println(ans.length)
      out.println(ans.map(_+1).mkString(" "))
    }
  }
}

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val s = readLine.zipWithIndex
        val l = s.foldLeft(List[(Char, Int, Int)]()) {
            case (l, (c, i)) => l match {
                case Nil => List((c, i + 1, 1))
                case (c2, k, n) :: tl =>  if (c2 == c) (c2, k, n + 1) :: tl else (c, i + 1, 1) :: l
            }
        }.reverse
        val k = f2(List[(Char, Int, Int)](), List[Int](), l)
        println(k.length)
        println(k.mkString(" "))
    }

    def f2(l: List[(Char, Int, Int)], rl: List[Int], cl: List[(Char, Int, Int)]): List[Int] = {
        cl match {
            case ('o', ooff, on) ::  ('n', noff, 1) :: ('e', eoff, en) :: tl => {
                l match {
                    case ('w', woff, 1) :: ('t', toff, tn) :: ltl => {
                        val (tS, tL) = (('w', woff, 1), ('t', toff, tn))
                        val (oS, oL) = (('n', noff, 1), ('e', eoff, en))
                        if (2 <= on) {
                            f2(oL :: ('o', ooff, on) :: tL :: ltl, oS._2 :: tS._2 :: rl, tl)
                        } else {
                            f2(('e', eoff, en) :: ('n', noff, 1) :: ('w', woff, 1) :: ('t', toff, tn) :: ltl, ooff :: rl, tl)
                        }
                    }
                    case _ => f2(cl.head :: l, rl, cl.tail)
                }
            }
            case ('o', ooff, on) :: tl => {
                l match {
                    case ('w', woff, 1) :: ('t', toff, tn) :: ltl => {
                        f2(('o', ooff, on) :: ('t', toff, tn) :: ltl, woff :: rl, tl)
                    }
                    case _ => f2(cl.head :: l, rl, cl.tail)
                }
            }
            case ('e', eoff, en) :: tl => {
                l match {
                    case ('n', noff, 1) :: ('o', ooff, on) :: ltl => {
                        f2(('e', eoff, en) :: ('o', ooff, on) :: ltl, noff :: rl, tl)
                    }
                    case _ => f2(cl.head :: l, rl, cl.tail)
                }
            }
            case head :: tl => f2(head :: l, rl, tl)
            case Nil => rl
        }
    }
  }

import scala.collection.mutable

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

  val t = nextInt
  for (_ <- 1 to t) {
    val s = nextLine.toCharArray
    def ch(i: Int): Char = if (i < 0 || i >= s.length) ' ' else s(i)
    val res = new mutable.ArrayBuilder.ofInt
    var i = 0
    while (i < s.length) {
      if (ch(i - 2) == 't' && ch(i - 1) == 'w' && ch(i) == 'o' && ch(i + 1) == 'n' && ch(i + 2) == 'e') {
        s(i) = ' '
        res += i + 1
      } else if (ch(i - 2) == 't' && ch(i - 1) == 'w' && ch(i) == 'o') {
        res += i
      } else if (ch(i - 2) == 'o' && ch(i - 1) == 'n' && ch(i) == 'e') {
        res += i
      }
      i += 1
    }
    val r = res.result()
    out.println(r.length)
    out.println(r.mkString(" "))
  }

  out.flush()

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

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val s = readLine.zipWithIndex
        val l = s.foldLeft(List[(Char, Int, Int)]()) {
            case (l, (c, i)) => l match {
                case Nil => List((c, i, 1))
                case (c2, k, n) :: tl =>  if (c2 == c) (c2, k, n + 1) :: tl else (c, i, 1) :: l
            }
        }.reverse
        //println(l)
        val k = f2(List[(Char, Int, Int)](), List[Int](), l)
        println(k.length)
        println(k.mkString(" "))
    }

    def f2(l: List[(Char, Int, Int)], rl: List[Int], cl: List[(Char, Int, Int)]): List[Int] = {
        cl match {
            case ('o', ooff, on) ::  ('n', noff, 1) :: ('e', eoff, en) :: tl => {
                l match {
                    case ('w', woff, 1) :: ('t', toff, tn) :: ltl => {
                        val (tS, tL) = (('w', woff, 1), ('t', toff, tn))
                        val (oS, oL) = (('n', noff, 1), ('e', eoff, en))
                        if (2 <= on) {
                            f2(oL :: ('o', ooff, on) :: tL :: ltl, oS._2 :: tS._2 :: rl, tl)
                        } else {
                            f2(('e', eoff, en) :: ('n', noff, 1) :: ('w', woff, 1) :: ('t', toff, tn) :: ltl, ooff :: rl, tl)
                        }
                    }
                    case _ => f2(cl.head :: l, rl, cl.tail)
                }
            }
            case ('o', ooff, on) :: tl => {
                l match {
                    case ('w', woff, 1) :: ('t', toff, tn) :: ltl => {
                        f2(('o', ooff, on) :: ('t', toff, tn) :: ltl, woff :: rl, tl)
                    }
                    case _ => f2(cl.head :: l, rl, cl.tail)
                }
            }
            case ('e', eoff, en) :: tl => {
                l match {
                    case ('n', noff, 1) :: ('o', ooff, on) :: ltl => {
                        f2(('e', eoff, en) :: ('o', ooff, on) :: ltl, noff :: rl, tl)
                    }
                    case _ => f2(cl.head :: l, rl, cl.tail)
                }
            }
            case head :: tl => f2(head :: l, rl, tl)
            case Nil => rl
        }
    }
  }