//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

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

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

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

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 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)

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

object Main {
  def solve(sc: => Scanner): Unit = {
    val A, B = sc.nextLong()
    val As = recursive(A, 2)
    val Bs = recursive(B, 2)
    println(As.intersect(Bs).size + 1)
  }

  def recursive(now: Long, minV: Long): Set[Long] = {
    if (now <= minV) Set(now) else {
      if (now % minV == 0) recursive(now / minV, minV + 1) + minV else recursive(now, minV + 1)
    }
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def calc(A: Array[Long]): Array[String] = {
    if (A.length == 0) Array.fill(0)("")
    else {
      val last = A.zipWithIndex.map(x => (x._1 - x._2, x._1)).takeWhile(x => x._1 == A.head).last._2
      if (last == A.head) "%d".format(A.head) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
      else "%d-%d".format(A.head, last) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
    }
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

object Util {
  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getPrimeList: Stream[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: Stream[Long]): Stream[Long] =
    Stream.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): Stream[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  val codeTable = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      @scala.annotation.tailrec
      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      @scala.annotation.tailrec
      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


import scala.io.StdIn._

object Main extends App {
  val Array(a, b) = readLine.split(" ").map(_.toLong)

  def gcd(l: Long, r: Long): Long = if (r == 0) l else gcd(r, l % r)

  def div(n: Long, d: Int, cnt: Int): Int = {
    if (n < d * d) {
      cnt + (if (n == 1) 1 else 2)
    } else {
      def divP(l: Long): Long = if (l % d == 0) divP(l / d) else l
      divP(n) match {
        case `n` => div(n, d + 1, cnt)
        case other => div(other, d + 1, cnt + 1)
      }
    }
  }

  println(div(gcd(a, b), 2, 0))
}

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

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

object Main extends App {
  val Array(a, b) = StdIn.readLine().split(" ").map(_.toLong)
  val gcd_v = gcd(a, b)

  println(primeDivSize(gcd_v))

  def isPrime(i: Long) : Boolean = {
    if (i == 2l)
      true
    else
      !(2l to (i-1l)).exists(x => i % x == 0l)
  }

  def primeDivSize(i: Long) : Int = {
    val range :Long = Math.sqrt(i).ceil.toLong
    var target = i
    val ans :scala.collection.mutable.Set[Long] = scala.collection.mutable.Set[Long](1)
    var j = 2
    while (j <= range) {
      if (target % j == 0) {
        ans += j
        target = target / j }
      else j = j + 1
    }

    if (target != 1) ans += target

    ans.size
  }

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


import scala.io.StdIn

object Main extends App {
  val Array(a, b) = StdIn.readLine().split(" ").map(_.toInt)
  var can : Array[Int] = Array.empty

  (1 to a.min(b)).foreach {i =>
    if (a % i == 0 && b % i == 0) can = can :+ i
  }

  println(can.filter(j => isPrime(j)).length)

  def isPrime(i: Int) : Boolean = {
    if (i == 1)
      true
    else if (i == 2)
      true
    else
      !(2 to (i-1)).exists(x => i % x == 0)
  }
}


import scala.io.StdIn._

object Main extends App {
  type Cost = Int
  type Boxes = Int
  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val boxPatterns = 1 << n
  val allKeys: Seq[(Cost, Boxes)] = (1 to m).map { i =>
    val Array(a, b) = readLine.split(" ").map(_.toInt)
    (a, readLine.split(" ").map(_.toInt).foldLeft(0){(z, bb) => z + (1 << (bb - 1))})
  }

  val Impossible = -1
  def dp(keys: List[(Cost, Boxes)], prev: Array[Int]): Int = {
    keys match {
      case Nil => prev(boxPatterns - 1)
      case (cost, boxes) :: ks =>
        val cur = new Array[Int](boxPatterns)
        (0 until boxPatterns).foreach { b =>
          cur(b) =
            if ((b & boxes) == 0) prev(b)
            else {
              (prev(b), prev(b - (b & boxes))) match {
                case (Impossible, Impossible) =>
                  if ((b | boxes) == boxes) cost
                  else Impossible
                case (Impossible, y) => y + cost
                case (x, Impossible) => Math.min(x, cost)
                case (x, y) => Math.min(x, y + cost)
              }
            }
        }
        dp(ks, cur)
    }
  }

  println(dp(allKeys.toList, Array.fill(boxPatterns)(Impossible)))
}

Score : 500 points

Problem Statement

We have N locked treasure boxes, numbered 1 to N.

A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times.

Find the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print -1.

Constraints

All values in input are integers.

1 \leq N \leq 12

1 \leq M \leq 10^3

1 \leq a_i \leq 10^5

1 \leq b_i \leq N

1 \leq c_{i1} < c_{i2} < ... < c_{i{b_i}} \leq N

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
c_{11} c_{12} ... c_{1{b_1}}
:
a_M b_M
c_{M1} c_{M2} ... c_{M{b_M}}

Output

Print the minimum cost required to unlock all the treasure boxes.
If it is impossible to unlock all of them, print -1.

Sample Input 1

2 3
10 1
1
15 1
2
30 2
1 2

Sample Output 1

25

We can unlock all the boxes by purchasing the first and second keys, at the cost of 25 yen, which is the minimum cost required.

Sample Input 2

12 1
100000 1
2

Sample Output 2

-1

We cannot unlock all the boxes.

Sample Input 3

4 6
67786 3
1 3 4
3497 1
2
44908 3
2 3 4
2156 3
2 3 4
26230 1
2
86918 1
3

Sample Output 3

69942


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N, M = in.next().toInt
  val graph = Array.fill[List[Int]](N+1)(Nil)
  for (_ <- 1 to M) {
    val a, b = in.next().toInt
    graph(a) = b :: graph(a)
  }

  def mkAns(now: Int, lst: List[Int]): List[Int] = {
    lst match {
      case a :: rest =>
        if (a == now)
          List(a)
        else
          a :: mkAns(now, rest)
    }
  }

  //
  val done = new Array[Boolean](N+1)
  var ans: List[Int] = Nil
  breakable {
    for (i <- 1 to N) {
      if (!done(i)) {
        done(i) = true

        val q = new Queue[(Int, List[Int])]
        //val dp = new Array[Boolean](N+1)
        //dp(i) = true
        q.enqueue((i, List()))

        breakable {
          while (!q.isEmpty) {
            val (now, alr) = q.dequeue()
            if (!done(now))
              done(now) = true

            if (alr.contains(now)) {
              ans = mkAns(now, alr)
              break
            }
            else {
              for (e <- graph(now))
                q.enqueue((e, now :: alr))
            }
          }
        }
      }

      if (ans != Nil)
        break
    }
  }

  if (ans == Nil)
    pw.println(-1)
  else {
    pw.println(ans.length)
    ans.foreach { x => pw.println(x) }
  }
  pw.flush()
}

class InputReader(stream: InputStream) {
  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

Score : 600 points

Problem Statement

Given is a directed graph G with N vertices and M edges.

The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.

It is guaranteed that the graph contains no self-loops or multiple edges.

Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph.

Here the null graph is not considered as a subgraph.

Notes

For a directed graph G = (V, E), we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G:

V' is a (non-empty) subset of V.

E' is the set of all the edges in E that have both endpoints in V'.

Constraints

1 \leq N \leq 1000

0 \leq M \leq 2000

1 \leq A_i,B_i \leq N

A_i \neq B_i

All pairs (A_i, B_i) are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
:
A_M B_M

Output

If there is no induced subgraph of G that satisfies the condition, print -1.
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:

K
v_1
v_2
:
v_K

This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\}. (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.

Sample Input 1

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

Sample Output 1

3
1
2
4

The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\}. The in-degree and out-degree of every vertex in this graph are both 1.

Sample Input 2

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

Sample Output 2

-1

There is no induced subgraph of G that satisfies the condition.

Sample Input 3

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

Sample Output 3

4
2
3
4
5


object Main {
  def main(args: Array[String]) = {
    val pw = new java.io.PrintWriter(System.out)
    val sc = new java.util.Scanner(System.in)
    val h, w, a, b = sc.nextInt
    sc.close()

    if ((w - a * 2) != (h - b * 2)) {
      pw.println("No")
    } else {
      (0 until h).foreach(hh => {
        (0 until w).foreach(ww => {
          val range = if (b == 0) 1 else hh / b * b
          pw.print(if (ww >= range && ww < range + a) "1" else "0")
        })
        pw.println()
      })
    }

    pw.flush()
  }
}

Score : 300 points

Problem Statement

We have a square grid with H rows and W columns.
Snuke wants to write 0 or 1 in each of the squares.
Here, all of the following conditions have to be satisfied:

For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers are equal, “the smaller” should be read as “either”.)

For every column, the smaller of the following is B: the number of 0s contained in the column, and the number of 1s contained in the column.

Determine if these conditions can be satisfied by writing 0 or 1 in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied.

Constraints

1 \leq H,W \leq 1000

0 \leq A

2 \times A \leq W

0 \leq B

2 \times B \leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W A B

Output

If the conditions cannot be satisfied by writing 0 or 1 in each of the squares, print -1.

If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format:

s_{11}s_{12}\cdots s_{1W}
s_{21}s_{22}\cdots s_{2W}
\vdots
s_{H1}s_{H2}\cdots s_{HW}

Here s_{ij} is the digit written in the square at the i-th row from the top and the j-th column from the left in the grid.

If multiple solutions exist, printing any of them will be accepted.

Sample Input 1

3 3 1 1

Sample Output 1

100
010
001

Every row contains two 0s and one 1, so the first condition is satisfied.
Also, every column contains two 0s and one 1, so the second condition is satisfied.

Sample Input 2

1 5 2 0

Sample Output 2

01010


object Main {
  def main(args: Array[String]) = {
    val pw = new java.io.PrintWriter(System.out)
    val sc = new java.util.Scanner(System.in)
    val h, w, a, b = sc.nextInt
    sc.close()

    if ((w - a * 2) - (h - b * 2) != 0) {
      pw.println("No")
    } else {
      (0 until h).foreach(hh => {
        (0 until w).foreach(ww => {
          val range = if (b == 0) 1 else hh / b * b
          pw.print(if (ww >= range && ww < range + a) "1" else "0")
        })
        pw.println()
      })
    }

    pw.flush()
  }
}


import scala.io.Source

object Main {
  val list = Seq("Sunny", "Cloudy", "Rainy")

  def succ(x: String): String = {
    (list zip (list.tail :+ list.head)).toMap.get(x).get
  }

  def main(args: Array[String]) {
    val s = Source.stdin.getLines.toSeq.head
    println(succ(s))
  }
}

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  private[this] val S = "0" + in.next()

  //
  // a は bに含まれているか
  def contain(a: String, b: String): Boolean = {
    val B = 5570293
    val h = 1e9.toLong

    val al = a.length; val bl = b.length
    if (al > bl)
      return false

    // B の al 乗を計算
    var t = 1L
    for (_ <- 1 to al) {
      t *= B
      t %= h
    }

    // aとbの最初のal文字に関するハッシュ値を計算
    var ah = 0L; var bh = 0L
    for (i <- 0 until al)
      ah = (ah * B + a(i).toLong) % h
    for (i <- 0 until al)
      bh = (bh * B + b(i).toLong) % h

    // bの場所を1つずつ進めながらハッシュ値をチェック
    for (i <- 0 to bl-al) {
      if (ah == bh && a == b.substring(i, i+al))
        return true
      if (i + al < bl) {
        bh *= B
        bh %= h
        bh += b(i+al).toLong - b(i).toLong * t
        if(bh < 0)
          bh += h * 1000
        bh %= h
      }
    }

    false
  }

  private[this] def check(end: Int, begin: Int): Boolean = {
    val a = S.substring(begin, end+1)
    val b = S.substring(end+1, N+1)

    contain(a, b)
  }

  // 条件を満たす最大の値を返す
  private[this] def binarySearch(min: Int, max: Int, begin: Int): Int = {
    val mid: Int = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(max, begin) match{
          case true  => max
          case false => min
        }
      case _ =>
        (check(mid, begin)) match{
          case true  => binarySearch(mid, max, begin)
          case false => binarySearch(min, mid, begin)
        }
    }
  }

  private[this] var ans = 0
  for (i <- 1 to N-1) {
    if (check(i, i)) {
      val tmp = binarySearch(i, i + (N-i) / 2, i) - (i-1)
      ans = Math.max(ans, tmp)
    }
  }
  println(ans)
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


object Main extends App {
  val in = readLine
  val weather = List("Sunny", "Cloudy", "Rainy")
  val idx = weather.indexOf(in) + 1
  println(weather(if(idx < weather.length - 1) idx else 0))
}


import java.util.Scanner

object Main {
  def readable(input: String): Boolean = {
    def readableOdd(str: String) = {
      str match {
        case "" => true
        case _ => List('R', 'U', 'D').contains(str.charAt(0)) && readableEven(str.substring(1))
      }
    }
    def readableEven(str: String): Boolean = {
      str match {
        case "" => true
        case _ => List('L', 'U', 'D').contains(str.charAt(0)) && readableOdd(str.substring(1))
      }
    }
    input match {
      case "" => true
      case _ => readableOdd(input)
    }
  }

  def main(args: Array[String]) = {
    val input = new Scanner(System.in).next()
    if(readable(input)) println("Yes")
    else println("No")
  }
}

Score: 200 points

Problem Statement

Takahashi will do a tap dance. The dance is described by a string S where each character is L, R, U, or D. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.

S is said to be easily playable if and only if it satisfies both of the following conditions:

Every character in an odd position (1-st, 3-rd, 5-th, \ldots) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th, \ldots) is L, U, or D.

Your task is to print Yes if S is easily playable, and No otherwise.

Constraints

S is a string of length between 1 and 100 (inclusive).

Each character of S is L, R, U, or D.

Input

Input is given from Standard Input in the following format:

S

Output

Print Yes if S is easily playable, and No otherwise.

Sample Input 1

RUDLUDR

Sample Output 1

Yes

Every character in an odd position (1-st, 3-rd, 5-th, 7-th) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th) is L, U, or D.

