Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1 ≤ a1 ≤ a2 ≤ ... ≤ an). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws each box vertically down on the first wi stairs of the staircase, that is, the box covers stairs with numbers 1, 2, ..., wi. Each thrown box flies vertically down until at least one of the two following events happen:  the bottom of the box touches the top of a stair;  the bottom of the box touches the top of a box, thrown earlier. We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width wi cannot touch the stair number wi + 1.You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.

The first line contains integer n (1 ≤ n ≤ 105) — the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of n integers, a1, a2, ..., an (1 ≤ ai ≤ 109; ai ≤ ai + 1). The next line contains integer m (1 ≤ m ≤ 105) — the number of boxes. Each of the following m lines contains a pair of integers wi, hi (1 ≤ wi ≤ n; 1 ≤ hi ≤ 109) — the size of the i-th thrown box. The numbers in the lines are separated by spaces.

Print m integers — for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteThe first sample are shown on the picture.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong).scanLeft(0l){Math.max}
  val m = in.next().toInt
  println((1 to m).map { _ =>
    val Array(w, h) = in.next().split(' ').map(_.toInt)
    val res = Math.max(data(1), data(w))
    data(1) = res + h
    res
  }.mkString("\n"))
}

import scala.math._
object C
{
    def main(args: Array[String])
    {
        val n = readInt
        val stairs = readLine split(" ") map(_.toInt)
        val m = readInt
        var height = 0L
        (0 until m) foreach
        {
            i =>
            val Array(w,h) = readLine split(" ") map(_.toInt)
            val hh = max(height, stairs(w-1))
            println(hh)
            height = h + hh
        }
    }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val m=readInt
    var height:Long=0
    for(_<-1 to m){
        val Array(w,h)=readLine.split(" ").map(_.toInt)
        val hh=math.max(height,a(w-1))
        println(hh)
        height=hh+h
    }
}

object Main272C {

  def main(args: Array[String]) {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val m = readInt
    var currentH = 0L
    for (i <- 1 to m) {
      val Array(w, h) = readLine.split(" ").map(_.toInt)
      val fallingH = currentH max a(w-1)
      println(fallingH)
      currentH = fallingH + h
    }
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).scanLeft(0){Math.max}
  val m = in.next().toInt
  println((1 to m).map { _ =>
    val Array(w, h) = in.next().split(' ').map(_.toInt)
    val res = Math.max(data(1), data(w))
    data(1) = res + h
    res
  }.mkString("\n"))
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val m=readInt
    var height=0
    for(_<-1 to m){
        val Array(w,h)=readLine.split(" ").map(_.toInt)
        val hh=math.max(height,a(w-1))
        println(hh)
        height=hh+h
    }
}

object Main272C {

  def main(args: Array[String]) {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val m = readInt
    var currentH = 0
    for (i <- 1 to m) {
      val Array(w, h) = readLine.split(" ").map(_.toInt)
      val fallingH = currentH max a(w-1)
      println(fallingH)
      currentH = fallingH + h
    }
  }

}


Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti. As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.It's time for Susie to go to bed, help her find such string p or state that it is impossible.

The first line contains string s of length n.  The second line contains string t of length n. The length of string n is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.

Print a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line "impossible" (without the quotes). If there are multiple possible answers, print any of them.

NoteIn the first sample different answers are possible, namely — 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101.

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val solve = (s : (String, String)) => {
      val str_builder = new StringBuilder(s._1);

      def flip_at = (i : Int) =>
        str_builder.setCharAt(i,
          str_builder.charAt(i) match {
            case '0' => '1'
            case '1' => '0'
          }
        )

      val indices_to_flip : Seq[Int] = s.zipped.toIndexedSeq.zipWithIndex.filter{ case ((x,y),_) => x != y }.map(_._2)

      def flip = (xs : Seq[Int], f : Int => Unit) =>
        (xs.size % 2, xs.size / 2) match {
          case (1, _) => println("impossible"); false
          case (0, halfsz) => xs.take(halfsz) foreach f; true
        }

      if (flip(indices_to_flip, flip_at)) {
        println(str_builder);
      }
    }

    solve(( (f : () => String) => (f(), f()) ) ( StdIn.readLine ));
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val solve = (s : (String, String)) => {
      val str_builder = new StringBuilder(s._1);

      def flip_at = (i : Int) =>
        str_builder.setCharAt(i,
          str_builder.charAt(i) match {
            case '0' => '1'
            case '1' => '0'
          }
        )

      val indices_to_flip : Seq[Int] = s.zipped.toIndexedSeq.zipWithIndex.filter{ case ((x,y),_) => x != y }.map(_._2)

      def flip = (xs : Seq[Int], f : Int => Unit) =>
        (xs.size % 2, xs.size / 2) match {
          case (1, _) => false
          case (0, halfsz) => xs.take(halfsz) foreach f; true
        }

      println(
        flip(indices_to_flip, flip_at) match {
          case true => str_builder;
          case false => "impossible"
        } )

    }

    solve(( (f : () => String) => (f(), f()) ) ( StdIn.readLine ));
  }
}

object P545_B_Equidistant_String {

  def find(s: String, t: String): String = {
    var flag = true
    val p: Seq[Char] = s.zip(t).map {
      case (a, b) =>
        if (a == b) a
        else {
          if (flag) {
            flag = false
            a
          } else {
            flag = true
            b
          }
        }
    }
    if (flag) p.mkString
    else "impossible"
  }

  def main(args: Array[String]) = {
    val s = scala.io.StdIn.readLine
    val t = scala.io.StdIn.readLine
    val p = find(s, t)
    println(p)
  }

}

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

object B extends App {
  val s = readLine().map(_.toString.toInt)
  val t = readLine().map(_.toString.toInt)
  val answer = new Array[Int](s.length)

  def dist(A: Seq[Int], B: Seq[Int]): Int = A.zip(B).map(x => Math.abs(x._1 - x._2)).sum

  def solve(): Boolean = {
    var dist1 = dist(s, answer)
    var dist2 = dist(t, answer)

    if (dist1 == dist2) true
    else {
      for (i <- 0 until s.length) {
        if (s(i) == 1 && t(i) == 0 && dist1 > dist2) {
          answer(i) = 1
          dist1 -= 1
          dist2 += 1
        } else if (s(i) == 0 && t(i) == 1 && dist2 > dist1) {
          answer(i) = 1
          dist1 += 1
          dist2 -= 1
        }

        if (dist1 == dist2) return true
      }
      false
    }
  }

  println(if (solve()) answer.mkString("") else "impossible")
}

import scala.io.StdIn
object b extends App {
  var l = List(StdIn.readLine, StdIn.readLine)
  var d = l(0).count(_=='1') - l(1).count(_=='1')
  if (d < 0) { d = -d; l=l.reverse }
  println(if (d%2 == 0) {
    d /= 2
    l(0).zip(l(1)).map(x =>
        if (x._1 != x._2 && x._2 == '0' && d > 0) {d-=1; '1'} else '0'
    ).mkString
  } else "impossible")
}

import scala.io.StdIn
object z1 extends App {
  var s = StdIn.readLine().toCharArray
  var t = StdIn.readLine().toCharArray
  var c = 0
  var p = StringBuilder.newBuilder
  (0 until s.length).foreach(i=>{
    if (s(i)!=t(i)) c+=1
    if (c%2==0) p+=s(i) else p+=t(i)
  })
  if (c%2==1) println("impossible") else println(p)
}

import java.util.StringTokenizer

object _545B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val s = next
  val t = next
  val n = s.length
  val diff = (0 until n).map(i => if (s(i) == t(i)) 0 else 1).sum
  if (diff % 2 == 1) println("impossible")
  else {
    val ans = new StringBuilder
    def doit(i: Int, cnt: Int): Unit = {
      if (i < n) {
        if (s(i) == t(i)) {
          ans += s(i)
          doit(i + 1, cnt)
        }
        else {
          if (cnt < diff / 2) {
            ans += s(i)
            doit(i + 1, cnt + 1)
          }
          else {
            ans += t(i)
            doit(i + 1, cnt)
          }
        }
      }
    }

    doit(0, 0)
    println(ans.toString)
  }
}

