There are $$$n$$$ seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from $$$1$$$ to $$$n$$$ from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat $$$i$$$ ($$$1 \leq i \leq n$$$) will decide to go for boiled water at minute $$$t_i$$$.Tank with a boiled water is located to the left of the $$$1$$$-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly $$$p$$$ minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the $$$i$$$-th seat wants to go for a boiled water, he will first take a look on all seats from $$$1$$$ to $$$i - 1$$$. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than $$$i$$$ are busy, he will go to the tank.There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment.Your goal is to find for each passenger, when he will receive the boiled water for his noodles.

The first line contains integers $$$n$$$ and $$$p$$$ ($$$1 \leq n \leq 100\,000$$$, $$$1 \leq p \leq 10^9$$$) — the number of people and the amount of time one person uses the tank. The second line contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$0 \leq t_i \leq 10^9$$$) — the moments when the corresponding passenger will go for the boiled water.

Print $$$n$$$ integers, where $$$i$$$-th of them is the time moment the passenger on $$$i$$$-th seat will receive his boiled water.

NoteConsider the example.At the $$$0$$$-th minute there were two passengers willing to go for a water, passenger $$$1$$$ and $$$5$$$, so the first passenger has gone first, and returned at the $$$314$$$-th minute. At this moment the passenger $$$2$$$ was already willing to go for the water, so the passenger $$$2$$$ has gone next, and so on. In the end, $$$5$$$-th passenger was last to receive the boiled water.

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[Int]]): 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._

  case class Event(t: Long, tpe: Int, i: Int) // 0: 戻る, 1: 腹減る, 2: waiting処理

  class Queue(n: Int) {
  private val as = Array.ofDim[Int](n)
  var p = 0
  var cur = 0

  def +=(a: Int): Unit = {
    as(p) = a
    p += 1
  }

  def dequeue(): Int = {
    val a = as(cur)
    cur += 1
    a
  }

  def head: Int = as(cur)

  def apply(i: Int): Int = as(cur + i)

  def length: Int = p - cur
  def isEmpty: Boolean = length == 0
  def nonEmpty: Boolean = !isEmpty

  def mkString(delimiter: String = ""): String = as.slice(cur, cur + length).mkString(delimiter)
}

  class BIT(n: Int, zero: Int)(f: (Int, Int) => Int) {
  def this(n: Int) = this(n, 0)(_ + _)

  private val N = {
    val a = Integer.highestOneBit(n)
    if (a == n) a else a << 1
  }
  private val bit = if (zero != 0) Array.fill[Int](N + 1)(zero) else Array.ofDim[Int](N + 1)

  /**
    * 1 index
    * addとindex違うよ
    * cumsumなんかといっしょ
    */
  def sum(i: Int): Int = {
    assert(i <= n)
    var x = i
    var s: Int = zero
    while(x > 0) {
      s = f(s, bit(x))
      x -= x & -x
    }
    s
  }

  /**
    * 0 index
    */
  def add(i: Int, a: Int): Unit = {
    assert(i < n)
    var x = i + 1
    while(x <= N) {
      bit(x) = f(bit(x), a)
      x += x & -x
    }
  }

  def sumAll: Int = sum(n)

  // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない
  private def sub(a: Int, b: Int) = a - b
  private def lt(a: Int, b: Int) = a < b

  /**
    * [l, r)
    */
  def query(l: Int, r: Int): Int = {
    assert(r > l)
    sub(sum(r), sum(l))
  }

  def lowerBound(W: Int): Int = {
    var k = N
    var x = 0
    var w = W
    while(k > 0) {
      if (x + k <= N && lt(bit(x + k), w)) {
        w = sub(w, bit(x + k))
        x += k
      }
      k /= 2
    }
    math.min(n, x)
  }
}

  class LongMinHeap(n: Int) {
  private val N = Integer.highestOneBit(n - 1) + 1 << 1
  private val heap = Array.ofDim[Long](N) // 1-indexed
  private var p = 0

  private def up(i: Int): Unit = {
    if (i >= 2) {
      val p = i / 2
      if (heap(i) < heap(p)) {
        val tmp = heap(p)
        heap(p) = heap(i)
        heap(i) = tmp
        up(p)
      }
    }
  }

  private def minchild(i: Int): Int = {
    if (i * 2 + 1 > p) {
      i * 2
    } else {
      if (heap(i * 2) < heap(i * 2 + 1)) i * 2
      else i * 2 + 1
    }
  }

  private def down(i: Int): Unit = {
    if (i * 2 <= p) {
      val mc = minchild(i)
      if (heap(i) > heap(mc)) {
        val tmp = heap(mc)
        heap(mc) = heap(i)
        heap(i) = tmp
        down(mc)
      }
    }
  }

  def add(x: Long): Unit = {
    p += 1
    heap(p) = x
    up(p)
  }

  def removeMin(): Unit = {
    heap(1) = heap(p)
    p -= 1
    down(1)
  }

  def min: Long = heap(1)
  def apply(i: Int): Long = heap(i + 1)
  def length: Int = p
  def toArray: Array[Long] = heap.slice(1, p + 1)
}
}

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 = {
    import java.util
    import java.util.Comparator
    val n, p = ni()
    val t = na(n)

    // イベントキュー
    val E = new util.TreeSet[Event](new Comparator[Event] {
      override def compare(o1: Event, o2: Event): Int = {
        if (o1.t == o2.t) {
          if (o1.tpe == o2.tpe) {
            Integer.compare(o1.i, o2.i) // 左側優先
          } else {
            Integer.compare(o1.tpe, o2.tpe)
          }
        }
        else java.lang.Long.compare(o1.t, o2.t)
      }
    })
    REP(n) { i =>
      E.add(Event(t(i), 1, i))
    }
    val q = new Queue(n) // 水飲みキュー
    val bit = new BIT(n) // 席が空いているか
    val waitings = new LongMinHeap(n) // 席で待っている人

    def processWaiting(t: Long): Unit = {
      // 一番左がだめで、２人め以降が大丈夫ってことはありえない
      if (waitings.length > 0) {
        val next = waitings.min.toInt
        if (bit.sum(next) == 0) {
          waitings.removeMin()
          bit.add(next, 1)
          debug(s"water($t:$next)")
          q += next
          if (q.length == 1) {
            E.add(Event(t + p, 0, -1))
          }
        }
      }
    }

    val ans = Array.ofDim[Long](n)
    while(!E.isEmpty) {
      val e = E.pollFirst()
      if (e.tpe == 1) {
        debug(s"addWait(${e.t}:${e.i})")
        waitings.add(e.i)
        E.add(Event(e.t, 2, -1))
      } else if (e.tpe == 0) {
        val ret = q.dequeue()
        debug(s"return(${e.t}:$ret)")
        ans(ret) = e.t
        bit.add(ret, -1)
        E.add(Event(e.t, 2, -1))
        if (q.nonEmpty) {
          E.add(Event(e.t + p, 0, -1))
        }
      } else {
        processWaiting(e.t)
      }
    }
    out.println(ans.mkString(" "))
  }
}


