import scala.annotation.tailrec
import net.pushl.io.MyConsole

package net.pushl.datastructure {
  import scala.reflect.ClassTag
  abstract class ASegmentTree[T: ClassTag](_n: Int) {
    protected val init: T
    protected def calc(left: T, right: T): T
    private val n = smallest2Powered(_n)
    private val data = {
      val d = implicitly[ClassTag[T]].newArray(2*n-1)
      (0 until n).foreach(d(_) = init)
      d
    }
    def update(i: Int, v: T) : Unit = {
      val k = i+n-1
      data(k) = v
      @tailrec
      def updateAux(k: Int) : Unit =
        if(k > 0) {
          val p   = parent(k)
          data(p) = calc(data(getLeft(p)),data(getRight(p)))
          updateAux(p)
        }
      updateAux(k)
    }
    // get data of [a,b)
    def get(a: Int, b: Int) : T = get(a,b,0,0,n)

    // l,r is segment of node k.
    protected def get(a: Int, b: Int, k: Int, l: Int, r: Int) : T = {
      if(r <= a || b <= l) init
      else if(a <= l && r <= b) data(k)
      else calc(get(a,b,getLeft(k) ,l,(l+r)/2),
                get(a,b,getRight(k),(l+r)/2,r))
    }

    final private def getLeft (i: Int) = 2*i+1
    final private def getRight(i: Int) = 2*i+2
    final private def parent  (i: Int) = (i-1)/2
    final private def smallest2Powered(n: Int) = {
      @tailrec
      def smallest2PoweredAux(k: Int) : Int = {
        if(k >= n) k
        else smallest2PoweredAux(k*2)
      }
      smallest2PoweredAux(1)
    }
    override def toString() = data.foldLeft("[")(_ + "," + _) + "]"
  }
  class RangeSumQueryTree[T: ClassTag](n: Int)(implicit num: Numeric[T])
                                               extends ASegmentTree[T](n) {
    override val init = num.zero
    override def calc(left: T, right: T) = num.plus(left,right)
  }
  // Numeric does not have INF.
  class RangeMinimumQueryTree(n: Int) extends ASegmentTree[Long](n) {
    override val init = 1l << 30
    override def calc(left: Long, right: Long) = left min right
  }
}

// Document: http://www.scala-lang.org/api/current/#package
// -----------------------------------------------------------------------------
import net.pushl.datastructure.RangeSumQueryTree
class Solver(val stdio: MyConsole){
  import stdio._ // shadow Console.~
  def main() : Unit = {
    val n,q = nextInt
    val rsq = new RangeSumQueryTree[Int](n)
    for(i <- 1 to q){
      val com,_x,_y = nextInt
      if(com == 0){
        val (x,y) = (_x-1,_y)
        rsq(x) = rsq.get(x,x+1) + y
      } else {
        val (x,y) = (_x-1,_y-1)
        println(rsq.get(x,y+1))
      }
    }
  }
}

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
object Main {
  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
}
package net.pushl.io {
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println("\u001b[36m" + obj + "\u001b[0m")

    def readIntVector()    : Vector[Int]    = parseLineToVector(() => nextInt)
    def readLongVector()   : Vector[Long]   = parseLineToVector(() => nextLong)
    def readStringVector() : Vector[String] = parseLineToVector(() => nextString)
    def nextInt()          : Int            = nextLong().toInt
    def nextBigInt()       : BigInt         = BigInt(nextString())
    def nextBigDecimal(  ) : BigDecimal     = BigDecimal(nextString())
    def nextDouble()       : Double         = nextString().toDouble
    def nextLong() : Long = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading long failed")
      val sgn = if(peek == '-') -1l else 1
      if(sgn == -1l) ignore(read())
      if(peek < '0' || '9' < peek)
        throw new NumberFormatException(s"readLong found only '-' or no number")
      @tailrec
      def readLong(next: Int, cur: Long) : Long =
        if('0' <= next && next <= '9'){
          ignore(read()) // is equal to next
          readLong(peek, cur*10 + next-'0')
        }
        else if(isEnd(next) || isSpaceOrControl(next))
          sgn*cur
        else
          throw new NumberFormatException(s"readLong found strange byte $next")
      val res = readLong(peek,0)
      skipTrailingSpaces()
      res
    }
    def nextString() : String = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading String failed")
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isSpaceOrControl(next)){
          builder.toString
        }else{
          builder.append(read().toChar) // here we skip.
          appendCode(peek)
        }
      }
      val res = appendCode(peek)
      skipTrailingSpaces()
      res
    }
    // TODO: refactoring to marge nextString
    def readLine() : String = {
      if(isEnd(peek))
        throw new NoSuchElementException("Reading Line failed")
      skipNewline()
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isNewLine(next)){
          builder.toString
        }else{
          builder.append(next.toChar)
          appendCode(read())
        }
      }
      appendCode(read())
    }
    // helpers
    private def ignore[T](x: => T) : Unit = { x; () }
    private[this] var peeked: Option[Int] = None
    private[this] var is_first = true
    protected def read() = {
      val res = peeked match {
        case None    => in.read()
        case Some(a) => { peeked = None; a }
      }
      is_first = false
      res
    }
    private def peek() =
      peeked match {
        case None    => {
          val res = in.read()
          peeked  = Some(res)
          res
        }
        case Some(a) => a
      }
    private def isEnd(c: Int)     = c == -1
    private def isCR(c: Int)      = c == 13
    private def isLF(c: Int)      = c == 10
    private def isNewLine(c: Int) = isLF(c) || isCR(c)
    private def isThereReadable() = !isEnd(peek)
    private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127
    @tailrec
    final private def goNextNotSpaceNorControl() : Unit =
      if(isSpaceOrControl(peek)){
        ignore(read())
        goNextNotSpaceNorControl()
      }
    final private def skipTrailingSpaces() : Unit = {
      @tailrec
      def skipTrailingSpacesAux() : Unit = {
        if(!isNewLine(peek) && isSpaceOrControl(peek)){
          ignore(read())
          skipTrailingSpacesAux()
        }
      }
      skipTrailingSpacesAux()
    }
    final private def skipNewline() : Unit =
      if(!is_first){
        if(isCR(peek))
          ignore(read())
        if(isLF(peek))
          ignore(read())
      }
    private def goNextValuable() : Boolean = {
      goNextNotSpaceNorControl()
      isThereReadable()
    }

    private def parseLineToVector[X](parser: () => X) : Vector[X] = {
      import scala.collection.immutable.VectorBuilder
      val vb = new VectorBuilder[X]()
      skipNewline()
      @tailrec
      def parseLineToVectorAux() : Vector[X] =
        if(isNewLine(peek) || isEnd(peek)) {
          vb.result
        }else{
          vb += parser()
          parseLineToVectorAux()
        }
      parseLineToVectorAux()
    }
  }
}


object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val INF = Int.MaxValue / 10
    val Vs, Es, root = sc.nextInt()
    val E = (0 until Es) map { _ =>
      val s, t, d = sc.nextInt()
      (s, t, d)
    }
    val W = Array.fill(Vs)(INF)
    W(root) = 0
    // ベルマンフォード, |V|-1回, 全ての辺を緩和させる
    (0 until Vs - 1) foreach { _ =>
      E foreach { case (u, v, w) =>
        if (W(v) > W(u) + w) {
          W(v) = W(u) + w
        }
      }
    }

    println(W. map { w =>
      if (w == INF) "INF" else w.toString
    }. mkString("\n"))
  }

}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Single Source Shortest Path

For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).

Input

An edge-weighted graph G (V, E) and the source r.

|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.

si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.

Output

Print the costs of SSSP in the following format.

c0
c1
:
c|V|-1

The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.

Constraints

1 ≤ |V| ≤ 100000

0 ≤ di ≤ 10000

0 ≤ |E| ≤ 500000

There are no parallel edges

There are no self-loops

Sample Input 1

4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5

Sample Output 1

0
1
3
4

Sample Input 2

4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5

Sample Output 2

3
0
2
INF

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


object Main{
  class Edge(val from:Int,val to:Int,val cost:Long){}

  // v:????????°
  // s:?§????
  // graph:??£??\?????????
  def dijkstra(v:Int,s:Int,graph:Array[Array[Edge]],inf:Long= Long.MaxValue / 10) : Array[Long] = {
    val d : Array[Long] = Array.fill(v)(inf)
    val que = new scala.collection.mutable.PriorityQueue[Tuple2[Long,Int]]()(Ordering.Tuple2[Long,Int].reverse)
    que += Tuple2(0,s)
    d(s) = 0
    while(que.nonEmpty){
      val (cost,node) = que.dequeue
      if(d(node) >= cost){
        for(e <- graph(node)){
          if(d(e.to) > d(node)+e.cost){
            d(e.to) = d(node)+e.cost
            que+=Tuple2(d(e.to),e.to)
          }
        }
      }
    }
    return d
  }

  def main(args : Array[String]){
    val inf = Long.MaxValue / 10
    val sc = new java.util.Scanner(System.in)
    val v,e,r = sc.nextInt
    val g : Array[Array[Edge]] = Array.fill(v)(Array.empty)

    for(i <- 0 to e-1){
      val s,t,d = sc.nextInt
      g(s) :+= new Edge(s,t,d)
    }

    val res = dijkstra(v,r,g,inf)
    res.foreach(x => if(x==inf) println("INF") else println(x))
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val Array(x1, y1, x2, y2, _*) = io.StdIn.readLine().split(" ").map(_.toDouble)

    val dx = Math.abs(x2 - x1)
    val dy = Math.abs(y2 - y1)
    val d = Math.sqrt(dx * dx + dy * dy)
    println(f"$d%.8f")
  }
}

Distance

Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).

Input

Four real numbers x1, y1, x2 and y2 are given in a line.

Output

Print the distance in real number. The output should not contain an absolute error greater than 10-4.

Sample Input

0 0 1 1

Sample Output

1.41421356


object Main {
  def main(args: Array[String]): Unit = {
    val scanner = new java.util.Scanner(System.in)
    val a, b = scanner.nextDouble
    val ca = math.toRadians(scanner.nextDouble)

    val h = b * math.sin(ca)
    val s = a * h / 2
    val c = math.sqrt(a * a + b * b * math.sin(ca) * math.sin(ca))
    println(f"$s%.5f")
    println(f"${a + b + c}%.5f")
    println(f"$h%.5f")
  }
}

Triangle

For given two sides of a triangle a and b and the angle C between them, calculate the following properties:

S: Area of the triangle

L: The length of the circumference of the triangle

h: The height of the triangle with side a as a bottom edge

Input

The length of a, the length of b and the angle C are given in integers.

Output

Print S, L and h in a line respectively. The output should not contain an absolute error greater than 10-4.

Sample Input

4 3 90

Sample Output

6.00000000
12.00000000
3.00000000


import java.util.Scanner

object Main {

  def solve(sc: => Scanner): Unit = {
    val N = sc.nextInt
    if (N != 0) {
      val A = Array.fill[Double](N)(sc.nextInt)
      val ave = A.sum / N: Double
      println(math.sqrt(A.map(X => (X - ave) * (X - ave)).sum / N))
      solve(sc)
    }
  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    solve(sc)
  }
}

