object Main extends App {
  var a = readLine.split(" ").map(_.toLong)
  var b = readLine.split(" ").map(_.toLong).sorted
  var sum = 0L
  for(i <- 0 until a(0).toInt - 1 if(a(1) >= b(i))) {
      a(1) -= b(i)
      sum = sum + 1
  }
    if(a(1) == b(a(0).toInt - 1)) {
      sum = sum + 1
    }
  print(sum)
}


object Main extends App {
	val Array(h, w) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
	val a = Array.ofDim[Int](h, w)

	for(i<-0 until h){
		a(i) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
	}

	var ans1 = List[(Int, Int, Int, Int)]()
	var list = List[(Int, Int)]()

	for(i<-0 until h){
		if(i%2 == 0){
			for(j<-0 until w){
				list = (i, j) :: list
			}
		}else{
			for(j<-(w-1) to 0 by -1){
				list = (i,j) :: list
			}
		}
	}

	for(i<-0 until (h*w-1)){
		val x = list(i)._1
		val y = list(i)._2

		val s = list(i+1)._1
		val t = list(i+1)._2

		if(a(x)(y)%2 == 1){
			a(x)(y) -= 1
			a(s)(t) += 1
			ans1 = (x,y,s,t) :: ans1
		}
	}

	println(ans1.size)
	for(x <- ans1.reverse){
		myP(x._1, x._2, x._3, x._4)
	}

	def myP(x: Int, y: Int, a: Int, b: Int): Unit = {
		println(Array(x+1,y+1,a+1,b+1).mkString(" "))
	}

}

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

Score : 400 points

Problem Statement

There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).

In Cell (i, j), a_{ij} coins are placed.

You can perform the following operation any number of times:

Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.

Maximize the number of cells containing an even number of coins.

Constraints

All values in input are integers.

1 \leq H, W \leq 500

0 \leq a_{ij} \leq 9

Input

Input is given from Standard Input in the following format:

H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}

Output

Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:

N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'

That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.

In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').

Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.

Sample Input 1

2 3
1 2 3
0 1 1

Sample Output 1

3
2 2 2 3
1 1 1 2
1 3 1 2

Every cell contains an even number of coins after the following sequence of operations:

Move the coin in Cell (2, 2) to Cell (2, 3).

Move the coin in Cell (1, 1) to Cell (1, 2).

Move one of the coins in Cell (1, 3) to Cell (1, 2).

Sample Input 2

3 2
1 0
2 1
1 0

Sample Output 2

3
1 1 1 2
1 2 2 2
3 1 3 2

Sample Input 3

1 5
9 9 9 9 9

Sample Output 3

2
1 1 1 2
1 3 1 4

Submitted source-code file size, in bytes.

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

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


object Main {
  import java.util.Scanner

  def readStrings(n: Int)(implicit sc: Scanner): Array[String] = Array.fill(n) { sc.next() }
  def readInts(n: Int)(implicit sc: Scanner): Array[Int] = Array.fill(n) { sc.nextInt() }
  def readLongs(n: Int)(implicit sc: Scanner): Array[Long] = Array.fill(n) { sc.nextLong() }
  def readLineStrings(implicit sc: Scanner): Array[String] = sc.nextLine().split(' ')
  def readLineInts(implicit sc: Scanner): Array[Int] = readLineStrings.map(_.toInt)
  def readLineLongs(implicit sc: Scanner): Array[Long] = readLineStrings.map(_.toLong)

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

  def solve(implicit sc: Scanner): Unit = {
    def evenResolution(row: Seq[Int]): Seq[Int] = row.scanLeft(0){ (a, carry) => (a + carry) % 2 }.drop(1).dropRight(1)
    def flattenZigzag[A]: Array[Array[A]] => scala.collection.mutable.ArraySeq[A] = { array =>
      val indexedArray = array.zipWithIndex
      val grouped = indexedArray.groupBy(_._2 % 2).mapValues(_.map(_._1))
      grouped(0).zip(grouped(1)).flatMap { case (ev, odd) => ev ++ odd }
    }

    val Array(h, w) = readLineInts
    val a = Array.fill(h)(readLineInts)
    val indexedCells = {
      a.zipWithIndex.map { case (row, rowIndex) =>
        row.zipWithIndex.map { case (cell, columnIndex) => (cell, (rowIndex, columnIndex)) }
      }
    }
    val zigzag = flattenZigzag(indexedCells)
    val moveFlags = evenResolution(zigzag.map(_._1))
    val moves: Seq[(Int, Int, Int, Int)] = {
      for((moveFlag, index) <- moveFlags.zipWithIndex;
          (y1, x1) <- Some(zigzag(index)._2) if moveFlag == 1;
          (y2, x2) <- Some(zigzag(index + 1)._2)) yield (y1, x1, y2, x2)
    }
    println(moves.length)
    for ((a, b, c, d) <- moves) println(s"$a $b $c $d")
  }

}


object Main {
  import java.util.Scanner

  def readStrings(n: Int)(implicit sc: Scanner): Array[String] = Array.fill(n) { sc.next() }
  def readInts(n: Int)(implicit sc: Scanner): Array[Int] = Array.fill(n) { sc.nextInt() }
  def readLongs(n: Int)(implicit sc: Scanner): Array[Long] = Array.fill(n) { sc.nextLong() }
  def readLineStrings(implicit sc: Scanner): Array[String] = sc.nextLine().split(' ')
  def readLineInts(implicit sc: Scanner): Array[Int] = readLineStrings.map(_.toInt)
  def readLineLongs(implicit sc: Scanner): Array[Long] = readLineStrings.map(_.toLong)

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

  def solve(implicit sc: Scanner): Unit = {
    def adjustRow(row: Seq[Int]): Seq[Int] = row.scanLeft(0){ (a, carry) => (a + carry) % 2 }.drop(1).dropRight(1)

    val Array(h, w) = readLineInts
    val a = Array.fill(h)(readLineInts)
    val b = a.map(row => row.map(aij => if (aij == 0) aij else if (aij % 2 == 0) 2 else 1))
    println(b(0).toList)
    val moveResults: Seq[(Seq[Int], Int)] = b.map { row =>
      val moves = adjustRow(row)
      (moves, row.last + moves.lastOption.getOrElse(0))
    }
    val rowMoves = moveResults.map(_._1)
    val column = moveResults.map(_._2)
    val columnMoves = adjustRow(column)

    val rowWiseMoves = {
      for((rowMove, rowIndex) <- rowMoves.zipWithIndex;
          (moveFlag, columnIndex) <- rowMove.zipWithIndex;
          move <- Some((rowIndex + 1, columnIndex + 1, rowIndex + 1, columnIndex + 2)) if moveFlag == 1) yield move
    }
    val columnWiseMoves = {
      for ((moveFlag, rowIndex) <- columnMoves.zipWithIndex;
            move <- Some((rowIndex + 1, w, rowIndex + 2, w)) if moveFlag == 1) yield move
    }
    val moves = rowWiseMoves ++ columnWiseMoves

    println(moves.length)
    for ((a, b, c, d) <- moves) println(s"$a $b $c $d")
  }
}


// A - Pair
// https://abc108.contest.atcoder.jp/tasks/abc108_a

import scala.io.StdIn.readLine

object Main extends App {

  val k = readLine.toInt

  val odd = k / 2
  val even = (k + 1) / 2

  val c = odd * even

  println(c)

}

Score : 100 points

Problem Statement

Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter.

Constraints

2\leq K\leq 100

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive).

Sample Input 1

3

Sample Output 1

2

Two pairs can be chosen: (2,1) and (2,3).

Sample Input 2

6

Sample Output 2

9

Sample Input 3

11

Sample Output 3

30

Sample Input 4

50

Sample Output 4

625


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    val Array(h, w) = sc.nextLine.split(" ").map(_.toInt)
    val table = List.fill(h)(sc.nextLine.toList).map(_.toList)
    table.filter(_.contains('#')).transpose.filter(_.contains('#')).transpose.map(_.mkString).foreach(println(_))
  }

}

