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

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

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

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

  def solve(): Unit = {
    val N, Q = ni()
    val uf = new UnionFind(N)
    REP(Q) { _ =>
      val com, x, y = ni()
      com match {
        case 0 => uf.unite(x, y)
        case 1 =>
          val res = if (uf.find(x) == uf.find(y)) 1 else 0
          out.println(res)
      }
    }
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    REP(n) (i => par(i) = i)
    val rank: Array[Int] = Array.fill[Int](n)(1) // 集合の要素数
    private val visits = Array.ofDim[Int](n) // 訪れた場所をfind毎に用意するのがもったいないのでつかいまわす

    def find(x: Int): Int = {
      var ptr = 0
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          visits(ptr) = x
          ptr += 1
          step(par(x))
        }
      }

      val res = step(x)
      REP(ptr){ i => par(visits(i)) = res }
      res
    }

    def unite(x: Int, y: Int): Int = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 == y1) x1
      else {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
          y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += rank(y1)
          x1
        }
      }
    }

    /**
      * xを解決する必要がないときは直にrankをみる
      */
    def cntNodes(x: Int): Int = rank(find(x))
  }

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

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

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

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

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

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

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

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

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

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

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

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

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


import scala.io.StdIn._

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

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

Range Minimum Query (RMQ)

Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations:

find(s, t): report the minimum element in as, as+1, . . . ,at.

update(i, x): change ai to x.

Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.

Input

n q
com0 x0 y0
com1 x1 y1
...
comq−1 xq−1 yq−1

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes update(xi, yi) and '1' denotes find(xi, yi).

Output

For each find operation, print the minimum element.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

If comi is 0, then 0 ≤ xi < n, 0 ≤ yi < 231-1.

If comi is 1, then 0 ≤ xi < n, 0 ≤ yi < n.

Sample Input 1

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

Sample Output 1

1
2

Sample Input 2

1 3
1 0 0
0 0 5
1 0 0

Sample Output 2

2147483647
5

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.


import scala.io.StdIn.readLine

object Main {

	def find(array: Seq[Int], s: Int, t: Int): Int = array.slice(s, t+1).min

	def update(array: Seq[Int], i: Int, x: Int): Seq[Int] = array.updated(i,x)

	def main(args: Array[String]){
		val in = readLine().split(" ").map(_.toInt)
		val n = in(0)
		val q = in(1)

		var a = Seq.fill(n)(Integer.MAX_VALUE)

		for(_ <- 1 to q){
			val in = readLine().split(" ").map(_.toInt)
			val com = in(0)
			val x = in(1)
			val y = in(2)

			if(com==0) a = update(a,x,y)
			else println(find(a,x,y))
		}
	}
}


object Main extends App {
    val in = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt))
    val x = List(Array(0, in.next.head-1, 2147483647))
    in.foldLeft(x)((qs, q) => q match {
        case Array(0, _*) => q.tail +: qs
        case Array(1, i) => {
            println((qs.find(y => y(0) <= i && y(1) >= i).get)(2))
            qs
        }
    })
}

Range Update Query (RUQ)

Write a program which manipulates a sequence A = {a0, a1, . . . , an−1} with the following operations:

update(s, t, x): change as, as+1, ..., at to x.

find(i): output the value of ai.

Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.

Input

n q
query1
query2
:
queryq

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:

0 s t x

or

1 i

The first digit represents the type of the query. '0' denotes update(s, t, x) and '1' denotes find(i).

Output

For each find operation, print the value.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

0 ≤ s ≤ t < n

0 ≤ i < n

0 ≤ x < 231−1

Sample Input 1

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

Sample Output 1

1
3

Sample Input 2

1 3
1 0
0 0 0 5
1 0

Sample Output 2

2147483647
5


import java.util.Scanner

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

object Main extends App {
  val in = new Scanner(System.in)
  val V = in.nextInt()
  val E = in.nextInt()
  val dinitz = new Dinitz(V)
  for (_ <- 0 until E) {
    val s = in.nextInt()
    val t = in.nextInt()
    val c = in.nextInt()
    dinitz.addEdge(s, t, c)
  }

  val f = dinitz.maxFlow(0, V - 1)
  println(f)
}

import java.util

class Dinitz(val V: Int) {

  class Edge(var to: Int, var cap: Long, var rev: Int)

  private val graph = (for (_ <- 0 until V) yield new ArrayBuffer[Edge]()).toArray
  private val iter = new Array[Int](V)

  def addEdge(from: Int, to: Int, cap: Long): Unit = {
    graph(from).append(new Edge(to, cap, graph(to).size))
    graph(to).append(new Edge(from, 0, graph(from).size - 1))
  }

  def maxFlow(source: Int, sink: Int): Long = {
    var flow = 0L

    while (true) {
      val queue = new mutable.Queue[Int]()
      val level = Array.fill[Int](V)(-1)
      level(source) = 0
      queue.enqueue(source)
      while (queue.nonEmpty) {
        val v = queue.dequeue()
        for (e <- graph(v)) {
          if (e.cap > 0 && level(e.to) < 0) {
            level(e.to) = level(v) + 1
            queue.enqueue(e.to)
          }
        }
      }

      if (level(sink) < 0) return flow
      util.Arrays.fill(iter, 0)

      def dfs(v: Int, t: Int, f: Long): Long = {
        if (v == t) return f

        while (iter(v) < graph(v).size) {
          val e = graph(v)(iter(v))
          if (e.cap > 0 && level(v) < level(e.to)) {
            val d = dfs(e.to, t, Math.min(f, e.cap))
            if (d > 0) {
              e.cap -= d
              graph(e.to)(e.rev).cap += d
              return d
            }
          }

          iter(v) += 1
        }
        0
      }

      var f = 1L
      while (f > 0) {
        f = dfs(source, sink, Long.MaxValue)
        flow += f
      }
    }

    throw new IllegalStateException()
  }
}

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

Maximum Flow

A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$.

Input

A flow network is given in the following format.

$|V|\;|E|$

$u_0\;v_0\;c_0$

$u_1\;v_1\;c_1$

:

$u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$

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

$u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network.
A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge.

Output

Print the maximum flow.

Constraints

$2 \leq |V| \leq 100$

$1 \leq |E| \leq 1000$

$0 \leq c_i \leq 10000$

Sample Input 1

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

Sample Output 1

3


object Main extends App {
  val in = readLine.split(' ').map(_.toDouble)
  val a = in(0)
  val b = in(1)
  val C = in(2).toRadians

  val c = math.sqrt(a*a + b*b - 2*a*b*math.cos(C))

  val L = a + b + c;

  val h = b * math.sin(C)

  val S = a * h / 2;