Standard Deviation

You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn.

The variance α2 is defined by

α2 = (∑ni=1(si - m)2)/n

where m is an average of si.

The standard deviation of the scores is the square root of their variance.

Input

The input consists of multiple datasets. Each dataset is given in the following format:

n
s1 s2 ... sn

The input ends with single zero for n.

Output

For each dataset, print the standard deviation in a line. The output should not contain an absolute error greater than 10-4.

Constraints

n ≤ 1000

0 ≤ si ≤ 100

Sample Input

5
70 80 100 90 20
3
80 80 80
0

Sample Output

27.85677655
0.00000000


object Main extends App {
    val in = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt))
    while (in.next.head != 0) {
        val x = in.next.foldLeft((0.0, 0.0, 0)){case ((m, mean, n), d) =>
            (m - ((d + n * mean) / (n + 1) - d) * (d - mean), mean + (d - mean) / (n + 1), n + 1)
        }
        println(math.sqrt(x._1 / x._3))
    }
}


import scala.io.StdIn.{readLine,readInt}
/**
  * AOJ
  */

object Main {

  def main(args: Array[String]): Unit = {

    var dice1 = read
    val dice2 = read

    for(side <- dice1){
      if(!dice2.contains(side)){println("No");return}
    }

    dice1 = findSide(dice2(4),4,"HHH",findSide(dice2(0),0,"WNNNW",dice1))
    println(
      dice1 match {
        case null => "No"
        case dice1 if((dice1 zip dice2).forall(x => x._1 == x._2)) => "Yes"
        case _ => "No"
      }
    )
  }

  def findSide(sideNum:Int, findSide:Int, searchCommands:String, dice:Array[Int]) : Array[Int] = {
    if(dice(findSide) == sideNum){return dice}
    var d = dice
    for(c <- searchCommands.toCharArray){
      d = getNextStatus(c,d)
      if(d(findSide) == sideNum){return d}
    }
    return null
  }

  def getNextStatus(cmd:Char,dice:Array[Int]): Array[Int] = cmd
    match {
      case 'N' => Array(dice(1),dice(5),dice(2),dice(3),dice(0),dice(4))
      case 'W' => Array(dice(2),dice(1),dice(5),dice(0),dice(4),dice(3))
      case 'H' => Array(dice(0),dice(3),dice(1),dice(4),dice(2),dice(5))
    }

  def read() : Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Dice III

Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the same as that of another dice, these dices can be considered as identical.

Input

In the first line, six integers assigned to faces of a dice are given in ascending order of their corresponding labels.

In the second line, six integers assigned to faces of another dice are given in ascending order of their corresponding labels.

Output

Print "Yes" if two dices are identical, otherwise "No" in a line.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

Sample Input 1

1 2 3 4 5 6
6 2 4 3 5 1

Sample Output 1

Yes

Sample Input 2

1 2 3 4 5 6
6 5 4 3 2 1

Sample Output 2

No


/**
  * http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_11_C&lang=jp
  * Structure and Class - Dice III
  */
object Main {

  case class Dice(numbers: IndexedSeq[Int]) {
    def apply(number: Int): Int = {
      numbers(number)
    }

    def rotateTo(direction: Char): Dice = {
      direction match {
        case 'N' => Dice(IndexedSeq(numbers(1), numbers(5), numbers(2), numbers(3), numbers(0), numbers(4)))
        case 'S' => Dice(IndexedSeq(numbers(4), numbers(0), numbers(2), numbers(3), numbers(5), numbers(1)))
        case 'W' => Dice(IndexedSeq(numbers(2), numbers(1), numbers(5), numbers(0), numbers(4), numbers(3)))
        case 'E' => Dice(IndexedSeq(numbers(3), numbers(1), numbers(0), numbers(5), numbers(4), numbers(2)))
      }
    }

    def find(number: Int): Int = {
      numbers.indexWhere(_ == number)
    }

    def adjustWith(dice: Dice): Dice = {
      val operationsToTop = Seq("", "N", "W", "E", "S", "NN")
      val operationsToFront = Seq("S", "", "WSE", "ESW", "SEEN", "N")
      val dice2 = operationsToTop(this.find(dice(0))).foldLeft(this)(_.rotateTo(_))
      val dice3 = operationsToFront(dice2.find(dice(1))).foldLeft(dice2)(_.rotateTo(_))
      dice3
    }
  }

  def main(args: Array[String]): Unit = {
    val dice1 = Dice(io.StdIn.readLine().split(" ").map(_.toInt))
    val dice2 = Dice(io.StdIn.readLine().split(" ").map(_.toInt))
    if (dice1 == dice2.adjustWith(dice1))
      println("Yes")
    else
      println("No")
  }
}


object Main{
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val x = sc.nextInt
    println(x*x*x)
  }
}

X Cubic

Write a program which calculates the cube of a given integer x.

Input

An integer x is given in a line.

Output

Print the cube of x in a line.

Constraints

1 ≤ x ≤ 100

Sample Input 1

2

Sample Output 1

8

Sample Input 2

3

Sample Output 2

27


object Main {
  case class Line(string: String) {
    def strings: Seq[String] = string.split(' ')
    def ints: Seq[Int] = strings.map(_.toInt)
    def i(n: Int): Int = ints(n)
  }

  def readLine: Line = Line(io.StdIn.readLine())
  def readLines(n: Int): Seq[Line] = List.fill(n)(Line(io.StdIn.readLine()))

  def yesNo(b: Boolean): String = if (b) "Yes" else "No"

  def main(args: Array[String]) {
    println(scala.math.pow(readLine.i(0), 3).toInt)
  }
}


object Main{
  def main(args:Array[String]) ={
    val scanner = new java.util.Scanner(System.in)
    val a = scanner.nextInt
    println(a * a * a)
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val x = sc.nextInt
  println(x * x * x)
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val a, b = sc.nextInt
    println(a * b + " " + (a * 2 + b * 2))
  }
}

Rectangle

Write a program which calculates the area and perimeter of a given rectangle.

Input

The length a and breadth b of the rectangle are given in a line separated by a single space.

Output

Print the area and perimeter of the rectangle in a line. The two integers should be separated by a single space.

Constraints

1 ≤ a, b ≤ 100

Sample Input 1

3 5

Sample Output 1

15 16


object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val x = sc.nextInt
    val y = sc.nextInt

    println(calcArea(x, y) + " " + calcPerimeter(x, y))
  }

  def calcArea(x: Int, y: Int): Int = x * y
  def calcPerimeter(x: Int, y: Int): Int = 2*x + 2*y
}


import java.util.Scanner
import java.util.concurrent.TimeUnit

object Main {
  def main (args: Array[String]) = {
    val in = new Scanner(System.in)
    val s = in.nextInt
    val hh = TimeUnit.SECONDS.toHours(s)
    val mm = TimeUnit.SECONDS.toMinutes(s) - TimeUnit.HOURS.toMinutes(hh)
    val ss = TimeUnit.SECONDS.toSeconds(s) - TimeUnit.HOURS.toSeconds(hh) - TimeUnit.MINUTES.toSeconds(mm)

    println("%d:%d:%d" format(hh, mm, ss))
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Watch

Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.

Input

An integer $S$ is given in a line.

Output

Print $h$, $m$ and $s$ separated by ':'. You do not need to put '0' for a value, which consists of a digit.

Constraints

$0 \leq S \leq 86400$

Sample Input 1

46979

Sample Output 1

13:2:59


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val sIn = sc.nextInt()
  println(calc(sIn))

  def calc(s:Int): String = s"${s/3600}:${s%3600/60}:${s%60}"
}


object Main extends App {
  import scala.io.StdIn.readLine;
  val toTime:(Int) => String = (s:Int) => {
    (s / 3600).toString + ':' + (s % 3600 / 60) + ':' + (s % 60)
  }
  println(toTime(readLine.toInt))
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val S = sc.nextInt()
  val s = S % 60
  val mm = S / 60
  val m = mm % 60
  val h = mm / 60
  println(s"$h:$m:$s")
}


import scala.io.StdIn._
object Main {
 def main(args :Array[String]) = {
	var mtrl = readInt
	val (i, j, k) = (mtrl/3600, (mtrl%3600)/60, mtrl%60)
	println(i+":"+j+":"+k)
 }
}


object Main{
 def main(args:Array[String]):Unit ={
  val S = readInt
  val s = S%60
  val m = (S - s)/60%60
  val h = ((S - s) - m*60)/(60*60)
  println(s"$h:$m:$s")
 }
}


object Main {
  def main(args: Array[String]): Unit = {
    val S = io.StdIn.readInt()
    var s = S % 60
    var m = S / 60
    var h = m / 60
    m -= h * 60
    println(h + ":" + m + ":" + s)

  }
}


object Main {
  def main(args:Array[String]) {
    val time = readLine().toInt
    val h = time / 3600
    val m = (time / 60) - h
    val s = time % 60
    println(h + ":"  + m + ":" + s)
  }
}


object Main extends App {
  val arr = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ans =
    if (arr(0) == arr(1)) "a == b"
    else if( arr(0) < arr(1)) "a < b"
    else "a > b"

 println(ans)
}

Small, Large, or Equal

Write a program which prints small/large/equal relation of given two integers a and b.

Input

Two integers a and b separated by a single space are given in a line.

Output

For given two integers a and b, print

a < b

if a is less than b,

a > b

if a is greater than b, and

a == b

if a equals to b.

Constraints

-1000 ≤ a, b ≤ 1000

Sample Input 1

1 2

Sample Output 1

a < b

Sample Input 2

4 3

Sample Output 2

a > b

Sample Input 3

5 5

Sample Output 3

a == b


import scala.io.StdIn.readLine

object Main{
	def main(args: Array[String]){
		val input = readLine().split(" ").map(_.toInt)
		val a: Int = input(0)
		val b: Int = input(1)

		if(a > b){
			println("a > b")
		}else if(a < b){
			println("a < b")
		}else{
			println("a == b")
		}
	}
}


import scala.io.Source

object Main{
  def main(args: Array[String]){
    val list =
      for{
        in <- Source.stdin.getLines.toList
      } yield in.map(_.toInt).toList

    boc(list.flatten)
  }

  def boc(a: List[Int])={
    if(a(0) - a(1) == 0) println("a == b")
    else if(a(0) - a(1) > 0) println("a > b")
    else if(a(0) - a(1) < 0) println("a < b")
    else println()
  }
}


import scala.io.StdIn

object Main {
  def main(args: Array[String]){

	val Array(a, b, c) = StdIn.readLine().split(" ").map(_.toInt)
    println(if (a < b && b < c) "Yes" else "No")
  }
}

Range

Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No".

Input

Three integers a, b and c separated by a single space are given in a line.

Output

Print "Yes" or "No" in a line.

Constraints

0 ≤ a, b, c ≤ 100

Sample Input 1

1 3 8

Sample Output 1

Yes

Sample Input 2

3 8 1

Sample Output 2

No


object Main extends App {
  println(scala.io.StdIn.readLine.split(" ").map(_.toInt).sorted.mkString(" "))
}

Sorting Three Numbers

Write a program which reads three integers, and prints them in ascending order.

Input

Three integers separated by a single space are given in a line.

Output

Print the given integers in ascending order in a line. Put a single space between two integers.

Constraints

1 ≤ the three integers ≤ 10000

Sample Input 1

3 8 1

Sample Output 1

1 3 8


import scala.io.StdIn._
object Main {