Score : 200 points

Problem Statement

There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black.

Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:

Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.

It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

Constraints

1 \leq H, W \leq 100

a_{i, j} is . or #.

There is at least one black square in the whole grid.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}...a_{1, W}
:
a_{H, 1}...a_{H, W}

Output

Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

Sample Input 1

4 4
##.#
....
##.#
.#.#

Sample Output 1

###
###
.##

The second row and the third column in the original grid will be removed.

Sample Input 2

3 3
#..
.#.
..#

Sample Output 2

#..
.#.
..#

As there is no row or column that consists only of white squares, no operation will be performed.

Sample Input 3

4 5
.....
.....
..#..
.....

Sample Output 3

#

Sample Input 4

7 6
......
....#.
.#....
..#...
..#...
......
.#..#.

Sample Output 4

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


import scala.io.StdIn._
import scala.math._

/**
 * ABC107B
 */
object Main extends App {

  val Seq(h, w) = readLine().split(" ").toSeq.map(_.toInt)
  val blob: Seq[String] = (0 until h).map(_ => readLine()).toIndexedSeq

  val calcNewRow = (b: String) => {
    (0 until w)
      .filter(colNum => blob.map(_(colNum).toString).contains("#"))
      .map(v => b(v))
      .mkString("")
  }

  val ans = blob.filter(v => v.contains("#"))
    .map(calcNewRow(_))

  ans.foreach(println)

}


import scala.io.StdIn

object Main extends App {
  StdIn.readLine

  Iterator.continually(StdIn.readLine)
    .takeWhile(_ != null)
    .filter(_.contains('#'))
    .map(_.toCharArray)
    .toArray
    .transpose
    .filter(_.contains('#'))
    .transpose
    .toArray
    .foreach(ch => println(ch.mkString))
}


object Main extends App{
println((1 to scala.io.StdIn.readInt by 2 filter { k =>
  (1 to k filter(k % _ == 0)).size == 8
}).size)}

Score: 200 points

Problem Statement

The number 105 is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?

Constraints

N is an integer between 1 and 200 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between 1 and 105, the only number that is odd and has exactly eight divisors is 105.

Sample Input 2

7

Sample Output 2

0

1 has one divisor. 3, 5 and 7 are all prime and have two divisors. Thus, there is no number that satisfies the condition.


object Main extends App {
  val str = io.StdIn.readLine()
  val index = io.StdIn.readInt

  val mrInfinity = new MrInfinity
  println(mrInfinity.superBrain(str, index))
}

class MrInfinity {
  /**
    * 500兆回処理を繰り返してできた文字列の、左からindex番目の値を返却する。
    * @str 捜査対象の文字列(1~9の数値で構成されている)
    * @index 検査位置
    * @return 左からindex番目にある値（0からでなく、1から開始）
    */
  def superBrain(str: String, index: Long): Char = {
    // 与えられた条件から、実際に5000兆回処理する必要はない。
    // indexより左に1しかない場合には何回処理をしても1になることが明確なので1を返却する。
    // 1以外の数値の場合、2の5000兆乗が優にindexの条件である10^18を越えるため、
    // 一番最初に出てきた数字でindexまでが埋め尽くされることになる。
    // ex) "21"の場合、2が2の5000兆乗個/1が1個となり、indexの最大値である10^18番目は2となる。
    //
    // 従って、以下の条件で返却値を決める。
    //   indexまでに1しかない場合 -> 1を返却
    //   1以外の値がある場合 -> 一番左にある1以外の値

    if (index == 1 || str.length == 1) str.head
    else {
      str.head match {
        case '1' => superBrain(str.tail, index - 1)
        case _   => str.head
      }
    }
  }

}

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

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

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


import scala.io.StdIn._
object Main extends App{
  val sc = new java.util.Scanner(System.in)
  val n,k = sc.nextInt
  if(n%k==0){
    print(0)
  }
  else{
    print(1)
  }
}

Score : 100 points

Problem Statement

Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is 1.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


object Main extends App {
  io.StdIn.readLine().split(' ').map(_.toInt).toList match {
    case n :: k :: Nil => println(if (n % k == 0) 0 else 1)
  }
}


import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine.toInt
  val ans = if ((n % 7) == 0 || (n % 4) == 0) "Yes"
    else if ((1 until n by 7).exists(i => (n - i) % 4 == 0)) "Yes"
    else "No"
  println(ans)
}

Score : 200 points

Problem Statement

La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each.
Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

If there is a way to buy some cakes and some doughnuts for exactly N dollars, print Yes; otherwise, print No.

Sample Input 1

11

Sample Output 1

Yes

If you buy one cake and one doughnut, the total will be 4 + 7 = 11 dollars.

Sample Input 2

40

Sample Output 2

Yes

If you buy ten cakes, the total will be 4 \times 10 = 40 dollars.

Sample Input 3

3

Sample Output 3

No

The prices of cakes (4 dollars) and doughnuts (7 dollars) are both higher than 3 dollars, so there is no such way.


import scala.io.StdIn

object Main {
	def main(args: Array[String]): Unit ={
		val N = StdIn.readLine.toInt

		val result = (0 to N/7 ).exists{ n =>
			(N - 7 * n ) % 4 == 0
		}
		println( if (result) "Yes" else "No")
	}
}


import java.util.Scanner

import scala.collection.mutable

object Main {
  def main(args: Array[String]): Unit = println(solve(new Scanner(System.in)))

  def solve(in: String): String = solve(new Scanner(in))

  def solve(sc: Scanner): String = {
    val N = sc.nextInt
    val M = sc.nextInt
    val A = Array.fill(N)(sc.nextInt)

    val checked = mutable.Set[Int](N)
    var ans = 0L
    for (l <- 0 until N if !checked(l)) {
      var sum = 0
      var r = 0
      for (i <- l until N) {
        if (sum == 0) {
          checked += i
        }
        sum += A(i)
        if (sum % M == 0) {
          r += 1
          ans += r
          sum = 0
        }
      }
    }
    ans.toString
  }
}

Score : 400 points

Problem Statement

There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies.

You will take out the candies from some consecutive boxes and distribute them evenly to M children.

Such being the case, find the number of the pairs (l, r) that satisfy the following:

l and r are both integers and satisfy 1 \leq l \leq r \leq N.

A_l + A_{l+1} + ... + A_r is a multiple of M.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

2 \leq M \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the number of the pairs (l, r) that satisfy the conditions.

Note that the number may not fit into a 32-bit integer type.

Sample Input 1

3 2
4 1 5

Sample Output 1

3

The sum A_l + A_{l+1} + ... + A_r for each pair (l, r) is as follows:

Sum for (1, 1): 4

Sum for (1, 2): 5

Sum for (1, 3): 10

Sum for (2, 2): 1

Sum for (2, 3): 6

Sum for (3, 3): 5

Among these, three are multiples of 2.

Sample Input 2

13 17
29 7 5 7 9 51 7 13 8 55 42 9 81

Sample Output 2

6

Sample Input 3

10 400000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

25


import scala.io.{StdIn => in}

object Main extends App {
  val r = in.readInt

  val ans = r match {
    case r if r < 1200 => "ABC"
    case r if r < 2000 => "ARC"
    case _ => "AGC"
  }
  println(ans)
}

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}

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

  val D, G = in.next().toInt
  val p = new Array[Int](D+1)
  val c = new Array[Int](D+1)

  for(i <- 1 to D) {
    val a, b = in.next().toInt
    p(i) = a; c(i) = b / 100
  }

  //
  val MAX = 100000
  val IM = Int.MaxValue
  val dp = Array.fill[Int](MAX+1)(IM)
  dp(0) = 0
  for(k <- 1 to D) {
    val np = p(k); val nc = c(k)

    for(i <- (1 to MAX).reverse) {
      for (j <- 1 until np) {
        val now = i - (k * j)
        if(now >= 0)
          if(dp(now) != IM) {
            dp(i) = dp(i) min (dp(now) + j)
          }
      }

      val clear = i - (k * np) - nc
      if(clear >= 0)
        if(dp(clear) != IM) {
          dp(i) = dp(i) min (dp(clear) + np)
        }
    }
  }

  var ans = IM
  for (i <- G/100 to MAX)
    ans = ans min dp(i)
  println(ans)
}

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