  println(S)
  println(L)
  println(h)
}

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 scala.io.Source
import scala.math._

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

    val num = lines.length / 2

    for(i <- 0 until num){
      println(stdDeviation(lines(i * 2 + 1).split(" ").toList.map(_.toDouble)))
    }
  }

  def stdDeviation(list: List[Double]): Double={
   sqrt(list.map{_ - (list.sum / list.length)}.map{pow(_, 2)}.sum / list.length)
  }
}

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


import scala.math.sqrt
import scala.io.Source

object Main extends App {
  val src: Iterator[String] = Source.stdin.getLines

  def deviator(n: Double, li: List[Double]): Double = {
    def predicate(a: Double, b: Double): Double = {
      val avg = li.sum / n
      a + (b-avg)*(b-avg)
    }

    sqrt(li.foldLeft(0.0)(predicate) / n)
  }

  for (n <- src if src.hasNext) {
    val li = src.next.split(" ").map(_.toDouble).toList
    println(deviator(n.toDouble, li))
  }
}


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

object Main {

  object Dice{
    private val north = List(2,6,3,4,1,5).map(_-1)
    private val east = List(4,2,1,6,5,3).map(_-1)
    private val ccw = List(3,2,6,1,5,4).map(_-1)
  }

  case class Dice(pip: List[Int]) {
    private def north = Dice(Dice.north.map(pip))
    private def east = Dice(Dice.east.map(pip))
    private def south = north.north.north
    private def west = east.east.east

    def rotate(com: Char):Dice = com match {
      case 'N' => north
      case 'E' => east
      case 'S' => south
      case 'W' => west
      case _ => this
    }
  }

  @tailrec
  def loop(com: String, dice: Dice):Dice = {
    if(com.isEmpty)dice
    else loop(com.tail,dice.rotate(com.head))
  }

  def main(args: Array[String]): Unit = {
    val pip = readLine.split(" ").map(_.toInt).toList
    println(loop(readLine,Dice(pip)).pip(0))
  }
}

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

Dice I

Write a program to simulate rolling a dice, which can be constructed by the following net.

As shown in the figures, each face is identified by a different label from 1 to 6.

Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the dice, and prints the integer on the top face. At the initial state, the dice is located as shown in the above figures.

Input

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

In the second line, a string which represents a sequence of commands, is given. The command is one of 'E', 'N', 'S' and 'W' representing four directions shown in the above figures.

Output

Print the integer which appears on the top face after the simulation.

Constraints

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

$0 \leq $ the length of the command $\leq 100$

Sample Input 1

1 2 4 8 16 32
SE

Sample Output 1

8

You are given a dice where 1, 2, 4, 8, 16 are 32 are assigned to a face labeled by 1, 2, ..., 6 respectively. After you roll the dice to the direction S and then to the direction E, you can see 8 on the top face.

Sample Input 2

1 2 4 8 16 32
EESWN

Sample Output 2

32


object Main {
    def step(s: (Int, Int, Int), i: Char) = i match {
        case 'N' => (s._2, 5-s._1, s._3)
        case 'E'  => (5-s._3, s._2, s._1)
        case 'W'  => (s._3, s._2, 5-s._1)
        case 'S' => (5-s._2, s._1, s._3)
    }

    def main(args: Array[String]) = {
        val in = io.Source.stdin.getLines
        val nums = in.next.split(" ").map(_.toInt)
        println(nums(in.next.foldLeft((0, 1, 2))(step)._1))
    }
}


import scala.io.StdIn.readLine

object Dice {
  def rollOnce(dir:Char)  =
    dir match {
      case 'S' => Array(4,0,2,3,5,1)
      case 'N' => Array(1,5,2,3,0,4)
      case 'W' => Array(2,1,5,0,4,3)
      case 'E' => Array(3,1,0,5,4,2)
    }
}

class Dice(var d:Array[Int]) {

  def roll(dirs:String)  = {
    d = dirs.foldLeft(Array(0,1,2,3,4,5)) { (x,y) => Dice.rollOnce(y).map(x) }.map(d)
  }

  def getTopFace() = d(0)
}

object Main extends App {
  val faces = readLine.split(" ").map(_.toInt)
  val dice = new Dice(faces)
  dice.roll(readLine)

  println(dice.getTopFace())
}


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

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

    def apply(number: Int): Int = {
      numbers(number)
    }
  }

  def main(args: Array[String]): Unit = {
    val dice = new Dice(io.StdIn.readLine().split(" ").map(_.toInt))
    val operations = io.StdIn.readLine()
    val operatedDice = operations.foldLeft(dice)(_.rotateTo(_))
    println(operatedDice(0))
  }
}


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

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

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

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

  def main(args: Array[String]): Unit = {
    val dice = new Dice(io.StdIn.readLine().split(" ").map(_.toInt))
    val questions = io.StdIn.readInt()
    Iterator.continually(io.StdIn.readLine()).takeWhile(_ != null).map(_.split(" ").map(_.toInt))
      .take(questions)
      .map {
        case Array(top, front) => determineRight(dice, top, front)
      }
      .foreach(println)
  }

  def determineRight(dice: Dice, top: Int, front: Int): Int = {
    val operationsToTop = Seq("", "N", "W", "E", "S", "NN")
    val operationsToFront = Seq("S", "", "WSE", "ESW", "SEEN", "N")
    val dice2 = operationsToTop(dice.find(top)).foldLeft(dice)(_.rotateTo(_))
    val dice3 = operationsToFront(dice2.find(front)).foldLeft(dice2)(_.rotateTo(_))
    dice3(2)
  }
}

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

Dice II

Construct a dice from a given sequence of integers in the same way as Dice I.

You are given integers on the top face and the front face after the dice was rolled in the same way as Dice I. Write a program to print an integer on the right side face.

Input

In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.
In the second line, the number of questions $q$ is given.

In the following $q$ lines, $q$ questions are given. Each question consists of two integers on the top face and the front face respectively.

Output

For each question, print the integer on the right side face.

Constraints

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

The integers are all different

$1 \leq q \leq 24$

Sample Input

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

Sample Output

3
5
6


object Main {
  def main(args: Array[String]) = {
    for (arg <- args.map(_.toInt)) println(arg * arg * arg)
  }
}

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 {
  def main(args: Array[String]) {
    for (arg <- args.map(_.toInt)) print(arg * arg * arg)
  }
}


import java.util.Scanner
import scala.math.pow

object Main {
  def main (args: Array[String]) = {
    val in = new Scanner(System.in)
    val x = in.nextInt
    println(pow(x, 3).toInt)
  }
}


import scala.io.StdIn.readInt
object Main extends App {
    val n = readInt()
    println(n * n * n)
}


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

object Main extends App {
    val x = readInt
    println( x*x*x )
}


object Main {
  def main(args: Array[String]): Unit = {
    val x = io.StdIn.readLine().toInt
    println(x * x * x)
  }
}


import scala.io.StdIn._

object Main{
  def main(args : Array[String]){
    val x : BigInt = readInt
    println(x * x * x)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val x = io.StdIn.readInt()
    println(x * x * x)
  }
}