  def main(args: Array[String]): Unit = {
    println(readLine.split(" ").map(_.toInt).sorted.mkString(" "))
  }
}


import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
      val Array(w, h, x, y, r, _*) = StdIn.readLine().split(" ").map(_.toInt)
      if(x - r >= 0 && x + r <= w && y - r >=0 && y + r <= h) println("Yes")
      else println("No")
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Circle in a Rectangle

Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given.

Input

Five integers $W$, $H$, $x$, $y$ and $r$ separated by a single space are given in a line.

Output

Print "Yes" if the circle is placed inside the rectangle, otherwise "No" in a line.

Constraints

$ -100 \leq x, y \leq 100$

$ 0 < W, H, r \leq 100$

Sample Input 1

5 4 2 2 1

Sample Output 1

Yes

Sample Input 2

5 4 2 4 1

Sample Output 2

No


object Main {
  def main (args: Array[String]) {
    val Array(width, height, x, y, r) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    width match{
      case w if (x-r >= 0) && (y-r >=0) && (x+r <= width) && (y+r <= height)  => println("Yes")
      case _     => println("No")
    }
  }
}


import java.util.Scanner

object Main extends App{
  val sc = new Scanner(System.in)
  val w,h,x,y,r = sc.nextInt()
  println(if(x-r >= 0 & x+r <= w & y-r >= 0 & y+r <= h) "Yes" else "No")
}


import scala.io.StdIn.readLine

object Main {

  def main(args: Array[String]) = {
      val n = readLine().split(" ").map(_.toInt)
      val (w,h,x,y,r) = (n(0),n(1),n(2),n(3),n(4))
      val s = if(x-r < 0 || y - r < 0 || x + r > w || y + r > h) "No" else "Yes"
      println(s)
  }
}


import scala.io.StdIn.readLine

object Main {
  def main(args:Array[String]) {
    val in = readLine().split(" ").map(_.toInt)
    val (w, h, x, y, r) = (in(0), in(1), in(2), in(3), in(4))

    if (0 <= x - r && 0 <= y - r && x + r <= w && y + r <= h) {
      println("Yes")
    } else {
      println("No")
    }
  }
}


import scala.io.StdIn.readLine
object Main extends App{
    val a = readLine().split(" ").map(_.toInt)
    val (w, h, x, y, r) = (a(0), a(1), a(2), a(3), a(4))
    if (0 <= x - r && x + r <= w && 0 <= y - r && y + r <= h)
    {
        println("Yes")
    }
    else
    {
        println("No")
    }
}


object Main {
	def main(args: Array[String]): Unit = {
			val in = new java.util.Scanner(System.in)
			rec(in,1)
	}
	def rec(in:java.util.Scanner,count:Int):Unit = {
	  val a = in.nextInt()
	  if(a == 0) return
	  println("Case "+count+": "+a)
	  rec(in,count+1)
	}
}

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


object Main extends App {
    import scala.annotation.tailrec

    val sc = new java.util.Scanner(System.in)
    val pw = new java.io.PrintWriter(System.out)
    @tailrec
    def output(i: Int = 1, n: Int = sc.nextInt): Unit = {
        if( n != 0 ) {
            pw.println("Case "+i+": "+n)
            output(i=i+1)
        }
    }

    output()
    pw.flush
}


import scala.io.Source

object Main{
  def main(args: Array[String]){
    val line =
      for{
        in <- Source.stdin.getLines.toList
      } yield in

    println(line.map{str => str.split(" ").map(_.toInt).sorted.mkString(" ")}.init.mkString("\n"))
  }
}

Swapping Two Numbers

Write a program which reads two integers x and y, and prints them in ascending order.

Input

The input consists of multiple datasets. Each dataset consists of two integers x and y separated by a single space.

The input ends with two 0 (when both x and y are zero). Your program should not process for these terminal symbols.

Output

For each dataset, print x and y in ascending order in a line. Put a single space between x and y.

Constraints

0 ≤ x, y ≤ 10000

the number of datasets ≤ 3000

Sample Input

3 2
2 2
5 3
0 0

Sample Output

2 3
2 2
3 5


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    try {
      val a = sc.nextInt
      val b = sc.nextInt
      val c = sc.nextInt

      def sub(x:Int):Int = {
        if(c % x == 0) 1 else 0
      }
      val ab = List(a,b)
      println(ab.map(sub).sum)
    } catch {
      case e: NoSuchElementException =>
        println("error: stdin is not found. Please take numbers.")
    }
  }
}

How Many Divisors?

Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b.

Input

Three integers a, b and c are given in a line separated by a single space.

Output

Print the number of divisors in a line.

Constraints

1 ≤ a, b, c ≤ 10000

a ≤ b

Sample Input 1

5 14 80

Sample Output 1

3


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val a, b, c = sc.nextInt()
  val divisors = getDivisorList(c,1)
  val range = (a to b).toList
  println(range.intersect(divisors).size)

  def getDivisorList(target: Int, start: Int): List[Int] = {
    if (target == start)
      List(target)
    else if (target % start == 0)
      start :: getDivisorList(target, start + 1)
    else
      getDivisorList(target, start + 1)
  }
}


import scala.io.StdIn.readLine
import Math.sqrt

object Main {

  def main(args: Array[String]) = {
      val Array(a,b,c) = readLine.split(" ").map(_.toInt)
      var cnt = 0
      for(i <- a to b)
          if(c % i == 0)
              cnt += 1
      println(cnt)
  }
}


object Main {
    def divisors(n: Int) =
        (1 to math.sqrt(n).toInt).flatMap(m =>
            if (n % m == 0 && m * m == n) List(m)
            else if (n % m == 0) List(m, n / m)
            else Nil
        )
    def main(args: Array[String]) = {
        val in = io.StdIn.readLine.split(" ").map(_.toInt)
        println((in(0) to in(1)).count(divisors(in(2)).contains))
    }
}


import scala.io.StdIn

object Main{
  def main(args: Array[String]){
    val line = StdIn.readLine.split(" ").toList.map(_.toInt)

    println((line.head to line.tail.head).map{i => line.last % i == 0}.filter{_ == true}.length)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val a, b = sc.nextInt
    println(f"${a / b} ${a % b} ${a * 1.0 / b}%.5f")
  }
}

A/B Problem

Write a program which reads two integers a and b, and calculates the following values:

a ÷ b: d (in integer)

remainder of a ÷ b: r (in integer)

a ÷ b: f (in real number)

Input

Two integers a and b are given in a line.

Output

Print d, r and f separated by a space in a line. For f, the output should not contain an absolute error greater than 10-5.

Constraints

1 ≤ a, b ≤ 109

Sample Input 1

3 2

Sample Output 1

1 1 1.50000


import scala.io.StdIn

object Main extends App {

  val a = StdIn.readLine().trim.split(' ').map(_.toInt)
  val f: Int = a(0)/a(1)
  val e: Int = a(0)/a(1)
  val d: Double = a(0).toDouble/a(1).toDouble

  println(f)
  println(e)
  println(f"$d%.5f")

}


object Main{
    def main(args: Array[String]): Unit ={
        var in = scala.io.StdIn.readDouble()
        var a = in * in * 3.141592653D
        var c = (in + in) * 3.141592653D
        println(f"$a%.7f"  + " " + f"$c%.7f")
    }
}

Circle

Write a program which calculates the area and circumference of a circle for given radius r.

Input

A real number r is given.

Output

Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-5.

Constraints

0 < r < 10000

Sample Input 1

2

Sample Output 1

12.566371 12.566371

Sample Input 2

3

Sample Output 2

28.274334 18.849556


object Main extends App {
  val r = BigDecimal(scala.io.StdIn.readLine().toDouble)

  println(r * r * Math.PI + " " + 2 * r * Math.PI)
}