object B545 {

  import IO._

  def main(args: Array[String]): Unit = {
    val s = read
    val t = read
    var dist = 0
    for(i <- 0 until s.length) {
      if(s(i) != t(i)) dist += 1
    }
    if(dist%2 == 0) {
      val res = Array.fill(s.length)('x')
      var j = 0
      for(i <- 0 until s.length) {
        if(s(i) != t(i)) {
          if(j%2 == 0)
            res(i) = s(i)
          else
            res(i) = t(i)
          j += 1
        } else {
          res(i) = s(i)
        }
      }
      println(res.mkString(""))
    } else {
      println("impossible")
    }
  }

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

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

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

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

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

}

object B545 extends App{

  val s  = readLine
  val t  = readLine
  val ln = s.size
  var flag = false
  var counter = 0

  val result = for(i <- 0 until ln) yield {
    if(s(i) == t(i))
      s(i)
    else
    {
      counter += 1
      if(flag)
        { flag = false; s(i) }
      else
        { flag = true ; t(i) }
    }
  }

  if(counter % 2 != 0)
    print("impossible")
  else
    print(result.mkString(""))
}

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

import scala.collection.mutable

object B {

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

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

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

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

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

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

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

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

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

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

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

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

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

  def solve: Int = {
    val s = next.toCharArray
    val p = next.toCharArray
    val n = s.length
    var diff = 0
    for (i <- 0 until n) {
      if (s(i) != p(i))
        diff += 1
    }
    if (diff % 2 == 1) {
      out.println("impossible")
    } else {
      var first = 0
      var second = 0
      for (i <- 0 until n) {
        if (s(i) != p(i)) {
            if (first > second) {
              out.print(p(i))
              second += 1
            } else {
              out.print(s(i))
              first += 1
            }
        } else {
          out.print(s(i))
        }
      }
    }
    return 0
  }
}

object _545B extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = (List[Char], List[Char])
  override type Output = Option[List[Char]]

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    (next.toList, next.toList)
  }

  override def solve(input: Input) = {
    val (s, t) = input

    var count = 0

    val result = mutable.ListBuffer.empty[Char]

    for {
      (s1, t1) <- s zip t
    } {
      if (s1 == t1) {
        result += s1
      } else {
        if (count == 0) {
          result += s1
          count += 1
        } else {
          result += t1
          count -= 1
        }
      }
    }
    when(count == 0)(result.toList)
  }

  override def format(result: Output) = result match {
    case None => "impossible"
    case Some(sol) => sol.mkString
  }
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

import scala.io.StdIn
object b extends App {
  var l = List(StdIn.readLine, StdIn.readLine)
  var d = l(0).count(_=='1') - l(1).count(_=='1')
  if (d < 0) { d = -d; l=l.reverse }
  println(if (d%2 == 0) {
    d /= 2
    val t = l(0).zip(l(1)).map(x =>
        if (x._1 != x._2 && x._2 == '0' && d > 0) {d-=1; '1'} else '0'
    ).mkString
  } else "impossible")
}

import scala.io.StdIn
object b extends App {
  val l = List(StdIn.readLine, StdIn.readLine)
  var d = l(0).count(_=='1') - l(1).count(_=='1')
  if (d < 0) { d = -d; l.reverse }
  println(if (d%2 == 0) {
    d /= 2
    l(0).zip(l(1)).map(x =>
        if (x._1 != x._2 && x._1 == '0' && d > 0) {d-=1; '1'} else '0'
    ).mkString
  } else "impossible")
}

import scala.io.StdIn
object b extends App {
  val (a, b) = (StdIn.readLine, StdIn.readLine)
  var d = (a.count(_=='1') - b.count(_=='1')).abs
  println(if (d%2 == 0) {
    d /= 2
    a.zip(b).map(x => if (x._1 != x._2 && d > 0) {d-=1; '1'} else '0').mkString
  } else "impossible")
}

object B545 {

  import IO._

  def main(args: Array[String]): Unit = {
    val s = read
    val t = read
    var dist = 0
    for(i <- 0 until s.length) {
      if(s(i) != t(i)) dist += 1
    }
    if(dist%2 == 0) {
      val res = Array.fill(s.length)('x')
      var j = 0
      for(i <- 0 until s.length) {
        if(s(i) != t(i)) {
          if(j%2 == 0)
            res(i) = '0'
          else
            res(i) = '1'
          j += 1
        } else {
          res(i) = s(i)
        }
      }
      println(res.mkString(""))
    } else {
      println("impossible")
    }
  }

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

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

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

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

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

}


Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the quantity of the numbers in the both given permutations.  Next line contains n space-separated integers — the first permutation. Each number between 1 to n will appear in the permutation exactly once.  Next line describe the second permutation in the same format.

Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.

NoteIn the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.In the second sample, he removes number 5 and inserts it after 1.In the third sample, the sequence of changes are like this:  1 5 2 3 4 1 4 5 2 3 1 3 4 5 2 1 2 3 4 5  So he needs three moves.

import scala.runtime.ScalaRunTime._

object Main
{
  def inv(p : Array[Int]) : Array[Int] =
  {
    var r = p.clone
    for(i <- 0 until p.length)
      r(p(i)-1) = i+1
    r
  }

  def permute(w : Array[Int], p : Array[Int]) : Array[Int] =
  {
    var r = w.clone
    for(i <- 0 until w.length)
      r(i) = p(w(i)-1)
    r
  }

  def main(args : Array[String]) : Unit =
  {
    val n = readInt
    val p1 = readLine split " " map (_.toInt)
    val p2 = readLine split " " map (_.toInt)
    val d = permute(p1,inv(p2))
    var i = 1
    while (i < n && d(i) > d(i-1))
      i += 1
    println(n-i)
  }
}

import java.util.Scanner

object CF119Div1A {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val xs = readIntArray(n)
    val ys = readIntArray(n)

    var px = 0
    var py = 0
    while (py < n) {
      if (xs(px) == ys(py)) {
        px += 1
        py += 1
      } else {
        py += 1
      }
    }
    println(n - px)
  }

  private def readIntArray(n: Int): Array[Int] = {
    val xs = new Array[Int](n)
    val line = readLine()
    val words = line.split(" ")
    for (i <- 0 until n) {
      xs(i) = words(i).toInt
    }
    xs
  }
}

import java.util.Scanner

object CF119Div1A {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val xs = new Array[Int](n)
    val ys = new Array[Int](n)
    for (i <- 0 until n) {
      xs(i) = sc.nextInt()
    }
    for (i <- 0 until n) {
      ys(i) = sc.nextInt()
    }

    var px = 0
    var py = 0
    while (py < n) {
      if (xs(px) == ys(py)) {
        px += 1
        py += 1
      } else {
        py += 1
      }
    }
    println(n - px)
  }
}

import annotation.tailrec

//package contest119.div2

/**
 * Created with IntelliJ IDEA.
 * User: Oleg
 * Date: 11.05.12
 * Time: 23:04
 * To change this template use File | Settings | File Templates.
 */

object C {
  val n = readInt()
  val List(from, to) = List.fill(2)(readLine().split(' ').map(_.toInt - 1))
  val invTo = Array.fill(n)(0)
  for (i <- 0 until n) invTo(to(i)) = i
  val convFrom = (for (i <- 0 until n) yield invTo(from(i))).toArray

  def grows: Int = {
    for (i <- 0 until n - 1) if (convFrom(i + 1) < convFrom(i)) return n - (i + 1)
    0
  }

  def main(args: Array[String]) {
    println(grows)
  }
}

object CF119Div1A {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val xs = toReversedIntArray(readLine().split(" "))
    val ys = toReversedIntArray(readLine().split(" "))