import scala.io.StdIn

object Main {
  def main(args:Array[String]) {
    val inputs = StdIn.readLine().split(" ")
    val a = inputs(0).toInt
    val b = inputs(1).toInt
    println((a * b) + " " + (2 * a + 2 * b))
  }
}

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]): Unit = {
    val ab = io.StdIn.readLine().split(" ").map(_.toInt)
    val a = ab(0)
    val b = ab(1)
    println(s"${a * b} ${2 * a + 2 * b}")
  }
}


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 scala.io.StdIn

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

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


import scala.io.StdIn.readInt

object Main {

  def main(args: Array[String]) = {
    val n = readInt
    println(n/3600 + ":" + n/60%60 + ":" + n%60)
  }
}


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]) {
    val s: Int = readLine.i(0)
    println(List(s / (60 * 60), (s % (60 * 60)) / 60, s % 60).mkString(":"))
  }
}


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


import scala.io.StdIn._
object Main {
	def main(args :Array[String]) = {
		var mtrl = readLine.split(" ").map(_.toInt)

		if (mtrl(0)==mtrl(1)) { val f = "=="; println(mtrl(0)+f+mtrl(1)) }
		else if (mtrl(0)>mtrl(1)) { val f = "<"; println(mtrl(0)+f+mtrl(1)) }
		else { val f = ">"; println(mtrl(0)+f+mtrl(1)) }
	}

}

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 java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val a, b = sc.nextInt()
  if (a < b) println("a < b")
  else if (a > b) println("a > b")
  else println("a == b")
}


import scala.io.StdIn

object Main{
  def main(args: Array[String]){
    var list = List[Int]()

    for(in <- StdIn.readLine.split(" ").map(_.toInt)){
      list = in :: list
    }

    boc(list.reverse)
  }

  def boc(a: List[Int])={
    if(a(0) < a(1) && a(1) < a(2)) println("Yes")
    else println("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 {
  def main(args:Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val a = sc.nextInt
    val b = sc.nextInt
    val c = sc.nextInt
    println(if(a<b && b<c)"Yes" else "No")
  }
}


import java.util.Scanner

object Main {
  def main (args: Array[String]) = {
    val in = new Scanner(System.in)
    val a = in.nextInt()
    val b = in.nextInt()
    val c = in.nextInt()
    val result = if (a < b && b < c) "Yes" else "No"

    println(result)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val in = new java.util.Scanner(System.in)
    val a = in.nextInt()
    val b = in.nextInt()
    val c = in.nextInt()
    if(a < b && b < c){
      println("Yes")
    }else{
      println("No")
    }

  }
}


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

		if( a < b && b < c) {
			println("Yes")
		} else {
			println("No")
		}
	}
}


object Main {
  def main(args: Array[String]) {
    val s = io.StdIn.readLine().split(" ") map (i => Integer.parseInt(i))
    println("%s".format(if (s(0)<s(1) && s(1)<s(2)) "Yes" else "No"))
  }
}


import scala.io.StdIn

/**
  * AOJ
  */
object Main {

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

    val in = StdIn.readLine().split(" ").map(s => s.toInt)

    println(if(in(0) < in(1) && in(1) < in(2)){"Yes"}else{"No"})
  }
}


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

    val input: String = readLine()
    val list: Array[String] = input.split(" ")

    val a: Int = list(0).toInt
    val b: Int = list(1).toInt
    val c: Int = list(2).toInt

    var ans = "No"
    if (a < b && b < c) {
      ans = "Yes"
    }
    println(ans)
  }

//  def readLine(): String = {"5 5"}
}


object Main extends App {
  val x = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val a = x(0)
  val b = x(1)
  val c = x(2)
  if (a < b && b < c) println("Yes")
  else println("No")
}


import scala.io.StdIn

object Main{
  def main(args: Array[String]){
    var list = List[Int]()

    for(in <- StdIn.readLine.split(" ").map(_.toInt)){
      list = in :: list
    }

    list.reverse.sortWith((s,t: Int) => s < t).foreach((s: Int) => printf("%d ", s))
    println()
  }
}

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.readLine

object Main {

  def main(args: Array[String]) = {
      val n = readLine().split(" ").map(_.toInt).sorted
      val (a,b,c) = (n(0),n(1),n(2))
      println(a + " " + b + " " + c)
  }
}


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(readLine.ints.sorted.mkString(" "))
  }
}


import scala.io.StdIn

object Main extends App {
  val a = StdIn.readLine().trim.split(' ').map(_.toInt)

  println(a.sorted.toList.mkString(" "))

}


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

    width match{
      case w if (x-r >= 0) && (y-r >=0) && (x+r <= width) && (y+r <= height)  => println("Yes")
      case _     => 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


import java.util.Scanner

object Main {
  def main (args: Array[String]) = {
    val in = new Scanner(System.in)
    val W = in.nextInt
    val H = in.nextInt
    val x = in.nextInt
    val y = in.nextInt
    val r = in.nextInt

    val wIn = (0 < (x - r)) && (W >= (x + r))
    val hIn = (0 < (y - r)) && (H >= (y + r))
    val result = if(wIn && hIn) "Yes" else "No"

    println(result)

  }
}


object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val w, h, x, y, r = sc.nextInt
    if (r <= x && r <= y  &&  (x <= ( w - r )) && ( y <= ( h - r ))) println("Yes")
      else println("No")

  }

}


import scala.io.StdIn.readLine

object Main {
  def main(args:Array[String]) {
    val in = readLine().split(" ").map(_.toInt)
    val (h, w, 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")
    }
  }
}


object Main extends App {
  var i = 0
  val sb = StringBuilder.newBuilder
  for(x <- io.Source.stdin.getLines() if x != "0") {
    i += 1
    sb.append("Case ").append(i).append(": ")
      .append(x).append('\n')
  }
  print(sb.toString())
}

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 {
  var i = 0
  val sb = StringBuilder.newBuilder
  for(x <- io.Source.stdin.getLines() if x != "0") {
    i += 1
    // sb.append("Case ").append(i).append(": ")
    //   .append(x).append('\n')
    sb.append(s"Case $i: $x\n")
  }
  print(sb.toString())
}


object Main {
  def main(args: Array[String]): Unit = {
    for(line <- io.Source.stdin.getLines() if line != "0 0") {
      val arr = line.split(" ").map(_.toInt).sorted
      println(arr(0) + " " + arr(1))
    }
  }
}

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]) {
    var count:Int = 0
    for(line <- scala.io.Source.stdin.getLines()){
      val Array(min, max, o) = line.split(" ").map(_.toInt)
      var list: List[Int] = List()
      for( i <- min to max if ((o % i)  == 0) ) list = i::list
      println(list)
    }
  }
}

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
  println((a to b).filter(c % _ == 0).size)
}