object Main{
  def main(args: Array[String]){
    val sc = new java.util.Scanner(System.in)
    val num = sc.nextInt
    var sum = 0
    var list = List[Int]()
    var min = 0L
    var max = 0L
    for(i <- 1 to num){
      val in = sc.nextInt
      if(i == 1){
        min = in
        max = in
      }

      if(in < min){
        min = in
      }
      if(in > max){
        max = in
      }
      sum = in + sum
    }

    println(min + " " + max + " " + sum)
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Min, Max and Sum

Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence.

Input

In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in a line.

Output

Print the minimum value, maximum value and sum in a line. Put a single space between the values.

Constraints

$0 < n \leq 10000$

$-1000000 \leq a_i \leq 1000000$

Sample Input

5
10 1 5 4 17

Sample Output

1 17 37


object Main {
  def main (args: Array[String]) {
    val num = scala.io.StdIn.readLine.toInt;
    val list = scala.io.StdIn.readLine.split(" ").map(_.toLong).toList;

    println(list.min + " " +  list.max + " " + list.sum)
  }
}


object Main {
  case class Line(string: String) {
    def strings: Seq[String] = string.split(' ')
    def ints: Seq[Int] = strings.map(_.toInt)
    def longs: Seq[Long] = strings.map(_.toLong)
    def doubles: Seq[Double] = strings.map(_.toDouble)
    def i(n: Int): Int = ints(n)
    def d(n: Int): Double = doubles(n)
  }

  def readLine: Line = Line(io.StdIn.readLine())
  def readLines(n: Int): Seq[Line] = List.fill(n)(Line(io.StdIn.readLine()))

  def yesNo(b: Boolean): String = if (b) "Yes" else "No"

  def main(args: Array[String]): Unit = {
    val m: Int = readLine.i(0)
    val ns: Seq[Long] = readLine.longs

    println(List(ns.min, ns.max, ns.sum).mkString(" "))
  }
}


object Main extends App {
  val n = readLine().toInt
  val a = readLine().split(' ').map(_.toLong).toList.take(n)
  println("%d %d %d".format(a.min, a.max, a.sum))
}


object Main extends App {
  for (line <- scala.io.Source.stdin.getLines() if line.size > 0 && line != "0 0") {
    var cnt = 1
    if (cnt != 1) println()
    for (h <- 1 to line.split(" ")(0).toInt) {
      val horizon: String = """???""" * line.split(" ")(1).toInt
      println(horizon)
    }
    cnt += 1
  }
}

Print a Rectangle

Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the rectangle made of H × W '#'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

3 4
5 6
2 2
0 0

Sample Output

####
####
####

######
######
######
######
######

##
##


object Main {
  def main(args: Array[String]): Unit = {
    val in =  new java.util.Scanner(System.in)
    val a = in.nextInt
    val b = in.nextInt
    for(i <- 1 to a){
      for(j <- 1 to b){
        print("#")
      }
      println("")
    }
  }

}


object Main {
  def main(args:Array[String]){
    val sc=new java.util.Scanner(System.in)
    var tmp=false
    println()
      while(true){
       val h,w=sc.nextInt
       if(h==0&&w==0) return
       if(tmp) println()
       for(i<-1 to h;j<-1 to w){
         if(j==w){
           if(i==h) println("# ")
           else println("#")
         }
         else print("#")
       }
       tmp=true
     }
  }
}


import scala.io.StdIn

/**
  * AOJ
  */
object Main {

  def main(args: Array[String]): Unit = {

    while(true) {
      val in = StdIn.readLine().split(" ").map(_.toInt)
      if(in(0) == 0 && in(1) == 0) return
      for(i <- 1 to in(0)){println("#" * in(1))}
      println()
    }
  }
}


object Main {
  def main(args:Array[String]):Unit = {
    for (line <- scala.io.Source.stdin.getLines() if line != "0 0") {
      val Array(h, w) = line.split(" ").map(_.toInt)
      for (i <- 1 to h) {
        println("#" * w)
      }
      println()
    }
  }
}


import scala.io.StdIn

object Main extends App {

  var hw = StdIn.readLine().split(' ').map(_.toInt)
  while(hw(0) != 0 && hw(1) != 0){
    (0 until hw(0)).foreach{ _ =>
      (0 until hw(1)).foreach( _ => print("#"))
      println("")
    }
    println("")
    hw = StdIn.readLine().split(' ').map(_.toInt)
  }

}


import scala.io.StdIn.readLine

object Main {
  def main(args: Array[String]) {
    def printFrame: Unit = {
      val Array(a, b) = readLine().split(" ").map(_.toInt)
      if(a != 0 && b != 0) {
        for(i <- 1 to a) {
          if(i == 1 || i == a) println("#" * b)
          else println("#" + "." * (b - 2) + "#")
        }
        println()
        printFrame
      }
    }

    printFrame
  }
}

Print a Frame

Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.

##########
#........#
#........#
#........#
#........#
##########

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the frame made of '#' and '.'.

Print a blank line after each dataset.

Constraints

3 ≤ H ≤ 300

3 ≤ W ≤ 300

Sample Input

3 4
5 6
3 3
0 0

Sample Output

####
#..#
####

######
#....#
#....#
#....#
######

###
#.#
###


import scala.io.StdIn.readLine

object Main {

  def main(args: Array[String]) = {
      var n = readLine.split(" ").map(_.toInt)
      while( n(0) != 0 || n(1) != 0) {
        println("#"*n(1))

        (2 to n(0)-1).foreach(s=> { print("#");print("."*(n(1)-2));print("#\n") })

        if(n(0)>1) {
          println("#"*n(1))
        }
        println("")
        n = readLine.split(" ").map(_.toInt)
      }
  }
}


import scala.io.Source

object Main{
  def main(args: Array[String]){
    val list =
      for{
        in <- Source.stdin.getLines.toList
      } yield in

    list.map(_.split(" ").map(_.toInt).toList).init.foreach{ list =>
      val height = list.head
      val width = list.last

      println("#" * width)
      (2 to height-1).foreach{ i =>
        println(s"#${"." * (width - 2)}#")
      }
      println("#" * width)
      println
    }
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val scanner = new java.util.Scanner(System.in)
    while(true) {
      val h, w = scanner.nextInt
      if((h == 0) && (w == 0)) System.exit(0)
      println("#" * w)
      println(("#" + "." * (w - 2) + "#") * (h - 2))
      println("#" * w)
      println()
    }
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val scanner = new java.util.Scanner(System.in)
    while(true) {
      val h, w = scanner.nextInt
      if((h == 0) && (w == 0)) System.exit(0)
      println("#" * w)
      print(("#" + "." * (w - 2) + "#\n") * (h - 2))
      println("#" * w)
      println()
    }
  }
}


import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val inputs = Iterator.continually(StdIn.readLine()).takeWhile(_ != null)
    for{
      in <- inputs
      val Array(h, w, _*) = in.split(" ").map(_.toInt)
      }{
        if(h != 0 && w != 0){
          println((List.tabulate(h, w){(i, j) =>
            val isSharp = (i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0)
            val isDot = !isSharp
            val EOL = j == w-1

            if(isSharp && EOL) "#\n"
            else if(isDot && EOL) ".\n"
            else if(isSharp) "#"
            else "."
          }).flatten.mkString)
        }
      }
  }
}

Print a Chessboard

Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm.

#.#.#.#.#.
.#.#.#.#.#
#.#.#.#.#.
.#.#.#.#.#
#.#.#.#.#.
.#.#.#.#.#

Note that the top left corner should be drawn by '#'.

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the chessboard made of '#' and '.'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

3 4
5 6
3 3
2 2
1 1
0 0

Sample Output

#.#.
.#.#
#.#.

#.#.#.
.#.#.#
#.#.#.
.#.#.#
#.#.#.

#.#
.#.
#.#

#.
.#

#


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  printChessboard(sc.nextInt(), sc.nextInt())

  def printChessboard(h: Int, w: Int): Unit = {
    (h, w) match {
      case (0, 0) => sc.close()
      case _ =>
        for (i <- 1 to h) i match {
          case _ if i % 2 != 0 => printOddRow(w)
          case _ if i % 2 == 0 => printEvenRow(w)
        }
        println()
        printChessboard(sc.nextInt(), sc.nextInt())
    }
  }

  def printOddRow(w: Int): Unit = {
    for (i <- 1 to w) i match {
      case _ if i % 2 != 0 => print("#")
      case _ if i % 2 == 0 => print(".")
    }
    print("\n")
  }

  def printEvenRow(w: Int): Unit = {
    for (i <- 1 to w) i match {
      case _ if i % 2 != 0 => print(".")
      case _ if i % 2 == 0 => print("#")
    }
    print("\n")
  }
}


object Main extends App {
  val n = scala.io.StdIn.readLine.toInt
  println((1 to n).filter(x => x % 3 == 0 | x.toString.exists(_ == '3')).map(" " + _).mkString(""))
}

Structured Programming

In programming languages like C/C++, a goto statement provides an unconditional jump from the "goto" to a labeled statement. For example, a statement "goto CHECK_NUM;" is executed, control of the program jumps to CHECK_NUM. Using these constructs, you can implement, for example, loops.

Note that use of goto statement is highly discouraged, because it is difficult to trace the control flow of a program which includes goto.

Write a program which does precisely the same thing as the following program (this example is wrtten in C++). Let's try to write the program without goto statements.

void call(int n){
int i = 1;
CHECK_NUM:
int x = i;
if ( x % 3 == 0 ){
cout << " " << i;
goto END_CHECK_NUM;
}
INCLUDE3:
if ( x % 10 == 3 ){
cout << " " << i;
goto END_CHECK_NUM;
}
x /= 10;
if ( x ) goto INCLUDE3;
END_CHECK_NUM:
if ( ++i <= n ) goto CHECK_NUM;

cout << endl;
}

Input

An integer n is given in a line.

Output

Print the output result of the above program for given integer n.

Constraints

3 ≤ n ≤ 10000

Sample Input

30

Sample Output

3 6 9 12 13 15 18 21 23 24 27 30

Put a single space character before each element.


object Main extends App {
  val scanner = new java.util.Scanner(System.in)
  val n = scanner.nextInt()

  val outputs = (1 to n).filter { i =>
    i % 3 == 0 || (i.toString).contains('3')
  }

  println(" " + outputs.mkString(" "))
}


/**
  * http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_5_D
  * Structured Program I - Structured Programming
  */
object Main {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val result = (1 to n).foldLeft("") {
      (str, i) => {
        str + {
          if (i % 3 == 0 || i.toString.contains("3"))
            s" $i"
          else
            ""
        }
      }
    }
    println(result)
  }
}


import scala.io.StdIn.readLine

object Main extends App {
  readLine()

  val xs = readLine().split(" ")
  println(xs.reverse.mkString(" "))
}

Reversing Numbers

Write a program which reads a sequence and prints it in the reverse order.

Input

The input is given in the following format:

n
a1 a2 . . . an

n is the size of the sequence and ai is the ith element of the sequence.

Output

Print the reversed sequence in a line. Print a single space character between adjacent elements (Note that your program should not put a space character after the last element).

Constraints

n ≤ 100

0 ≤ ai < 1000

Sample Input 1

5
1 2 3 4 5

Sample Output 1

5 4 3 2 1

Sample Input 2

8
3 3 4 4 5 8 7 9

Sample Output 2

9 7 8 5 4 4 3 3

Note

      解説


object Main {
    def main(args: Array[String]) = {
        val in = io.Source.stdin.getLines.toList.tail
        val ans = "SHCD".flatMap(c => (1 to 13).map(c + " " + _)) diff in
        ans.foreach(println)
    }
}

Finding Missing Cards

Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers).

The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond.

Input

In the first line, the number of cards n (n ≤ 52) is given.

In the following n lines, data of the n cards are given. Each card is given by a pair of a character and an integer which represent its suit and rank respectively. A suit is represented by 'S', 'H', 'C' and 'D' for spades, hearts, clubs and diamonds respectively. A rank is represented by an integer from 1 to 13.

Output

Print the missing cards. The same as the input format, each card should be printed with a character and an integer separated by a space character in a line.
Arrange the missing cards in the following priorities:

Print cards of spades, hearts, clubs and diamonds in this order.

If the suits are equal, print cards with lower ranks first.

Sample Input

47
S 10
S 11
S 12
S 13
H 1
H 2
S 6
S 7
S 8
S 9
H 6
H 8
H 9
H 10
H 11
H 4
H 5
S 2
S 3
S 4
S 5
H 12
H 13
C 1
C 2
D 1
D 2
D 3
D 4
D 5
D 6
D 7
C 3
C 4
C 5
C 6
C 7
C 8
C 9
C 10
C 11
C 13
D 9
D 10
D 11
D 12
D 13

Sample Output

S 1
H 3
H 7
C 12
D 8

Note

      解説


object Main {
    def main(args: Array[String]) = {
        val in = io.Source.stdin.getLines.toList.tail
        ("SHCD".flatMap(c => (1 to 13).map(c + " " + _)) diff in).foreach(println)
    }
}


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

/**
  * AOJ
  */
object Main {

  def main(args: Array[String]): Unit = {

    val house = Array.ofDim[Int](House.building, House.floor, House.room)
    for (_ <- 1 to StdIn.readInt()) {
      val in = StdIn.readLine().split(" ").map(_.toInt)
      house(in(0) - 1)(in(1) - 1)(in(2) - 1) += in(3)
    }
    for(i <- 0 to House.building - 1; j <- 0 to House.floor - 1){
      println(" " + house(i)(j).mkString(" "))
      if(j == House.floor - 1){println("#" * 20)}
    }
  }
}

object House {
  val building = 4
  val floor = 3
  val room = 10
}

Official House

You manage 4 buildings, each of which has 3 floors, each of which consists of 10 rooms. Write a program which reads a sequence of tenant/leaver notices, and reports the number of tenants for each room.

For each notice, you are given four integers b, f, r and v which represent that v persons entered to room r of fth floor at building b. If v is negative, it means that −v persons left.