You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.

The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.

Print the minimum non-zero element before each operation in a new line.

NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val A = na(N)
    val nums = mutable.Set[Int]()
    REP(N) { i =>
      nums += A(i)
    }
    val sorted = nums.toSeq.sorted
    var sum = 0L
    val n = sorted.length
    REP(K) { i =>
      if (i < n) {
        val a = sorted(i) - sum
        sum += a
        out.println(a)
      } else {
        out.println(0)
      }
    }
  }

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

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

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

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

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

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

import java.io.PrintWriter
import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Seq[Int] = {
    val xs = SortedSet(as: _*).toStream
    val xs0 = 0 #:: xs
    (xs0, xs).zipped.map((a, b) => b-a).take(k).padTo(k, 0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()})
    val out = new PrintWriter(System.out)
    solution foreach out.println
    out.close()
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

import java.io.PrintWriter
import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Seq[Int] = {
    val xs = SortedSet(as: _*).toStream
    val xs0 = 0 #:: xs
    (xs0, xs).zipped.map((a, b) => b-a).take(k).padTo(k, 0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()})
    val out = new PrintWriter(System.out)
    out.println(solution.mkString("\n"))
    out.close()
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Unit = {
    // println in the middle of a function makes me feel sick
    // Just submitting this to test performance
    val out = new java.io.PrintWriter(System.out)
    val xs = SortedSet(as: _*).take(k).toList
    var last = 0
    for {
      x <- xs
    } {
      out.println(x - last)
      last = x
    }
    for {
      i <- xs.length until k
    } out.println(0)
    out.close()
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    solve(int, int, {nextLine; intSeq()})
  }

    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }
}

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

  override def apply(io: IO): io.type = {
    val n, k = io.read[Int]
    val as = io.read[IndexedSeq, Int](n).sorted.lift

    var i, s = 0
    val ans = mutable.ArrayBuffer.empty[Int]
    while(ans.length < k) {
      as(i) match {
        case None => ans.append(0)
        case Some(a) if a > s =>
          ans.append(a - s)
          s += a - s
        case _ =>
      }
      i += 1
    }

    io.writeAll(ans, separator = "\n")
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[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")

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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
      }
    }
  }
}

 import scala.io.StdIn

object B extends App {
  def readInts = StdIn.readLine().split(" ").map(_.toInt)

  val Array(n, k) = readInts
  val A = readInts.distinct.sorted

  def solve() = {
    var i = 0
    var offset = 0

    (0 until k).map { _ =>
      while (i < A.length && (A(i) - offset) == 0) i += 1
      if (i >= A.length) 0
      else {
        val res = A(i) - offset
        offset = A(i)
        res
      }
    }
  }

  println(solve().mkString("\n"))
}

object CF_525_2_B {
  def solve(n: Int, k: Int, arr: Array[Int]): Vector[Int] = {
    // Going mutable for performance - blech
    if(arr.forall(_ == 0))
      Vector.fill(n)(0)
    else {
      var min = arr.filter(_ > 0).min
      var pass = 0
      var out = Vector.empty[Int]
      while (pass < k) {
        out :+= min
        var newMin = min
        var i = 0
        var allAreZero = true
        while (i < arr.length) {
          if (arr(i) > 0) {
            arr(i) -= min
            if (arr(i) > 0) {
              allAreZero = false
              if (arr(i) < newMin)
                newMin = arr(i)
            }
          }
          i += 1
        }
        if(allAreZero) min = 0 else min = newMin
        pass += 1
      }
      out
    }
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()}.toArray)
    solution foreach println
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Unit = {
    // println in the middle of a function makes me feel sick
    // Just submitting this to test performance
    val out = new java.io.PrintWriter(System.out)
    val xs = SortedSet(as: _*).take(k).toList
    var last = 0
    for {
      x <- xs
    } {
      out.println(x - last)
      last = x
    }
    for {
      i <- xs.length until k
    } out.println(0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    solve(int, int, {nextLine; intSeq()})
  }

    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }
}