Thus, S is easily playable.

Sample Input 2

DULL

Sample Output 2

No

The 3-rd character is not R, U, nor D, so S is not easily playable.

Sample Input 3

UUUUUUUUUUUUUUU

Sample Output 3

Yes

Sample Input 4

ULURU

Sample Output 4

No

Sample Input 5

RDULULDURURLRDULRLR

Sample Output 5

Yes


object Main extends App {
  val in = readLine.split("").tail
  val evenStr = List("R", "U", "D")
  val oddStr = List("L", "U", "D")
  val odd = (1 to in.length - 1 by 2).map(i => in(i)).forall(s => oddStr.contains(s))
  val even = (0 to in.length - 1 by 2).map(i => in(i)).forall(s => evenStr.contains(s))
  println(if(even && odd) "Yes" else "NO")
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextLong
  val k = sc.nextLong
  val q = sc.nextInt
  val array: Array[Long] = Array.fill(q)(sc.nextLong)

  (1L to n).map(i => (k - q + array.count(winner => winner == i) > 0)).foreach(isRemainig => {
    if(isRemainig){
      println("Yes")
    }else{
      println("No")
    }
  })

}

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

10 13 15
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


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

object Main extends App {
  val Array(n, k, q) = readLine().split(" ").map(_.toInt)
  var scores = Array.fill(n)(k)