    val used = new Array[Boolean](n + 1)
    var xIndex = 0
    var yIndex = 0
    var cost = 0
    while (yIndex < n) {
      if (used(ys(yIndex))) {
        yIndex += 1
      } else if (used(xs(xIndex))) {
        xIndex += 1
      } else if (xs(xIndex) == ys(yIndex)) {
        used(ys(yIndex)) = true
        xIndex += 1
        yIndex += 1
      } else {
        used(xs(xIndex)) = true
        xIndex += 1
        cost += 1
      }
    }
    println(cost)
  }

  private def toReversedIntArray(strings: Array[String]): Array[Int] = {
    val intValues = new Array[Int](strings.length)
    for (i <- 0 until strings.length) {
      intValues((strings.length - 1) - i) = strings(i).toInt
    }
    intValues
  }
}

import scala.runtime.ScalaRunTime._

object Main
{
  def permute[T](w : Array[T], p : Array[Int]) : Array[T] =
  {
    var r = w.clone
    for(i <- 0 until w.length)
      r(p(i)-1) = w(i)
    r
  }

  def main(args : Array[String]) : Unit =
  {
    val n = readInt
    val p1 = readLine split " " map (_.toInt)
    val p2 = readLine split " " map (_.toInt)
    val d = permute(p1,p2)
    var i = 1
    while (i < n && d(i) > d(i-1))
      i += 1
    println(n-i)
  }
}


A permutation p of length n is a sequence of distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n). A permutation is an identity permutation, if for any i the following equation holds pi = i. A swap (i, j) is the operation that swaps elements pi and pj in the permutation. Let's assume that f(p) is the minimum number of swaps that you need to make the permutation p an identity permutation. Valera wonders, how he can transform permutation p into any permutation q, such that f(q) = m, using the minimum number of swaps. Help him do that.

The first line contains integer n (1 ≤ n ≤ 3000) — the length of permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — Valera's initial permutation. The last line contains integer m (0 ≤ m < n).

In the first line, print integer k — the minimum number of swaps. In the second line, print 2k integers x1, x2, ..., x2k — the description of the swap sequence. The printed numbers show that you need to consecutively make swaps (x1, x2), (x3, x4), ..., (x2k - 1, x2k).  If there are multiple sequence swaps of the minimum length, print the lexicographically minimum one.

NoteSequence x1, x2, ..., xs is lexicographically smaller than sequence y1, y2, ..., ys, if there is such integer r (1 ≤ r ≤ s), that x1 = y1, x2 = y2, ..., xr - 1 = yr - 1 and xr < yr.

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

/**
 * Created by hama_du on 2014/06/14.
 */
object ProblemD extends App {
  val INF = 1000000000

  def breakLoops(count: Int, initialLoop: ArrayBuffer[ArrayBuffer[Int]]) = {
    var loops = initialLoop
    val answers = new Array[Int](count * 2)
    (1 to count).foreach(i => {
      var bestV = INF
      var smallestLi = -1
      for ((loop, li) <- loops.zipWithIndex) {
        if (loop.size >= 2) {
          for (v <- loop) {
            if (bestV > v) {
              bestV = v
              smallestLi = li
            }
          }
        }
      }

      val bestLoop = loops(smallestLi)
      val sortedLoop = bestLoop.zipWithIndex.sorted
      answers((i-1)*2) = sortedLoop(0)._1+1
      answers((i-1)*2+1) = sortedLoop(1)._1+1

      val left = Math.min(sortedLoop(0)._2, sortedLoop(1)._2)
      val right = Math.max(sortedLoop(0)._2, sortedLoop(1)._2)
      loops += bestLoop.slice(0, left+1) ++ bestLoop.slice(right+1,bestLoop.size)
      loops += bestLoop.slice(left+1, right+1)
      loops(smallestLi) = ArrayBuffer[Int]()
      loops = loops.filter(p => p.size >= 2)
    })
    answers
  }

  def connectLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {
    val l = loops.size
    val answers = new Array[Int](count * 2)
    (1 to count).foreach(i => {
      answers((i-1)*2) = 1
      answers((i-1)*2+1) = loops(i)(0)+1
    })
    answers
  }

  def countSwaps(loops: ArrayBuffer[ArrayBuffer[Int]]) = {
    loops.map(loop => loop.size-1).sum
  }

  def makeLoops(array: Array[Int]): ArrayBuffer[ArrayBuffer[Int]] = {
    val n = array.size
    val done = new Array[Boolean](n)
    val loops = new ArrayBuffer[ArrayBuffer[Int]]()
    (0 until n).foreach(i => {
      if (!done(i)) {
        val loopIndices = new ArrayBuffer[Int]()
        var li = i
        while (!done(li)) {
          done(li) = true
          loopIndices += li
          li = array(li)
        }
        loops += loopIndices
      }
    })
    loops
  }

  val in = new Scanner(System.in)
  val n = in.nextInt
  val array = (0 until n).map(_ => in.nextInt-1).toArray
  val m = in.nextInt
  val loops = makeLoops(array)
  val swapValue = countSwaps(loops)

  val countOperation = Math.abs(m-swapValue)

  println(countOperation)
  if (m < swapValue) {
    val answer = breakLoops(countOperation, loops)
    println(answer.mkString(" "))
  } else if (m > swapValue) {
    val answer = connectLoops(countOperation, loops)
    println(answer.mkString(" "))
  }
}

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

/**
 * Created by hama_du on 2014/06/14.
 */
object ProblemD extends App {
  val INF = 1000000000

  def breakLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {
    val answers = new Array[Int](count * 2)
    (1 to count).foreach(i => {
      var best = ((INF, INF), -1, -1)
      for ((loop, li) <- loops.zipWithIndex) {
        for ((value, vi) <- loop.zipWithIndex) {
          val min = Math.min(value, loop((vi+1)%loop.size))
          val max = Math.max(value, loop((vi+1)%loop.size))
          if (best._1._1 > min || (best._1._1 == min && best._1._2 > max)) {
            best = ((min, max), li, vi)
          }
        }
      }
      answers((i-1)*2) = best._1._1+1
      answers((i-1)*2+1) = best._1._2+1
      val deleteIndex = (best._3+1) % loops(best._2).size
      loops(best._2).remove(deleteIndex)
    })
    answers
  }

  def connectLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {
    val l = loops.size
    val answers = new Array[Int](count * 2)
    (1 to count).foreach(i => {
      answers((i-1)*2) = 1
      answers((i-1)*2+1) = loops(i)(0)+1
    })
    answers
  }

  def countSwaps(loops: ArrayBuffer[ArrayBuffer[Int]]) = {
    loops.map(loop => loop.size-1).sum
  }

  def makeLoops(array: Array[Int]): ArrayBuffer[ArrayBuffer[Int]] = {
    val n = array.size
    val done = new Array[Boolean](n)
    val loops = new ArrayBuffer[ArrayBuffer[Int]]()
    (0 until n).foreach(i => {
      if (!done(i)) {
        val loopIndices = new ArrayBuffer[Int]()
        var li = i
        while (!done(li)) {
          done(li) = true
          loopIndices += li
          li = array(li)
        }
        loops += loopIndices
      }
    })
    loops
  }

  val in = new Scanner(System.in)
  val n = in.nextInt
  val array = (0 until n).map(_ => in.nextInt-1).toArray
  val m = in.nextInt
  val loops = makeLoops(array)
  val swapValue = countSwaps(loops)

  val countOperation = Math.abs(m-swapValue)

  println(countOperation)
  if (m < swapValue) {
    val answer = breakLoops(countOperation, loops)
    println(answer.mkString(" "))
  } else if (m > swapValue) {
    val answer = connectLoops(countOperation, loops)
    println(answer.mkString(" "))
  }
}

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

/**
 * Created by hama_du on 2014/06/14.
 */
object ProblemD extends App {
  val INF = 1000000000

  def breakLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {
    val answers = new Array[Int](count * 2)
    (1 to count).foreach(i => {
      var best = ((INF, INF), -1, -1)
      for ((loop, li) <- loops.zipWithIndex) {
        if (loop.size >= 2) {
          for ((value, vi) <- loop.zipWithIndex) {
            val min = Math.min(value, loop((vi + 1) % loop.size))
            val max = Math.max(value, loop((vi + 1) % loop.size))
            if (best._1._1 > min || (best._1._1 == min && best._1._2 > max)) {
              best = ((min, max), li, vi)
            }
          }
        }
      }
      answers((i-1)*2) = best._1._1+1
      answers((i-1)*2+1) = best._1._2+1
      val deleteIndex = (best._3+1) % loops(best._2).size
      loops(best._2).remove(deleteIndex)
    })
    answers
  }