Assume that initially no person lives in the building.

Input

In the first line, the number of notices n is given. In the following n lines, a set of four integers b, f, r and v which represents ith notice is given in a line.

Output

For each building, print the information of 1st, 2nd and 3rd floor in this order. For each floor information, print the number of tenants of 1st, 2nd, .. and 10th room in this order. Print a single space character before the number of tenants. Print "####################" (20 '#') between buildings.

Constraints

No incorrect building, floor and room numbers are given.

0 ≤ the number of tenants during the management ≤ 9

Sample Input

3
1 1 3 8
3 2 2 7
4 3 8 1

Sample Output

0 0 8 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
####################
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
####################
0 0 0 0 0 0 0 0 0 0
0 7 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
####################
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0


object Main extends App {
    val x :: y = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt)).toList
    val a = y.take(x(0))
    val b = y.drop(x(0)).flatten
    a.foreach(x => println(x.zip(b).map(p => p._1 * p._2).sum))
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Matrix Vector Multiplication

Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$.

A column vector with m elements is represented by the following equation.

\[
b = \left(
\begin{array}{c}
b_1 \\
b_2 \\
: \\
b_m \\
\end{array}
\right)
\]

A $n \times m$ matrix with $m$ column vectors, each of which consists of $n$ elements, is represented by the following equation.

\[
A = \left(
\begin{array}{cccc}
a_{11} & a_{12} & ... & a_{1m} \\
a_{21} & a_{22} & ... & a_{2m} \\
: & : & : & : \\
a_{n1} & a_{n2} & ... & a_{nm} \\
\end{array}
\right)
\]

$i$-th element of a $m \times 1$ column vector $b$ is represented by $b_i$ ($i = 1, 2, ..., m$), and the element in $i$-th row and $j$-th column of a matrix $A$ is represented by $a_{ij}$ ($i = 1, 2, ..., n,$ $j = 1, 2, ..., m$).

The product of a $n \times m$ matrix $A$ and a $m \times 1$ column vector $b$ is a $n \times 1$ column vector $c$, and $c_i$ is obtained by the following formula:

\[
c_i = \sum_{j=1}^m a_{ij}b_j = a_{i1}b_1 + a_{i2}b_2 + ... + a_{im}b_m
\]

Input

In the first line, two integers $n$ and $m$ are given. In the following $n$ lines, $a_{ij}$ are given separated by a single space character. In the next $m$ lines, $b_i$ is given in a line.

Output

The output consists of $n$ lines. Print $c_i$ in a line.

Constraints

$1 \leq n, m \leq 100$

$0 \leq b_i, a_{ij} \leq 1000$

Sample Input

3 4
1 2 0 1
0 3 0 1
4 1 1 0
1
2
3
0

Sample Output

5
6
9


import scala.io.StdIn

object Main{
  def main(args: Array[String]){
    val num = StdIn.readLine().split(" ").map(_.toInt)
    var count = 0

    for(i <- 1 to num(0)){
      for(j <- i+1 to num(0)){
         for(k <- j+1 to num(0)){
           if(i + j + k == num(1)){
             count += 1
           }
         }
      }
    }
    if(num(0) > 0){
      println(count)
    }
  }
}

How many ways?

Write a program which identifies the number of combinations of three integers which satisfy the following conditions:

You should select three distinct integers from 1 to n.

A total sum of the three integers is x.

For example, there are two combinations for n = 5 and x = 9.

1 + 3 + 5 = 9

2 + 3 + 4 = 9

Input

The input consists of multiple datasets. For each dataset, two integers n and x are given in a line.

The input ends with two zeros for n and x respectively. Your program should not process for these terminal symbols.

Constraints

3 ≤ n ≤ 100

0 ≤ x ≤ 300

Output

For each dataset, print the number of combinations in a line.

Sample Input

5 9
0 0

Sample Output

2

Note

      解説


import scala.io.StdIn.readLine
import scala.math.{max,min}

object Main extends App {

  var (n,x) = (0,0)
  while({val Array(n2,x2) = readLine.split(" ").map(_.toInt);n=n2;x=x2;(n,x)} != (0,0) ) {
    println(
      ( 1 until min(n-1,x/3) ).foldLeft(0) { (sum,i) =>
        sum + (max(i+1,x-i-n) until min(n,(x-i+1)/2)).length
      }
    )
  }
}


object Main extends App {
  val scanner = new java.util.Scanner(System.in)

  val r = scanner.nextInt()
  val c = scanner.nextInt()

  val inputs = (1 to r).map {
    _ => (1 to c).map(_ => scanner.nextInt())
  }

  val row_sum = inputs.map { row =>
    row :+ row.sum
  }
  val column_sum = row_sum.foldLeft(Vector.fill(c+1)(0)) { (acc, row) =>
    (acc zip row).map(t => t._1 + t._2)
  }

  val outputs = row_sum :+ column_sum

  outputs.map(_.mkString(" ")).foreach(println)
}

Spreadsheet

Your task is to perform a simple table calculation.

Write a program which reads the number of rows r, columns c and a table of r × c elements, and prints a new table, which includes the total sum for each row and column.

Input

In the first line, two integers r and c are given. Next, the table is given by r lines, each of which consists of c integers separated by space characters.

Output

Print the new table of (r+1) × (c+1) elements. Put a single space character between adjacent elements. For each row, print the sum of it's elements in the last column. For each column, print the sum of it's elements in the last row. Print the total sum of the elements at the bottom right corner of the table.

Constraints

1 ≤ r, c ≤ 100

0 ≤ an element of the table ≤ 100

Sample Input

4 5
1 1 3 4 5
2 2 2 4 5
3 3 0 1 1
2 3 4 4 6

Sample Output

1 1 3 4 5 14
2 2 2 4 5 15
3 3 0 1 1 8
2 3 4 4 6 19
8 9 9 13 17 56


import scala.io.StdIn

object Main extends App {

  val Array(r, c) = StdIn.readLine().split(' ').map(_.toInt)
  val result = Array.fill(r, c+1)(0)
  val temp = Array.fill(c+1)(0)

  (0 until r).foreach{ i =>
    result(i) = (StdIn.readLine() + " 0").split(' ').map(_.toInt)
    result(i)(c) = result(i).sum

    (0 to c).foreach{ k =>
      temp(k) += result(i)(k)
    }
  }

  (0 until r).foreach{ i =>
    println(result(i).toList.mkString(" "))
  }
  println(temp.toList.mkString(" "))

}


object Main{
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    while (sc.hasNext()){
      sc.next.toCharArray.foreach(x => print(swap_case_as_int(x.toInt).toChar))
      print(" ")
    }
    println()
  }
  def swap_case_as_int(int: Int) : Int ={
    if (65 <= int && int <= 90) int + 32
    else if (97 <= int && int <= 122) int - 32
    else  int
  }
}

Toggling Cases

Write a program which converts uppercase/lowercase letters to lowercase/uppercase for a given string.

Input

A string is given in a line.

Output

Print the converted string in a line. Note that you do not need to convert any characters other than alphabetical letters.

Constraints

The length of the input string < 1200

Sample Input

fAIR, LATER, OCCASIONALLY CLOUDY.

Sample Output

Fair, later, occasionally cloudy.


object Main extends App {
  io.Source.stdin.getLines.toList.init.map(_.map(_.toString.toInt).sum).map(println)
}

Sum of Numbers

Write a program which reads an integer and prints sum of its digits.

Input

The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000.

The input ends with a line including single zero. Your program should not process for this terminal symbol.

Output

For each dataset, print the sum of digits in x.

Sample Input

123
55
1000
0

Sample Output

6
10
1


import scala.collection.mutable.ListBuffer
import scala.io.StdIn

object Main extends App {

  var target = "-1"
  val buff = ListBuffer.empty[String]
  while(target != "0"){
    target = StdIn.readLine()
    buff += target.foldLeft(0){ (acc, f) =>
      acc + f.toString.toInt
    }.toString
  }

  println(buff.dropRight(1).mkString(f"%n"))
}


object Main {
    def main(args: Array[String]) = {
        val a = io.StdIn.readLine.toLowerCase
        ('a' to 'z').foreach(c => println(c + " : " + a.count(_ == c)))
    }
}

Counting Characters

Write a program which counts and reports the number of each alphabetical letter. Ignore the case of characters.

Input

A sentence in English is given in several lines.

Output

Prints the number of alphabetical letters in the following format:

a : The number of 'a'
b : The number of 'b'
c : The number of 'c'
.
.
z : The number of 'z'

Constraints

The number of characters in the sentence < 1200

Sample Input

This is a pen.

Sample Output

a : 1
b : 0
c : 0
d : 0
e : 1
f : 0
g : 0
h : 1
i : 2
j : 0
k : 0
l : 0
m : 0
n : 1
o : 0
p : 1
q : 0
r : 0
s : 2
t : 1
u : 0
v : 0
w : 0
x : 0
y : 0
z : 0


object Main extends App {
  val scanner = new java.util.Scanner(System.in)
  scanner.useDelimiter("")

  val input = Iterator.continually{
    scanner.next().head
  }.filter(_ != ' ').takeWhile(_ != '.')

  val outputs = input.foldLeft(List.fill('z' - 'a' + 1)(0)) { (list, c) =>
    val lower = c.toLower
    val index = lower - 'a'

    println(lower)

    list.updated(index, list(index) + 1)
  }.zipWithIndex

  outputs.foreach { t =>
    println(s"${('a' + t._2).toChar} : ${t._1}")
  }
}


import scala.collection.mutable.ListBuffer

object Main extends App {

  private val alphabets = Array.ofDim[Int](26)
  private val buff = ListBuffer.empty[String]
  val sc = new java.util.Scanner(System.in)
  while(sc.hasNext){
    buff += sc.next
  }

  buff.mkString("").foreach{ c =>
    val idx = c.toLower - 'a'
    if(idx >= 0) alphabets(idx) += 1
  }
  println(('a' to 'z').map(f => f.toString + " : " + alphabets(f - 'a')).mkString(f"%n"))

}


import scala.collection.mutable
import scala.io.Source.stdin

object Main extends App {

  val lines = stdin.getLines()
  val xs = {
    val nums = ('a' to 'z').map { (_, 0) }

    val m = mutable.Map(nums: _*)
    for {
      line <- lines
      c    <- line.map { _.toLower }
      if c.isLetter && c <= 'z'
    } {
      m(c) += 1
    }
    m.toSeq.sorted
  }

  for ((k, v) <- xs) {
    println(s"$k : $v")
  }
}