import java.util.Scanner

object Main {
  def main (args: Array[String]) = {
    val in = new Scanner(System.in)
    val a = in.nextInt
    val b = in.nextInt
    val c = in.nextInt

    val div = for (
      i <- 1 to c
      if ((c % i) == 0)
      if (a <= i && b >= i)
    ) yield i

    println(div.length)
  }
}


object Main {
  def main(args:Array[String]){
    var count=0
    val sc=new java.util.Scanner(System.in)
    val a,b,c=sc.nextInt
    for(i<-a to b){
      if(c%i==0) count+=1
    }
    println(count)
  }
}


object Main{
    def main(args: Array[String]): Unit ={
        var in = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        println((in(0) to in(1)).filter(i => in(2) % i == 0).length)
    }
}


object Main {
    def main(args : Array[String]) : Unit = {
        val input = io.StdIn.readLine().split(" ").map(_.toInt)
        var count = 0
        for (i <- input(0) to input(1)) {
            if ((input(2) % i) == 0)
                count += 1
        }
        println(count)
    }
}


import scala.io.StdIn.readLine

object Main extends App {

  val Array(a, b, c) = readLine().split(" ").map { _.toInt }

  val n = (a to b).count { c % _ == 0 }
  println(n)
}


object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val a, b = sc.nextInt
    val d:Int = a / b
    val r:Int = a % b
    val f:Double = a.toDouble / b
    println("%d %d %f".format(d, r, f))

  }
}

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


object Main {
  def main(args:Array[String]){
    val sc=new java.util.Scanner(System.in)
    val a,b=sc.nextInt
    println("%d %d %.8f".format(a/b,a%b,a/b.toDouble))
  }
}


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


import scala.io.StdIn

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

    printf("%d %d %10.8f\n", list(0) / list(1), list(0) % list(1), list(0).toDouble / list(1).toDouble)
  }
}


import scala.io.StdIn

object Main extends App {

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

  print(d + " " + r + " " + f"$f%.5f")

}


import scala.io.StdIn.readDouble
import scala.math.Pi

object Main {

  def main(args: Array[String]) = {
      val r = readDouble()
      println("%.6f".format(r*r*Pi) + " " + "%.6f".format(2*r*Pi))
  }
}

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


import scala.io.StdIn.readLine
import scala.math.Pi

object Main {
	def main(args: Array[String]) = {
		val r = io.StdIn.readLine.split(" ").map(_.toDouble)
		printf("%.6f %.6f\n", r(0)*r(0)*math.Pi, 2*r(0)*math.Pi)
	}
}


import scala.io.Source

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

    for(i <- 0 until list.length){
      if(list(list.length - i - 1).size > 4){
        val arr = list(list.length - i - 1).split(Array(' '))

        arr(1) match {
          case "+" => println(arr(0).toInt + arr(2).toInt)
          case "-" => println(arr(0).toInt - arr(2).toInt)
          case "*" => println(arr(0).toInt * arr(2).toInt)
          case "/" => println(arr(0).toInt / arr(2).toInt)
          case "?" =>
        }
      }
    }
  }
}

Simple Calculator

Write a program which reads two integers a, b and an operator op, and then prints the value of a op b.

The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.

Input

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

a op b

The input ends with a dataset where op = '?'. Your program should not process for this dataset.

Output

For each dataset, print the value in a line.

Constraints

0 ≤ a, b ≤ 20000

No divisions by zero are given.

Sample Input 1

1 + 2
56 - 18
13 * 2
100 / 10
27 + 81
0 ? 0

Sample Output 1

3
38
26
10
108


import scala.io.Source

object Main extends App{
  Source.stdin.getLines.toList.init
    .map(_.split(" "))
    .map(x => (x(0).toInt,x(1),x(2).toInt))
    .map(x => (if(x._2 == "+") x._1+x._3 else if(x._2 == "-") x._1-x._3 else if(x._2 == "*") x._1*x._3 else if(x._2 == "/") x._1/x._3))
    .map(println)
}


object Main extends App {
  val n = scala.io.StdIn.readLine.toInt
  val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  println(s"${a.min} ${a.max} ${a.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


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

object Main {

  def main(args: Array[String]) = {
    val n = readInt
    val (min,max,sum) = readLine.split(" ")
                                .map(_.toInt)
                                .foldLeft(Int.MaxValue,Int.MinValue,0){ case ((min,max,sum),x)=>(Math.min(min,x),Math.max(max,x),sum+x) }
    printf("%d %d %d\n",min,max,sum)
  }
}


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

object Main {

  def main(args: Array[String]) = {
    val n = readInt
    val l = readLine.split(" ").map(_.toInt)
    printf("%d %d %d\n",l.min,l.max,l.foldLeft(0.toLong)(_+_))
  }
}


object Main {

    def main(args: Array[String]) = {
        val sc = new java.util.Scanner(System.in)
        val n = sc.nextInt
        val a = Array.fill(n)(sc.nextLong).sorted

        println(a.head + " " + a.last + " " + a.foldLeft(0L){ (acc, x) => acc+x })
    }
}


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){
          for{i <- 0 until h; j <- 0 until h}{
            print("#")
            if(j == h-1)println()
          }
          println()
        }
      }
  }
}

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)
    rec(in)
  }
  def rec(in:java.util.Scanner):Unit ={
    val a = in.nextInt
    val b = in.nextInt
    if(a ==0 && b == 0) return
    for(i <- 1 to a){
      for(j <- 1 to b){
        print("#")
      }
      println("")
    }
    println("")
    return rec(in)
  }
}


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


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

object Main extends App {

  var temp = Array(-1, -1)
  val buff = new ListBuffer[(Int, Int)]
  while(temp(0) != 0 && temp(1) != 0){
    temp = StdIn.readLine().split(' ').map(_.toInt)
    buff += ((temp(0), temp(1)))
  }

  val result = buff.dropRight(1).map { case (h, w) =>
    (0 until h).map { _ =>
      Array.fill(w)("#").mkString("")
    }.mkString(f"%n")
  }
  print(result.mkString(f"%n"))
}


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(h: Int = sc.nextInt, w: Int = sc.nextInt): Unit = {
        if( h != 0 && w != 0 ) {
            pw.println("#"*w)
            for(i <- 1 to h-2) pw.println("#"+"."*(w-2)+"#")
            pw.println("#"*w)
            pw.println()
            output()
        }
    }

    output()
    pw.flush
}

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.Source

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

    for(line <- Source.stdin.getLines()) {
      val items = line.split(" ").toList.map(_.toInt)
      if (items(0) == 0 && items(1) == 0) {
        return
      }

      for (hIndex <- (1 to items(0))) {
        val w = (1 to items(1)).toList.map{ wIndex =>
          if ((hIndex % 2 == 0 && wIndex % 2 != 0) || (hIndex % 2 != 0 && wIndex % 2 == 0)) "."
          else "#"
        }
        println(w.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

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

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

#.#
.#.
#.#

#.
.#

#


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) {
      val h = n(0)
      val w = n(1)

      for(i <- 0 to h-1) {
        val str = if(i%2==0) "#."*w else ".#"*w
        println(str.take(w))
      }
      println()
      n = readLine.split(" ").map(_.toInt)
    }
  }
}