import scala.io.StdIn

object Main extends App {
  val s = StdIn.readLine.split(" ")

  val res = s.filter(_.charAt(0) == 'A')
    .filter(l => l.count(_.isUpper) == 2)
    .map(_.toCharArray)
    .map(_.drop(2).init)
    .exists(l => l.count(ch => ch == 'C') == 1)

  println(if (res) "AC" else "WA")
}

Score : 200 points

Problem Statement

You are given a string S. Each character of S is uppercase or lowercase English letter.
Determine if S satisfies all of the following conditions:

The initial character of S is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

4 ≤ |S| ≤ 10 (|S| is the length of the string S.)

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


//import java.util.Scanner

import scala.collection.Searching._
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.immutable._
import scala.io.StdIn.readLine

import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

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(Files.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 = 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 = current.hasNext

  @inline def next() = 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() = 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)(new Node(None, 1))

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

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

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

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

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

  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 S = sc.next()
    println(if (
      S.filter(c => c == 'C').size == 1
        && S.filter(c => c == 'A').size == 1
        && S.indexOf('A') == 0
        && 2 <= S.indexOf('C')
        && S.indexOf('C') < S.size - 1
        && S.filter(c => c.isLower).size + 2 == S.size
    ) ("AC") else ("WA"))
  }

  def recursive(A: Array[Array[Long]], pq: mutable.PriorityQueue[(Long, Int)], used: Set[Int]): Long = {
    if (pq.length == 0) (0) else {
      val now = pq.dequeue()
      (if (used.contains(now._2)) (0) else {
        for (i <- 0 until A(now._2).size) {
          if (A(now._2)(i) != -1) (pq.enqueue((A(now._2)(i), i)))
        }
        now._1
      }) + recursive(A, pq, used + now._2)
    }
  }

  def recursive2(N: Long): String = {
    if (N == 0) ("") else (('a'.toInt + (N % 26)).toChar + recursive2(N / 26))
  }

  def check(A: Array[List[Int]]): Boolean = {
    A.map(_.size == 0).fold(true)((a, b) => a & b)
  }

  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 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) == None)
    }
    }) => {

      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 {
	val s = scala.io.StdIn.readLine.toList.toArray
	val size = s.size

	val A = Array('a', 'B', 'c', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')

	if(s(0) == 'A'){
		var flag = false
		var cnt  = 0

		if(A.contains(s(1))) flag = true

		for(i<-2 to size-2){
			if(s(i) == 'C') cnt += 1
			if(A.contains(s(i))) flag = true
		}

		if(flag) println("WA")
		else if(cnt == 1) println("AC")
		else println("WA")
	}else{
		println("WA")
	}
}


object Main extends App {
  case class Problem(n: Int, ratio: Long, bonus: Long) {
    val completeScore = n * ratio + bonus
  }
  case class Result(score: Long, count: Int)

  val in = new java.util.Scanner(System.in)
  val D = in.nextInt
  val G = in.nextLong / 100

  val Ps = Array.tabulate(D){i => Problem(in.nextInt, i + 1, in.nextLong / 100)}
  val comps: IndexedSeq[Result] = (0 until (1 << D)).map {mask =>
    (0 to D).foldLeft(Result(0L, 0)) {case (r, i) =>
      if (((1 << i) & mask) == 0) r else Result(r.score + Ps(i).completeScore, r.count + Ps(i).n)
    }
  }

  def getAll(i: Int): Seq[Int] = {
    val targetComps: Seq[Result] = (0 until (1 << D)).flatMap {mask =>
      if (((1 << i) & mask) != 0) None else Some(comps(mask))
    }

    val p = Ps(i)
    val halfways: Seq[Result] = (0 to p.n).map {n =>
      if (n == p.n) Result(p.completeScore, n) else Result(n * p.ratio, n)
    }

    for {
      c <- targetComps
      h <- halfways
      if (c.score + h.score >= G)
    } yield c.count + h.count
  }

  println((0 until D).flatMap(getAll).min)
}

Score : 300 points

Problem Statement

A programming competition site AtCode provides algorithmic problems.
Each problem is allocated a score based on its difficulty.
Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points.
These p_1 + … + p_D problems are all of the problems available on AtCode.

A user of AtCode has a value called total score.
The total score of a user is the sum of the following two elements:

Base score: the sum of the scores of all problems solved by the user.

Perfect bonuses: when a user solves all problems with a score of 100i points, he/she earns the perfect bonus of c_i points, aside from the base score (1 ≤ i ≤ D).

Takahashi, who is the new user of AtCode, has not solved any problem.
His objective is to have a total score of G or more points.
At least how many problems does he need to solve for this objective?

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

It is possible to have a total score of G or more points.

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

Print the minimum number of problems that needs to be solved in order to have a total score of G or more points. Note that this objective is always achievable (see Constraints).

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

In this case, there are three problems each with 100 points and five problems each with 200 points. The perfect bonus for solving all the 100-point problems is 500 points, and the perfect bonus for solving all the 200-point problems is 800 points. Takahashi's objective is to have a total score of 700 points or more.

One way to achieve this objective is to solve four 200-point problems and earn a base score of 800 points. However, if we solve three 100-point problems, we can earn the perfect bonus of 500 points in addition to the base score of 300 points, for a total score of 800 points, and we can achieve the objective with fewer problems.

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

This case is similar to Sample Input 1, but the Takahashi's objective this time is 2000 points or more. In this case, we inevitably need to solve all five 200-point problems, and by solving two 100-point problems additionally we have the total score of 2000 points.

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

This case is again similar to Sample Input 1, but the Takahashi's objective this time is 400 points or more. In this case, we only need to solve two 200-point problems to achieve the objective.

Sample Input 4

5 25000
20 1000
40 1000
50 1000
30 1000
1 1000

Sample Output 4

66

There is only one 500-point problem, but the perfect bonus can be earned even in such a case.


import scala.math.ceil

object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val d, g = sc.nextInt
    val table : List[List[Int]] = List.fill(d, 2)(sc.nextInt)

    val is = 0 until d

    var n = 0
    var gLeft = g
    var psLeft= is.map(table(_)(0))
    val cs = is.map(table(_)(1))
    while(gLeft > 0) {
      val isSufficient = is.filter(i => gLeft.toFloat / 100 / (i + 1) <= psLeft(i))
      if(isSufficient.nonEmpty) {
        n = n + ceil(gLeft.toFloat / 100 / (isSufficient.max + 1)).toInt
        gLeft = 0
      } else {
        val iMax = is.maxBy(i =>
          ((i + 1) * 100 * psLeft(i) + cs(i)).toFloat / psLeft(i)
        )
        n = n + psLeft(iMax)
        gLeft = gLeft - (iMax + 1) * psLeft(iMax) * 100 + cs(iMax)
        psLeft = psLeft.updated(iMax, 0)
      }
    }
    println(n)
  }
}


import scala.io.StdIn._
import scala.math._
object Main extends App{
  val sc = new java.util.Scanner(System.in)
  val a,b,c = sc.nextInt
  if(a<b){
    if(c<a){//cab
      print(abs(c-a)+abs(a-b))
    }
    else{
      if(b<c){//abc
        print(abs(a-b)+abs(b-c))
      }
      else{//acb
        print(abs(a-c)+abs(c-b))
      }
    }
  }
  else{
    if(c<b){//cba
      print(abs(c-b)+abs(b-a))
    }
    else{
      if(a<c){//bac
        print(abs(b-a)+abs(a-c))
      }
      else{//bca
        print(abs(b-c)+abs(c-a))
      }
    }
  }
}

Score : 100 points

Problem Statement

You have three tasks, all of which need to be completed.

First, you can complete any one task at cost 0.

Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.

Here, |x| denotes the absolute value of x.

Find the minimum total cost required to complete all the task.