  def connectLoops(count: Int, loops: ArrayBuffer[ArrayBuffer[Int]]) = {
    val l = loops.size
    val answers = new Array[Int](count * 2)
    (1 to count).foreach(i => {
      answers((i-1)*2) = 1
      answers((i-1)*2+1) = loops(i)(0)+1
    })
    answers
  }

  def countSwaps(loops: ArrayBuffer[ArrayBuffer[Int]]) = {
    loops.map(loop => loop.size-1).sum
  }

  def makeLoops(array: Array[Int]): ArrayBuffer[ArrayBuffer[Int]] = {
    val n = array.size
    val done = new Array[Boolean](n)
    val loops = new ArrayBuffer[ArrayBuffer[Int]]()
    (0 until n).foreach(i => {
      if (!done(i)) {
        val loopIndices = new ArrayBuffer[Int]()
        var li = i
        while (!done(li)) {
          done(li) = true
          loopIndices += li
          li = array(li)
        }
        loops += loopIndices
      }
    })
    loops
  }

  val in = new Scanner(System.in)
  val n = in.nextInt
  val array = (0 until n).map(_ => in.nextInt-1).toArray
  val m = in.nextInt
  val loops = makeLoops(array)
  val swapValue = countSwaps(loops)

  val countOperation = Math.abs(m-swapValue)

  println(countOperation)
  if (m < swapValue) {
    val answer = breakLoops(countOperation, loops)
    println(answer.mkString(" "))
  } else if (m > swapValue) {
    val answer = connectLoops(countOperation, loops)
    println(answer.mkString(" "))
  }
}


Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k.Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins.

The first line contains two integers n and k (1  ≤  n, k  ≤  500) — the number of coins and the price of the chocolate, respectively. Next line will contain n integers c1, c2, ..., cn (1 ≤ ci ≤ 500) — the values of Pari's coins. It's guaranteed that one can make value k using these coins.

First line of the output must contain a single integer q— the number of suitable values x. Then print q integers in ascending order — the values that Arya can make for some subset of coins of Pari that pays for the chocolate.

object C687 {
  def mark(
    n: Int,
    k: Int,
    subK: Int,
    dp: Array[Array[Array[Option[Boolean]]]],
    c: Array[Int]
  ): Boolean = {
    if (k == 0 && subK == 0) true
    else if (k < 0 || subK < 0) false
    else if (n == 0) false
    else if (dp(n % 2)(k)(subK) != null) dp(n)(k)(subK).get
    else {
      val ret = (mark(n - 1, k - c(n - 1), subK, dp, c) ||
          mark(n - 1, k - c(n - 1), subK - c(n - 1), dp, c) ||
          mark(n - 1, k, subK, dp, c))

      dp(n)(k)(subK) = Some(ret)

      ret
    }
  }

  def main(args: Array[String]) = {
    val n :: k :: rest = readLine.split(" ").map(_.toInt).toList

    val c = readLine.split(" ").map(_.toInt).toArray

    val dp = Array.ofDim[Boolean](2, k + 1, k + 1)

    dp(0)(0)(0) = true

    var nn = 1

    while (nn <= n) {
      val index = nn % 2
      val prev = 1 - index

      var kk = 0
      while (kk <= k) {

        var subK = 0

        while (subK <= kk) {
          dp(index)(kk)(subK) = (if (kk - c(nn - 1) >= 0) dp(prev)(kk - c(nn - 1))(subK) else false) ||
              (if (kk - c(nn - 1) >= 0 && subK - c(nn - 1) >= 0) dp(prev)(kk - c(nn - 1))(subK - c(nn - 1)) else false) ||
              dp(prev)(kk)(subK)
          if (dp(index)(kk)(subK)) {
            //println(s"$index, $kk, $subK")
            //readLine
          }

          subK += 1
        }

        kk += 1
      }

      nn += 1
    }

    val ret = (0 to k).filter { case sum => dp(n % 2)(k)(sum) }

    println(ret.length)
    println(ret.mkString(" "))
  }
}

object C687 {
  def main(args: Array[String]) = {
    val n :: k :: rest = readLine.split(" ").map(_.toInt).toList
    val c = readLine.split(" ").map(_.toInt).toArray
    val dp = Array.ofDim[Boolean](2, k + 1, k + 1)
    dp(0)(0)(0) = true
    var nn = 1
    while (nn <= n) {
      val index = nn % 2
      val prev = 1 - index
      var kk = 0
      while (kk <= k) {
        var subK = 0
        while (subK <= kk) {
          dp(index)(kk)(subK) = (if (kk - c(nn - 1) >= 0) dp(prev)(kk - c(nn - 1))(subK) else false) ||
              (if (kk - c(nn - 1) >= 0 && subK - c(nn - 1) >= 0) dp(prev)(kk - c(nn - 1))(subK - c(nn - 1)) else false) ||
              dp(prev)(kk)(subK)
          subK += 1
        }
        kk += 1
      }
      nn += 1
    }
    val ret = (0 to k).filter { case sum => dp(n % 2)(k)(sum) }
    println(ret.length)
    println(ret.mkString(" "))
  }
}


When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.

The first line contains a single integer $$$n$$$ ($$$1 \leqslant n \leqslant 10^5$$$) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'. It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit $$$0$$$ or "one" which corresponds to the digit $$$1$$$.

Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.

NoteIn the first example, the correct initial ordering is "zero".In the second example, the correct initial ordering is "oneonezero".

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 private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 = {
    var i = from
    while(i <= to) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

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

  def solve(): Unit = {
    val n = ni()
    val s = ns(n)
    val c = Array.ofDim[Int](26)
    REP(n) { i =>
      c(s(i)-'a') += 1
    }
    val ones = c('n'-'a')
    val zeros = c('z'-'a')
    val ans = ArrayBuffer[Int]()
    REP(ones) { _ => ans += 1}
    REP(zeros) { _ => ans += 0}
    out.println(ans.mkString(" "))
  }
}

import scala.io.StdIn

object Codeforces1120A extends App {
  StdIn.readLine()
  val cards = StdIn.readLine().split("")
  val ones = cards.filter(a => a == "n").map(a => "1")
  val zeroes = cards.filter(a => a == "z").map(a => "0")
  println((ones ++ zeroes).mkString(" "))
}

import scala.io.StdIn

object Codeforces1120A extends App {
  StdIn.readLine()
  val word = StdIn.readLine()
  val ones = word.split("").filter(a => a == "n").map(a => "1")
  val zeroes = word.split("").filter(a => a == "z").map(a => "0")
  val n = ones ++ zeroes
  println(n.mkString(" "))
}

import scala.io.StdIn

object Codeforces1120A extends App {
  StdIn.readLine()
  val word = StdIn.readLine()
  val ones = word.split("").filter(a => a == "n").map(a => "1")
  val zeroes = word.split("").filter(a => a == "z").map(a => "0")
  if (ones.length > 0)
    println(ones.mkString(" ") + " " + zeroes.mkString(" "))
  else
    println("0")
}


International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.You are given a list of abbreviations. For each of them determine the year it stands for.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.  Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.

For each abbreviation given in the input, find the year of the corresponding Olympiad.

import scala.io.StdIn._

object C extends App {

  // 1989 - 1998   1 digit

  def findYear(s: String) = {
    val len = s.length
    var pow = 10
    var offset = 0
    for (_ <- 1 until len) {
      offset += pow
      pow *= 10
    }

    val year = s.toInt
    val L = 1989 + offset
    val m = L / pow
    val result = m * pow + year
    if (result < L) result + pow else result
  }

  val n = readInt()
  (1 to n).foreach { _ =>
    val s = readLine().drop(4)
    println(findYear(s))
  }

}