import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Unit = {
    // println in the middle of a function makes me feel sick
    val xs = as.sorted.take(k)
    var last = 0
    for {
      x <- xs
    } {
      println(x - last)
      last = x
    }
    for {
      i <- xs.length until k
    } println(0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    solve(int, int, {nextLine; intSeq()})
  }

    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }
}

import java.io.PrintWriter
import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Seq[Int] = {
    val xs = SortedSet(as: _*).toStream
    val xs0 = 0 #:: xs
    (xs0, xs).zipped.map((a, b) => b-a).take(k).padTo(k, 0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()})
    val out = new PrintWriter(System.out)
    solution foreach out.println
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Unit = {
    // println in the middle of a function makes me feel sick
    val xs = SortedSet(as: _*).take(k).toList
    var last = 0
    for {
      x <- xs
    } {
      println(x - last)
      last = x
    }
    for {
      i <- xs.length to k
    } println(0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    solve(int, int, {nextLine; intSeq()})
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

object CF_525_2_B {
  def solve(n: Int, k: Int, xs: Vector[Int], out: Vector[Int] = Vector.empty): Vector[Int] = k match {
    case 0 => out
    case k => {
      val m = xs.min
      solve(n, k - 1, xs.map(_-m), out :+ m)
    }
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()})
    solution foreach println
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}


Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when:  all parts of the wall has the same height;  the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial heights of the parts of the wall.

Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise.

NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put a brick vertically on part 3 to make the wall $$$[4, 5, 5]$$$, then horizontally on parts 2 and 3 to make it $$$[4, 6, 6]$$$ and then vertically on part 1 to make it $$$[6, 6, 6]$$$.In the third example the wall is already complete.

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

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

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

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

  def solve(): Unit = {
    import java.util
    val N = ni()
    val A = na(N)
    REP(N) { i =>
      A(i) = A(i) % 2
    }
    val set = new java.util.TreeSet[Integer]()
    REP(N) { i =>
      set.add(i)
    }

    val q = new util.ArrayDeque[Integer]()

    var i = 0
    while(i < N - 1) {
      if (A(i) == A(i + 1)) {
        set.remove(i)
        set.remove(i + 1)
        q.add(i - 1)
        i += 1
      }
      i += 1
    }

    while(!q.isEmpty) {
      val pos = q.poll()
      if (set.contains(pos)) {
        val pos2 = set.higher(pos)
        if (pos2 != null && A(pos) == A(pos2)) {
          set.remove(pos)
          set.remove(pos2)
          val prev = set.lower(pos)
          if (prev != null) q.add(prev)
        }
      }
    }

    val ok = set.size() < 2

    if (ok) {
      out.println("YES")
    } else {
      out.println("NO")
    }
  }

  /**
    * 最大M個のグループに分割してグループ毎の配列に入れる
    */
  def grouped(N: Int, M: Int, g: Array[Int], v: Array[Int]): Array[Array[Int]] = {
    val cnt = Array.ofDim[Int](M)
    val C = Array.ofDim[Array[Int]](M)
    REP(N) { i =>
      cnt(g(i)) += 1
    }
    REP(M) { i =>
      C(i) = new Array(cnt(i))
    }
    REP_r(N) { i =>
      cnt(g(i)) -= 1
      C(g(i))(cnt(g(i))) = v(i)
    }
    C
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val set = new java.util.TreeSet[Integer]()
    REP(N) { i =>
      set.add(i)
    }

    val P = mutable.Map[Int, java.util.PriorityQueue[Integer]]()
    REP_r(N) { i =>
      if (!P.contains(A(i))) P(A(i)) = new java.util.PriorityQueue[Integer]()
      P(A(i)).add(i)
    }
    val nums = new java.util.PriorityQueue[Integer]()
    P.keys.foreach(k => nums.add(k))

    def ok: Boolean = {
      // 一番大きい高さは考慮しなくていい
      val mx = nums.size + 2
      var i = 0
      while(!nums.isEmpty && i < mx) {
        val num = nums.poll()
        val p = P(num)
        var addNext = false
        while(!p.isEmpty) {
          if (p.size() == 1) {
            if (!P.contains(num + 2)) P(num + 2) = new java.util.PriorityQueue[Integer]()
            P(num + 2).add(p.poll())
            addNext = true
          } else {
            val p1 = p.poll()
            val p2 = p.poll()
            if (set.higher(p1) == p2) {
              set.remove(p1)
              set.remove(p2)
            } else {
              if (!P.contains(num + 2)) P(num + 2) = new java.util.PriorityQueue[Integer]()
              P(num + 2).add(p1)
              P(num + 2).add(p2)
              addNext = true
            }
          }
        }

        if (addNext) nums.add(num + 2)

        i += 1
      }

      nums.size() <= 1
    }

    if (ok) {
      out.println("YES")
    } else {
      out.println("NO")
    }
  }

  /**
    * 最大M個のグループに分割してグループ毎の配列に入れる
    */
  def grouped(N: Int, M: Int, g: Array[Int], v: Array[Int]): Array[Array[Int]] = {
    val cnt = Array.ofDim[Int](M)
    val C = Array.ofDim[Array[Int]](M)
    REP(N) { i =>
      cnt(g(i)) += 1
    }
    REP(M) { i =>
      C(i) = new Array(cnt(i))
    }
    REP_r(N) { i =>
      cnt(g(i)) -= 1
      C(g(i))(cnt(g(i))) = v(i)
    }
    C
  }

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

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

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

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

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

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


Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $$$a$$$ sticks and $$$b$$$ diamonds?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^9$$$) — the number of sticks and the number of diamonds, respectively.