Constraints

All values in input are integers.

1 \leq A_1, A_2, A_3 \leq 100

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

Print the minimum total cost required to complete all the task.

Sample Input 1

1 6 3

Sample Output 1

5

When the tasks are completed in the following order, the total cost will be 5, which is the minimum:

Complete the first task at cost 0.

Complete the third task at cost 2.

Complete the second task at cost 3.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0


import scala.io.StdIn.readLine

object Main extends App {
  val s = readLine()
  val t = readLine()

  def rotate(str: String): String = {
    str.last + str.init
  }

  def verify(in: String): String = {
    if (in == t)
      "Yes"
    else
      if (in == s)
        "No"
      else
        verify(rotate(in))
  }

  val result = if (s == t)
    "Yes"
  else
    verify(rotate(s))

  println(result)
}

Score : 200 points

Problem Statement

You are given string S and T consisting of lowercase English letters.

Determine if S equals T after rotation.

That is, determine if S equals T after the following operation is performed some number of times:

Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.

Here, |X| denotes the length of the string X.

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S equals T after rotation, print Yes; if it does not, print No.

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


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.nextLong())

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

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

    val LCM = A.reduce((a, b) => lcm(a, b)) - 1L
    val r = A.foldLeft(0L)((b, n) => b + LCM % n)
    println(r)
  }

}

Score : 300 points

Problem Statement

You are given N positive integers a_1, a_2, ..., a_N.

For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).

Here, X\ mod\ Y denotes the remainder of the division of X by Y.

Find the maximum value of f.

Constraints

All values in input are integers.

2 \leq N \leq 3000

2 \leq a_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum value of f.

Sample Input 1

3
3 4 6

Sample Output 1

10

f(11) = (11\ mod\ 3) + (11\ mod\ 4) + (11\ mod\ 6) = 10 is the maximum value of f.

Sample Input 2

5
7 46 11 20 11

Sample Output 2

90

Sample Input 3

7
994 518 941 851 647 2 581

Sample Output 3

4527


object Main extends App {
  val Array(n, m) = io.StdIn.readLine().split(' ').map(_.toInt)
  val against = (for(_ <- 0 until m) yield
    io.StdIn.readLine().split(' ').map(_.toInt) match {
      case Array(a, b) => (a-1, b-1)
    }).sortWith{case (x, y) => x._2 < y._2}

  var end = 0
  var count = 0
  for ((a,b) <- against) {
    if (end <= a) {
      end = b
      count += 1
    }
  }

  println(count)
}

Score : 400 points

Problem Statement

There are N islands lining up from west to east, connected by N-1 bridges.

The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.

One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:

Request i: A dispute took place between the a_i-th island from the west and the b_i-th island from the west. Please make traveling between these islands with bridges impossible.

You decided to remove some bridges to meet all these M requests.

Find the minimum number of bridges that must be removed.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq a_i < b_i \leq N

All pairs (a_i, b_i) are distinct.

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

Print the minimum number of bridges that must be removed.

Sample Input 1

5 2
1 4
2 5

Sample Output 1

1

The requests can be met by removing the bridge connecting the second and third islands from the west.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

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

Sample Output 3

4


object Scanner {
  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}

object Main extends App {
  def func(routes:Array[Array[Int]]):Int = {
    if (routes.isEmpty){
      0
    } else {
      val removeBridge = routes.flatten.distinct.map(r=>{
        (r,routes.count(rr=>rr.contains(r)))
      }).maxBy(_._2)._1
      func(routes.filter(!_.contains(removeBridge)))+1
    }
  }

  val n = Scanner.nextInt()
  val m = Scanner.nextInt()
  val ab = Array.fill(m,2)(Scanner.nextInt())
  val routes = ab.map(abi=>{
    (abi(0) until abi(1)).toArray
  })
  println(func(routes))
}


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

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

  val n, m, s, t = in.next().toInt

  val graphA = Array.fill[List[(Int, Int)]](n+1)(Nil)
  val graphB = Array.fill[List[(Int, Int)]](n+1)(Nil)

  for(_ <- 1 to m) {
    val u, v, a, b = in.next().toInt
    graphA(u) = (v, a) :: graphA(u)
    graphA(v) = (u, a) :: graphA(v)
    graphB(u) = (v, b) :: graphB(u)
    graphB(v) = (u, b) :: graphB(v)
  }

  // fro から to への最短距離(v は頂点数)
  def dijkstra(from: Int, to: Int, v: Int, edge: Array[List[(Int, Int)]]): Array[Long] = {
    val MAX = Long.MaxValue

    val dist = Array.fill(v+1)(MAX)   // fro からの距離を格納する
    val check = new Array[Boolean](v+1)  // すでにその頂点からを調べたかのフラグ

    dist(from) = 0

    val pq = new PriorityQueue[(Long, Int)]  // (-cost, node) queue
    pq.enqueue((-0, from))

    // 頂点は v 個あるので、v 周する
    for(_ <- 0 until v) {
      // 調べ済みでない頂点のうち、最も近い頂点を now に入れる
      var nowNode = -1       // このターンにフォーカスするノード

      breakable {
        while(true) {
          nowNode = pq.dequeue._2  // 最小コストから貪欲に取っていく
          if(!check(nowNode)){  // まだチェックされていないノードだったら決定
            check(nowNode) = true
            break
          }
        }
      }

      // その頂点からたどり着ける頂点の情報を更新する
      for((nextNode, cost) <- edge(nowNode)) {
        val nextDist = dist(nowNode) + cost
        if(nextDist < dist(nextNode)){  // 既存の通路より近いなら更新
          dist(nextNode) = nextDist
          pq.enqueue((-nextDist, nextNode))
        }
      }
    }

    dist
  }

  val init = 1e15.toLong

  val dpA = dijkstra(s, t, n, graphA)
  val dpB = dijkstra(t, s, n, graphB)

  val ans = new Array[Long](n+1)
  ans(n) = 0L

  for(i <- (0 until n).reverse) {
    val now = init - (dpA(i+1) + dpB(i+1))
    ans(i) = now max ans(i+1)
  }

  for(i <- 0 until n) {
    pw.println(ans(i))
  }
  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 : 400 points

Problem Statement

Kenkoooo is planning a trip in Republic of Snuke.
In this country, there are n cities and m trains running.
The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally.
Any city can be reached from any city by changing trains.

Two currencies are used in the country: yen and snuuk.
Any train fare can be paid by both yen and snuuk.
The fare of the i-th train is a_i yen if paid in yen, and b_i snuuk if paid in snuuk.

In a city with a money exchange office, you can change 1 yen into 1 snuuk.
However, when you do a money exchange, you have to change all your yen into snuuk.
That is, if Kenkoooo does a money exchange when he has X yen, he will then have X snuuk.
Currently, there is a money exchange office in every city, but the office in City i will shut down in i years and can never be used in and after that year.

Kenkoooo is planning to depart City s with 10^{15} yen in his pocket and head for City t, and change his yen into snuuk in some city while traveling.
It is acceptable to do the exchange in City s or City t.

Kenkoooo would like to have as much snuuk as possible when he reaches City t by making the optimal choices for the route to travel and the city to do the exchange.
For each i=0,...,n-1, find the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i years.
You can assume that the trip finishes within the year.

Constraints

2 \leq n \leq 10^5

1 \leq m \leq 10^5

1 \leq s,t \leq n

s \neq t

1 \leq u_i < v_i \leq n

1 \leq a_i,b_i \leq 10^9

If i\neq j, then u_i \neq u_j or v_i \neq v_j.

Any city can be reached from any city by changing trains.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m s t
u_1 v_1 a_1 b_1
:
u_m v_m a_m b_m

Output

Print n lines.
In the i-th line, print the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i-1 years.

Sample Input 1

4 3 2 3
1 4 1 100
1 2 1 10
1 3 20 1

Sample Output 1

999999999999998
999999999999989
999999999999979
999999999999897

After 0 years, it is optimal to do the exchange in City 1.

After 1 years, it is optimal to do the exchange in City 2.