import scala.io.Source

object Main extends App {
  for (line <- Source.stdin.getLines if line != "0 0") {
    val Array(h, w) = line.split(" ").map(_.toInt)
    for (i <- 1 to h) {
      for ( j <- 1 to w) {
        print { if ((i+j) % 2 == 0) "#" else "." }
      }
      println()
    }
    println()
  }
}


import io.Source.stdin

object Main {

  def main(args: Array[String]) {
    for ((list) <- stdin.getLines().takeWhile(_ != "0 0").map(_.split(" ").map(_.toInt))) {
      val (h: Int, w: Int) = (list(0), list(1))
      printChessBoard(h, w)
    }
  }

  def printChessBoard(h: Int, w: Int) {
    for (i <- 1 to h) {
      for (j <- 1 to w) {
        printChar(isSharp(i, j))
      }
      println()
    }
    println()
  }

  def printChar(isSharp: Boolean) {
    if (isSharp) {
      print("#")
    } else {
      print(".")
    }
  }

  def isSharp(i: Int, j: Int): Boolean = {
    if ((i % 2 == 0 && j % 2 != 0) || (j % 2 == 0 && i % 2 != 0)) {
      false
    } else {
      true
    }
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  println(" " + (1 to n).filter(i => isMultipleOf3(i) || hasNumberOf3(i)).mkString(" "))

  def isMultipleOf3(i: Int): Boolean = i % 3 == 0
  def hasNumberOf3(i: Int): Boolean = i % 10 == 3 || i / 10 == 3
}

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 {
	def main(args: Array[String]): Unit = {
	  val in = new java.util.Scanner(System.in)
	  val n =  in.nextInt
	  call(1,n)
	}
	def call(n : Int,lim:Int): Unit = {
	  if (lim < n){
           println("")
           return
          }
	  val i = n
	  if(i % 3 == 0){
	    printf(" "+i)
	  }else{
	    callRec(i)
	  }
	  call(i+1,lim)
	}
	def callRec(n:Int):Unit={
	  if(n == 0) return
	  if(n % 10 == 3) {
	    printf(" "+n)
	    return
	  }
	  callRec(n/10)
	}
}


object Main {
	def main(args: Array[String]): Unit = {
	  val in = new java.util.Scanner(System.in)
	  val n =  in.nextInt
	  call(1,n)
	}
	def call(n : Int,lim:Int): Unit = {
	  if (lim < n){
	    println("")
	    return
	  }
	  val i = n
	  if(i % 3 == 0){
	    printf(" "+i)
	  }else{
	    callRec(i,i)
	  }
	  call(i+1,lim)
	}
	def callRec(ori:Int,n:Int):Unit={
	  if(n == 0) return
	  if(n % 10 == 3) {
	    printf(" "+ori)
	    return
	  }
	  callRec(ori,n/10)
	}
}


object Main {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val output =
      (for {
        i <- 1 to n
        if i % 3 == 0 || include3(i)
      } yield s" $i").mkString
    println(output)
  }

  def include3(x: Int): Boolean = {
    var included = false
    var i = x
    while (!included && i > 0) {
      included |= i % 10 == 3
      i /= 10
    }
    included
  }
}


import scala.io.StdIn.readLine

object Main {
  def main(args: Array[String]): Unit = {
    readLine
    println(readLine.split(" ").map(_.toInt).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

      解説


import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readInt()
    val list = StdIn.readLine().split(" ")
    println(list.reverse.mkString(" "))
  }
}


object Main {
  def main(args: Array[String]) {
    val num = scala.io.StdIn.readInt()
    println(scala.io.StdIn.readLine().split(" ").toList.reverse.mkString(" "))
  }
}


import scala.io.StdIn.readLine

object Main {
  def main(args: Array[String]) {
    readLine()
    val input = readLine().split(" ").map(_.toInt).sortWith(_ > _).mkString(" ")
    println(input)
  }
}


import scala.io.StdIn.readLine

object Main {

  def main(args: Array[String]) = {
    readLine
    println(readLine.split(" ").reverse.mkString(" "))

  }
}


object Main {
  def main(args: Array[String]): Unit =
    println(io.StdIn.readLine().split(" ").reverse.mkString(" "))
}


import scala.io.StdIn

object Main extends App {

  val n = StdIn.readLine().toInt
  var k = n - 1
  val out = Array.fill(n)("0")
  val buff = StdIn.readLine().split(' ').foreach{ e =>
    out(k) = e
    k -= 1
  }
  println(out.mkString(" "))

}


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]): Unit = {
    val scanner = new java.util.Scanner(System.in)
    val record = List.fill(4)(List.fill(3)(Array.fill(10)(0)))

    val n = scanner.nextInt
    for(_ <- 1 to n) {
      val b, f, r, v = scanner.nextInt
      record(b - 1)(f - 1)(r - 1) = record(b - 1)(f - 1)(r - 1) + v
    }

    for(b <- record) {
      for(f <- b) {
        println(" " + f.mkString(" "))
      }
      println("#" * 20)
    }
  }
}

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 sc = new java.util.Scanner(System.in)
  val n, m = sc.nextInt()
  val matrix = List.fill(n, m)(sc.nextInt())
  val vector = List.fill(m)(sc.nextInt())

  println(matrix.map(multiply(_, vector)).map(_.sum).mkString("\n"))

  def multiply(row: Seq[Int], vector: Seq[Int]): Seq[Int] = row.zip(vector).map(e => e._1 * e._2)
}

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]) {
    def testResultPrint(test: String): Unit ={
      val Array(test1, test2, test3) = test.split(" ").map(_.toInt)
      val testResult = testCheck(test1, test2, test3)
      if(testResult != "end") {
        println(testResult)
        testResultPrint(readLine())
      }
    }

    def testCheck(t1: Int, t2: Int, t3: Int): String = {
      val t12 = t1 + t2
      if(t1 + t2 + t3 == -3) "end"
      else if(t1 == -1 || t2 == -1 || t12 < 30) "F"
      else if(t12 >= 80) "A"
      else if(t12 >= 65) "B"
      else if(t12 >= 50 || (t12 >= 30 && t3 >= 50)) "C"
      else if(t12 >= 30) "D"
      else "end"
    }

    testResultPrint(readLine())
  }
}

Grading

Write a program which reads a list of student test scores and evaluates the performance for each student.

The test scores for a student include scores of the midterm examination m (out of 50), the final examination f (out of 50) and the makeup examination r (out of 100). If the student does not take the examination, the score is indicated by -1.