  for (_ <- 1 to q) {
    val answer = readInt - 1
    scores = scores.map(e => e - 1)
    scores(answer) += 1
  }

  scores.foreach(e => if (e > 0) println("YES") else println("No"))
}


object Main extends App {
  import scala.io.StdIn._
  val Array(n, k, q) = readLine.trim.split(' ').map(_.toInt)
  val score = Array.fill(n){k - q}
  for (_ ← 0 until q) {
    val winner = readInt()
    score(winner - 1) += 1
  }
  println(score.map{
    case i if i > 0 ⇒ "Yes"
    case _ ⇒ "No"
  }.mkString("\n"))
}


import java.io.{BufferedReader, InputStreamReader}

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val _ = in.readLine().toInt
    val as = in.readLine().split("\\s+").map(_.toInt)
    val bs = in.readLine().split("\\s+").map(_.toInt)
    val cs = in.readLine().split("\\s+").map(_.toInt)

    System.out.println(
      bs.sum + as.zip(as.tail).filter {
        case (a1, a2) => a1 + 1 == a2
      }.map {
        case (a1, _) => cs.apply(a1 - 1)
      }.sum
    )
  }
}

Score : 200 points

Problem Statement

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

A_1, A_2, ..., A_N are all different.

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

First, he ate Dish 3 and gained 4 satisfaction points.

Next, he ate Dish 1 and gained 2 satisfaction points.

Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

Sample Input 2

4
2 3 4 1
13 5 8 24
45 9 15

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


object Main extends App {
  val forecast = scala.io.StdIn.readLine.toList
  val actual = scala.io.StdIn.readLine.toList
  val zipped = forecast zip actual
  val answer = zipped count { z => z._1 == z._2 }
  println(answer)
}

Score : 100 points

Problem Statement

You will be given a string S of length 3 representing the weather forecast for three days in the past.

The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

You will also be given a string T of length 3 representing the actual weather on those three days.

The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

Print the number of days for which the forecast was correct.

Constraints

S and T are strings of length 3 each.

S and T consist of S, C, and R.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the number of days for which the forecast was correct.

Sample Input 1

CSS
CSR

Sample Output 1

2

For the first day, it was forecast to be cloudy, and it was indeed cloudy.

For the second day, it was forecast to be sunny, and it was indeed sunny.

For the third day, it was forecast to be sunny, but it was rainy.

Thus, the forecast was correct for two days in this case.

Sample Input 2

SSR
SSR

Sample Output 2

3

Sample Input 3

RRR
SSS

Sample Output 3

0


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

    var cnt = 0
    for(i <- 0 to 2){
      if(s.charAt(i) == t.charAt(i)) cnt+=1
    }

    println(cnt)
  }
}


import java.util.Scanner

object Main {

  def read(): (Int, Int) = {
    val sc: Scanner = new Scanner(System.in)
    val a, b= sc.nextInt
    sc.close()
    (a, b)
  }

  def solve(a: Int, b: Int): Int = {
    Math.floor(b / a).toInt
  }

  def main(args: Array[String]): Unit = {
    val (a, b) = read()
    println(solve(a, b))
  }

}

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


object Main extends App {
    val input = scala.io.Source.stdin.getLines.toList
    val n = input(0).toInt
    val stairs = input(1).split(" ").map(_.toInt)
    var max = 0
    var current = 0
    for (i <- 0 until n - 1) {
      if (stairs(i) >= stairs(i + 1))
        current = current + 1
      else {
        if (current > max) {
          max = current
        }
        current = 0
      }
    }
    if (current > max)
      max = current

    println(max)
}

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right.

The height of the i-th square from the left is H_i.

You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.

Find the maximum number of times you can move.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the maximum number of times you can move.

Sample Input 1

5
10 4 8 7 3

Sample Output 1

2

By landing on the third square from the left, you can move to the right twice.

Sample Input 2

7
4 4 5 6 6 5 5

Sample Output 2

3

By landing on the fourth square from the left, you can move to the right three times.

Sample Input 3

4
1 2 3 4

Sample Output 3

0


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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val v = new Array[Long](n)
    for (i <- 0 until n) {
      v(i) = sc.nextLong
    }
    var count = 0
    var max = 0
    for (i <- 0 until n - 1) {
      if (v(i) >= v(i + 1)) {
        count += 1
        max = math.max(max, count)
      } else {
        count = 0
      }
    }

    println(max)
  }
}