For each test case print one integer — the maximum number of emeralds Polycarp can earn.

NoteIn the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel.In the second test case Polycarp does not have any diamonds, so he cannot craft anything.

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val ab = readIntLine()
      println(calc(ab.head, ab.last))
    }
  }

  def calc(a: Int, b: Int) = {
    val min = math.min(a, b)
    val max = math.max(a, b)
    val diff = max - min
    val diffMoney = diff
    val rest = min - diff
    if (rest < 0) min else diffMoney + rest / 3 * 2 + (if (rest % 3 == 2) 1 else 0)
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

//  def printArray[T](arr: Array[T]): Unit = {
//    val str = new StringBuilder()
//    str.addAll((if (arr.head == -1) 0 else arr.head).toString)
//    //    print(arr(0))
//    for (i <- 1 until arr.length) {
//      str.addAll(" " + (if (arr(i) == -1) 0 else arr(i)))
//    }
//    println(str)
//  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

    val t2 = a min ((2 * b - a) / 3)
    val t1 = (a - t2) / 2

    val ans = t1 + t2

    println(ans)
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

    val ans = a min b min ((a + b) / 3)

    println(ans)
  }
}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val ab = readIntLine()
      println(calc(ab.head, ab.last))
    }
  }

  def calc(a: Int, b: Int) = {
    val min = math.min(a, b)
    val max = math.max(a, b)
    val diff = max - min
    val diffMoney = diff
    val rest = min - diff
    if (rest < 0) min else diffMoney + rest / 3 * 2
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

//  def printArray[T](arr: Array[T]): Unit = {
//    val str = new StringBuilder()
//    str.addAll((if (arr.head == -1) 0 else arr.head).toString)
//    //    print(arr(0))
//    for (i <- 1 until arr.length) {
//      str.addAll(" " + (if (arr(i) == -1) 0 else arr(i)))
//    }
//    println(str)
//  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted
    val t1          = (b - a) min a
    val (a1, b1)    = (a - t1, b - 2 * t1)
    val t2          = 2 * a1 / 3
    val (a2, b2)    = (a1 - t2 / 2 * 3, b1 - t2 / 2 * 3)
    val t3          = a2 min (b2 / 2)

    val ans = t1 + t2 + t3

    println(ans)
  }
}