The final performance of a student is evaluated by the following procedure:

If the student does not take the midterm or final examination, the student's grade shall be F.

If the total score of the midterm and final examination is greater than or equal to 80, the student's grade shall be A.

If the total score of the midterm and final examination is greater than or equal to 65 and less than 80, the student's grade shall be B.

If the total score of the midterm and final examination is greater than or equal to 50 and less than 65, the student's grade shall be C.

If the total score of the midterm and final examination is greater than or equal to 30 and less than 50, the student's grade shall be D. However, if the score of the makeup examination is greater than or equal to 50, the grade shall be C.

If the total score of the midterm and final examination is less than 30, the student's grade shall be F.

Input

The input consists of multiple datasets. For each dataset, three integers m, f and r are given in a line.

The input ends with three -1 for m, f and r respectively. Your program should not process for the terminal symbols.

The number of datasets (the number of students) does not exceed 50.

Output

For each dataset, print the grade (A, B, C, D or F) in a line.

Sample Input

40 42 -1
20 30 -1
0 2 -1
-1 -1 -1

Sample Output

A
C
F


import scala.io.StdIn.readLine

object Main extends App {
  var n:Array[Int] = readLine.split(" ").map(_.toInt)

  while( n(0) != -1 || n(1) != -1 || n(2) != -1 ) {
    val Array(m,f,r) = n
    val score = m+f
    var grade = ""

    if( m == -1 || f == -1)
      grade = "F"
    else if(score >= 80)
      grade = "A"
    else if(score < 80 && score >= 65)
      grade = "B"
    else if(score < 65 && score >= 50)
      grade = "C"
    else if(score < 50 && score >= 30)
      if(r>=50)
          grade = "C"
      else
          grade = "D"
    else
        grade = "F"

    println(grade)

    n = readLine.split(" ").map(_.toInt)
  }
}


/**
  * http://judge.u-aizu.ac.jp/onlinejudge/topic.jsp?cid=ITP1#problems/ITP1_7
  */
object Main {
  def main(args: Array[String]): Unit = {
    Iterator.continually(io.StdIn.readLine()).takeWhile(_ != null).map(_.split(" ").map(_.toInt))
      .map { case Array(m, f, r) => (m, f, r) }
      .takeWhile(_ != (-1, -1, -1))
      .map {
        case (m, f, _) if m == -1 || f == -1 => "F"
        case (m, f, _) if 80 <= (m + f) => "A"
        case (m, f, _) if 65 until 80 contains (m + f) => "B"
        case (m, f, _) if 50 until 65 contains (m + f) => "C"
        case (m, f, r) if 30 until 50 contains (m + f) => if (r >= 50) "C" else "D"
        case (m, f, _) if (m + f) < 30 => "F"
      }
      .foreach(println)
  }
}


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

object Main extends App {

  val result = ListBuffer.empty[String]
  var Array(m, f, r) = Array(0, 0, 0)
  while(m != -1 || f != -1 || r != -1){
    val Array(inm, inf, inr) = StdIn.readLine().split(' ').map(_.toInt)
    m = inm
    f = inf
    r = inr
    val rank = (m, f, r) match {
      case (-1, -1, -1) =>  ""
      case (-1,  y, z) =>  "F"
      case ( x, -1, z) =>  "F"
      case ( x,  y, z) if x + y >= 80 =>  "A"
      case ( x,  y, z) if (65 <= x + y ) && (x + y < 80)  =>  "B"
      case ( x,  y, z) if (50 <= x + y ) && (x + y < 65)  =>  "C"
      case ( x,  y, z) if (30 <= x + y ) && (x + y < 50)  =>  {
        if (50 <= z) "C" else "D"
      }
      case ( x,  y, z) if x + y < 30  =>  "F"
      case _ => ""
    }
    result += rank

  }

  print(result.mkString(f"%n"))
  //result.foreach(println)

}


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
      }
    )
  }
}

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.collection.mutable
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 }

      var count = 0
      for(i <- 1 to in(0); j <- 1 to in(0); k <- 1 to in(0)){
        if(Set(i,j,k).size == 3 && i + j + k == in(1)){
          count += 1
        }
      }
      println(count / 6)
    }
  }
}


object Main{
  def main(args:Array[String]){
    val sc=new java.util.Scanner(System.in)
    val r,c=sc.nextInt
    val a=Array.fill(r,c)(sc.nextInt)
    a.foreach(b=>println(b.mkString(" ")+" "+b.sum))
    var SUM=0
    for(i<-0 until c){
      var sum=0
      for(j<-0 until r){
        sum+=a(j)(i)
        SUM+=a(j)(i)
      }
      print(sum+" ")
    }
    println(SUM)
  }
}

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.Source

object Main extends App {
  val lines = Source.stdin.getLines.map(_.split(" ").map(_.toInt).toList).toList
  val (rows, cols) = (lines(0)(0), lines(0)(1))
  val linesOfNum: List[List[Int]] = lines.tail

  val newLines: List[Int] = for {
                              line <- linesOfNum
                            } yield { val str = line.mkString(" ")
                                println(s"$str ${line.sum}")
                                line.sum
                            }

  // non-tail-recursive
  def addEachElement(ixx: List[List[Int]]): List[Int] = ixx match {
    case Nil => List(0, 0, 0, 0, 0)
    case h :: tail => (h zip addEachElement(tail)).map { case (i, j) => i + j }
  }

  // tail-recursive
  def addEachElement(acc: List[Int], ixx: List[List[Int]]): List[Int] = ixx match {
    case Nil => acc
    case h :: tail => addEachElement((acc zip h).map { case (i, j) => i + j }, tail)
  }

  println(addEachElement(linesOfNum).mkString(" ") + " " + newLines.sum)
  // println(addEachElement(List(0, 0, 0, 0, 0), linesOfNum))
}


object Main{
  def main(args:Array[String]) = {
    io.Source.stdin.mkString.toCharArray.foreach(x => print(swap_case_as_int(x.toInt).toChar))
    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{
  def main(args:Array[String]) = {
    io.Source.stdin.mkString.toCharArray.foreach(x => print(swap_case_as_int(x.toInt).toChar))
  }
  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
  }
}


import scala.io.Source

object Main extends App {
  val line: String = Source.stdin.getLines.toList.head

  def isCapital(c: Char): Boolean = ('A' to 'Z').toList.contains(c)

  val str = line.map { c => if (isCapital(c)) c.toString.toLowerCase else c.toString.capitalize }

  str.map(print)
  println()
}


import io.Source.stdin

/**
  * AOJ
  */
object Main {

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

    for(line <- stdin.getLines()){
      if(line == "0"){return}
      println(line.map(_.toString.toInt).sum)
    }
  }
}

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.io.StdIn

object Main extends App {