import scala.io.StdIn._

object C extends App {

  // 1989 - 1998   1 digit

  def findYear(s: String) = {
    val len = s.length
    var pow = 10
    var offset = 0
    for (_ <- 1 until len) {
      offset += pow
      pow *= 10
    }

    val year = s.toInt
    val L = 1989 + offset
    if (year == 0) {
      1990
    } else {
      val m = L / pow
      val result = m * pow + year
      if (result < L) result + pow else result
    }
  }

  val n = readInt()
  (1 to n).foreach { _ =>
    val s = readLine().drop(4)
    println(findYear(s))
  }

}


Heidi is a statistician to the core, and she likes to study the evolution of marmot populations in each of V (1 ≤ V ≤ 100) villages! So it comes that every spring, when Heidi sees the first snowdrops sprout in the meadows around her barn, she impatiently dons her snowshoes and sets out to the Alps, to welcome her friends the marmots to a new season of thrilling adventures.Arriving in a village, Heidi asks each and every marmot she comes across for the number of inhabitants of that village. This year, the marmots decide to play an April Fools' joke on Heidi. Instead of consistently providing the exact number of inhabitants P (10 ≤ P ≤ 1000) of the village, they respond with a random non-negative integer k, drawn from one of two types of probability distributions:  Poisson (d'avril) distribution: the probability of getting an answer k is  for k = 0, 1, 2, 3, ...,  Uniform distribution: the probability of getting an answer k is  for k = 0, 1, 2, ..., 2P. Heidi collects exactly 250 answers per village. Every village follows either the Poisson or the uniform distribution. Heidi cannot tell marmots apart, so she may query some marmots several times, and each time the marmot will answer with a new number drawn from the village's distribution.Can you help Heidi to find out whether a village follows a Poisson or a uniform distribution?

The first line of input will contain the number of villages V (1 ≤ V ≤ 100). The following V lines each describe one village. The description of each village consists of 250 space-separated integers k, drawn from one of the above distributions.

Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answer came from a uniform distribution.

NoteThe full example input is visually represented below, along with the probability distribution function it was drawn from (the y-axis is labeled by its values multiplied by 250).

import java.util.StringTokenizer

import scala.collection.mutable

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  val Z = 250

  read()
  val n = int()
  for (i <- 1 to n) {
    read()
    val arr = Array.fill(Z)(int())

    val avg = arr.sum.toDouble / Z
    val disp = arr.map(x => (x - avg) * (x - avg)).sum / (Z - 1)

    val limit = Math.sqrt(avg * avg * avg / 3)
    //println(s"$avg, $disp, $limit")
    if (disp > limit) println("uniform") else println("poisson")
  }

}

import java.util.StringTokenizer

object E extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  val Z = 250

  read()
  val n = int()
  for (i <- 1 to n) {
    read()
    val arr = Array.fill(Z)(int())

    val avg = arr.sum.toDouble / Z
    val disp = arr.map(x => (x - avg) * (x - avg)).sum / (Z - 1)

    val limit = Math.sqrt(avg * avg * avg / 3)
    //println(s"$avg, $disp, $limit")
    val ans = if (disp > limit) {
      //uniform
      avg
    } else {
      //poisson
      avg
    }
    println(ans.round)
  }

}


A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.

The first line contains a pair of integer numbers n and v (1 ≤ n ≤ 105; 1 ≤ v ≤ 109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti, pi (1 ≤ ti ≤ 2; 1 ≤ pi ≤ 104), where ti is the vehicle type (1 – a kayak, 2 – a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.

In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.

import annotation._
import io.Source
// two lists: kayak list and catamaran list

// while we still have two metres available:
// choose either the biggest catamaran, or the two biggest kayaks (whichever is bigger)
// reduce the lists appropriately, and repeat
//
// we have one metre, or no metres:
// choose biggest kayak, or do nothing

object Lorry {
    val cataSize = 2
    val kayakSize = 1

    def main(args: Array[String]) = {
        val lines = Source.stdin.getLines()
        val firstLine = lines.next().split(" ")
        val numBoats = firstLine(0).toInt
        var truckVolume = firstLine(1).toInt

        // need to cover the case where truckVolume is odd:
        // choose the best kayak first
        val boats = getBoatLists(lines, numBoats)

        var kayaks = boats._1
        val catamarans = boats._2
        var accum: Pair[List[Int], Int] = Pair(Nil, 0)
        if (truckVolume % 2 == 1 && !kayaks.isEmpty) {
            accum = Pair(List(kayaks.head._1), kayaks.head._2)
            kayaks = kayaks.tail
            truckVolume -= kayakSize
        }
        val chosenBoatsAndCapacity = getOptimalSet(kayaks, catamarans, truckVolume, accum)
        println(chosenBoatsAndCapacity._2)
        // should split the output... put a space between the boats or something?
        chosenBoatsAndCapacity._1.foreach(x => print(x + " "))
        println()
    }

    def getBoatLists(lines: Iterator[String], numBoats: Int) = {
        var kayaks: List[Pair[Int, Int]] = Nil
        var catamarans: List[Pair[Int, Int]] = Nil

        for (i <- 1 to numBoats) {
            var current = lines.next().split(" ")
            if (current(0).toInt == 1)
                kayaks = Pair(i, current(1).toInt) :: kayaks
            else
                catamarans = Pair(i, current(1).toInt) :: catamarans
        }
        kayaks = kayaks.sortWith((first, second) => first._2 > second._2)
        catamarans = catamarans.sortWith((first, second) => first._2 > second._2)

        Pair(kayaks, catamarans)
    }

    @tailrec
    final def getOptimalSet(kayaks: List[Pair[Int, Int]], catas: List[Pair[Int, Int]], spaceLeft: Int, accum: Pair[List[Int], Int]):
    Pair[List[Int], Int] = {
        catas match {
            case Nil => finish(kayaks, spaceLeft, kayakSize, accum)
            case (cnum, ccargo) :: rcatas =>
                if (spaceLeft >= cataSize)
                    kayaks match {
                        case (knum1, kcargo1) :: (knum2, kcargo2) :: rkayaks =>
                            if (kcargo1 + kcargo2 > ccargo)
                                getOptimalSet(rkayaks, catas, spaceLeft - cataSize, Pair(knum1 :: knum2 :: accum._1, accum._2 + kcargo1 +
                                    kcargo2))
                            else
                                getOptimalSet(kayaks, rcatas, spaceLeft - cataSize, Pair(cnum :: accum._1, accum._2 + ccargo))
                        case List(Pair(knum, kcargo)) =>
                            if (kcargo > ccargo)
                                finish(catas, spaceLeft - kayakSize, cataSize, Pair(knum :: accum._1, accum._2 + kcargo))
                            else
                                getOptimalSet(kayaks, rcatas, spaceLeft - cataSize, Pair(cnum :: accum._1, accum._2 + ccargo))
                        case Nil =>
                            finish(catas, spaceLeft, cataSize, accum)
                    }
                else
                    finish(kayaks, spaceLeft, kayakSize, accum)
        }
    }

    def finish(boats: List[Pair[Int, Int]], spaceLeft: Int, boatSize: Int, accum: Pair[List[Int], Int]): Pair[List[Int], Int] = {

        @tailrec
        def finishHelper(boats: List[Pair[Int, Int]], spaceLeft: Int, accum: Pair[List[Int], Int]): Pair[List[Int], Int] = {
            boats match {
                case (bnum, bcargo) :: rboats if (spaceLeft >= boatSize) =>
                    finishHelper(rboats, spaceLeft - boatSize, Pair(bnum :: accum._1, accum._2 + bcargo))
                case _ => accum
            }
        }
        finishHelper(boats, spaceLeft, accum)
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, v) = in.next().split(' ').map(_.toInt)
  val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))
  val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse
  val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))
  val bigSmallBoat = if (v % 2 == 0 || smallBoats.length == 0) None else Some(smallBoats.head)
  val newSmallBoats = bigSmallBoat match {
    case None => smallBoats
    case Some(_) => smallBoats.tail
  }

  val pairsSmallBoats = newSmallBoats.grouped(2).map{l =>
    if (l.length == 2)
      (l.head._1 + l.last._1, l.head._2 + " " + l.last._2)
    else
      (l.head._1, l.head._2)
  }.toList
  val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)
  println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)
  println(r.map(_._2).mkString(bigSmallBoat.map(_._2 + " ").getOrElse(""), " ", ""))
}