Note that City 1 can still be visited even after the exchange office is closed.
Also note that, if it was allowed to keep 1 yen when do the exchange in City 2 and change the remaining yen into snuuk, we could reach City 3 with 999999999999998 snuuk, but this is NOT allowed.

After 2 years, it is optimal to do the exchange in City 3.

After 3 years, it is optimal to do the exchange in City 4.
Note that the same train can be used multiple times.

Sample Input 2

8 12 3 8
2 8 685087149 857180777
6 7 298270585 209942236
2 4 346080035 234079976
2 5 131857300 22507157
4 8 30723332 173476334
2 6 480845267 448565596
1 4 181424400 548830121
4 5 57429995 195056405
7 8 160277628 479932440
1 6 475692952 203530153
3 5 336869679 160714712
2 7 389775999 199123879

Sample Output 2

999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994


object Main extends App {
  val in = readLine.toInt
  println(if(in % 2 == 0) in else in * 2)
}

Score : 100 points

Problem Statement

You are given a positive integer N.
Find the minimum positive integer divisible by both 2 and N.

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum positive integer divisible by both 2 and N.

Sample Input 1

3

Sample Output 1

6

6 is divisible by both 2 and 3.
Also, there is no positive integer less than 6 that is divisible by both 2 and 3.
Thus, the answer is 6.

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998


import scala.io.{StdIn => in}
import scala.collection.{mutable => mu}

object Main extends App {
  val n = in.readInt
  val a = in.readLine.split(" ").map(_.toInt)

  val c = (0 until n).map { i =>
    a(i) - (i+1)
   }.sorted
  val b = c(n/2)

  val ans = a./:(0L, 1L){  (elm, ai) =>
    val (acc, idx) = elm
    (acc + (ai - (b + idx)).abs, idx + 1L)
  }._1

  println(ans)
}

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

He will freely choose an integer b.
Here, he will get sad if A_i and b+i are far from each other.
More specifically, the sadness of Snuke is calculated as follows:

abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))

Here, abs(x) is a function that returns the absolute value of x.

Find the minimum possible sadness of Snuke.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

If we choose b=0, the sadness of Snuke would be abs(2-(0+1))+abs(2-(0+2))+abs(3-(0+3))+abs(5-(0+4))+abs(5-(0+5))=2.
Any choice of b does not make the sadness of Snuke less than 2, so the answer is 2.

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


object Main extends App {
	val n = scala.io.StdIn.readInt
	var a = scala.io.StdIn.readLine.split(" ").map(_.toLong)

	for(i<-0 until n){
		a(i) -= i.toLong + 1L
	}

//	println(a.mkString(" "))

	a = a.sorted

	var ans = 0L

	val t = n/2

	if(n%2 == 1){
		val b = a(t)

		for(x<-a){
			ans += math.abs(x - b)
		}
		println(ans)

	}else{
		val b1 = a(t)
		val b2 = a(t-1)

		var ans1 = 0L

		for(x<-a){
			ans += math.abs(x - b1)
			ans1 += math.abs(x - b2)
		}
		println(math.min(ans, ans1))
	}
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}

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

  val N = in.next().toInt
  val A = new Array[Int](1 << N)
  for (i <- 0 to (1 << N) - 1)
    A(i) = in.next().toInt

  //
  val dp = Array.fill[(Int, Int)](1 << N)((-1, -1))
  dp(0) = (0, 0)
  dp(1) = (0, 1)
  var ans = A(0) + A(1)
  println(ans)

  import scala.collection.mutable.PriorityQueue

  for (i <- 2 to (1 << N) - 1) {
    val pq = new PriorityQueue[(Int, Int)]
    pq.enqueue(A(i) -> i)

    for (k <- 0 to N) {
      val hoge = i & 1 << k
      if(hoge != 0) {
        val now = i ^ hoge
        val (a, b) = dp(now)
        pq.enqueue(A(a) -> a)
        pq.enqueue(A(b) -> b)
      }
    }

    var lst: List[Int] = Nil
    while(lst.length < 2) {
      val (_, ind) = pq.dequeue
      if(!lst.contains(ind))
        lst = ind :: lst
    }

    dp(i) = (lst(0), lst(1))
    ans = Math.max(ans, lst.map(ind => A(ind)).sum)
    println(ans)
  }
}

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 : 700 points

Problem Statement

There is an integer sequence of length 2^N: A_0, A_1, ..., A_{2^N-1}. (Note that the sequence is 0-indexed.)

For every integer K satisfying 1 \leq K \leq 2^N-1, solve the following problem:

Let i and j be integers. Find the maximum value of A_i + A_j where 0 \leq i < j \leq 2^N-1 and (i or j) \leq K.
Here, or denotes the bitwise OR.

Constraints

1 \leq N \leq 18

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 ... A_{2^N-1}

Output

Print 2^N-1 lines.
In the i-th line, print the answer of the problem above for K=i.

Sample Input 1

2
1 2 3 1

Sample Output 1

3
4
5

For K=1, the only possible pair of i and j is (i,j)=(0,1), so the answer is A_0+A_1=1+2=3.

For K=2, the possible pairs of i and j are (i,j)=(0,1),(0,2).
When (i,j)=(0,2), A_i+A_j=1+3=4. This is the maximum value, so the answer is 4.

For K=3, the possible pairs of i and j are (i,j)=(0,1),(0,2),(0,3),(1,2),(1,3),(2,3) .
When (i,j)=(1,2), A_i+A_j=2+3=5. This is the maximum value, so the answer is 5.

Sample Input 2

3
10 71 84 33 6 47 23 25

Sample Output 2

81
94
155
155
155
155
155

Sample Input 3

4
75 26 45 72 81 47 97 97 2 2 25 82 84 17 56 32

Sample Output 3

101
120
147
156
156
178
194
194
194
194
194
194
194
194
194


object Main extends App {
  import scala.io.StdIn.readLine

  val s=readLine
  var ans=0
  for(c <- s)if(c=='+')ans+=1 else ans-=1
  println(s"${ans}")
}

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is + or -. When he eats +, the integer in his mind increases by 1; when he eats -, the integer in his mind decreases by 1.

The symbols Takahashi is going to eat are given to you as a string S. The i-th character in S is the i-th symbol for him to eat.

Find the integer in Takahashi's mind after he eats all the symbols.

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

Print the integer in Takahashi's mind after he eats all the symbols.

Sample Input 1

+-++

Sample Output 1

2

Initially, the integer in Takahashi's mind is 0.

The first integer for him to eat is +. After eating it, the integer in his mind becomes 1.

The second integer to eat is -. After eating it, the integer in his mind becomes 0.

The third integer to eat is +. After eating it, the integer in his mind becomes 1.

The fourth integer to eat is +. After eating it, the integer in his mind becomes 2.

Thus, the integer in Takahashi's mind after he eats all the symbols is 2.

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


object Main extends App {
  import scala.io.StdIn

  val input = StdIn.readLine()
  val sum   = input.split("").map(_.toInt).sum
  if (input.toInt / sum == 0) {
    println("Yes")
  } else {
    println("No")
  }
}

Score : 200 points

Problem Statement

Let S(n) denote the sum of the digits in the decimal notation of n.
For example, S(101) = 1 + 0 + 1 = 2.

Given an integer N, determine if S(N) divides N.

Constraints

1 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

If S(N) divides N, print Yes; if it does not, print No.

Sample Input 1

12

Sample Output 1

Yes

In this input, N=12.
As S(12) = 1 + 2 = 3, S(N) divides N.

Sample Input 2

101

Sample Output 2

No

As S(101) = 1 + 0 + 1 = 2, S(N) does not divide N.

Sample Input 3

999999999

Sample Output 3

Yes


object Main {
  def main(args: Array[String]): Unit = {
    val num  = scala.io.StdIn.readInt
    val nums = num.toString.split("")
    var snum = 0

    nums.foreach({ i =>
      snum += i.toInt
    })

    if(num%snum == 0) println("Yes")
    else              println("No")
  }
}


import java.util.Scanner