For some binary string $$$s$$$ (i.e. each character $$$s_i$$$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $$$2$$$ were written. For each pair (substring of length $$$2$$$), the number of '1' (ones) in it was calculated.You are given three numbers:  $$$n_0$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$0$$$;  $$$n_1$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$1$$$;  $$$n_2$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$2$$$. For example, for the string $$$s=$$$"1110011110", the following substrings would be written: "11", "11", "10", "00", "01", "11", "11", "11", "10". Thus, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.Your task is to restore any suitable binary string $$$s$$$ from the given values $$$n_0, n_1, n_2$$$. It is guaranteed that at least one of the numbers $$$n_0, n_1, n_2$$$ is greater than $$$0$$$. Also, it is guaranteed that a solution exists.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then test cases follow. Each test case consists of one line which contains three integers $$$n_0, n_1, n_2$$$ ($$$0 \le n_0, n_1, n_2 \le 100$$$; $$$n_0 + n_1 + n_2 > 0$$$). It is guaranteed that the answer for given $$$n_0, n_1, n_2$$$ exists.

Print $$$t$$$ lines. Each of the lines should contain a binary string corresponding to a test case. If there are several possible solutions, print any of them.

import scala.io.StdIn

object F {

   def check(s: String) = {
      val pairs = s zip s.tail
      (pairs.count { case (a, b) => a == b && a == '0'},
        pairs.count { case (a, b) => a != b},
        pairs.count { case (a, b) => a == b && a == '1'})
   }

   def solution(n00: Int, n01: Int, n11: Int): String = {
      if (n01 == 0)
         if (n00 == 0)
            Seq.fill(n11 + 1)("1")
         else // n11 == 0
            Seq.fill(n00 + 1)("0")
      else {
         val s01 = Stream.continually(Seq("0", "1")).flatten.take(n01 - 1).toSeq
         val s00 = Seq.fill(n00 + 1)("0")
         val s11 = Seq.fill(n11 + 1)("1")
         s01 ++ (if (n01 % 2 == 1) s00 ++ s11 else s11 ++ s00)
      }
   }
     .mkString("")

   def main(args: Array[String]): Unit = {
      for (_ <- (0 until StdIn.readLine.toInt)) {
         val Seq(n00, n01, n11) = StdIn.readLine.split(" ").toSeq.map(_.toInt)
         println(F.solution(n00, n01, n11))
      }
   }
}

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

import scala.collection.immutable
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 C640B(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 C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t =ni()
    REP(t) { _ =>
      val n0 = ni()
      val n1 = ni()
      val n2 = ni()

      val sb = new StringBuilder
      if(n1 > 0) {
        REP(n1+1) { i =>
          if(i%2 == 0) sb.append("1")
          else sb.append("0")
        }
        sb.insert(1, (0 until n0 map(_ => '0')).mkString(""))
        sb.insert(0, (0 until n2 map(_ => '1')).mkString(""))
        out.println(sb.toString())
      } else {
        if(n0 > 0) 0 to n0 foreach(_ => sb.append("0"))
        if(n2 > 0) 0 to n2 foreach(_ => sb.append("1"))
        out.println(sb.toString())
      }
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn

object F {

   def check(s: String) = {
      val pairs = s zip s.tail
      (pairs.count { case (a, b) => a == b && a == '0'},
        pairs.count { case (a, b) => a != b},
        pairs.count { case (a, b) => a == b && a == '1'})
   }

   def solution(n00: Int, n01: Int, n11: Int): String = {
      if (n01 == 0)
         if (n00 == 0)
            Seq.fill(n11 + 1)("1")
         else // n11 == 0
            Seq.fill(n00 + 1)("0")
      else {
           Seq.fill(n01 / 2)("01").take(n01 - 1) ++
             Seq.fill(n00 + 1)("0") ++
             Seq.fill(n11 + 1)("1")
      }
      /*
      01      1
      01 0    2
      01 01   3
      01 010  4
      01 0100 5
       */
   }
     .mkString("")

   def main(args: Array[String]): Unit = {
      for (_ <- (0 until StdIn.readLine.toInt)) {
         val Seq(n00, n01, n11) = StdIn.readLine.split(" ").toSeq.map(_.toInt)
         println(F.solution(n00, n01, n11))
      }
   }
}

import scala.annotation.tailrec
import scala.io.StdIn

object F {

   def check(s: String) = {
      val pairs = s zip s.tail
      (pairs.count { case (a, b) => a == b && a == '0'},
        pairs.count { case (a, b) => a != b},
        pairs.count { case (a, b) => a == b && a == '1'})
   }

   def solution(n00: Int, n01: Int, n11: Int): String = {
      if (n01 == 0)
         if (n00 == 0)
            Seq.fill(n11 + 1)("1")
         else // n11 == 0
            Seq.fill(n00 + 1)("0")
      else {
         Seq.fill(n11 + 1)("1") ++
           Seq.fill(n00 + 1)("0") ++
           Seq.fill(n01 / 2)("01").take(n01 - 1)
      }
      /*
      01      1
      01 0    2
      01 01   3
      01 010  4
      01 0100 5
       */
   }
     .mkString("")

   def main(args: Array[String]): Unit = {
      for (_ <- (0 until StdIn.readLine.toInt)) {
         val Seq(n00, n01, n11) = StdIn.readLine.split(" ").toSeq.map(_.toInt)
         println(F.solution(n00, n01, n11))
      }
   }
}

import scala.annotation.tailrec
import scala.io.StdIn

object F {

   def check(s: String) = {
      val pairs = s zip s.tail
      (pairs.count { case (a, b) => a == b && a == '0'},
        pairs.count { case (a, b) => a != b},
        pairs.count { case (a, b) => a == b && a == '1'})
   }

   def solution(n00: Int, n01: Int, n11: Int): String = {
      if (n01 == 0)
         if (n00 == 0)
            Seq.fill(n11 + 1)("1")
         else // n11 == 0
            Seq.fill(n00 + 1)("0")
      else {
         Seq.fill(n11)("1") ++
           Seq.fill(n00)("0") ++
           Seq.fill(n01 / 2)("01").take(n01 - 1)
      }
      /*
      01      1
      01 0    2
      01 01   3
      01 010  4
      01 0100 5
       */
   }
     .mkString("")

   def main(args: Array[String]): Unit = {
      for (_ <- (0 until StdIn.readLine.toInt)) {
         val Seq(n00, n01, n11) = StdIn.readLine.split(" ").toSeq.map(_.toInt)
         println(F.solution(n00, n01, n11))
      }
   }
}

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

import scala.collection.immutable
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 C640B(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 C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t =ni()
    REP(t) { _ =>
      val n0 = ni()
      val n1 = ni()
      val n2 = ni()

      val sb = new StringBuilder
      if(n1 > 0) {
        0 until (n1+1)/2 foreach(_ => sb.append("10"))
        0 until n0 foreach(_ => sb.append("0"))
        out.println((1 to n2 map(_ => "1")).mkString("") + sb.toString())
      } else {
        if(n0 > 0) 0 to n0 foreach(_ => sb.append("0"))
        if(n2 > 0) 0 to n2 foreach(_ => sb.append("1"))
        out.println(sb.toString())
      }
    }
  }
}

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

import scala.collection.immutable
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 C640B(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 C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t =ni()
    REP(t) { _ =>
      val n0 = ni()
      val n1 = ni()
      val n2 = ni()

      val sb = new StringBuilder
      if(n1 > 0) {
        0 until (n1+1)/2 foreach(_ => sb.append("10"))
        0 until n0 foreach(_ => sb.append("0"))
        out.println((1 until n2 map(_ => "1")).mkString("") + sb.toString())
      } else {
        if(n0 > 0) 0 to n0 foreach(_ => sb.append("0"))
        if(n2 > 0) 0 to n2 foreach(_ => sb.append("1"))
        out.println(sb.toString())
      }
    }
  }
}

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

import scala.collection.immutable
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 C640B(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 C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t =ni()
    REP(t) { _ =>
      val n0 = ni()
      val n1 = ni()
      val n2 = ni()

      val sb = new StringBuilder
      if(n1 > 0) {
        REP(n1+1) { i =>
          if(i%2 == 0) sb.append("1")
          else sb.append("0")
        }
        sb.insert(1, (0 until n0 map(_ => '0')).mkString(""))
        sb.insert(0, (0 until n1 map(_ => '1')).mkString(""))
        out.println(sb.toString())
      } else {
        if(n0 > 0) 0 to n0 foreach(_ => sb.append("0"))
        if(n2 > 0) 0 to n2 foreach(_ => sb.append("1"))
        out.println(sb.toString())
      }
    }
  }
}