import java.util.Scanner
import scala.collection.mutable
import scala.util.Random

object Boats extends App {

  val scanner = new Scanner(System.in)

  val boatsNum = scanner.nextInt()
  val truckSize = scanner.nextInt()

  var light = mutable.PriorityQueue.empty[Boat]
  var heavy = mutable.PriorityQueue.empty[Boat]

  (1 until boatsNum + 1).foreach {
    cnt =>
      val t =scanner.next().toInt
      if (t == 1) {
        light += Boat(1, scanner.next().toInt, cnt)
      } else {
        heavy += Boat(2, scanner.next().toInt, cnt)
      }
  }

  var res = new StringBuffer()
  var sum = 0

  def append(b: Boat): Unit = {
    sum += b.weight
    res.append(b.order)
    res.append(" ")
  }

  solve(truckSize)

  def solve(sizeLeft: Int): Unit = {
    if (sizeLeft == 0) {
      printResult()
    } else if (sizeLeft == 1 && !light.isEmpty) {
      append(light.head)
      printResult()
    } else if (sizeLeft == 1 && light.isEmpty) {
      printResult()
    } else if (light.isEmpty && heavy.isEmpty) {
      printResult()
    } else if (light.isEmpty) {
      append(heavy.head)
      heavy = heavy.tail
      solve(sizeLeft - 2)
    } else if (heavy.isEmpty) {
      append(light.head)
      light = light.tail
      solve(sizeLeft - 1)
    } else if (light.size == 1) {
      if (heavy.head.weight > light.head.weight) {
        append(heavy.head)
        heavy = heavy.tail
        solve(sizeLeft - 2)
      } else {
        append(light.head)
        light = light.tail
        solve(sizeLeft - 1)
      }
    } else {
      val f = light.dequeue()
      val s = light.head
      if (heavy.head.weight > s.weight + f.weight) {
        append(heavy.dequeue())
        light += f
        solve(sizeLeft - 2)
      } else {
        append(f)
        solve(sizeLeft - 1)
      }
    }
  }

  def printResult(): Unit = {
    println(sum)
    println(res)
  }

  case class Boat(size: Int, weight: Int, order: Int) extends Ordered[Boat] {
    override def compare(that: Boat): Int = this.weight.compareTo(that.weight)
  }

  /*
  * 20 19
2 47
1 37
1 48
2 42
2 48
1 38
2 47
1 48
2 47
1 41
2 46
1 28
1 49
1 45
2 34
1 43
2 29
1 46
2 45
2 18
  * */

}

object P3B {
  def main(args : Array[String]) {
    val Array(n, v) = readLine split " " map {_.toInt}
    val a = Array.fill(n) {
      val Array(t, p) = readLine split " " map {_.toInt}
      (t, p)
    }.zipWithIndex
    val a1 = a filter {_._1._1 == 1} sortBy {-_._1._2}
    val s1 = a1.scanLeft(0){_ + _._1._2}
    val a2 = a filter {_._1._1 == 2} sortBy {-_._1._2}
    val s2 = a2.scanLeft(0){_ + _._1._2}
    val vU = v min (a1.size + a2.size * 2)
    val s = for (i <- 0 to vU / 2) yield {
      s1(vU - i * 2 min a1.size) + s2(i min a2.size)
    }
    val m = s.max
    println(m)
    val k = s indexOf m
    val w = ((a1 take vU - k * 2) ++ (a2 take k)) map {_._2 + 1}
    println(w mkString " ")
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, v) = in.next().split(' ').map(_.toInt)
  val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))
  val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse
  val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))
  val bigSmallBoat = if (v % 2 == 0) None else Some(smallBoats.head)
  val newSmallBoats = bigSmallBoat match {
    case None => smallBoats
    case Some(_) => smallBoats.tail
  }

  val pairsSmallBoats = newSmallBoats.grouped(2).map(l => (l.head._1 + l.last._1, l.head._2 + " " + l.last._2)).toList
  val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)
  println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)
  println(r.map(_._2).mkString(bigSmallBoat.map(_._2 + " ").getOrElse(""), " ", ""))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, v) = in.next().split(' ').map(_.toInt)
  val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))
  val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse
  val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))
  val bigSmallBoat = if (v % 2 == 0) None else Some(smallBoats.head)
  val newSmallBoats = bigSmallBoat match {
    case None => smallBoats
    case Some(_) => smallBoats.tail
  }

  val pairsSmallBoats = newSmallBoats.sliding(2).map(l => (l.head._1 + l.last._1, l.head._2 + " " + l.last._2)).toList
  val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)
  println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)
  println(r.map(_._2).mkString(bigSmallBoat.map(_._2 + " ").getOrElse(""), "\n", ""))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, v) = in.next().split(' ').map(_.toInt)
  val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))
  val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse
  val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))
  val bigSmallBoat = if (v % 2 == 0) None else Some(smallBoats.head)
  val newSmallBoats = bigSmallBoat match {
    case None => smallBoats
    case Some(_) => smallBoats.tail
  }

  val pairsSmallBoats = newSmallBoats.sliding(2).map(l => (l.head._1 + l.last._1, l.head._2 + " " + l.last._2)).toList
  val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)
  println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)
  println(r.map(_._2).mkString(bigSmallBoat.map(_._2).getOrElse(""), "\n", ""))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, v) = in.next().split(' ').map(_.toInt)
  val boats = in.take(n).toList.zipWithIndex.map(i => (i._1, (i._2 + 1).toString))
  val smallBoats = boats.filter(_._1.head == '1').map(i => (i._1.drop(2).toInt, i._2)).sorted.reverse
  val bigBoats: List[(Int, String)] = boats.filter(_._1.head == '2').map(i => (i._1.drop(2).toInt, i._2))
  val bigSmallBoat = if (v % 2 == 0) None else Some(smallBoats.head)
  val newSmallBoats = bigSmallBoat match {
    case None => smallBoats
    case Some(_) => smallBoats.tail
  }

  val pairsSmallBoats = newSmallBoats.sliding(2).map(l => (l.head._1 + l.last._1, l.head._2 + " " + l.last._2)).toList
  val r = (pairsSmallBoats ::: bigBoats).sorted.reverse.take(v / 2)
  println(bigSmallBoat.map(_._1).getOrElse(0) + r.map(_._1).sum)
  println(r.map(_._2).mkString(bigSmallBoat.map(_._2 + " ").getOrElse(""), " ", ""))
}

import java.util.Scanner

object Boats extends App {

  val scanner = new Scanner(System.in)

  val boatsNum = scanner.nextInt()
  val truckSize = scanner.nextInt()

  var light = List.empty[Boat]
  var heavy = List.empty[Boat]

  (1 until boatsNum + 1).foreach { cnt =>
    val t = scanner.nextInt()
    if (t == 1) {
      light :+= Boat(1, scanner.nextInt(), cnt)
    } else {
      heavy :+= Boat(2, scanner.nextInt(), cnt)
    }
  }

  light = light.sortBy(_.weight).reverse
  heavy = heavy.sortBy(_.weight).reverse

  var res = List.empty[Boat]

  solve(truckSize)