import scala.collection.Searching._
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.immutable._
import scala.io.StdIn.readLine

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {
  def solve(sc: => Scanner): Unit = {
    val N = sc.nextLong
    println(if (N % recursive(N) == 0) ("Yes") else ("No"))
  }

  def recursive(N: Long): Long = {
    if (N == 0) (0) else (recursive(N / 10) + N % 10)
  }

  def recursive2(N: Long): String = {
    if (N == 0) ("") else (('a'.toInt + (N % 26)).toChar + recursive2(N / 26))
  }

  def check(A: Array[List[Int]]): Boolean = {
    A.map(_.size == 0).fold(true)((a, b) => a & b)
  }

  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 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) == None)
    }
    }) => {

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


import java.util.Scanner

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

  val (n, k) = (sc.nextInt, sc.nextInt)
  val li = (1 to n).map(_ => sc.nextInt)

  println(1 + (n - 2) / (k - 1))
}

Score : 300 points

Problem Statement

There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.

On this sequence, Snuke can perform the following operation:

Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

2 \leq K \leq N \leq 100000

A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.

In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


object Main extends App {
  val E869120, square1001 = io.StdIn.readLine().split(" ")
  println(if(E869120.toString.toInt <= 8 && square1001.toString.toInt <= 8) "Yay!" else ":(")
}

Score: 100 points

Problem Statement

E869120's and square1001's 16-th birthday is coming soon.

Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.

E869120 and square1001 were just about to eat A and B of those pieces, respectively,

when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".

Can both of them obey the instruction in the note and take desired numbers of pieces of cake?

Constraints

A and B are integers between 1 and 16 (inclusive).

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print Yay!; otherwise, print :(.

Sample Input 1

5 4

Sample Output 1

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 2

8 8

Sample Output 2

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 3

11 4

Sample Output 3

:(

In this case, there is no way for them to take desired number of pieces, unfortunately.


object Main {
  def main(args: Array[String]): Unit = {
    val piece_of_cakes = scala.io.StdIn.readLine.split(" ")
    if(piece_of_cakes(0).toInt <= 8 && piece_of_cakes(1).toInt <= 8) println("Yay!")
    else                                                             println(":(")
  }
}


import java.util.Scanner

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n  = sc.nextInt()
    val a=List.fill(n)(sc.nextInt())
    println(a.map(x=>f(x)).sum)
  }

  def f(n:Int):Int={
    if (n%2!=0){
      0
    }else{
      1+f(n/2)
    }
  }
}

Score: 300 points

Problem Statement

As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.

Snuke, an employee, would like to play with this sequence.

Specifically, he would like to repeat the following operation as many times as possible:

For every i satisfying 1 \leq i \leq N, perform one of the following: "divide a_i by 2" and "multiply a_i by 3".
Here, choosing "multiply a_i by 3" for every i is not allowed, and the value of a_i after the operation must be an integer.

At most how many operations can be performed?

Constraints

N is an integer between 1 and 10 \ 000 (inclusive).

a_i is an integer between 1 and 1 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

The sequence is initially {5, 2, 4}. Three operations can be performed as follows:

First, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {15, 6, 2}.

Next, multiply a_1 by 3, divide a_2 by 2 and multiply a_3 by 3. The sequence is now {45, 3, 6}.

Finally, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {135, 9, 3}.

Sample Input 2

4
631 577 243 199

Sample Output 2

0

No operation can be performed since all the elements are odd. Thus, the answer is 0.

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39


object Main extends App {
  def abs(num:Long) = {
    if (num > 0){
      num
    } else {
      -num
    }
  }
  val sc = new java.util.Scanner(System.in)
  val n,m = sc.nextInt()
  val a = Array.fill(n,3)(sc.nextLong())
  val result = a.combinations(m).map(ai=>{
    val x = abs(ai.map(_(0)).sum)
    val y = abs(ai.map(_(1)).sum)
    val z = abs(ai.map(_(2)).sum)
    x+y+z
  }).max
  println(result)
}

Score: 400 points

Problem Statement

Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.

The shop sells N kinds of cakes.

Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.

These values may be zero or negative.

Ringo has decided to have M pieces of cakes here. He will choose the set of cakes as follows:

Do not have two or more pieces of the same kind of cake.

Under the condition above, choose the set of cakes to maximize (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity).

Find the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Constraints

N is an integer between 1 and 1 \ 000 (inclusive).

M is an integer between 0 and N (inclusive).

x_i, y_i, z_i \ (1 \leq i \leq N) are integers between -10 \ 000 \ 000 \ 000 and 10 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1 z_1
x_2 y_2 z_2
: :
x_N y_N z_N

Output

Print the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Sample Input 1

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

Sample Output 1

56

Consider having the 2-nd, 4-th and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 3 + 9 = 13

Tastiness: 5 + 5 + 7 = 17

Popularity: 9 + 8 + 9 = 26

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 13 + 17 + 26 = 56. This is the maximum value.

Sample Input 2

5 3
1 -2 3
-4 5 -6
7 -8 -9
-10 11 -12
13 -14 15

Sample Output 2

54

Consider having the 1-st, 3-rd and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 7 + 13 = 21

Tastiness: (-2) + (-8) + (-14) = -24

Popularity: 3 + (-9) + 15 = 9

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 21 + 24 + 9 = 54. This is the maximum value.

Sample Input 3

10 5
10 -80 21
23 8 38
-94 28 11
-26 -2 18
-69 72 79
-26 -86 -54
-72 -50 59
21 65 -32
40 -94 87
-62 18 82

Sample Output 3

638

If we have the 3-rd, 4-th, 5-th, 7-th and 10-th kinds of cakes, the total beauty, tastiness and popularity will be -323, 66 and 249, respectively.

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 323 + 66 + 249 = 638. This is the maximum value.

Sample Input 4

3 2
2000000000 -9000000000 4000000000
7000000000 -5000000000 3000000000
6000000000 -1000000000 8000000000

Sample Output 4

30000000000

The values of the beauty, tastiness and popularity of the cakes and the value to be printed may not fit into 32-bit integers.


object Main extends App {
  val n = scala.io.StdIn.readLine.toInt
  if(n >= 1000){
    println("ABD")
  }else{
    println("ABC")
  }
}

Score : 100 points

Problem Statement

Decades have passed since the beginning of AtCoder Beginner Contest.

The contests are labeled as ABC001, ABC002, ... from the first round, but after the 999-th round ABC999, a problem occurred: how the future rounds should be labeled?

In the end, the labels for the rounds from the 1000-th to the 1998-th are decided: ABD001, ABD002, ..., ABD999.

You are given an integer N between 1 and 1998 (inclusive). Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Constraints

1 \leq N \leq 1998

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Sample Input 1

999

Sample Output 1

ABC

The 999-th round of AtCoder Beginner Contest is labeled as ABC999.

Sample Input 2

1000

Sample Output 2

ABD

The 1000-th round of AtCoder Beginner Contest is labeled as ABD001.

Sample Input 3

1481

Sample Output 3

ABD

The 1481-th round of AtCoder Beginner Contest is labeled as ABD482.


import scala.io.StdIn._

object Main extends App {
  val Seq(a, b) = readLine().split(" ").map(_.toInt).toSeq
  println((1 until (b - a)).sum - a)
}

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1


object Main extends App {
  import scala.math._

  val n = readInt
  val dp = Array.fill[Int](n+1)(Int.MaxValue)
  dp(0) = 0

  for (i <- 0 until n) {
    dp(i+1) = min(dp(i+1),dp(i)+1) //1円引き出す
    for (j <- 0 to ((log((n-i).toDouble)/log(6.0)).toInt)) dp(i+pow(6,j).toInt) = min(dp(i+pow(6,j).toInt),dp(i)+1) //6のべき乗円引き出す
    for (j <- 0 to ((log((n-i).toDouble)/log(9.0)).toInt)) dp(i+pow(9,j).toInt) = min(dp(i+pow(9,j).toInt),dp(i)+1) //9のべき乗円引き出す
  }

  println(dp(n))
}

Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16