  private val alphabets = Array.ofDim[Int](26)
  private val target = StdIn.readLine()

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

}

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


import scala.io.Source

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

      println(if((line(0) + line(0)).contains(line(1))) "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


import scala.io.StdIn._

object Main {
  def mkInputText(i: Iterator[String]): List[String] = {
    (for(j <- i if j != "END_OF_TEXT") yield j.replace("\n", "")).mkString(" ").split(" ").toList
  }

  def main(args: Array[String]) {
    val searchText = readLine()
    val inputTextList = mkInputText(scala.io.Source.stdin.getLines)
    println(inputTextList.count(_ == searchText))
  }
}

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


object Main {
  def main(args: Array[String]): Unit = {
    val scanner = new java.util.Scanner(System.in)
    val w = scanner.next.toLowerCase()
    var c = 0
    while(true) {
      val t = scanner.next
      if(t.equals("END_OF_TEXT")) {
        println(c)
        System.exit(0)
      }
      if(w.equals(t.toLowerCase())) c = c + 1
    }
  }
}


import java.util.Scanner

import scala.collection.Searching._
import scala.annotation.tailrec
import scala.collection.immutable.Queue

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(new Node(None, 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  @tailrec
  private def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) => root(p)
  }
}

object Main {
  def solve(sc: => Scanner): Unit = {
    var S = sc.next
    if (S != "-") {
      Array.fill(sc.nextInt) {
        val n = sc.nextInt
        S = S.substring(n) + S.substring(0, n)
        ()
      }
      println(S)
      solve(sc)
    }
  }

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

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

/**
  * AOJ
  */
object Main {

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

    val p = new Point(0,0)
    val n = StdIn.readInt()
    for(_ <- 1 to n){
      val animals = StdIn.readLine().split(" ")
      if(animals(0) > animals(1)){
        p.taro += 3
      } else if(animals(0) < animals(1)){
        p.hanako += 3
      } else {
        p.taro += 1
        p.hanako += 1
      }
    }
    println(p.taro + " " + p.hanako)
  }
  class Point(var taro:Int,var hanako:Int)
}

Card Game

Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card.
The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner obtains 3 points. In the case of a draw, they obtain 1 point each.

Write a program which reads a sequence of cards Taro and Hanako have and reports the final scores of the game.

Input

In the first line, the number of cards n is given. In the following n lines, the cards for n turns are given respectively. For each line, the first string represents the Taro's card and the second one represents Hanako's card.

Constraints

n ≤ 1000

The length of the string ≤ 100

Output

Print the final scores of Taro and Hanako respectively. Put a single space character between them.

Sample Input

3
cat dog
fish fish
lion tiger

Sample Output

1 7


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

object Main extends App {

  //val a = List.empty[Int]
  val a = ArrayBuffer.empty[Int]

  // 2,147,483,647
  def pushBuck(x: Int) = a.append(x)

  def popBuck() = if(a.nonEmpty) a.remove(a.size - 1)

  def randomAccess(i: Int): Int = a(i)

  val q = StdIn.readLine().trim.toInt
  (0 until q).foreach { i =>
    val input = StdIn.readLine()
    val temp = if (input.startsWith("2")) Array(2, 0) else input.split(' ').map(_.toInt)
    val (cmd, x): (Int, Int) = (temp(0), temp(1))

    cmd match {
      case 0 =>
        pushBuck(x)
      case 1 => println(randomAccess(x))
      case 2 =>
        popBuck()
    }
  }
}

Vector

For a dynamic array $A = \{a_0, a_1, ...\}$ of integers, perform a sequence of the following operations:

pushBack($x$): add element $x$ at the end of $A$

randomAccess($p$):print element $a_p$

popBack(): delete the last element of $A$

$A$ is a 0-origin array and it is empty in the initial state.

Input

The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $x$

or

1 $p$

or

2

where the first digits 0, 1 and 2 represent pushBack, randomAccess and popBack operations respectively.

randomAccess and popBack operations will not be given for an empty array.

Output

For each randomAccess, print $a_p$ in a line.

Constraints

$1 \leq q \leq 200,000$

$0 \leq p < $ the size of $A$

$-1,000,000,000 \leq x \leq 1,000,000,000$

Sample Input 1

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

Sample Output 1

1
2
4


import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn.{readInt, readLine}

object Main extends App {
  val pushBack     = 0
  val randomAccess = 1
  val popBack      = 2

  val n     = readInt()
  val lines = Iterator.fill(n)(readLine())

  val orders = lines.map { _.split(" ").map { _.toInt } }
  var xs     = Vector[Int]()
  orders.foreach {
    case Array(`pushBack`, x)     => xs = xs :+ x
    case Array(`randomAccess`, x) => println(xs(x))
    case Array(`popBack`)         => xs = xs.init
  }
}


import scala.io.StdIn

object Main extends App {

  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(" ")
  val q = StdIn.readLine().toInt

  (0 until q).foreach { i =>
    val qa = StdIn.readLine().split(" ").map(_.toInt)
    val buff = a.slice(qa(0), qa(1)).reverse
    buff.zipWithIndex.foreach{ case (s, index) =>
      a(qa(0) + index) = s
    }
  }
  println(a.mkString(" "))

}

Reverse

Write a program which reads a sequence of integers $A = \{a_0, a_1, ..., a_{n-1}\}$ and reverse specified elements by a list of the following operation:

reverse($b, e$): reverse the order of $a_b, a_{b+1}, ..., a_{e-1}$

Input

The input is given in the following format.

$n$
$a_0 \; a_1 \; ...,\; a_{n-1}$
$q$
$b_1 \; e_1$
$b_2 \; e_2$
:
$b_{q} \; b_{q}$

In the first line, $n$ (the number of elements in $A$) is given. In the second line, $a_i$ (each element in $A$) are given. In the third line, the number of queries $q$ is given and each query is given by two integers $b_i \; e_i$ in the following $q$ lines.

Output

Print all elements of $A$ in a line after performing the given operations. Put a single space character between adjacency elements and a newline at the end of the last element.

Constraints

$1 \leq n \leq 1,000$

$-1,000,000,000 \leq a_i \leq 1,000,000,000$

$1 \leq q \leq 1,000$

$0 \leq b < e \leq n$

Sample Input 1

8
1 2 3 4 5 6 7 8
2
1 6
3 8

Sample Output 1