  def solve(sizeLeft: Int): Unit = {
    if (sizeLeft == 0) {
      printResult()
    } else if (sizeLeft == 1 && !light.isEmpty) {
      res :+= light.head
      printResult()
    } else if (light.isEmpty && heavy.isEmpty) {
      printResult()
    } else if(light.isEmpty) {
      res :+= heavy.head
      heavy = heavy.tail
      solve(sizeLeft - 2)
    } else if (heavy.isEmpty) {
      res :+= light.head
      light = light.tail
      solve(sizeLeft - 1)
    } else if (light.size == 1) {
      if (heavy.head.weight > light.head.weight) {
        res :+= heavy.head
        heavy = heavy.tail
        solve(sizeLeft - 2)
      } else {
        res :+= light.head
        light = light.tail
        solve(sizeLeft - 1)
      }
    } else {
      if (heavy.head.weight > light.head.weight + light.tail.head.weight) {
        res :+= heavy.head
        heavy = heavy.tail
        solve(sizeLeft - 2)
      } else {
        res :+= light.head
        light = light.tail
        res :+= light.head
        light = light.tail
        solve(sizeLeft - 2)
      }
    }
  }

  def printResult(): Unit = {
    println(res.foldLeft(0)((acc, t) => acc + t.weight))
    println(res.map(_.order).mkString)
  }

  case class Boat(size: Int, weight: Int, order: Int) {

  }

}

import java.util.Scanner
import scala.collection.mutable
import scala.util.Random

object Boats extends App {

  val scanner = new Scanner(System.in)

  val boatsNum = scanner.nextInt()
  val truckSize = scanner.nextInt()

  var light = mutable.PriorityQueue.empty[Boat]
  var heavy = mutable.PriorityQueue.empty[Boat]

  (1 until boatsNum + 1).foreach {
    cnt =>
      val t =scanner.next().toInt
      if (t == 1) {
        light += Boat(1, scanner.next().toInt, cnt)
      } else {
        heavy += Boat(2, scanner.next().toInt, cnt)
      }
  }

  var res = ""
  var sum = 0

  def append(b: Boat): Unit = {
    sum += b.weight
    res += " " + b.order
  }

  solve(truckSize)

  def solve(sizeLeft: Int): Unit = {
    if (sizeLeft == 0) {
      printResult()
    } else if (sizeLeft == 1 && !light.isEmpty) {
      append(light.head)
      printResult()
    } else if (sizeLeft == 1 && light.isEmpty) {
      printResult()
    } else if (light.isEmpty && heavy.isEmpty) {
      printResult()
    } else if (light.isEmpty) {
      append(heavy.head)
      heavy = heavy.tail
      solve(sizeLeft - 2)
    } else if (heavy.isEmpty) {
      append(light.head)
      light = light.tail
      solve(sizeLeft - 1)
    } else if (light.size == 1) {
      if (heavy.head.weight > light.head.weight) {
        append(heavy.head)
        heavy = heavy.tail
        solve(sizeLeft - 2)
      } else {
        append(light.head)
        light = light.tail
        solve(sizeLeft - 1)
      }
    } else {
      val f = light.dequeue()
      val s = light.head
      if (heavy.head.weight > s.weight + f.weight) {
        append(heavy.dequeue())
        light += f
        solve(sizeLeft - 2)
      } else {
        append(f)
        solve(sizeLeft - 1)
      }
    }
  }

  def printResult(): Unit = {
    println(res)
    println(sum)
  }

  case class Boat(size: Int, weight: Int, order: Int) extends Ordered[Boat] {
    override def compare(that: Boat): Int = this.weight.compareTo(that.weight)
  }

  /*
  * 20 19
2 47
1 37
1 48
2 42
2 48
1 38
2 47
1 48
2 47
1 41
2 46
1 28
1 49
1 45
2 34
1 43
2 29
1 46
2 45
2 18
  * */

}

import java.util.Scanner

object Boats extends App {

  val scanner = new Scanner(System.in)

  val boatsNum = scanner.nextInt()
  val truckSize = scanner.nextInt()

  var light = List.empty[Boat]
  var heavy = List.empty[Boat]

  (1 until boatsNum + 1).foreach { cnt =>
    val t = scanner.nextInt()
    if (t == 1) {
      light :+= Boat(1, scanner.nextInt(), cnt)
    } else {
      heavy :+= Boat(2, scanner.nextInt(), cnt)
    }
  }

  light = light.sortBy(_.weight).reverse
  heavy = heavy.sortBy(_.weight).reverse

  var res = List.empty[Boat]

  solve(truckSize)

  def solve(sizeLeft: Int): Unit = {
    if (sizeLeft == 0) {
      printResult()
    } else if (sizeLeft == 1 && !light.isEmpty) {
      res :+= light.head
      printResult()
    } else if (light.isEmpty && heavy.isEmpty) {
      printResult()
    } else if(light.isEmpty) {
      res :+= heavy.head
      heavy = heavy.tail
      solve(sizeLeft - 2)
    } else if (heavy.isEmpty) {
      res :+= light.head
      light = light.tail
      solve(sizeLeft - 1)
    } else if (light.size == 1) {
      if (heavy.head.weight > light.head.weight) {
        res :+= heavy.head
        heavy = heavy.tail
        solve(sizeLeft - 2)
      } else {
        res :+= light.head
        light = light.tail
        solve(sizeLeft - 1)
      }
    } else {
      if (heavy.head.weight > light.head.weight + light.tail.head.weight) {
        res :+= heavy.head
        heavy = heavy.tail
        solve(sizeLeft - 2)
      } else {
        res :+= light.head
        light = light.tail
        res :+= light.head
        light = light.tail
        solve(sizeLeft - 2)
      }
    }
  }

  def printResult(): Unit = {
    println(res.foldLeft(0)((acc, t) => acc + t.weight))
    println(res.map(_.order).mkString(" "))
  }

  case class Boat(size: Int, weight: Int, order: Int) {

  }

}

object P3B {
    def main(args : Array[String]) {
        val Array(n, v) = readLine split " " map {_.toInt}
        val a = Array.fill(n) {
            val Array(t, p) = readLine split " " map {_.toInt}
            (t, p)
        }.zipWithIndex groupBy {_._1._1}
        val a1 = a(1) sortBy {_._1._2}
        val s1 = a1.scanLeft(0){_ + _._1._2}
        val a2 = a(2) sortBy {_._1._2}
        val s2 = a2.scanLeft(0){_ + _._1._2}
        val vU = v min (a1.size + a2.size * 2)
        val s = for (i <- 0 to vU / 2) yield s1(vU - i * 2) + s2(i)
        val m = s.max
        println(m)
        val k = s indexOf m
        val w = ((a1 take vU - k * 2) ++ (a2 take k)) map {_._2 + 1}
        println(w.mkString)
    }
}

object P3B {
    def main(args : Array[String]) {
        val Array(n, v) = readLine split " " map {_.toInt}
        val a = Array.fill(n) {
            val Array(t, p) = readLine split " " map {_.toInt}
            (t, p)
        }.zipWithIndex groupBy {_._1._1}
        val a1 = a(1) sortBy {_._1._2}
        val s1 = a1.scanLeft(0){_ + _._1._2}
        val a2 = a(2) sortBy {_._1._2}
        val s2 = a2.scanLeft(0){_ + _._1._2}
        val vU = v min (a1.size + a2.size * 2)
        val s = for {
            i <- 0 to vU / 2
            if (vU - i * 2 < s1.size)
            if (i < s2.size)
        } yield s1(vU - i * 2) + s2(i)
        val m = s.max
        println(m)
        val k = s indexOf m
        val w = ((a1 take vU - k * 2) ++ (a2 take k)) map {_._2 + 1}
        println(w mkString " ")
    }
}


There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.

The first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000). The second string contains n integers ti (1 ≤ ti ≤ T).

Output one integer  — the answer to the problem.

NoteIn the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 =  - 5 points. This is 35 in total.