In the evening Polycarp decided to analyze his today's travel expenses on public transport.The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops.Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes.It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b < a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment.For example, if Polycarp made three consecutive trips: "BerBank"  "University", "University"  "BerMall", "University"  "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus.Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction.What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards?

The first line contains five integers n, a, b, k, f (1 ≤ n ≤ 300, 1 ≤ b < a ≤ 100, 0 ≤ k ≤ 300, 1 ≤ f ≤ 1000) where:   n — the number of Polycarp trips,  a — the cost of a regualar single trip,  b — the cost of a trip after a transshipment,  k — the maximum number of travel cards Polycarp can buy,  f — the cost of a single travel card.  The following n lines describe the trips in the chronological order. Each line contains exactly two different words separated by a single space — the name of the start stop and the name of the finish stop of the trip. All names consist of uppercase and lowercase English letters and have lengths between 1 to 20 letters inclusive. Uppercase and lowercase letters should be considered different.

Print the smallest amount of money Polycarp could have spent today, if he can purchase no more than k travel cards.

3 5 3 1 8
BerBank University
University BerMall
University BerBank

NoteIn the first example Polycarp can buy travel card for the route "BerBank  University" and spend 8 burles. Note that his second trip "University"  "BerMall" was made after transshipment, so for this trip Polycarp payed 3 burles. So the minimum total sum equals to 8 + 3 = 11 burles.In the second example it doesn't make sense to buy travel cards. Note that each of Polycarp trip (except the first) was made with transshipment. So the minimum total sum equals to 2 + 1 + 1 + 1 = 5 burles.

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

import scala.collection.mutable._

/**
  * @author Mehdi Maick
  */
object Main {

  def solve(in: InputReader): Unit = {
    var (n, a, b, k, f) = (in.next.toInt, in.next.toInt, in.next.toInt, in.next.toInt, in.next.toInt)
    val map = HashMap[String, Int]()
    var last : String = "";
    for(i <- 0 until n){
      var (from, to) = (in.next, in.next)
      var cost = if(last == from) b else a
      last = to
      var key = if(from > to) from + to else to + from
      map.put(key, map.getOrElse(key, 0) + cost)
    }
    var ans = 0
    map.values.toList.sorted.reverse.foreach((e) => {
      if(e > f && k > 0){
        k -= 1
        ans += f
      }else{
        ans += e
      }
    })
    println(ans)
  }

  def main(args: Array[String]): Unit = {
    val in = new InputReader
    solve(in)
  }

  class InputReader() {
    var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var st: StringTokenizer = null

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

    def nextLine(): String = in.readLine
  }

}


Recently Petya walked in the forest and found a magic stick.Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:   If the chosen number $$$a$$$ is even, then the spell will turn it into $$$\frac{3a}{2}$$$;  If the chosen number $$$a$$$ is greater than one, then the spell will turn it into $$$a-1$$$. Note that if the number is even and greater than one, then Petya can choose which spell to apply.Petya now has only one number $$$x$$$. He wants to know if his favorite number $$$y$$$ can be obtained from $$$x$$$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $$$x$$$ as it is.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^9$$$) — the current number and the number that Petya wants to get.

For the $$$i$$$-th test case print the answer on it — YES if Petya can get the number $$$y$$$ from the number $$$x$$$ using known spells, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

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[Int]]): 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 x, y = ni()
      val ok = y <= x ||
        x == 2 && y == 3 ||
        x >= 4
      if (ok) out.println("YES")
      else out.println("NO")
    }
  }
}

object B1257 {

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