import scala.io.{StdIn => in}

object Main extends App {
  val Array(n, c) = in.readLine.split(" ").map(_.toInt)
  val dcf = Iterator.continually(in.readLine)
    .take(c).map(_.split(" ").map(_.toInt)).toArray
  val pallet = Iterator.continually(in.readLine)
    .take(n).map(_.split(" ").map(_.toInt - 1)).toArray

  val table = Array.ofDim[Int](3,c)
  for {
    k <- 0 until c
    i <- 0 until n
    j <- 0 until n
  } {
    table((i+j)%3)(k) += dcf(pallet(i)(j))(k)
  }

  // debug(table.mkString(" "))

  def dfsEnum(d:Int, n:Int):Int = {
    // d進 n個列挙
    val enum = Array.ofDim[Int](n)
    var ret = Int.MaxValue

    def evalute():Unit = {
      if(enum.toSet.size == 3) {
        val res =
          enum.map(i => table(i)(enum(i))).sum
        ret = math.min(ret, res)
        // debug(enum.mkString(" "), " ", res)
      }
    }

    def dfs(cnt:Int):Unit = {
      if(cnt == n) evalute
      else {
        for(i <- 0 until c) {
          enum(cnt) = i
          dfs(cnt+1)
        }
      }
    }

    dfs(0)
    ret
  }

  val ans = dfsEnum(c,3)
  println(ans)

  def debug(any:Any*):Unit = {
    if(this.getClass.toString != "class Main$")
      println(any.mkString(" "))
  }
}

Score : 400 points

Problem Statement

There is a grid with N rows and N columns of squares. Let (i,j) be the square at the i-th row from the top and the j-th column from the left.

These squares have to be painted in one of the C colors from Color 1 to Color C. Initially, (i,j) is painted in Color c_{i,j}.

We say the grid is a good grid when the following condition is met for all i,j,x,y satisfying 1 \leq i,j,x,y \leq N:

If (i+j) \% 3=(x+y) \% 3, the color of (i,j) and the color of (x,y) are the same.

If (i+j) \% 3 \neq (x+y) \% 3, the color of (i,j) and the color of (x,y) are different.

Here, X \% Y represents X modulo Y.

We will repaint zero or more squares so that the grid will be a good grid.

For a square, the wrongness when the color of the square is X before repainting and Y after repainting, is D_{X,Y}.

Find the minimum possible sum of the wrongness of all the squares.

Constraints

1 \leq N \leq 500

3 \leq C \leq 30

1 \leq D_{i,j} \leq 1000 (i \neq j),D_{i,j}=0 (i=j)

1 \leq c_{i,j} \leq C

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N C
D_{1,1} ... D_{1,C}
:
D_{C,1} ... D_{C,C}
c_{1,1} ... c_{1,N}
:
c_{N,1} ... c_{N,N}

Output

If the minimum possible sum of the wrongness of all the squares is x, print x.

Sample Input 1

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

Sample Output 1

3

Repaint (1,1) to Color 2. The wrongness of (1,1) becomes D_{1,2}=1.

Repaint (1,2) to Color 3. The wrongness of (1,2) becomes D_{2,3}=1.

Repaint (2,2) to Color 1. The wrongness of (2,2) becomes D_{3,1}=1.

In this case, the sum of the wrongness of all the squares is 3.

Note that D_{i,j} \neq D_{j,i} is possible.

Sample Input 2

4 3
0 12 71
81 0 53
14 92 0
1 1 2 1
2 1 1 2
2 2 1 3
1 1 2 2

Sample Output 2

428


import java.util.Comparator

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

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

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

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

  def solve(): Unit = {
    val N = ni()

    case class Seg(id: Int, l: Int, r: Int) {

      /**
        * @return (距離, 場所)
        */
      def move(p: Int): (Int, Int) = {
        if (l to r contains p) {
          (0, p)
        } else if (abs(p - l) > abs(p - r)) {
          (abs(p - r), r)
        } else {
          (abs(p - l), l)
        }
      }
    }

    def newQueue(f: Seg => Int) = new java.util.PriorityQueue[Seg](N, new Comparator[Seg] {
      override def compare(o1: Seg, o2: Seg): Int = Integer.compare(f(o1), f(o2))
    })

    val MAX = 1e5.toInt
    val S = Array(newQueue(MAX - _.l), newQueue(_.r))

    rep(N) { i =>
      val s = Seg(i, ni(), ni())
      map(2)(i => S(i).add(s))
    }

    var ans = 0L
    var p = 0
    val removed = mutable.Set[Int]()
    def maintain(): Unit = {
      rep(2) { i =>
        var s = S(i).peek()
        while(!S(i).isEmpty && removed.contains(s.id)) {S(i).remove(); s = S(i).peek()}
      }
    }

    rep(N) { _ =>
      maintain()
      val s = map(2)(i => S(i).peek()).maxBy(_.move(p)._1)
      removed += s.id
      val (len, pos) = s.move(p)
      ans += len
      p = pos
    }
    ans += abs(p)

    out.println(ans)
  }

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

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

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

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

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

Score : 700 points

Problem Statement

Takahashi and Aoki will play a game with a number line and some segments.
Takahashi is standing on the number line and he is initially at coordinate 0.
Aoki has N segments. The i-th segment is [L_i,R_i], that is, a segment consisting of points with coordinates between L_i and R_i (inclusive).

The game has N steps. The i-th step proceeds as follows:

First, Aoki chooses a segment that is still not chosen yet from the N segments and tells it to Takahashi.

Then, Takahashi walks along the number line to some point within the segment chosen by Aoki this time.

After N steps are performed, Takahashi will return to coordinate 0 and the game ends.

Let K be the total distance traveled by Takahashi throughout the game. Aoki will choose segments so that K will be as large as possible, and Takahashi walks along the line so that K will be as small as possible. What will be the value of K in the end?

Constraints

1 ≤ N ≤ 10^5

-10^5 ≤ L_i < R_i ≤ 10^5

L_i and R_i are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 R_1
:
L_N R_N

Output

Print the total distance traveled by Takahashi throughout the game when Takahashi and Aoki acts as above.
It is guaranteed that K is always an integer when L_i,R_i are integers.

Sample Input 1

3
-5 1
3 7
-4 -2

Sample Output 1

10

One possible sequence of actions of Takahashi and Aoki is as follows:

Aoki chooses the first segment. Takahashi moves from coordinate 0 to -4, covering a distance of 4.

Aoki chooses the third segment. Takahashi stays at coordinate -4.

Aoki chooses the second segment. Takahashi moves from coordinate -4 to 3, covering a distance of 7.

Takahashi moves from coordinate 3 to 0, covering a distance of 3.