object Main extends App {
  var n = readLine.toInt
  val in = readLine().split(" ").map(i => i.toInt)
  var a = 0
  while (in(n - 2) >= in(n - 1)) {
    n -= 1
  	a += 1
  }
  println(a)
}


object Main extends App {
  val N = io.StdIn.readInt()
  val numArray = io.StdIn.readLine().split(" ").map(_.toFloat).map(1/_)
  println(1/numArray.sum)
}

Score : 200 points

Problem Statement

Given is a sequence of N integers A_1, \ldots, A_N.

Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Constraints

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10 30

Sample Output 1

7.5

\frac{1}{\frac{1}{10} + \frac{1}{30}} = \frac{1}{\frac{4}{30}} = \frac{30}{4} = 7.5.

Printing 7.50001, 7.49999, and so on will also be accepted.

Sample Input 2

3
200 200 200

Sample Output 2

66.66666666666667

\frac{1}{\frac{1}{200} + \frac{1}{200} + \frac{1}{200}} = \frac{1}{\frac{3}{200}} = \frac{200}{3} = 66.6666....

Printing 6.66666e+1 and so on will also be accepted.

Sample Input 3

1
1000

Sample Output 3

1000

\frac{1}{\frac{1}{1000}} = 1000.

Printing +1000.0 and so on will also be accepted.


object Main {

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

    val N = sc.nextInt()
    val A = Array.fill(N)(sc.nextDouble())

    println(1 / A.map(1 / _).sum)
  }

}


object Main extends App {
    val n = scala.io.StdIn.readInt
    val v = scala.io.StdIn.readLine.split(" ").map(_.toDouble).sorted

    println(v.reduce((e1,e2) => (e1 +e2) / 2.0))
}

Score : 300 points

Problem Statement

You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.

When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where x and y are the values of the ingredients consumed, and you can put this ingredient again in the pot.

After you compose ingredients in this way N-1 times, you will end up with one ingredient. Find the maximum possible value of this ingredient.

Constraints

2 \leq N \leq 50

1 \leq v_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
v_1 v_2 \ldots v_N

Output

Print a decimal number (or an integer) representing the maximum possible value of the last ingredient remaining.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
3 4

Sample Output 1

3.5

If you start with two ingredients, the only choice is to put both of them in the pot. The value of the ingredient resulting from the ingredients of values 3 and 4 is (3 + 4) / 2 = 3.5.

Printing 3.50001, 3.49999, and so on will also be accepted.

Sample Input 2

3
500 300 200

Sample Output 2

375

You start with three ingredients this time, and you can choose what to use in the first composition. There are three possible choices:

Use the ingredients of values 500 and 300 to produce an ingredient of value (500 + 300) / 2 = 400. The next composition will use this ingredient and the ingredient of value 200, resulting in an ingredient of value (400 + 200) / 2 = 300.

Use the ingredients of values 500 and 200 to produce an ingredient of value (500 + 200) / 2 = 350. The next composition will use this ingredient and the ingredient of value 300, resulting in an ingredient of value (350 + 300) / 2 = 325.

Use the ingredients of values 300 and 200 to produce an ingredient of value (300 + 200) / 2 = 250. The next composition will use this ingredient and the ingredient of value 500, resulting in an ingredient of value (250 + 500) / 2 = 375.

Thus, the maximum possible value of the last ingredient remaining is 375.

Printing 375.0 and so on will also be accepted.

Sample Input 3

5
138 138 138 138 138

Sample Output 3

138


import java.util.Scanner

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val itemCount: Int = sc.nextInt
  val items = List.fill(itemCount)(sc.nextInt).map(_.toDouble).sortWith(_.compareTo(_) < 0)
  println(items)
  val ans = items.fold(items(0))((acc, curr) => ( acc + curr ) / 2)
  println(ans)
}


import scala.io.StdIn

object Main {

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

    val n = StdIn.readLine().toInt
    val vs = StdIn.readLine().split(' ').toVector.map(_.toDouble).sorted
    assert(!vs.isEmpty)
    val ans = vs.tail.foldLeft(vs.head)((acc, v) => (acc + v) / 2)
    println(ans)

  }

}


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

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

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

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

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

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val A, B = ni()
    val ans = max(A + B, max(A - B, A * B))
    out.println(ans)
  }
}

Score : 100 points

Problem Statement

We have two integers: A and B.

Print the largest number among A + B, A - B, and A \times B.

Constraints

All values in input are integers.

-100 \leq A,\ B \leq 100

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest number among A + B, A - B, and A \times B.

Sample Input 1

-13 3

Sample Output 1

-10

The largest number among A + B = -10, A - B = -16, and A \times B = -39 is -10.

Sample Input 2

1 -33

Sample Output 2

34

The largest number among A + B = -32, A - B = 34, and A \times B = -33 is 34.

Sample Input 3

13 3

Sample Output 3

39

The largest number among A + B = 16, A - B = 10, and A \times B = 39 is 39.


import scala.io.StdIn.readLine

object Main extends App {
  val Array(k, x) = readLine().split(' ').map(_.toInt)
  val excludeK = k - 1
  println((x - excludeK to x + excludeK).mkString(" "))
}

Score : 200 points

Problem Statement

There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000.

Among them, some K consecutive stones are painted black, and the others are painted white.

Additionally, we know that the stone at coordinate X is painted black.

Print all coordinates that potentially contain a stone painted black, in ascending order.

Constraints

1 \leq K \leq 100

0 \leq X \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K X

Output

Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate 7 is painted black. There are three possible cases:

The three stones painted black are placed at coordinates 5, 6, and 7.

The three stones painted black are placed at coordinates 6, 7, and 8.

The three stones painted black are placed at coordinates 7, 8, and 9.

Thus, five coordinates potentially contain a stone painted black: 5, 6, 7, 8, and 9.

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val k, x = sc.nextInt
  val min = x - k + 1
  val max = x + k - 1
  println((min to max).mkString(" "))
}


object Main{
  def main(args: Array[String]) : Unit = {
val arr1 = io.StdIn.readLine().split(' ')
    val n = arr1(0).toInt
    var mm = scala.collection.mutable.HashMap.empty[String, Long]

    (0 until n).foreach{
      i =>
        val s = io.StdIn.readLine().toString
        val str = s.sorted

        if(mm.contains(str)){
          mm(str) = mm(str) + 1L
        }else{
          mm.update(str, 0L)
        }
    }

    var max: Long = mm.values.map(i => (0L to i).sum).sum

    println(max)
  }
}

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