import java.util.Scanner;
object Main {
  def main(args: Array[String]): Unit = {
    var sc = new Scanner(System.in)
    var s = sc.next * 2
    var p = sc.next
    println(if(s.contains(p)) "Yes" else "No")
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Ring

Write a program which finds a pattern $p$ in a ring shaped text $s$.

Input

In the first line, the text $s$ is given.

In the second line, the pattern $p$ is given.

Output

If $p$ is in $s$, print Yes in a line, otherwise No.

Constraints

$1 \leq $ length of $p \leq $ length of $s \leq 100$

$s$ and $p$ consists of lower-case letters

Sample Input 1

vanceknowledgetoad
advance

Sample Output 1

Yes

Sample Input 2

vanceknowledgetoad
advanced

Sample Output 2

No


object Main {
    def main(args: Array[String]) = {
        val in = io.Source.stdin.getLines
        if (in.next * 2 contains in.next) println("Yes")
        else println("No")
    }
}


import scala.io.StdIn.readLine

object Main extends App {
  val s = readLine.trim
  val w = readLine.trim

  if ((s+s).contains(w)) println("Yes") else println("No")
}


import scala.io.Source

object Main extends App {
  val src = Source.stdin.getLines.toList.flatMap(_.split(" ").map(_.toLowerCase).toList)
  println(src.tail.filter(str => str == src(0)).length)
}

Finding a Word

Write a program which reads a word W and a text T, and prints the number of word W which appears in text T

T consists of string Ti separated by space characters and newlines. Count the number of Ti which equals to W. The word and text are case insensitive.

Constraints

The length of W ≤ 10

W consists of lower case letters

The length of T in a line ≤ 1000

Input

In the first line, the word W is given. In the following lines, the text T is given separated by space characters and newlines.

"END_OF_TEXT" indicates the end of the text.

Output

Print the number of W in the text.

Sample Input

computer
Nurtures computer scientists and highly-skilled computer engineers
who will create and exploit "knowledge" for the new era.
Provides an outstanding computer environment.
END_OF_TEXT

Sample Output

3


import scala.io.StdIn.{readLine,readInt}

object Main extends App {
  var w = ""

  def shuffle(cnt:Int, w:String):String =
    if(cnt == 0)  w else { val m = readInt;shuffle(cnt-1, (w drop m)+(w take m)) }

  def exec(w:String):Unit =
    if(w=="-") return else { val n = readInt;println(shuffle(n,w));exec(readLine) }

  exec(readLine.trim)
}

Shuffle

Your task is to shuffle a deck of n cards, each of which is marked by a alphabetical letter.

A single shuffle action takes out h cards from the bottom of the deck and moves them to the top of the deck.

The deck of cards is represented by a string as follows.

abcdeefab

The first character and the last character correspond to the card located at the bottom of the deck and the card on the top of the deck respectively.

For example, a shuffle with h = 4 to the above deck, moves the first 4 characters "abcd" to the end of the remaining characters "eefab", and generates the following deck:

eefababcd

You can repeat such shuffle operations.

Write a program which reads a deck (a string) and a sequence of h, and prints the final state (a string).

Input

The input consists of multiple datasets. Each dataset is given in the following format:

A string which represents a deck
The number of shuffle m
h1
h2
.
.
hm

The input ends with a single character '-' for the string.

Constraints

The length of the string ≤ 200

1 ≤ m ≤ 100

1 ≤ hi < The length of the string

The number of datasets ≤ 10

Output

For each dataset, print a string which represents the final state in a line.

Sample Input

aabc
3
1
2
1
vwxyz
2
3
4
-

Sample Output

aabc
xyzvw


import scala.io.StdIn.{readLine,readInt}

object Main extends App {

  def exec(w:String):Unit =  {
    val len = w.length

    if(w=="-") return else {
      val n = readInt
      var cnt = 0

      for(i <- 1 to n) cnt += readInt
      println((w drop (cnt%len)) + (w take (cnt%len)))
      exec(readLine)
    }
  }

  exec(readLine)
}


import scala.io.StdIn._

object Main {
  def transformation(s: String, n: Int, l: List[String] = Nil): List[String] = {
    if (n > 0) {
      val transformType = readLine().split(" ")
      val start = transformType(1).toInt
      val end = transformType(2).toInt + 1
      val to = transformType(2).toInt - start + 1
      transformType(0) match {
        case "print"   => transformation(s, n - 1, l :+ s.slice(start, end))
        case "replace" => transformation(s.patch(start, transformType(3), to), n - 1, l)
        case "reverse" =>
          val reverseText = s.slice(start, end).reverse
          val sReverse = s.patch(start, reverseText, to)
          transformation(sReverse, n - 1, l)
      }
    } else l
  }

  def main(args: Array[String]): Unit = {
    val originText = readLine()
    val transformNum = readInt()
    transformation(originText, transformNum).foreach(println)
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Transformation

Write a program which performs a sequence of commands to a given string $str$. The command is one of:

print a b: print from the a-th character to the b-th character of $str$

reverse a b: reverse from the a-th character to the b-th character of $str$

replace a b p: replace from the a-th character to the b-th character of $str$ with p

Note that the indices of $str$ start with 0.

Input

In the first line, a string $str$ is given. $str$ consists of lowercase letters. In the second line, the number of commands q is given. In the next q lines, each command is given in the above mentioned format.

Output

For each print command, print a string in a line.

Constraints

$1 \leq $ length of $str \leq 1000$

$1 \leq q \leq 100$

$0 \leq a \leq b < $ length of $str$

for replace command, $b - a + 1 = $ length of $p$

Sample Input 1

abcde
3
replace 1 3 xyz
reverse 0 2
print 1 4

Sample Output 1

xaze

Sample Input 2

xyz
3
print 0 2
replace 0 2 abc
print 0 2

Sample Output 2

xyz
abc


object Main {
    def step(s: String, cmd: Array[String]) = cmd(0) match {
        case "print" => {println(s.slice(cmd(1).toInt, cmd(2).toInt+1)); s}
        case "reverse" => s.take(cmd(1).toInt) + s.slice(cmd(1).toInt, cmd(2).toInt+1).reverse +s.drop(cmd(2).toInt+1)
        case "replace" => s.take(cmd(1).toInt) + cmd(3) +s.drop(cmd(2).toInt+1)
    }
    def main(args: Array[String]): Unit = {
        val in = io.Source.stdin.getLines
        val s = in.next
        in.next
        in.map(_.split(" ")).foldLeft(s)(step)
    }
}


import scala.io.StdIn

/**
  * AOJ
  */
object Main {

  def main(args: Array[String]): Unit = {

    var str = StdIn.readLine()
    val q =  StdIn.readInt()

    for(_ <- 1 to q){

      val line = StdIn.readLine().split(" ")
      val a = line(1).toInt
      val b = line(2).toInt

      line(0) match {
        case "replace" => {
          str = str.take(a) + line(3) + str.takeRight(str.length - b - 1)
        }
        case "reverse" => {
          str = str.take(a) + str.slice(a,b + 1).reverse + str.takeRight(str.length - b - 1)
        }
        case "print"   => println(str.slice(a,b + 1))
      }
    }
  }
}


import scala.io.StdIn.{readLine, readInt}

sealed trait Order
case class Print(a: Int, b: Int)              extends Order
case class Reverse(a: Int, b: Int)            extends Order
case class Replace(a: Int, b: Int, p: String) extends Order

object Main extends App {
  val str    = readLine()
  val n      = readInt()
  val lines  = Iterator.fill(n)(readLine())
  val orders = lines.map { _.split(" ") }.map {
    case Array("print", a, b)      => Print(a.toInt, b.toInt)
    case Array("reverse", a, b)    => Reverse(a.toInt, b.toInt)
    case Array("replace", a, b, p) => Replace(a.toInt, b.toInt, p)
  }

  val printStrings = {
    val (_, printStrings) = orders.foldLeft((str, Nil: List[String])) { (accum, order) =>
      val (s, printStrings) = accum
      order match {
        case Print(a, b)      =>
          val ps = s.slice(a, b + 1)
          (s, ps :: printStrings)
        case Reverse(a, b)    =>
          val rev = s.slice(a, b + 1).reverse
          (s.patch(a, rev, b - a + 1), printStrings)
        case Replace(a, b, p) =>
          (s.patch(a, p, b - a + 1), printStrings)
      }
    }
    printStrings.reverse
  }

  printStrings.foreach(println)
}


import collection.mutable.ListBuffer
import io.StdIn

object Main extends App {

  def primeFact(n:Long):List[Long] = {
    val ret = ListBuffer.empty[Long]

    var num = n
    var root = 2L
    while(root * root <= num) {
      if(num % root == 0L) {
        ret += root
        num /= root
      }
      else root += 1L
    }

    ret.toList
  }

  val n = StdIn.readLong

  val ans = primeFact(n)
  println(n + ": " + ans.mkString(" "))
}

Prime Factorization

Factorize a given integer n.

Input

n

An integer n is given in a line.

Output

Print the given integer n and :. Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a space before each prime factor.

Constraints

2 ≤ n ≤ 109

Sample Input 1

12

Sample Output 1

12: 2 2 3

Sample Input 2

126

Sample Output 2

126: 2 3 3 7


object Main {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    println(s"$n: ${Primes.primeFactorize(n).mkString(" ")}")
  }

  object Primes {
    private def mod_exp(x: BigInt, n: Int, m: Int): BigInt = {
      def loop(x: BigInt, n: Int, acc: BigInt): BigInt = {
        if (n == 0) acc
        else loop (
          (x * x) % m,
          n >> 1,
          if ((n & 1) == 1) (acc * x) % m else acc
        )
      }
      loop(x,n,1)
    }
    private def div_pow_2(d: Int, s: Int = 0): (Int, Int) ={
      if ((d % 2) != 0) (d,s)
      else div_pow_2(d/2, s+1)
    }

    private def miller_rabin(n: Int, a: Int): Boolean = {
      val (d,s): (Int, Int) = div_pow_2(n-1)
      val a_exp_d: BigInt = mod_exp(a,d,n)
      def double(x: BigInt): BigInt = mod_exp(x,2,n)
      def loop(e: BigInt, i: Int): Boolean = {
        if (i == 0) false
        else if (e == n-1) true
        else loop(double(e), i-1)
      }
      a_exp_d == 1 || loop(a_exp_d, s)
    }
    def miller_rabin_test(n: Int, k: Int = 20): Boolean = {
      def loop(i: Int): Boolean = {
        if (i == 0) true
        else {
          val a = scala.util.Random.nextInt(n-1)+1
          if (miller_rabin(n,a)) loop(i-1)
          else false
        }
      }
      if (n < 2) false
      else loop(k)
    }
    def primeFactorize(n: Int): Seq[Int] = {
      val ab = collection.mutable.ArrayBuffer.empty[Int]
      var x = n
      while (x !=1) {
        if (isPrime(x)) {ab += x; x = 1}
        else {
          val p = rho(x)
          if (isPrime(p))
            while (x % p == 0) {
              x /= p
              ab += p
            }
          else {
            val ps = primeFactorize(p)
            ps foreach (p => while (x % p == 0) {x /= p; ab += p})
          }
        }
      }
      ab
    }
    def rho(n: Int): Int = {
      def f(x: Int, c: Int): Int = (x * x + c) % n
      def loop(x: Int, y: Int, d: Int, c: Int = 1): Int =
        if (d != 1) {
          if (d == n) loop(2,2,1,c+1)
          else d
        }
        else {
          val a = f(x, c)
          val b = f(f(y, c), c)
          loop(a, b, gcd(Math.abs(a-b), n), c)
        }
      if (n % 2 == 0) 2
      else loop(2,2,1)
    }
    def gcd(x: Int, y: Int): Int = {
      if (x < y) gcd(y, x)
      else {
        if (y > 0) {
          val r = x % y
          gcd(y, r)
        } else x
      }
    }
    def isPrime(n: Int): Boolean = Primes.miller_rabin_test(n)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val _ = io.StdIn.readInt()
    val an: Seq[Int] = io.StdIn.readLine().split(" ").map(_.toInt)
    println(an.tail.foldLeft(an.head)((acc, ai) => lcm(acc, ai)))
  }
  def lcm(m: Int, n: Int): Int = (m * n) / gcd(m, n)
  def gcd(x: Int, y: Int): Int = {
    var (m, n) = if (x < y) (y, x) else (x, y)
    while(n > 0) {
      val tmp = m
      m = n
      n = tmp % n
    }
    m
  }
}

Least Common Multiple

Find the least common multiple (LCM) of given n integers.

Input

n
a1 a2 ... an

n is given in the first line. Then, n integers are given in the second line.

Output

Print the least common multiple of the given integers in a line.

Constraints

2 ≤ n ≤ 10

1 ≤ ai ≤ 1000

Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1

Sample Input 1

3
3 4 6

Sample Output 1

12

Sample Input 2

4
1 2 3 5

Sample Output 2

30


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  println("ACL" * sc.nextInt())
}

Score : 100 points

Problem Statement

You are given an integer K.
Print the string obtained by repeating the string ACL K times and concatenating them.

For example, if K = 3, print ACLACLACL.

Constraints

1 \leq K \leq 5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the string obtained by repeating the string ACL K times and concatenating them.

Sample Input 1

3

Sample Output 1

ACLACLACL


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val S = sc.next()
  println(S + (if (S.last == 's') "es" else "s"))
}

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datS) = readLine.split(" ")

    val ans = datS + (if (datS.last != 's') "s" else "es")

    println(ans)
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  println(1.to(N).foldLeft(0)(_ + (N - 1) / _))
}