1 6 5 8 7 2 3 4


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 += num).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 _ = io.StdIn.readInt()
    val an: Iterator[Int] = io.StdIn.readLine().split(" ").map(_.toInt).toIterator
    var acc = an.next()
    while(an.hasNext) acc = lcm(acc, an.next())
    println(acc)
  }
  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 n = io.StdIn.readInt()

  println(phi(n))

  def phi(n: Int): Int =
    if (isPrime(n)) n-1
    else {
      val pfs = primeFactors(n)
      val x = n*pfs.map(1 - 1/_.toDouble).product
      x.toInt
    }
  def primeFactors(n: Int): Seq[Int] = {
    if (n == 1) Seq()
    else if (isPrime(n)) Seq(n)
    else {
      var x = n
      val p = rho(n)
      if (isPrime(p)) {
        while(x % p == 0) x /= p
        p +: primeFactors(x)
      }
      else {
        val ps = primeFactors(p)
        ps foreach (p => while(x % p == 0) x /= p)
        ps ++ primeFactors(x)
      }
    }
  }

  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 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)
    }
  }
}

Euler's Phi Function

For given integer n, count the totatives of n, that is, the positive integers less than or equal to n that are relatively prime to n.

Input

n

An integer n (1 ≤ n ≤ 1000000000).

Output

The number of totatives in a line.

Sample Input 1

6

Sample Output 1

2

Sample Input 2

1000000

Sample Output 2

400000


import scala.io.Source.stdin

object Main {

  def euclid(m:Int, n:Int):(Int, Int) = {
    if(m==0) {
      (0,1)
    } else {
      val (x,y) = euclid(n%m,m)
      if(x*m+y*n == x*n+y*m) {
        if(y-(n/m)*x < x)
          (y-(n/m)*x, x)
        else
          (x, y-(n/m)*x)
      } else {
        (y-(n/m)*x, x)
      }
    }
  }
  def main(args:Array[String]) =
    stdin.getLines.foreach { s=>
      val n = s.split(" ").map(_.toInt)
      val (x,y) = euclid(n(0),n(1))
      println(x+" "+y)
    }
}

Extended Euclid Algorithm

Given positive integers a and b, find the integer solution (x, y) to ax + by = gcd(a, b), where gcd(a, b) is the greatest common divisor of a and b.

Input

a b

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

Output

Print two integers x and y separated by a space. If there are several pairs of such x and y, print that pair for which |x| + |y| is the minimal (primarily) and x ≤ y (secondarily).

Constraints

1 ≤ a, b ≤ 109

Sample Input 1

4 12

Sample Output 1

1 0

Sample Input 2

3 8

Sample Output 2

3 -1


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val s = sc.nextInt()
  val d = Array.fill(s)(sc.nextInt(), sc.nextInt())
  val ret = d.sliding(3).exists{
    l => l(0)._1 == l(0)._2 && l(1)._1 == l(1)._2 && l(2)._1 == l(2)._2
  }
  println(if(ret) "Yes" else "No")
}

Score : 200 points

Problem Statement

Tak performed the following action N times: rolling two dice.
The result of the i-th roll is D_{i,1} and D_{i,2}.

Check if doublets occurred at least three times in a row.
Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.

Constraints

3 \leq N \leq 100

1\leq D_{i,j} \leq 6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
D_{1,1} D_{1,2}
\vdots
D_{N,1} D_{N,2}

Output

Print Yes if doublets occurred at least three times in a row. Print No otherwise.

Sample Input 1

5
1 2
6 6
4 4
3 3
3 2

Sample Output 1

Yes

From the second roll to the fourth roll, three doublets occurred in a row.

Sample Input 2

5
1 1
2 2
3 4
5 5
6 6

Sample Output 2

No

Sample Input 3

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

Sample Output 3

Yes


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

  val answer = (1 to (n-1)).map(i => (n-1) / i).sum;
  println(answer);
}

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.nextLong()
  val x, m = sc.nextInt()

  val a = Array.fill(m)(0L)
  val idx = Array.fill(m)(-1)

  var i = 0
  var now = x.toLong
  while (idx(now.toInt) == -1) {
    idx(now.toInt) = i
    a(i) = now
    now = (now * now) % m
    i += 1
  }

  val s = idx(now.toInt)
  val e = i - 1
  val l = e - s + 1
  val ac = a.scanLeft(0L)(_+_)
  var ans = 0L

  if (n < s) {
    ans += ac(n.toInt)
  } else {
    var r = n
    ans += ac(s)
    r -= s

    ans += (ac(e+1) - ac(s)) * (r / l)
    ans += ac(s + (r % l).toInt) - ac(s)
  }

  println(ans)
}

Score : 500 points

Problem Statement

Let us denote by f(x, m) the remainder of the Euclidean division of x by m.

Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M).
Find \displaystyle{\sum_{i=1}^N A_i}.

Constraints

1 \leq N \leq 10^{10}

0 \leq X < M \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X M

Output

Print \displaystyle{\sum_{i=1}^N A_i}.

Sample Input 1

6 2 1001

Sample Output 1

1369

The sequence A begins 2,4,16,256,471,620,\ldots Therefore, the answer is 2+4+16+256+471+620=1369.

Sample Input 2

1000 2 16

Sample Output 2

6

The sequence A begins 2,4,0,0,\ldots Therefore, the answer is 6.

Sample Input 3

10000000000 10 99959

Sample Output 3

492443256176507


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val x = sc.nextInt()
  println(if (x == 1) 0 else 1)
}

Score : 100 points

Problem Statement

Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

Constraints

0 \leq x \leq 1

x is an integer

Input

Input is given from Standard Input in the following format:

x

Output

Print 1 if x is equal to 0, or 0 if x is equal to 1.

Sample Input 1

1

Sample Output 1

0

Sample Input 2

0

Sample Output 2

1


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 idx = idxa(p).head
      ans(idx) = 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(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(" "))
  }
}

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


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val a, b = List.fill(n)(sc.nextInt()-1)
  val c = Array.fill(n)(0)
  val d = Array.fill(n)(0)
  for (i <- a) {
    c(i) += 1
  }

  for (i <- b) {
    d(i) += 1
  }

  if ((0 until n).exists(i => c(i) + d(i) > n)) {
    println("No")
  } else {
    val cc = c.scanLeft(0)(_+_)
    val cd = d.scanLeft(0)(_+_)
    var m = 0
    for (i <- 1 to n) {
      m = m.max(cc(i) - cd(i-1))
    }
    println("Yes")
    println((b.takeRight(m) ++ b.dropRight(m)).map(_+1).mkString(" "))
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val d, t, s = sc.nextInt()
  println(if (d <= s * t) "Yes" else "No")
}

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N, X, T = sc.nextInt

  val z = (N / X + (if (N % X != 0) 1 else 0)) * T

  println(z)
}

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, x, t = sc.nextInt()
  println(((n + x - 1) / x) * t)
}


import java.util.Scanner

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

  val z = if (N == "0" || N.foldLeft(0L)((z, x) => z + x.toLong) % 9L == 0L) "Yes" else "No"

  println(z)
}

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


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val x :: xs = List.fill(sc.nextInt())(sc.nextInt())
  val (_, sum) = xs.foldLeft((x, 0)) {
    case ((l, acc), r) => (l.max(r), acc + (l - r).max(0))
  }
  println(sum)
}

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.