object Solution {
  def main(args: Array[String]) {
    val r = new Reader
    val n, A, B, C, T = r.read[Int]
    val xs = r.read[Array[Int]](n).filter(_ <= T)

    if (B >= C) {
      println(A * xs.length)
    } else {
      println(xs.map(x => A + (T - x) * (C - B)).sum)
    }
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

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

  override def apply(io: IO): io.type = {
    val n, a, b, c, t = io.read[Int]
    val ts = io.read[Vector, Int](n)
    val ans = ts.sumWith(i => a + (((c - b)*(t - i)) max 0))
    io.write(ans)
  }

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

  }
}
/****************************[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

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  import IO._
  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: C of A): C[A] = Iterator.fill(n)(read).to[C]

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  private[IO] type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.head)
    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
      }
    }
  }
}


Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $$$n$$$ streets along the Eastern direction and $$$m$$$ streets across the Southern direction. Naturally, this city has $$$nm$$$ intersections. At any intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.When Dora passes through the intersection of the $$$i$$$-th Eastern and $$$j$$$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.Formally, on every of $$$nm$$$ intersections Dora solves an independent problem. She sees $$$n + m - 1$$$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $$$x$$$ and assign every skyscraper a height from $$$1$$$ to $$$x$$$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $$$x$$$.For example, if the intersection and the two streets corresponding to it look as follows:  Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved)  The largest used number is $$$5$$$, hence the answer for this intersection would be $$$5$$$.Help Dora to compute the answers for each intersection.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of streets going in the Eastern direction and the number of the streets going in Southern direction. Each of the following $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1}$$$, $$$a_{i,2}$$$, ..., $$$a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^9$$$). The integer $$$a_{i,j}$$$, located on $$$j$$$-th position in the $$$i$$$-th line denotes the height of the skyscraper at the intersection of the $$$i$$$-th Eastern street and $$$j$$$-th Southern direction.

Print $$$n$$$ lines containing $$$m$$$ integers each. The integer $$$x_{i,j}$$$, located on $$$j$$$-th position inside the $$$i$$$-th line is an answer for the problem at the intersection of $$$i$$$-th Eastern street and $$$j$$$-th Southern street.

NoteIn the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.In the second example, the answers are as follows:   For the intersection of the first line and the first column  For the intersection of the first line and the second column  For the intersection of the second line and the first column  For the intersection of the second line and the second column

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = nm(N, M)
    val Hmax = Array.ofDim[Int](N)
    val Vmax= Array.ofDim[Int](M)
    val H, V = Array.ofDim[Int](N, M)

    REP(N) { i =>
      val as = Array.ofDim[Int](M)
      REP(M) { j =>
        as(j) = A(i)(j)
      }
      val zip = new Zipper(as)

      REP(M) { j =>
        H(i)(j) = zip.get(A(i)(j))
      }

      Hmax(i) = zip.last
    }

    REP(M) { j =>
      val as = Array.ofDim[Int](N)
      REP(N) { i =>
        as(i) = A(i)(j)
      }
      val zip = new Zipper(as)

      REP(N) { i =>
        V(i)(j) = zip.get(A(i)(j))
      }

      Vmax(j) = zip.last
    }

    debug(Hmax)
    debug(Vmax)
    DEBUG {
      debug("H")
      REP(N) { i =>
        debug(H(i))
      }
      debug("V")
      REP(N) { i =>
        debug(V(i))
      }
    }

    val ans = Array.ofDim[Int](N, M)
    REP(N) { i =>
      REP(M) { j =>
        val v = max(H(i)(j), V(i)(j)) + max(Hmax(i) - H(i)(j), Vmax(j) - V(i)(j))
        ans(i)(j) = v
      }
    }

    REP(N) { i =>
      out.println(ans(i).mkString(" "))
    }
  }

  class Zipper(as: Array[Int]) {
    import java.util

    val A = as.distinct
    util.Arrays.sort(A)

    def get(x: Int): Int = {
      lowerBound(A, x) + 1
    }

    def last = A.length
  }

  // あえてコピペ
  // 要はcountLt
  // a >= x  [x-2, x-1, x, x, x, x+1] の 2
  def lowerBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = nm(N, M)
    val Hmax = Array.ofDim[Int](N)
    val Vmax= Array.ofDim[Int](M)
    val H, V = Array.ofDim[Int](N, M)

    REP(N) { i =>
      val as = Array.ofDim[Int](M)
      REP(M) { j =>
        as(j) = A(i)(j)
      }
      val zip = new Zipper(as)

      REP(M) { j =>
        H(i)(j) = zip.get(A(i)(j))
      }

      Hmax(i) = zip.last
    }

    REP(M) { j =>
      val as = Array.ofDim[Int](N)
      REP(N) { i =>
        as(i) = A(i)(j)
      }
      val zip = new Zipper(as)

      REP(N) { i =>
        V(i)(j) = zip.get(A(i)(j))
      }

      Vmax(j) = zip.last
    }

    debug(Hmax)
    debug(Vmax)
    DEBUG {
      debug("H")
      REP(N) { i =>
        debug(H(i))
      }
      debug("V")
      REP(N) { i =>
        debug(V(i))
      }
    }

    val ans = Array.ofDim[Int](N, M)
    REP(N) { i =>
      REP(M) { j =>
        val v = max(H(i)(j) + Vmax(j) - V(i)(j), V(i)(j) + Hmax(i) - H(i)(j))
        ans(i)(j) = v
      }
    }

    REP(N) { i =>
      out.println(ans(i).mkString(" "))
    }
  }

  class Zipper(as: Array[Int]) {
    import java.util

    val A = as.distinct
    util.Arrays.sort(A)

    def get(x: Int): Int = {
      lowerBound(A, x) + 1
    }

    def last = A.length
  }

  // あえてコピペ
  // 要はcountLt
  // a >= x  [x-2, x-1, x, x, x, x+1] の 2
  def lowerBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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


You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime.  Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.

NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime.  The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.

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

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

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val g = new Array[Vector[pair]](n+1)
        val ans = new Array[Int](n+1)
        for (i <- 1 to n) {
            g(i) = Vector[pair]()
        }
        var x = 0
        var y = 0
        var ok = true
        for (i <- 1 until n) {
            x = readInt()
            y = readInt()
            g(x) +:= pair(y, i)
            g(y) +:= pair(x, i)
        }
        for (i <- 1 to n) {
            if (g(i).length > 2) {
                ok = false
            }
        }
        if (!ok) {
            writer.println(-1)
        } else {
            for (i <-  1 to n) {
                if (g(i).length == 1) {
                    dfs(i, 0)
                }
            }
            for (i <- 1 until n) {
                writer.print(ans(i) + " ")
            }
            writer.println()
        }
        def dfs(v: Int, p: Int): Int = {
            if (p == 0) {
                ans(g(v)(0).b) = 2
                dfs(g(v)(0).a, v)
            } else {
                if (g(v).length == 1){
                    return 0
                }
                var x = g(v)(0)
                var y = g(v)(1)
                if (x.a == p) {
                    if (ans(x.b) == 2) {
                        ans(y.b) = 3
                        dfs(y.a, v)
                    } else {
                        ans(y.b) = 2
                        dfs(y.a, v)
                    }
                } else {
                    if (ans(y.b) == 2) {
                        ans(x.b) = 3
                        dfs(x.a, v)
                    } else {
                        ans(x.b) = 2
                        dfs(x.a, v)
                    }
                }
            }
            return 0
        }

        def check(kk: Long): Boolean = {
            return true
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}


Polycarp remembered the $$$2020$$$-th year, and he is happy with the arrival of the new $$$2021$$$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $$$n$$$ as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$.For example, if:   $$$n=4041$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2021$$$;  $$$n=4042$$$, then the number $$$n$$$ can be represented as the sum $$$2021 + 2021$$$;  $$$n=8081$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2020 + 2020 + 2021$$$;  $$$n=8079$$$, then the number $$$n$$$ cannot be represented as the sum of the numbers $$$2020$$$ and $$$2021$$$. Help Polycarp to find out whether the number $$$n$$$ can be represented as the sum of a certain number of numbers $$$2020$$$ and a certain number of numbers $$$2021$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$) — the number that Polycarp wants to represent as the sum of the numbers $$$2020$$$ and $$$2021$$$.

For each test case, output on a separate line:    "YES" if the number $$$n$$$ is representable as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

import io.StdIn.readLine

object newyearsnumber {
  def main(args: Array[String]): Unit = {
    val T = readLine().toInt
    for(i <- 1 to T){
      val N = readLine().toInt
      if((N%2020) <= N/2021){
        println("YES")
      }else{
        println("NO")
      }
    }
  }
}