object Main extends App {
  val n = scala.io.StdIn.readInt()
  var sArray = Vector.empty[String]
  (1 to n).foreach { _ =>
    val readS = scala.io.StdIn.readLine()
    sArray :+= readS.sorted
  }
  val result = sArray.groupBy(s => s).map(s => s._2.size).filter(_ >= 2).map(s => ( (s * (s - 1)) / 2 ).toLong).sum
  println(result)
}


object Main {

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

    val N = sc.nextInt(); sc.nextLine()
    val S = List.fill(N)(sc.nextLine()).map(_.sorted)
    val count =
      scala.collection.mutable.Map[String, Int](
        S.groupBy(identity).mapValues(_.length - 1).toSeq: _*)

    var r = BigInt(0)
    var i = 0
    while (i < N) {
      val c = count(S(i))
      if (c > 0) {
        r += c
        count.update(S(i), c - 1)
      }
      i += 1
    }

    println(r)
  }

}


import scala.io.StdIn._
import scala.collection.mutable.{ArrayBuffer, PriorityQueue}
object Main extends App {
  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val arbeits = Array.fill(m + 1)(new ArrayBuffer[Int]())
  for (i <- 1 to n) {
    val Array(a, b) = readLine.split(" ").map(_.toInt)
    arbeits(a) += b
  }

  def exec(day: Int, possible: PriorityQueue[Int], income: Int): Int = {
    println(s"$day, $possible, $income")
    if (day > m) income
    else {
      val newPossible = possible ++ arbeits(day)
      if (newPossible.isEmpty) {
        exec(day + 1, newPossible, income)
      } else {
        val a = newPossible.dequeue()
        exec(day + 1, newPossible, income + a)
      }
    }
  }

  println(exec(1, PriorityQueue[Int](), 0))
}

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


import scala.collection.mutable.PriorityQueue
case class fuckingJob(days : Int , money : Int)

object Main extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt() //job
  val m = sc.nextInt() //day
  var mwhile = m - 1

  var array = new Array[fuckingJob](n)
  val pq : PriorityQueue[fuckingJob] = PriorityQueue()(Ordering.by(_.money))
  var ans = 0L

  for (i <- 0 until n) {
    val a = sc.nextInt()
    val b = sc.nextInt()
    array(i) = fuckingJob(a,b)
  }

  array.sortBy(_.days)

  for(i <- 0 until array.length)
    pq.enqueue(array(i))

  while(mwhile >= 0 && pq.nonEmpty){
    val wara  = pq.dequeue()
    if(wara.days <= mwhile+1){
      ans += wara.money
      mwhile = mwhile - 1
    }

  }

  println(ans)
}


import scala.io.StdIn
object Main extends App {
  val List(a,b,c) = StdIn.readLine().split(" ").map(_.toInt).toList
  println(if (c >= (a-b)) c - (a-b) else 0)
}

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


import scala.io.StdIn

object Main {

  def main(args: Array[String]): Unit = {
    val Array(a, b, c) = StdIn.readLine().split(' ').map(_.toInt)
    println((c - (a - b)) max 0)
  }

}


object Main {
  def main(args:Array[String]) {
    val S = readLine()
    var ansarr = Array.fill(S.length)(1)

    for(i <- 0 until S.length) {
      if(S(i) == 'R') {
        if(S(i + 1) == 'R') {
          ansarr(i + 2) += ansarr(i)
          ansarr(i) = 0
        }
      }
    }
    for(i <- S.length - 1 to 0 by -1) {
      if(S(i) == 'L') {
        if(S(i - 1) == 'L') {
          ansarr(i - 2) += ansarr(i)
          ansarr(i) = 0
        }
      }
    }
    ansarr.map(a => print(a))
  }
}

Score : 400 points

Problem Statement

Given is a string S consisting of L and R.

Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.

The character written on the leftmost square is always R, and the character written on the rightmost square is always L.

Initially, one child is standing on each square.

Each child will perform the move below 10^{100} times:

Move one square in the direction specified by the character written in the square on which the child is standing. L denotes left, and R denotes right.

Find the number of children standing on each square after the children performed the moves.

Constraints

S is a string of length between 2 and 10^5 (inclusive).

Each character of S is L or R.

The first and last characters of S are R and L, respectively.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of children standing on each square after the children performed the moves, in order from left to right.

Sample Input 1

RRLRL

Sample Output 1

0 1 2 1 1

After each child performed one move, the number of children standing on each square is 0, 2, 1, 1, 1 from left to right.

After each child performed two moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

After each child performed 10^{100} moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

Sample Input 2

RRLLLLRLRRLL

Sample Output 2

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

Sample Input 3

RRRLLRLLRRRLLLLL

Sample Output 3

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


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N, K = in.next().toInt
  val A = new Array[Int](N+1)
  for (i <- 1 to N) {
    A(i) = in.next().toInt
  }

  //
  val S = A.sum
  var B = new Array[Int](N+1)

  var ans = 1L
  var n = 1
  while (n * n <= S) {
    if (S % n == 0) {
      for (i <- 1 to N) {
        B(i) = A(i) % n
      }
      B = B.sorted

      var fu = 0L
      var sei = 0L
      var l = 1
      var r = N
      while (l <= r) {
        if (fu > sei) {
          fu += B(l)
          l += 1
        }
        else {
          sei += n - B(r)
          r -= 1
        }
      }

      if (fu == sei && sei <= K)
        ans = ans max n
    }

    val m = S / n
    if (S % m == 0) {
      for (i <- 1 to N) {
        B(i) = A(i) % m
      }
      B = B.sorted

      var fu = 0L
      var sei = 0L
      var l = 1
      var r = N
      while (l <= r) {
        if (fu < sei) {
          fu += B(l)
          l += 1
        }
        else {
          sei += m - B(r)
          r -= 1
        }
      }

      if (fu == sei && sei <= K)
        ans = ans max m
    }

    n += 1
  }

  println(ans)
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.deep))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

Score : 500 points

Problem Statement

We have a sequence of N integers: A_1, A_2, \cdots, A_N.

You can perform the following operation between 0 and K times (inclusive):

Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element.

Compute the maximum possible positive integer that divides every element of A after the operations. Here a positive integer x divides an integer y if and only if there exists an integer z such that y = xz.

Constraints

2 \leq N \leq 500

1 \leq A_i \leq 10^6

0 \leq K \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_{N-1} A_{N}

Output

Print the maximum possible positive integer that divides every element of A after the operations.

Sample Input 1

2 3
8 20

Sample Output 1

7

7 will divide every element of A if, for example, we perform the following operation:

Choose i = 2, j = 1. A becomes (7, 21).

We cannot reach the situation where 8 or greater integer divides every element of A.

Sample Input 2