Score : 300 points

Problem Statement

Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

2 \leq N \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

3

Sample Output 1

3

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

Sample Input 2

100

Sample Output 2

473

Sample Input 3

1000000

Sample Output 3

13969985


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  val counts = for {
    a <- 1 to N
    b <- 1 to (N / a)
    if a * b < N
  } yield 1
  println(counts.sum)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  var ans = 0
  for (a <- 1 to n) {
    ans += (n-1) / a
  }

  println(ans)
}


import scala.io.StdIn

object Main extends App {
  val s = StdIn.readInt()
  def factorial(n: Int):BigInt = List.range(1, n+1).map(BigInt(_)).foldLeft(BigInt(1))(_*_)
  def factorialPart(from:Int,to:Int):BigInt = List.range(from, to+1).map(BigInt(_)).foldLeft(BigInt(1))(_*_)
  var sum = BigInt(0)
  var seqLength = 1
  while(3*seqLength < s){
    val retNum = s - 3*seqLength
    sum += factorialPart(retNum+1,retNum + (seqLength -1))/factorial(seqLength -1)
    seqLength += 1
  }

  val mod = BigInt(10).pow(9) + 7
  println(sum % mod)
}

Score : 400 points

Problem Statement

Given is an integer S.
Find how many sequences there are whose terms are all integers greater than or equal to 3, and whose sum is equal to S.
The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq S \leq 2000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer.

Sample Input 1

7

Sample Output 1

3

3 sequences satisfy the condition: \{3,4\}, \{4,3\} and \{7\}.

Sample Input 2

2

Sample Output 2

0

There are no sequences that satisfy the condition.

Sample Input 3

1729

Sample Output 3

294867501


import scala.collection.mutable.Map

object Main extends App {
  val sc = new FastScanner(System.in)
  val n = sc.nextInt()
  val a, b = Array.fill(n)(sc.nextInt() - 1)
  val count = Array.fill(n)(0)
  val idxa = Map[Int, List[Int]]().withDefaultValue(Nil)
  val idxb = Map[Int, List[Int]]().withDefaultValue(Nil)

  for (i <- 0 until n) {
    count(a(i)) += 1
    count(b(i)) += 1
    idxa(a(i)) ::= i
    idxb(b(i)) ::= i
  }

  if (count.max > n) {
    println("No")
  } else {
    val x = Array.fill(n+1)(Set[Int]())
    for (i <- 0 until n) {
      x(count(i)) += i
    }

    val ans = Array.fill(n)(-1)

    def update(p: Int, q: Int): Unit = {
      val idxap = idxa(p)
      val idxbq = idxb(q)
      ans(idxap.head) = q + 1

      if (idxap.tail.isEmpty) {
        idxa -= p
      } else {
        idxa(p) = idxap.tail
      }

      if (idxbq.tail.isEmpty) {
        idxb -= q
      } else {
        idxb(q) = idxbq.tail
      }

      val cp = count(p)
      val cq = count(q)
      count(p) -= 1
      count(q) -= 1

      x(cp) -= p
      x(cq) -= q
      x(cp - 1) += p
      x(cq - 1) += q
    }

    def getAny(m: Map[Int, List[Int]], except: Int): Int = {
      m.keys.find(_ != except).get
    }

    for (i <- n until 0 by -1) {
      var p = -1
      var q = -1
      x(i).toList match {
        case Nil =>
          p = getAny(idxa, -1)
          q = getAny(idxb, p)
        case x1 :: Nil =>
          if (idxa.isDefinedAt(x1)) {
            p = x1
            q = getAny(idxb, p)
          } else {
            q = x1
            p = getAny(idxa, q)
          }
        case x1 :: x2 :: Nil =>
          if (idxa.isDefinedAt(x1)) {
            p = x1
            q = x2
          } else {
            p = x2
            q = x1
          }
      }
      update(p, q)
    }

    println("Yes")
    println(ans.mkString(" "))
  }
}

class FastScanner(source: java.io.InputStream) {
  val buf = new Array[Byte](1024)
  var now, end = 0

  def isPrintable(b: Byte): Boolean = 33 <= b && b <= 126
  def isNum(b: Byte): Boolean = 48 <= b && b <= 57

  def hasNextByte: Boolean = {
    if (now < end) {
      true
    } else {
      now = 0
      end = source.read(buf)
      end > 0
    }
  }

  def nextByte(): Byte = {
    if (hasNextByte) {
      val b = buf(now)
      now += 1
      b
    } else {
      -1
    }
  }

  def hasNext: Boolean = {
    while (hasNextByte && !isPrintable(buf(now))) {
      now += 1
    }
    hasNextByte
  }

  def next(): String = {
    if (hasNext) {
      val sb = new StringBuilder()
      var b = nextByte()
      while (isPrintable(b)) {
        sb += b.toChar
        b = nextByte()
      }
      sb.toString
    } else {
      throw new NoSuchElementException()
    }
  }

  def nextInt(): Int = {
    nextLong().toInt
  }

  def nextLong(): Long = {
    if (hasNext) {
      var b = nextByte()
      var sign = 1
      var n = 0L
      if (b == '-') {
        sign = -1
        b = nextByte()
      }
      while (isNum(b)) {
        n = n * 10 + (b - 48)
        b = nextByte()
      }
      sign * n
    } else {
      throw new NoSuchElementException()
    }
  }

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

Score : 600 points

Problem Statement

Given are two sequences A and B, both of length N.
A and B are each sorted in the ascending order.
Check if it is possible to reorder the terms of B so that for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.

Constraints

1\leq N \leq 2 \times 10^5

1\leq A_i,B_i \leq N

A and B are each sorted in the ascending order.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N

Output

If there exist no reorderings that satisfy the condition, print No.

If there exists a reordering that satisfies the condition, print Yes on the first line.
After that, print a reordering of B on the second line, separating terms with a whitespace.

If there are multiple reorderings that satisfy the condition, you can print any of them.

Sample Input 1

6
1 1 1 2 2 3
1 1 1 2 2 3

Sample Output 1

Yes
2 2 3 1 1 1

Sample Input 2

3
1 1 2
1 1 3

Sample Output 2

No

Sample Input 3

4
1 1 2 3
1 2 3 3

Sample Output 3

Yes
3 3 1 2


import scala.collection.mutable.Map

object Main extends App {
  val sc = new FastScanner(System.in)
  val n = sc.nextInt()
  val a, b = Array.fill(n)(sc.nextInt() - 1)
  val count = Array.fill(n)(0)
  val idxa = Map[Int, List[Int]]()
  val idxb = Map[Int, List[Int]]()
  for (i <- 0 until n) {
    count(a(i)) += 1
    count(b(i)) += 1
    if (idxa.isDefinedAt(a(i))) {
      idxa(a(i)) ::= i
    } else {
      idxa(a(i)) = List(i)
    }
    if (idxb.isDefinedAt(b(i))) {
      idxb(b(i)) ::= i
    } else {
      idxb(b(i)) = List(i)
    }
  }

  if (count.max > n) {
    println("No")
  } else {
    val x = Array.fill(n+1)(Set[Int]())
    for (i <- 0 until n) {
      x(count(i)) += i
    }

    val ans = Array.fill(n)(-1)

    def update(p: Int, q: Int): Unit = {
      ans(idxa(p).head) = q + 1
      idxa(p) = idxa(p).tail
      idxb(q) = idxb(q).tail

      if (idxa(p).isEmpty) {
        idxa -= p
      }

      if (idxb(q).isEmpty) {
        idxb -= q
      }

      x(count(p)) -= p
      x(count(q)) -= q
      count(p) -= 1
      count(q) -= 1
      x(count(p)) += p
      x(count(q)) += q
    }

    def getAny(m: Map[Int, List[Int]], except: Int): Int = {
      m.keys.find(_ != except).get
    }

    for (i <- n until 0 by -1) {
      var p = -1
      var q = -1
      x(i).size match {
        case 0 =>
          p = getAny(idxa, -1)
          q = getAny(idxb, p)
        case 1 =>
          if (idxa.isDefinedAt(x(i).head)) {
            p = x(i).head
            q = getAny(idxb, p)
          } else {
            q = x(i).head
            p = getAny(idxa, q)
          }
        case 2 =>
          if (idxa.isDefinedAt(x(i).head)) {
            p = x(i).head
            q = x(i).last
          } else {
            p = x(i).last
            q = x(i).head
          }
      }
      update(p, q)
    }

    println("Yes")
    println(ans.mkString(" "))
  }
}

class FastScanner(source: java.io.InputStream) {
  val buf = new Array[Byte](1024)
  var now, end = 0

  def isPrintable(b: Byte): Boolean = 33 <= b && b <= 126
  def isNum(b: Byte): Boolean = 48 <= b && b <= 57

  def hasNextByte: Boolean = {
    if (now < end) {
      true
    } else {
      now = 0
      end = source.read(buf)
      end > 0
    }
  }

  def nextByte(): Byte = {
    if (hasNextByte) {
      val b = buf(now)
      now += 1
      b
    } else {
      -1
    }
  }

  def hasNext: Boolean = {
    while (hasNextByte && !isPrintable(buf(now))) {
      now += 1
    }
    hasNextByte
  }