The distance covered by Takahashi here is 14 (because Takahashi didn't move optimally).
It turns out that if both players move optimally, the distance covered by Takahashi will be 10.

Sample Input 2

3
1 2
3 4
5 6

Sample Output 2

12

Sample Input 3

5
-2 0
-2 0
7 8
9 10
-2 -1

Sample Output 3

34


import java.util.Scanner

object Main {
  val sc = new Scanner(System.in)
  def main(args: Array[String]) {
    sc.next
    val s = sc.next
    val n = s.length
    println(1.until(n).map(
      i => s.splitAt(i)
    ).map({
      case (l, r) => l.distinct.count(x => r.contains(x))
    }).max)
  }
}

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.
We will cut this string at one position into two strings X and Y.
Here, we would like to maximize the number of different letters contained in both X and Y.
Find the largest possible number of different letters contained in both X and Y when we cut the string at the optimal position.

Constraints

2 \leq N \leq 100

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the largest possible number of different letters contained in both X and Y.

Sample Input 1

6
aabbca

Sample Output 1

2

If we cut the string between the third and fourth letters into X = aab and Y = bca, the letters contained in both X and Y are a and b.
There will never be three or more different letters contained in both X and Y, so the answer is 2.

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

However we divide S, only a will be contained in both X and Y.

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9


object Main extends App {
  val n = scala.io.StdIn.readLine.toInt
  val s = scala.io.StdIn.readLine
  var arr1 = Array.fill[Int](n)(0)
  var arr2 = Array.fill[Int](n)(0)
  var cnt = n

  arr1(0) = 0

  // 0人目をリーダーに
  cnt = s.takeRight(n - 1).count(_ == 'E')
  arr2(0) = cnt

  (1 until n).foreach { x =>
    if (s.charAt(x - 1) == 'W') {
      arr1(x) = arr1(x - 1) + 1
    } else {
      arr1(x) = arr1(x - 1)
    }

    if (s.charAt(x) == 'E') {
      arr2(x) = arr2(x - 1) - 1
    } else {
      arr2(x) = arr2(x - 1)
    }
    /*
    println("====A")

    println(cnt)
    println(arr1(x))
    println(arr2(x - 1))
    println(arr1(x) + arr2(x - 1) - 1)
    println("====B")
    */
    cnt = List(cnt, arr1(x) + arr2(x)).min
  }

/*
  arr1.foreach(print)
  println()

  arr2.foreach(print)
  println()
  */
  println(cnt)

}

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

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

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = println(solve(new Scanner(System.in)))

  def solve(in: String): String = solve(new Scanner(in))

  def solve(sc: Scanner): String = {
    val N = sc.nextInt
    val S = sc.next

    var n = 0
    val sL = 0 +: S.map {
      case 'W' => n += 1; n
      case 'E' => n
    }
    n = 0
    val sR = 0 +: S.reverse.map {
      case 'E' => n += 1; n
      case 'W' => n
    }
    val ss = for (i <- 0 until N)
      yield sL(i) + sR(N - i - 1)
    ss.min.toString
  }
}


object Main {
  import java.io.PrintStream

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

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

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

  val MOD = 1000000007

  def solve(): Unit = {
    val A, B, C, K = nl()
    val ans = if (K % 2 == 0) A - B else B - A
    println(ans)
  }

  class InputReader(reader: BufferedReader) {
    private var tokenizer: StringTokenizer = _

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

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

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

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

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

Score : 300 points

Problem Statement

Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively.
After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get:

Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own integer with the result.

However, if the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Constraints

1 \leq A,B,C \leq 10^9

0 \leq K \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the integer Takahashi will get minus the integer Nakahashi will get, after repeating the following operation K times.
If the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Sample Input 1

1 2 3 1

Sample Output 1

1

After one operation, Takahashi, Nakahashi and Hikuhashi have 5, 4 and 3, respectively. We should print 5-4=1.

Sample Input 2

2 3 2 0

Sample Output 2

-1

Sample Input 3

1000000000 1000000000 1000000000 1000000000000000000

Sample Output 3

0


import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = println(solve(new Scanner(System.in)))

  def solve(in: String): String = solve(new Scanner(in))

  def solve(sc: Scanner): String = {
    val N = sc.nextInt
    val A = Array.fill(N)(sc.nextInt)
    val B = ArrayBuffer.fill(N)(0)

    var ans = 0
    for (i <- (N - 1) to 0 by -1) {
      if (A(i) > i) {
        return "-1"
      }
      for (j <- 0 until A(i)) {
        val n = A(i) - j
        if (B(i - j) < n) {
          B(i - j) = n
          ans += 1
        } else if (B(i - j) > n) {
          return "-1"
        }

      }
      println(B)
    }
    ans.toString
  }
}

Score : 700 points

Problem Statement

There is a sequence X of length N, where every element is initially 0. Let X_i denote the i-th element of X.

You are given a sequence A of length N. The i-th element of A is A_i. Determine if we can make X equal to A by repeating the operation below. If we can, find the minimum number of operations required.

Choose an integer i such that 1\leq i\leq N-1. Replace the value of X_{i+1} with the value of X_i plus 1.

Constraints

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

0 \leq A_i \leq 10^9(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

If we can make X equal to A by repeating the operation, print the minimum number of operations required. If we cannot, print -1.

Sample Input 1

4
0
1
1
2

Sample Output 1

3

We can make X equal to A as follows:

Choose i=2. X becomes (0,0,1,0).

Choose i=1. X becomes (0,1,1,0).

Choose i=3. X becomes (0,1,1,2).

Sample Input 2

3
1
2
1

Sample Output 2

-1

Sample Input 3

9
0
1
1
0
1
2
2
1
2

Sample Output 3

8


object Main {

  def calc(a: Int, b: Int, c: Int, d: Int): Boolean = {
    math.abs(a - b) <= d && math.abs(b - c) <= d
  }

  def main(args: Array[String]): Unit = {
    val in = io.Source.fromInputStream(System.in).getLines()
    val Array(a, b, c, d) = in.next().split(' ') map (_.toInt)
    if (calc(a, b, c, d)) "Yes" else "No"
  }
}

Score : 100 points

Problem Statement

Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the distance between them is at most d meters.
Determine if A and C can communicate, either directly or indirectly.
Here, A and C can indirectly communicate when A and B can directly communicate and also B and C can directly communicate.

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

If A and C can communicate, print Yes; if they cannot, print No.

Sample Input 1

4 7 9 3

Sample Output 1

Yes

A and B can directly communicate, and also B and C can directly communicate, so we should print Yes.

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes


object Main extends App {
    val x = io.StdIn.readInt

    if (x == 1) println(1)
    else {

        /*
        def exponentiation(base: Int): Int = {
            var tmp = base
            while (tmp < x) tmp *= base

            if (tmp == x) x
            else tmp/base
        }
        */

        def exponentiation(base: Int, acc: Int): Int =
            if (x < acc) acc/base
            else exponentiation(base, acc*base)

        // 1 <= 基数 <= √x
        val result = (2 to math.sqrt(x).toInt).map(exponentiation(_, 1)).max
        println(result)

    }

}

Score : 200 points

Problem Statement

You are given a positive integer X.
Find the largest perfect power that is at most X.
Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.

Constraints

1 ≤ X ≤ 1000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the largest perfect power that is at most X.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most 10: 1, 4, 8 and 9.
We should print the largest among them, 9.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961


import scala.io.{StdIn => in}

object Main extends App {
  val x = in.readInt
  val ans = (1 to math.sqrt(x).toInt + 1)./:(1)( (acc, i) => {
    val y = i * i
    if(y <= x) y else acc
  })
  println(ans)
}


import scala.io.StdIn
object Main extends App {
  val x = StdIn.readLine.toInt
  val r = math.sqrt(x).toInt
  val ans = if( r == 1) x else
    (2 to r).map { i =>
      val e = for {
        j <- (2 to r)
        e = math.pow(i,j).toInt if(e <= x)
      } yield e
      e.last
    }.max
  println(ans)
}


import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)

  val month = sc.nextInt()
  val date = sc.nextInt()
  var counter = 0
  (1 to month).foreach( m =>
    (1 to date).foreach( d =>
      if (m == d) {
        counter = counter +1
      }
    )
  )
  println(counter)
}

Score: 100 points

Problem Statement

In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.

For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.

In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.

How many days from 2018-1-1 through 2018-a-b are Takahashi?

Constraints

a is an integer between 1 and 12 (inclusive).

b is an integer between 1 and 31 (inclusive).

2018-a-b is a valid date in Gregorian calendar.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.

Sample Input 1

5 5

Sample Output 1

5

There are five days that are Takahashi: 1-1, 2-2, 3-3, 4-4 and 5-5.

Sample Input 2

2 1

Sample Output 2

1

There is only one day that is Takahashi: 1-1.

Sample Input 3

11 30

Sample Output 3

11

There are eleven days that are Takahashi: 1-1, 2-2, 3-3, 4-4, 5-5, 6-6, 7-7, 8-8, 9-9, 10-10 and 11-11.


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val A, B, C, X, Y = sc.nextLong()
  val sum = if (A + B < C * 2) {
    A * X + B * Y
  } else {
    val diff = X min Y
    diff * C * 2 +
      (A min (C * 2)) * (X - diff) +
      (B min (C * 2)) * (Y - diff)
  }
  println(sum)
}

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.