2 10
3 5

Sample Output 2

8

Consider performing the following five operations:

Choose i = 2, j = 1. A becomes (2, 6).

Choose i = 2, j = 1. A becomes (1, 7).

Choose i = 2, j = 1. A becomes (0, 8).

Choose i = 2, j = 1. A becomes (-1, 9).

Choose i = 1, j = 2. A becomes (0, 8).

Then, 0 = 8 \times 0 and 8 = 8 \times 1, so 8 divides every element of A. We cannot reach the situation where 9 or greater integer divides every element of A.

Sample Input 3

4 5
10 1 2 22

Sample Output 3

7

Sample Input 4

8 7
1 7 5 6 8 2 6 5

Sample Output 4

5


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

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

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

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

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

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, K = ni()
    val A = na(N)
    val S = A.sum

    def ok(d: Int): Boolean = {
      val P = map(N) { i =>
        val m = A(i) % d
        if (m == 0) 0 else d - m
      }
      sort(P)
      val cumP = cumSum(P)
      val cumM = Array.ofDim[Int](N + 1)
      REP(N) { i =>
        val m = if (P(i) == 0) 0 else d - P(i)
        cumM(i + 1) = cumM(i) + m
      }

      debug(P)
      debug(cumP)
      debug(cumM)

      var k = 1e9.toInt
      REP(N - 1) { i =>
        val plus = cumP(i + 1)
        val minus = cumM(N) - cumM(i + 1)
        debug(s"plus:$plus minus:$minus")
        k = min(k, plus + max(0, minus - plus))
      }

      debug(s"ok($d) k:$k")

      k <= K
    }

    val D = divisors(S)
    var ans = 0
    REP(D.length) { i =>
      val d = D(i)
      if (ok(d)) {
        ans = max(ans, d)
      }
    }

    out.println(ans)
  }

  /**
    * O(√x)
    */
  def divisors(x: Int): Array[Int] = {
    val pre = ArrayBuffer[Int]()
    val post = ArrayBuffer[Int]()
    REP(math.sqrt(x).toInt, 1) { d =>
      if (x % d == 0) {
        pre += d
        if (d * d != x) post += x / d
      }
    }

    val res = Array.ofDim[Int](pre.length + post.length)
    REP(pre.length)(i => res(i) = pre(i))
    val preLen = pre.length
    val postLen = post.length
    REP(postLen)(i => res(i + preLen) = post(postLen - 1 - i))
    res
  }
}


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

  var c = 0
  for(i <- 0 to p.length - 2; if /*p(i) >= p(i + 1)*/p(i) != i + 1) c += 1
//条件が違っていた, p(i) != i で カウントを増やし 2まで許容する
  if(/*c < 2*/c < 3){
    println("YES")
  }else{
    println("NO")
  }
}

Score : 200 points

Problem Statement

We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.

You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.

Print YES if you can sort p in ascending order in this way, and NO otherwise.

Constraints

All values in input are integers.

2 \leq N \leq 50

p is a permutation of {1,\ 2,\ ...,\ N}.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

You can sort p in ascending order by swapping p_1 and p_5.

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

In this case, swapping any two elements does not sort p in ascending order.

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

p is already sorted in ascending order, so no operation is needed.


object Main extends App {
  val n = scala.io.StdIn.readInt()
  val read = scala.io.StdIn.readLine()
  val array =  read.split(" ").map(_.toInt).toVector
  val array_sorted = array.sorted
  var diff = 0
  array.zipWithIndex.foreach { case (j, index) =>
    if(j != array_sorted(index)) {
      diff = diff + 1
    }
  }
  if (diff <= 2) {
    println("YES")
  } else {
    println("NO")
  }
}


import java.util.Scanner

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

    var ans = 0L

    val enemies = new Array[Int](n + 1)
    for (i <- enemies.indices) {
      enemies(i) = sc.nextInt()
    }

    val hero = new Array[Int](n)
    for (i <- hero.indices) {
      hero(i) = sc.nextInt()

    }

    for (i <- hero.indices) {
      if (hero(i) <= enemies(i)) {
        ans += hero(i)
      } else {
        hero(i) -= enemies(i)
        ans += enemies(i) + math.min(enemies(i + 1), hero(i))
      }
    }

    println(ans)
  }

  def printArray[T](arr: Array[T]): Unit = {
    for (i <- arr.indices) {
      print(s"${arr(i)} ")
    }
    println()
  }
}

Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N: Int = sc.nextInt
  val monsters :List[Int] = List.fill(N + 1)(sc.nextInt)
  val savers :List[Int] = List.fill(N)(sc.nextInt)

  def go(monster: Int, monsters: List[Int], savers :List[Int], sum: Int): Int = savers match {
    case Nil => sum
    case h::t if h < monster => go(monsters.head, monsters.tail, t, sum + h)
    case h::t => go(math.max(0, monsters.head - (h - monster)), monsters.tail, t, sum + math.min(h, monster + monsters.head))
  }
  println(go(monsters.head, monsters.tail, savers, 0))
}


object Main extends App {
  val max = (x:Int,y:Int)=>if(x>y)x else y
  val min = (x:Int,y:Int)=>if(x<y)x else y

  val n = readInt
  val as = readLine.split(" ").map(_.toInt)
  val bs = readLine.split(" ").map(_.toInt) :+ 0
  var rest = 0
  var beat = 0
  Range(0,n+1).foreach{i=>
    beat += min(bs(i)+rest, as(i))
    rest = max(bs(i)-max(as(i)-rest, 0), 0)
  }
  println(beat)
}


//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

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

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

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

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 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)

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