  def main(args: Array[String]): Unit = {
    var t = readInt
    while (t > 0) {
      val Array(x, y) = readInts(2)
      val res = if (x == 1) {
        if (y == 1)
          "YES"
        else
          "NO"
      } else if (x == 2) {
        if (Array(1, 2, 3).contains(y))
          "YES"
        else
          "NO"
      } else if (x == 3) {
        if (Array(1, 2, 3).contains(y))
          "YES"
        else
          "NO"
      } else "YES"

      out.println(res)
      t -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.For example, if the string s is abacaba and the query is l1 = 3, r1 = 6, k1 = 1 then the answer is abbacaa. If after that we would process the query l2 = 1, r2 = 4, k2 = 2 then we would get the string baabcaa.

The first line of the input contains the string s (1 ≤ |s| ≤ 10 000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters. Second line contains a single integer m (1 ≤ m ≤ 300) — the number of queries. The i-th of the next m lines contains three integers li, ri and ki (1 ≤ li ≤ ri ≤ |s|, 1 ≤ ki ≤ 1 000 000) — the description of the i-th query.

Print the resulting string s after processing all m queries.

NoteThe sample is described in problem statement.

import java.util.Scanner

/**
 * Created by enxhell on 11/25/15.
 */
object StringShift {

  def gcd(a: Int,b: Int): Int = {
    if(b ==0) a else gcd(b, a%b)
  }

  def mod(v: Long, m: Int)  = {
    if(v >= 0){
      v % m
    }else if((-v) % m == 0) {
      0l
    }else{
        m - ((-v) % m)
    }
  }

  def processQuery(l: Int, r: Int, k: Int, str: Array[Char]) = {
//    println(l,r,k)
//    println(gcd(k,r-l+1))
    for(i <- 0 until gcd(k,r-l+1)){
      val tmp = str(i+l)
      var j : Long = i
      while(mod(j-k,r-l+1)!=i){
//        println(j,mod(j,r-l+1),mod(j-k, r-l+1))
        str((mod(j, r-l+1)+l).toInt) = str((mod(j-k, r-l+1)+l).toInt)
        j -= k
      }
      str((mod(j, (r-l+1))+l).toInt) = tmp
    }
  }

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    val str = scanner.next().toCharArray
    scanner.nextLine()

    val n = scanner.nextInt()
    (1 to n).foreach(x => processQuery(scanner.nextInt()-1, scanner.nextInt()-1, scanner.nextInt(), str))

    println(str.foldLeft("")((r,c)=> r+c))

  }
}

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

object B {
  def main(args: Array[String]): Unit = {
    val s = StdIn.readLine
    val seq = s.to[ArrayBuffer]
    val n = StdIn.readInt
    for (_ <- 1 to n) {
      var Array(l, r, k) = StdIn.readLine.split(" ").map(_.toInt)
      val len = r - l + 1
      k %= len
      r -= 1
      l -= 1
      val nseq = new ArrayBuffer[Char]
      for (i <- 0 to r-l) {
        nseq += seq(l + (i - k + len) % len)
      }
      for (i <- l to r) {
        seq(i) = nseq(i - l)
      }
    }
    println(seq.mkString)
  }
}

import scala.io.StdIn

object B {
  def main(args: Array[String]): Unit = {
    val seq = StdIn.readLine.toCharArray
    val n = StdIn.readInt
    (1 to n).foreach { _ =>
      var Array(l, r, k) = StdIn.readLine.split(" ").map(_.toInt)
      val len = r - l + 1
      k %= len; r -= 1; l -= 1
      val tmp = Array.ofDim[Char](len)
      tmp.indices.foreach { i => tmp(i) = seq(l + (i - k + len) % len) }
      tmp.indices.foreach { i => seq(i+l) = tmp(i) }
    }
    println(seq.mkString)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next().toCharArray
  val m = in.next().toInt
  (1 to m).foreach { _ =>
    val Array(l, r, k) = in.next().split(' ').map(_.toInt)
    val distance = r - l + 1
    val leftover = k % distance
    val temp = Array.ofDim[Char](distance)
    (0 until distance).foreach { i =>
      temp((i + k) % distance) = str(i + l - 1)
    }
    temp.indices.foreach(i => str(i + l - 1) = temp(i))
  }
  println(str.mkString(""))

}

object B598 {

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

  def main(args: Array[String]): Unit = {
    val in = read.toCharArray
    val Array(m) = readInts(1)
    for(_ <- 0 until m) {
      var Array(l, r, k) = readInts(3)
      k %= (r-l+1)
      l -= 1
      val temp = in.slice(l, r)
      val left = temp.takeRight(k).clone()
      val right = temp.take(r-l-k).clone()
      for(i <- 0 until k){
        in(l+i) = left(i)
      }
      for(i <- 0 until r-l-k){
        in(l+k+i) = right(i)
      }
    }
    println(in.mkString(""))
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import java.util.Scanner

/**
 * Created by enxhell on 11/25/15.
 */
object StringShift {

  def gcd(a: Int,b: Int): Int = {
    if(b ==0) a else gcd(b, a%b)
  }

  def mod(v: Int, m: Int) = {
    if(v >= 0){
      v % m
    }else if((-v) % m == 0) {
      0
    }else{
        m - ((-v) % m)
    }
  }

  def processQuery(l: Int, r: Int, k: Int, str: Array[Char]) = {
//    println(l,r,k)
//    println(gcd(k,r-l+1))
    for(i <- 0 until gcd(k,r-l+1)){
      val tmp = str(i+l)
      var j = i
      while(mod(j-k,r-l+1)!=i){
//        println(j,mod(j,r-l+1),mod(j-k, r-l+1))
        str(mod(j, r-l+1)+l) = str(mod(j-k, r-l+1)+l)
        j -= k
      }
      str(mod(j, (r-l+1))+l) = tmp
    }
  }

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    val str = scanner.next().toCharArray
    scanner.nextLine()

    val n = scanner.nextInt()
    (1 to n).foreach(x => processQuery(scanner.nextInt()-1, scanner.nextInt()-1, scanner.nextInt(), str))

    println(str.foldLeft("")((r,c)=> r+c))

  }
}

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

object B {
  def main(args: Array[String]): Unit = {
    val s = StdIn.readLine
    val seq = s.to[ArrayBuffer]
    val n = StdIn.readInt
    for (j <- 1 to n) {
      var Array(l, r, k) = StdIn.readLine.split(" ").map(_.toInt)
      val len = r - l + 1
      k %= len
      r -= 1
      l -= 1
      val nseq = new ArrayBuffer[Char]
      for (i <- l to r) {
        nseq += seq((i - k + len) % len)
      }
      for (i <- l to r) {
        seq(i) = nseq(i - l)
      }
    }
    println(seq.mkString)
  }
}


A multi-subject competition is coming! The competition has $$$m$$$ different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students. He has $$$n$$$ candidates. For the $$$i$$$-th person he knows subject $$$s_i$$$ the candidate specializes in and $$$r_i$$$ — a skill level in his specialization (this level can be negative!). The rules of the competition require each delegation to choose some subset of subjects they will participate in. The only restriction is that the number of students from the team participating in each of the chosen subjects should be the same.Alex decided that each candidate would participate only in the subject he specializes in. Now Alex wonders whom he has to choose to maximize the total sum of skill levels of all delegates, or just skip the competition this year if every valid non-empty delegation has negative sum.(Of course, Alex doesn't have any spare money so each delegate he chooses must participate in the competition).

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le m \le 10^5$$$) — the number of candidates and the number of subjects. The next $$$n$$$ lines contains two integers per line: $$$s_i$$$ and $$$r_i$$$ ($$$1 \le s_i \le m$$$, $$$-10^4 \le r_i \le 10^4$$$) — the subject of specialization and the skill level of the $$$i$$$-th candidate.

Print the single integer — the maximum total sum of skills of delegates who form a valid delegation (according to rules above) or $$$0$$$ if every valid non-empty delegation has negative sum.

NoteIn the first example it's optimal to choose candidates $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, so two of them specialize in the $$$2$$$-nd subject and other two in the $$$3$$$-rd. The total sum is $$$6 + 6 + 5 + 5 = 22$$$.In the second example it's optimal to choose candidates $$$1$$$, $$$2$$$ and $$$5$$$. One person in each subject and the total sum is $$$6 + 6 + 11 = 23$$$.In the third example it's impossible to obtain a non-negative sum.

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val (s, r) = na2(N)
    rep(N) { i => s(i) -= 1 }

    val cnt = Array.ofDim[Int](M)
    val cumR = Array.ofDim[Array[Long]](M)
    rep(N) { i =>
      cnt(s(i)) += 1
    }
    rep(M) { i =>
      cumR(i) = new Array(cnt(i))
    }
    rep(N) { i =>
      cnt(s(i)) -= 1
      cumR(s(i))(cnt(s(i))) = r(i)
    }

    var len = 0
    rep(M) { i =>
      val R = cumR(i)
      len = max(len, R.length)
      Sorting.quickSort(R)

      // reverse
      rep(R.length / 2) { j =>
        val t = R(j)
        R(j) = R(R.length - 1 - j)
        R(R.length - 1 - j) = t
      }

      rep(R.length - 1, 1) { j =>
        R(j) += R(j - 1)
      }
    }
    Sorting.quickSort(cumR)(Ordering.by(_.length))

    var ans = 0L
    var l = 0
    rep(len, 1) { k =>
      var sum = 0L
      while(l < M && cumR(l).length < k) l += 1
      if (l < M) {
        l until M foreach { i =>
          if (cumR(i)(k - 1) > 0) sum += cumR(i)(k - 1)
        }
        ans = max(ans, sum)
      }
    }

    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val (s, r) = na2(N)
    rep(N) { i => s(i) -= 1 }

    val cnt = Array.ofDim[Int](M)
    val cumR = Array.ofDim[Array[Int]](M)
    rep(N) { i =>
      cnt(s(i)) += 1
    }
    rep(M) { i =>
      cumR(i) = new Array(cnt(i))
    }
    rep(N) { i =>
      cnt(s(i)) -= 1
      cumR(s(i))(cnt(s(i))) = r(i)
    }

    var len = 0
    rep(M) { i =>
      val R = cumR(i)
      len = max(len, R.length)
      Sorting.quickSort(R)

      // reverse
      rep(R.length / 2) { j =>
        val t = R(j)
        R(j) = R(R.length - 1 - j)
        R(R.length - 1 - j) = t
      }

      rep(R.length - 1, 1) { j =>
        R(j) += R(j - 1)
      }
    }
    Sorting.quickSort(cumR)(Ordering.by(_.length))

    var ans = 0
    var l = 0
    rep(len, 1) { k =>
      var sum = 0
      while(l < M && cumR(l).length < k) l += 1
      if (l < M) {
        l until M foreach { i =>
          sum += cumR(i)(k - 1)
        }
        ans = max(ans, sum)
      }
    }

    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val (s, r) = na2(N)
    rep(N) { i => s(i) -= 1 }

    val cnt = Array.ofDim[Int](M)
    val cumR = Array.ofDim[Array[Long]](M)
    rep(N) { i =>
      cnt(s(i)) += 1
    }
    rep(M) { i =>
      cumR(i) = new Array(cnt(i))
    }
    rep(N) { i =>
      cnt(s(i)) -= 1
      cumR(s(i))(cnt(s(i))) = r(i)
    }

    var len = 0
    rep(M) { i =>
      val R = cumR(i)
      len = max(len, R.length)
      Sorting.quickSort(R)

      // reverse
      rep(R.length / 2) { j =>
        val t = R(j)
        R(j) = R(R.length - 1 - j)
        R(R.length - 1 - j) = t
      }

      rep(R.length - 1, 1) { j =>
        R(j) += R(j - 1)
      }
    }
    Sorting.quickSort(cumR)(Ordering.by(_.length))

    var ans = 0L
    var l = 0
    rep(len, 1) { k =>
      var sum = 0L
      while(l < M && cumR(l).length < k) l += 1
      if (l < M) {
        l until M foreach { i =>
          sum += cumR(i)(k - 1)
        }
        ans = max(ans, sum)
      }
    }

    out.println(ans)
  }

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

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

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

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

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

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