  def next(): String = {
    if (hasNext) {
      val sb = new StringBuilder()
      var b = nextByte()
      while (isPrintable(b)) {
        sb += b.toChar
        b = nextByte()
      }
      sb.toString
    } else {
      throw new NoSuchElementException()
    }
  }

  def nextInt(): Int = {
    nextLong().toInt
  }

  def nextLong(): Long = {
    if (hasNext) {
      var b = nextByte()
      var sign = 1
      var n = 0L
      if (b == '-') {
        sign = -1
        b = nextByte()
      }
      while (isNum(b)) {
        n = n * 10 + (b - 48)
        b = nextByte()
      }
      sign * n
    } else {
      throw new NoSuchElementException()
    }
  }

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


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val a, b = Array.fill(n)(sc.nextInt() - 1)
  val count = Array.fill(n)(0)
  var idxa = Map[Int, List[Int]]().withDefaultValue(Nil)
  var idxb = Map[Int, List[Int]]().withDefaultValue(Nil)
  for (i <- 0 until n) {
    count(a(i)) += 1
    count(b(i)) += 1
    idxa += a(i) -> (i :: idxa(a(i)))
    idxb += b(i) -> (i :: idxb(b(i)))
  }

  if (count.max > n) {
    println("No")
  } else {
    val x = Array.fill(n+1)(Set[Int]())
    for (i <- 0 until n) {
      x(count(i)) += i
    }

    val ans = Array.fill(n)(-1)

    def update(p: Int, q: Int): Unit = {
      val idx = idxa(p).head
      ans(idx) = q + 1
      idxa += p -> idxa(p).tail
      idxb += q -> idxb(q).tail
      x(count(p)) -= p
      x(count(q)) -= q
      count(p) -= 1
      count(q) -= 1
      x(count(p)) += p
      x(count(q)) += q
    }

    def getAny(m: Map[Int, List[Int]], except: Int): Int = {
      m.find{case (k, v) => k != except && v.nonEmpty}.get._1
    }

    for (i <- n until 0 by -1) {
      var p = -1
      var q = -1
      x(i).size match {
        case 0 =>
          p = getAny(idxa, -1)
          q = getAny(idxb, p)
        case 1 =>
          if (idxa(x(i).head).nonEmpty) {
            p = x(i).head
            q = getAny(idxb, p)
          } else {
            q = x(i).head
            p = getAny(idxa, q)
          }
        case 2 =>
          if (idxa(x(i).head).nonEmpty) {
            p = x(i).head
            q = x(i).last
          } else {
            p = x(i).last
            q = x(i).head
          }
      }
      update(p, q)
    }

    println("Yes")
    println(ans.mkString(" "))
  }
}


import java.io.{BufferedOutputStream, BufferedReader, FileOutputStream, InputStreamReader, PrintWriter}
import java.lang

import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object Main {
  val DEBUG = false

  lazy val debugOut: PrintWriter = {
    new PrintWriter(new BufferedOutputStream(new FileOutputStream("log.txt", true)))
  }

  def log(message: => String): Unit = {
    if (DEBUG) {
      Console.err.println(message)
    }
  }

  def debug(closure: => Unit): Unit = {
    if (DEBUG) {
      closure
    }
  }

  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  def get[T1, T2, T3, T4](
                           implicit in: BufferedReader,
                           converter1: String => T1,
                           converter2: String => T2,
                           converter3: String => T3,
                           converter4: String => T4
                         ): (T1, T2, T3, T4) = {
    getArray[String] match {
      case Array(v1, v2, v3, v4) => (converter1(v1), converter2(v2), converter3(v3), converter4(v4))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def primes(n: Long): ArrayBuffer[Long] = {
    val buf = ArrayBuffer.empty[Long]
    val s = Math.sqrt(n).toInt

    var v = n
    for (i <- 2 to s) {
      if (v == 1 || v == 0) {
        return buf
      } else {
        while (v % i == 0) {
          buf.append(i)
          v /= i
        }
      }
    }
    if (v > s) {
      buf.append(v)
    }
    buf
  }

  def divisors(n: Int): ArrayBuffer[Int] = {
    val buf = ArrayBuffer.empty[Int]
    val s = Math.sqrt(n).toInt

    for (i <- 1 to s) {
      if (n % i == 0) {
        buf.append(i)
        if (i != n / i) {
          buf.append(n / i)
        }
      }
    }
    buf
  }

  @tailrec
  def gcd(a: Long, b: Long): Long = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

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

  def lcm(a: Long, b: Long): Long = {
    a / gcd(a, b) * b
  }

  def toBitArray(n: Int, width: Int): Array[Boolean] = {
    val buf = ArrayBuffer.fill(width)(false)

    @tailrec
    def inner(n: Int, i: Int): Array[Boolean] = {
      buf(i) = (n & 1) == 0
      if (i == 0) {
        buf.toArray
      } else {
        inner(n / 2, i - 1)
      }
    }

    inner(n, width - 1)
  }

  def modpow(n: Long, p: Long, m: Long): Long = {
    @tailrec
    def inner(n: Long, p: Long, acc: Long): Long = {
      if (p == 0) {
        acc
      } else if ((p & 1) == 0) {
        inner(n * n % m, p >> 1, acc)
      } else {
        inner(n * n % m, p >> 1, acc * n % m)
      }
    }

    inner(n % m, p, 1)
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val s = get[String]
    val t = get[String]

    var min = Int.MaxValue
    for(i <- 0 to s.length - t.length) {
      var same = 0

      for(j <- 0 until t.length) {
        if (s(i + j) == t(j)) {
          same += 1
        }
      }

      min = Math.min(min, t.length - same)
    }

    out.println(min)

    log("=== start")

    out.flush()
    log("=== end")
    debug {
      debugOut.flush()
    }
  }
}

Score : 200 points

Problem Statement

Given are two strings S and T.

Let us change some of the characters in S so that T will be a substring of S.

At least how many characters do we need to change?

Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

Constraints

The lengths of S and T are each at least 1 and at most 1000.

The length of T is at most that of S.

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the minimum number of characters in S that need to be changed.

Sample Input 1

cabacc
abc

Sample Output 1

1

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.

Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

Sample Input 2

codeforces
atcoder

Sample Output 2

6


import java.io.{BufferedOutputStream, BufferedReader, FileOutputStream, InputStreamReader, PrintWriter}
import java.lang

import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object Main {
  val DEBUG = false

  lazy val debugOut: PrintWriter = {
    new PrintWriter(new BufferedOutputStream(new FileOutputStream("log.txt", true)))
  }

  def log(message: => String): Unit = {
    if (DEBUG) {
      Console.err.println(message)
    }
  }

  def debug(closure: => Unit): Unit = {
    if (DEBUG) {
      closure
    }
  }

  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  def get[T1, T2, T3, T4](
                           implicit in: BufferedReader,
                           converter1: String => T1,
                           converter2: String => T2,
                           converter3: String => T3,
                           converter4: String => T4
                         ): (T1, T2, T3, T4) = {
    getArray[String] match {
      case Array(v1, v2, v3, v4) => (converter1(v1), converter2(v2), converter3(v3), converter4(v4))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def primes(n: Long): ArrayBuffer[Long] = {
    val buf = ArrayBuffer.empty[Long]
    val s = Math.sqrt(n).toInt

    var v = n
    for (i <- 2 to s) {
      if (v == 1 || v == 0) {
        return buf
      } else {
        while (v % i == 0) {
          buf.append(i)
          v /= i
        }
      }
    }
    if (v > s) {
      buf.append(v)
    }
    buf
  }

  def divisors(n: Int): ArrayBuffer[Int] = {
    val buf = ArrayBuffer.empty[Int]
    val s = Math.sqrt(n).toInt

    for (i <- 1 to s) {
      if (n % i == 0) {
        buf.append(i)
        if (i != n / i) {
          buf.append(n / i)
        }
      }
    }
    buf
  }

  @tailrec
  def gcd(a: Long, b: Long): Long = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

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

  def lcm(a: Long, b: Long): Long = {
    a / gcd(a, b) * b
  }

  def toBitArray(n: Int, width: Int): Array[Boolean] = {
    val buf = ArrayBuffer.fill(width)(false)

    @tailrec
    def inner(n: Int, i: Int): Array[Boolean] = {
      buf(i) = (n & 1) == 0
      if (i == 0) {
        buf.toArray
      } else {
        inner(n / 2, i - 1)
      }
    }

    inner(n, width - 1)
  }

  def modpow(n: Long, p: Long, m: Long): Long = {
    @tailrec
    def inner(n: Long, p: Long, acc: Long): Long = {
      if (p == 0) {
        acc
      } else if ((p & 1) == 0) {
        inner(n * n % m, p >> 1, acc)
      } else {
        inner(n * n % m, p >> 1, acc * n % m)
      }
    }

    inner(n % m, p, 1)
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val (n, m) = get[Int, Int]
    val friendships = Array.fill(m) {
      get[Int, Int] match {
        case (a, b) => (a - 1, b - 1)
      }
    }

    log("=== start")

    class UnionFind(n: Int) {
      val roots: Array[Int] = Array.ofDim[Int](n)
      for(i <- 0 until n) {
        roots(i) = i
      }

      val sizes: Array[Int] = Array.fill(n)(1)

      def root(i: Int): Int = {
        if (roots(i) == i) {
          i
        } else {
          roots(i) = root(roots(i))
          roots(i)
        }
      }

      def unite(i: Int, j: Int): Unit = {
        val rootI = root(i)
        val rootJ = root(j)
        if (rootI != rootJ) {
          sizes(rootI) += sizes(rootJ)
          sizes(rootJ) = 0
          roots(rootJ) = rootI
        }
      }

      def isSameRoot(i: Int, j: Int): Boolean = {
        root(i) == root(j)
      }

      def getSize(i: Int): Int = {
        sizes(root(i))
      }
    }

    val unionFind = new UnionFind(n)

    for((a,b) <- friendships) {
      unionFind.unite(a,b)
    }

    var max = 0
    for(i <- 0 until n) {
      max = Math.max(unionFind.getSize(i), max)
    }

    out.println(max)

    out.flush()
    log("=== end")
    debug {
      debugOut.flush()
    }
  }
}

Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

2 \leq N \leq 2\times 10^5

0 \leq M \leq 2\times 10^5

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

4 10
1 2
2 1
1 2
2 1
1 2
1 3
1 4
2 3
2 4
3 4

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3


import scala.io.StdIn._

object Main extends App {

  val Array(n,t,x) = readLine().split(" ").map(_.toInt)

  def solve() = {
    (n.toDouble / t).ceil.toInt * x
  }

  println(solve())

}

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val N: Seq[Char] = sc.next()
  val sum = N.map(_.asDigit).sum
  if (sum % 9 == 0) {
    println("Yes")
  } else {
    println("No")
  }

}

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


import scala.io.StdIn

object Main extends App {
  val nums=StdIn.readLine().split("").map(_.toInt)
  val sum=nums.sum
  val ans = if(sum % 9 == 0) "Yes" else "No"
  println(ans)

}