object Main {
  def solve(sc: => Scanner): Unit = {
    val N = sc.nextInt()
    val A = Array.fill(N + 1)(sc.nextLong())
    val B = Array.fill(N)(sc.nextLong())
    println(A.tail.zip(B).foldLeft((0L, A.head)) { case (a, b) => {
      val x = Math.max(0, a._2 + b._1 - b._2)
      (Math.max(Math.min(a._2 + b._1, b._2), 0L) + a._1, Math.max(0L, Math.max(b._1, a._2 + b._1 - x)))
    }
    }._1)
  }

  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def calc(A: Array[Long]): Array[String] = {
    if (A.length == 0) Array.fill(0)("")
    else {
      val last = A.zipWithIndex.map(x => (x._1 - x._2, x._1)).takeWhile(x => x._1 == A.head).last._2
      if (last == A.head) "%d".format(A.head) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
      else "%d-%d".format(A.head, last) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
    }
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

  def recursive(N: Long, S: String): Long = {
    if (S.length == 0) {
      if (N % 13 == 5) 1 else 0
    } else {
      S.head match {
        case '?' => (0 to 9).map(i => recursive(N * 10 + i, S.tail)).sum
        case c => recursive(N * 10 + c.toLong, S.tail)
      }
    }
  }

  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  def check(s: String): Boolean = {
    s.isEmpty ||
      s.startsWith("dream") && check(s.drop(5)) ||
      s.startsWith("dreamer") && check(s.drop(7)) ||
      s.startsWith("erase") && check(s.drop(5)) ||
      s.startsWith("eraser") && check(s.drop(6))
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

object Util {
  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getPrimeList: Stream[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: Stream[Long]): Stream[Long] =
    Stream.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): Stream[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  val codeTable = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}


object Main extends App {
  import scala.util.control.Breaks

  val n = io.StdIn.readLine.toInt
  val a = io.StdIn.readLine.split(" ").map(_.toInt)
  val b = io.StdIn.readLine.split(" ").map(_.toInt)

  var s = 0

  for(i <- 0 to n - 1){

    if (a(i) >= b(i) ) {
      s += b(i)
    }
    if (a(i) < b(i)) {
      s += a(i)
      b(i) -= a(i)
      if(a(i+1) < b(i)){
        s += a(i+1)
        a(i+1) = 0
      }else{
        s += b(i)
        a(i+1) -= b(i)
      }
      /*
      if (a(i+1) >= b(i)) {
        s += b(i)
        a(i+1) -=  b(i)
        b(i) += a(i + 1)
      }else{
        s += a(i+1)
        a(i+1) = 0
      }
      */
    }
  }
  println(s)
}


object Main {

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

    val N = sc.nextInt()
    val A = Array.fill(N+1)(sc.nextInt())
    val B = Array.fill(N)(sc.nextInt())

    // 倒せる分だけ倒す
    var i = 0
    var score = 0L
    while (i < N) {
      val at = A(i) min B(i) // aiで倒した数
      B(i) -= at // 倒した数で残り数を更新
      val att = A(i+1) min B(i) // ai+1で倒した数
      A(i+1) -= att
      score += at + att
      i += 1
    }
    println(score)
  }

}


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

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

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

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

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

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val A = na(N + 1)
    val B = na(N)
    var ans = 0L
    REP(N) { i =>
      val l = min(B(i), A(i))
      B(i) -= l
      ans += l
      val r = min(B(i), A(i + 1))
      A(i + 1) -= r
      ans += r
    }

    out.println(ans)
  }
}


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

    val pw = new java.io.PrintWriter(System.out)
    val sc = new java.util.Scanner(System.in)
    val S = sc.nextLong
    sc.close()

    pw.println(s"${S / 2} ${S % 2} 0 2 0 0")

    pw.flush()
  }
}

Score : 400 points

Problem Statement

Given is an integer S.
Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions:

0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9

The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2.

We can prove that there always exist six integers that satisfy the conditions under the constraints of this problem.

Constraints

1 \leq S \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfy the conditions, in this order, with spaces in between.
If multiple solutions exist, any of them will be accepted.

Sample Input 1

3

Sample Output 1

1 0 2 2 0 1

The area of the triangle in a two-dimensional plane whose vertices are (1,0),(2,2), and (0,1) is 3/2.
Printing 3 0 3 1 0 1 or 1 0 0 1 2 2 will also be accepted.

Sample Input 2

100

Sample Output 2

0 0 10 0 0 10

Sample Input 3

311114770564041497

Sample Output 3

314159265 358979323 846264338 327950288 419716939 937510582


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

Score : 100 points

Problem Statement

It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2.

Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r.

Constraints

1 \leq r \leq 100

r is an integer.

Input

Input is given from Standard Input in the following format:

r

Output

Print an integer representing the area of the regular dodecagon.

Sample Input 1

4

Sample Output 1

48

The area of the regular dodecagon is 3 \times 4^2 = 48.

Sample Input 2

15

Sample Output 2

675

Sample Input 3

80

Sample Output 3

19200


object Main extends App {
    println(((t:Int) => 3 * t * t)(readLine.toInt))
}


import scala.math._

object Main extends App {

  val YES = "YES"
  val Yes = "Yes"
  val NO = "NO"
  val No = "No"
  ///////////////////////////////////////////

  val sc = new java.util.Scanner(System.in)
  val r = sc.nextInt
//  val list = List.fill(3)(sc.nextInt)

  val ans = 3 * pow(r, 2)

  println(ans.toInt)

  ///////////////////////////////////////////

  def bigIterator(start: BigInt, end: BigInt, step: BigInt = 1) =
    Iterator.iterate(start)(_ + step).takeWhile(_ <= end)

  def lcm(a :Int, b :Int): Int =
    a / gcd(a, b) * b

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

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

  def gcd(a: Long, b: Long): Long =
    if (b == 0) a else gcd(b, a % b)

  def setOrUpdated[A, B](a: Map[A, B], key: A, value: B, f: (B, B) => B) =
    a.get(key) match {
      case Some(v) => a.updated(key, f(value, v))
      case _ => a + (key -> value)
    }
}


import scala.io.StdIn._
object Main extends App {
  val n = readInt
  val as = Array.fill(n)(readInt)
  val sorted = as.sorted
  val max = sorted(n - 1)
  val second = sorted(n - 2)

  val pw = new java.io.PrintWriter(System.out)
  as.foreach {a => pw.println(if (a == max) second else max)}
  pw.flush()
}

Score : 300 points

Problem Statement

You are given a sequence of length N: A_1, A_2, ..., A_N.
For each integer i between 1 and N (inclusive), answer the following question:

Find the maximum value among the N-1 elements other than A_i in the sequence.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 200000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print N lines. The i-th line (1 \leq i \leq N) should contain the maximum value among the N-1 elements other than A_i in the sequence.

Sample Input 1

3
1
4
3

Sample Output 1

4
3
4

The maximum value among the two elements other than A_1, that is, A_2 = 4 and A_3 = 3, is 4.

The maximum value among the two elements other than A_2, that is, A_1 = 1 and A_3 = 3, is 3.

The maximum value among the two elements other than A_3, that is, A_1 = 1 and A_2 = 4, is 4.

Sample Input 2

2
5
5

Sample Output 2

5
5


object Main extends App {
  val n = scala.io.StdIn.readInt
  val a = Array.tabulate(n)(i => scala.io.StdIn.readInt)
  var b = a.sorted.reverse
  var m0 = b(0)
  var m1 = b(1)
  for(i <- 0 until n) {
    if(a(i) == m0) {
      println(m1)
    } else {
      println(m0)
    }
  }
}


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

    val max2 = A.sorted.takeRight(2)
    A.foreach(d => {
      if (d == max2.last) {
        println(max2.head)
      } else {
        println(max2.last)
      }
    })
  }
}


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

  for (i <- (0 to n - 1)) {
    val tmp = a.splitAt(i)
    println((tmp._1 ++ tmp._2.tail).max)
  }
}


object Main extends App {

  import scala.collection.mutable

  val n = scala.io.StdIn.readLine.toInt
  val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  var data = mutable.TreeSet.empty[Int]

  var cnt = n

  def getOdd(cnt: Int): Boolean = {
    data.count { a => a % cnt == 0 } % 2 == 0
  }

  def getOdd2(cnt: Int): Boolean = {
    var sumcnt = 0
    var now = cnt + cnt
    while (now <= n) {
      if (data(now)) {
        sumcnt += 1
      }

      now += cnt
    }

    sumcnt % 2 == 0
  }

  while (cnt >= 1) {
    val array_cnt = cnt - 1
    // 偶数 or 奇数
    val odd = getOdd2(cnt)

    if (odd && a(array_cnt) == 0) {
      // 偶数 & 求めるのも偶数
      //何もしない
    } else if (odd && a(array_cnt) == 1) {
      // 偶数 & 求めるのは奇数
      data += cnt
    } else if (!odd && a(array_cnt) == 0) {
      // 奇数 & 求めるのは偶数
      data += cnt
    } else if (!odd && a(array_cnt) == 1) {
      // 奇数 & 求めるのは奇数
      // なにもしない
    }
    cnt -= 1
  }

  println(data.size)
  if (data.nonEmpty) {
    println(data.toList.sorted.mkString(" "))
  }
}

Score : 400 points

Problem Statement

There are N empty boxes arranged in a row from left to right.
The integer i is written on the i-th box from the left (1 \leq i \leq N).

For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.

We say a set of choices to put a ball or not in the boxes is good when the following condition is satisfied:

For every integer i between 1 and N (inclusive), the total number of balls contained in the boxes with multiples of i written on them is congruent to a_i modulo 2.

Does there exist a good set of choices? If the answer is yes, find one good set of choices.

Constraints

All values in input are integers.

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

a_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If a good set of choices does not exist, print -1.

If a good set of choices exists, print one such set of choices in the following format:

M
b_1 b_2 ... b_M

where M denotes the number of boxes that will contain a ball, and b_1,\ b_2,\ ...,\ b_M are the integers written on these boxes, in any order.

Sample Input 1

3
1 0 0

Sample Output 1

1
1

Consider putting a ball only in the box with 1 written on it.

There are three boxes with multiples of 1 written on them: the boxes with 1, 2, and 3. The total number of balls contained in these boxes is 1.

There is only one box with a multiple of 2 written on it: the box with 2. The total number of balls contained in these boxes is 0.

There is only one box with a multiple of 3 written on it: the box with 3. The total number of balls contained in these boxes is 0.

Thus, the condition is satisfied, so this set of choices is good.

Sample Input 2

5
0 0 0 0 0

Sample Output 2

0

Putting nothing in the boxes can be a good set of choices.


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

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

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

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

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

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val C = mutable.Map[Int, Int]().withDefaultValue(0)
    REP(N) { _ =>
      val a = ni()
      C(a) += 1
    }

    val ok = (C.size == 1 && C(0) > 0) ||
      (C.size == 2 && C(0) > 0 && {
        val Ca = C.toArray
        val (a, aCnt) = Ca(0)
        val (_, bCnt) = Ca(1)
        if (a == 0) {
          aCnt * 2 == bCnt
        } else {
          aCnt == bCnt * 2
        }
      }) ||
      (C.size == 3 && {
        val Ca = C.toArray
        val (a, aCnt) = Ca(0)
        val (b, bCnt) = Ca(1)
        val (c, cCnt) = Ca(2)
        (a ^ b) == c && aCnt == bCnt && bCnt == cCnt
      })

    if (ok) out.println("Yes")
    else out.println("No")
  }
}

Score : 300 points

Problem Statement

Snuke has N hats. The i-th hat has an integer a_i written on it.

There are N camels standing in a circle.
Snuke will put one of his hats on each of these camels.

If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print Yes; otherwise, print No.

The bitwise XOR of the numbers written on the hats on both adjacent camels is equal to the number on the hat on itself.

What is XOR?

The bitwise XOR x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows:

- When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3 \oplus 5 = 6.

Constraints

All values in input are integers.

3 \leq N \leq 10^{5}

0 \leq a_i \leq 10^{9}

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_{N}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

Yes

If we put the hats with 1, 2, and 3 in this order, clockwise, the condition will be satisfied for every camel, so the answer is Yes.

Sample Input 2

4
1 2 4 8

Sample Output 2

No

There is no such way to distribute the hats; the answer is No.


import scala.io.StdIn._
object Main extends App {
  val Array(n, a, b) = readLine.split(" ").map(_.toInt)
  println(Math.min(n * a, b))
}

Score : 100 points

Problem Statement

N of us are going on a trip, by train or taxi.

The train will cost each of us A yen (the currency of Japan).

The taxi will cost us a total of B yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq A \leq 50

1 \leq B \leq 50

Input

Input is given from Standard Input in the following format:

N A B

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8


object Main {

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

    val N, A, B = sc.nextInt()

    println((A * N) min B)
  }

}


object Main extends App {
  var a = readLine.split(" ").map(_.toInt)
  if(a(0)*a(1)<a(2)) {
    println(a(0)*a(1))
  } else {
    println(a(2))
  }
}


object Main extends App {

  import scala.math._

  val Array(n, d) = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  val x = (1 to n).map { i =>
    scala.io.StdIn.readLine.split(" ").map(_.toInt).toList
  }

  var ans = 0
  (0 until n - 1).foreach { i =>
    (i + 1 until n).foreach { j =>
      val sum = (0 until d).map { k =>
        //println(x(i)(k) + " " + x(j)(k))
        Math.pow(abs(x(i)(k) - x(j)(k)), 2)
      }.sum
    //  println(sum)
      val sq = sqrt(sum).toInt
      if (sq * sq == sum) {
        ans += 1
      }
    }
  }

  println(ans)
}

Score : 200 points

Problem Statement

There are N points in a D-dimensional space.

The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).

The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.

How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?

Constraints

All values in input are integers.

2 \leq N \leq 10

1 \leq D \leq 10

-20 \leq X_{ij} \leq 20

No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.

Input

Input is given from Standard Input in the following format:

N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}

Output

Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

The number of pairs with an integer distance is one, as follows:

The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.

The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.

The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.

Sample Input 2

3 4
-3 7 8 2
-12 1 10 2
-2 8 9 3

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10