object Main{
	def main(args:Array[String]){
		val s = new java.util.Scanner(System.in)
		val n,m = s.nextInt
		val c = Array.fill(100001)(0)
		for(_ <- 1 to n)
			c(s.nextInt) += 1
		val a,b = Array.fill(m)(0)
		for(i <- 1 to 100000) {
			a(i % m) += c(i) % 2
			b(i % m) += c(i) / 2
		}
		//println(a.mkString(" "))
		//println(b.mkString(" "))
		var r = 0
		for(i <- 0 until m) {
			if(i * 2 % m == 0) {
				r += a(i) / 2
				a(i) %= 2
			} else {
				{
					val t = math.min(a(i),a(m - i))
					r += t
					a(i) -= t
					a(m - i) -= t
				}
				{
					val t = math.min(a(i) / 2,b(m - i))
					r += t * 2
					a(i) -= t * 2
					b(m - i) -= t
				}
			}
		}
		for(i <- 0 until m) {
			r += b(i)
			b(i) = 0
		}
		//println(a.mkString(" "))
		//println(b.mkString(" "))
		println(r)
	}
}

Score : 700 points

Problem Statement

Takahashi is playing with N cards.

The i-th card has an integer X_i on it.

Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions:

The integers on the two cards are the same.

The sum of the integers on the two cards is a multiple of M.

Find the maximum number of pairs that can be created.

Note that a card cannot be used in more than one pair.

Constraints

2≦N≦10^5

1≦M≦10^5

1≦X_i≦10^5

Input

The input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_N

Output

Print the maximum number of pairs that can be created.

Sample Input 1

7 5
3 1 4 1 5 9 2

Sample Output 1

3

Three pairs (3,2), (1,4) and (1,9) can be created.

It is possible to create pairs (3,2) and (1,1), but the number of pairs is not maximized with this.

Sample Input 2

15 10
1 5 6 10 11 11 11 20 21 25 25 26 99 99 99

Sample Output 2

6


import io.StdIn.readLine

object Main {

  def main(args: Array[String]): Unit = {
    val Array(n, t) = readLine().split(' ').map(_.toInt)
    val a = readLine().split(' ').map(_.toInt)

    val rew = (1 to (n - 1)).groupBy(i => a.slice(i, n).max - a(i - 1))
    println(rew(rew.keys.max).length)
  }

}

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

Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

The input is given from Standard Input in the following format:

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

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

Sample Output 3

2

Submitted source-code file size, in bytes.

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

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


import java.util.Scanner

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

  val n = sc.nextInt
  val s, t = sc.next
  val ans = (0 until n)
    .map(i => (i, s.substring(i), t.substring(0, n - i)))
    .find(t => t._2 == t._3)
    .map(n + _._1)
    .getOrElse(2 * n)
  println(ans)
}

Score : 200 points

Problem Statement

Snuke is interested in strings that satisfy the following conditions:

The length of the string is at least N.

The first N characters equal to the string s.

The last N characters equal to the string t.

Find the length of the shortest string that satisfies the conditions.

Constraints

1≤N≤100

The lengths of s and t are both N.

s and t consist of lowercase English letters.

Input

The input is given from Standard Input in the following format:

N
s
t

Output

Print the length of the shortest string that satisfies the conditions.

Sample Input 1

3
abc
cde

Sample Output 1

5

The shortest string is abcde.

Sample Input 2

1
a
z

Sample Output 2

2

The shortest string is az.

Sample Input 3

4
expr
expr

Sample Output 3

4

The shortest string is expr.


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

  val n = readInt
  val t = readLine.trim.split(' ').map(_.toInt)
  val a = readLine.trim.split(' ').map(_.toInt)
  var isParadoxical = false
  val confirmed = Array.tabulate(n){_ ⇒ -1}
  confirmed(0) = t.head
  confirmed(n - 1) = a.last
  for (i ← t.indices.tail){
    if (t(i) != t(i - 1)){
      if (confirmed(i) != -1 && confirmed(i) != t(i)) isParadoxical = true
      confirmed(i) = t(i)
    }
  }
  for (i ← a.indices.reverse.tail){
    if (confirmed(i) != -1 && confirmed(i) > a(i)) isParadoxical = true
    if (a(i) != a(i + 1)){
      if (confirmed(i) != -1 && confirmed(i) != a(i)) isParadoxical = true
      confirmed(i) = a(i)
    }
  }
  val mod = 1000000007L
  if (isParadoxical) println(0)
  else {
    var count = 1L
    val mountains = confirmed.indices.filter(i ⇒ confirmed(i) != -1).toArray
    for (i ← mountains.indices.tail){
      count *= expWithMod(math.min(confirmed(mountains(i)), confirmed(mountains(i - 1))), mountains(i) - mountains(i - 1) - 1)
      count %= mod
    }
    println(count)
  }
  def expWithMod(base: Long, exp: Int): Long = {
    exp match {
      case 0 ⇒ 1
      case 1 ⇒ base
      case _ ⇒ expWithMod(base, exp / 2).let(it ⇒ (it * it % mod) * expWithMod(base, exp % 2)) % mod
    }
  }

  implicit class Scope[T](val value: T) extends AnyVal {
    @inline def also(@inline func: T ⇒ Unit): T = {
      func(value)
      value
    }
    @inline def let[A](@inline func: T ⇒ A): A = func(value)
  }
}

Score : 400 points

Problem Statement

Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range.
The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N.
Mr. Takahashi traversed the range from the west and Mr. Aoki from the east.

The height of Mt. i is h_i, but they have forgotten the value of each h_i.
Instead, for each i (1 ≤ i ≤ N), they recorded the maximum height of the mountains climbed up to the time they reached the peak of Mt. i (including Mt. i).
Mr. Takahashi's record is T_i and Mr. Aoki's record is A_i.

We know that the height of each mountain h_i is a positive integer.
Compute the number of the possible sequences of the mountains' heights, modulo 10^9 + 7.

Note that the records may be incorrect and thus there may be no possible sequence of the mountains' heights.
In such a case, output 0.

Constraints

1 ≤ N ≤ 10^5

1 ≤ T_i ≤ 10^9

1 ≤ A_i ≤ 10^9

T_i ≤ T_{i+1} (1 ≤ i ≤ N - 1)

A_i ≥ A_{i+1} (1 ≤ i ≤ N - 1)

Input

The input is given from Standard Input in the following format:

N
T_1 T_2 ... T_N
A_1 A_2 ... A_N

Output

Print the number of possible sequences of the mountains' heights, modulo 10^9 + 7.

Sample Input 1

5
1 3 3 3 3
3 3 2 2 2

Sample Output 1

4

The possible sequences of the mountains' heights are:

1, 3, 2, 2, 2

1, 3, 2, 1, 2

1, 3, 1, 2, 2

1, 3, 1, 1, 2

for a total of four sequences.

Sample Input 2

5
1 1 1 2 2
3 2 1 1 1

Sample Output 2

0

The records are contradictory, since Mr. Takahashi recorded 2 as the highest peak after climbing all the mountains but Mr. Aoki recorded 3.

Sample Input 3

10
1 3776 3776 8848 8848 8848 8848 8848 8848 8848
8848 8848 8848 8848 8848 8848 8848 8848 3776 5

Sample Output 3

884111967

Don't forget to compute the number modulo 10^9 + 7.

Sample Input 4

1
17
17

Sample Output 4

1

Some mountain ranges consist of only one mountain.


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, K = sc.nextLong()
  println(K * math.pow(K - 1, N - 1).toLong)
}

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

The input is given from Standard Input in the following format:

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val Array(n, k) = sc.nextLine.split(" ").map(_.toInt)
    if (n == 1) println(k)
    else println((2 to n).foldLeft(k) {
      (acc, _) => acc * (k - 1)
    })
  }
}


object Main {

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

    val S = sc.nextLine().toCharArray

    // 各プレイヤーは, パーをグーよりも多く出してはいけない
    // 片方の手が全て先にわかっている状態で特点を最大化する
    // つまり, 入力として入ってくる手はそれを満たしている
    // 制約の中でより多く勝てばいい
    // グーかパーしか出せない
    // グーはいつでも出せる
    // 負けとあいこでは, あいこの方がいい
    // あいこでグーの数を稼がないと, パーは出すことができない
    // 途中どこかで負ける方が高いケースがあるか？ ..不明
    // とりあえず貪欲に行く
    // 勝ちに行った場所を負けた場所に補填したとして, 結局 +- 0なので変わらなそう
    def solve(S: Array[Char]): Int = {
      @scala.annotation.tailrec
      def loop(i: Int, g: Int, p: Int, point: Int): Int =
        if (i < S.length) {
          S(i) match {
            case 'g' =>
              if (p < g) loop(i + 1, g, p + 1, point + 1)
              else loop(i + 1, g + 1, p, point)
            case 'p' =>
              if (p < g) loop(i + 1, g, p + 1, point)
              else loop(i + 1, g + 1, p, point - 1)
          }
        } else point
      loop(0, 0, 0, 0)
    }

    println(solve(S))
  }

}

Score : 300 points

Problem Statement

AtCoDeer the deer and his friend TopCoDeer is playing a game.
The game consists of N turns.
In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:

(※) After each turn, (the number of times the player has played Paper)≦(the number of times the player has played Rock).

Each player's score is calculated by (the number of turns where the player wins) - (the number of turns where the player loses), where the outcome of each turn is determined by the rules of Rock-paper-scissors.

(For those who are not familiar with Rock-paper-scissors: If one player plays Rock and the other plays Paper, the latter player will win and the former player will lose. If both players play the same gesture, the round is a tie and neither player will win nor lose.)

With his supernatural power, AtCoDeer was able to foresee the gesture that TopCoDeer will play in each of the N turns, before the game starts.
Plan AtCoDeer's gesture in each turn to maximize AtCoDeer's score.

The gesture that TopCoDeer will play in each turn is given by a string s. If the i-th (1≦i≦N) character in s is g, TopCoDeer will play Rock in the i-th turn. Similarly, if the i-th (1≦i≦N) character of s in p, TopCoDeer will play Paper in the i-th turn.

Constraints

1≦N≦10^5

N=|s|

Each character in s is g or p.

The gestures represented by s satisfy the condition (※).

Input

The input is given from Standard Input in the following format:

s

Output

Print the AtCoDeer's maximum possible score.

Sample Input 1

gpg

Sample Output 1

0

Playing the same gesture as the opponent in each turn results in the score of 0, which is the maximum possible score.

Sample Input 2

ggppgggpgg

Sample Output 2

2

For example, consider playing gestures in the following order: Rock, Paper, Rock, Paper, Rock, Rock, Paper, Paper, Rock, Paper. This strategy earns three victories and suffers one defeat, resulting in the score of 2, which is the maximum possible score.


object Main extends App{
  case class Input(p: Seq[Long], q: Seq[Long])

  def kruskal(p: Seq[Long], q: Seq[Long]): Long = {
    type Node = Option[(Int, Int)]

    case class Edge(n1: Node, n2: Node, cost: Long)
    case class Graph(vs: Set[Node], es: Set[Edge])

    val pn = p.last
    val qn = q.last

    import scala.collection.mutable
    val nodes: Set[Node] =
      (0 until p.size map { i => Option((i, q.size - 1)): Node }).toSet ++
      (0 until p.size map { i => Option((p.size - 1, i)): Node }).toSet +
      None

    val F = mutable.Set[Graph]() ++ (nodes map { n => Graph(Set(n), Set()) })
    val S = mutable.Set[Edge]()
    S ++= p.init.zipWithIndex map {
      case (cost, index) => Edge(Option((index, q.size - 1)), Option((index + 1, q.size - 1)), cost)
    }
    S ++= q.init.zipWithIndex map {
      case (cost, index) => Edge(Option((p.size - 1, index)), Option((p.size - 1, index + 1)), cost)
    }
    S ++= (0 to p.size - 2) map { index => Edge(Option((index, q.size - 1)), None, qn) }
    S ++= (0 to q.size - 2) map { index => Edge(Option((p.size - 1, index)), None, pn) }
    S += Edge(Option((p.size - 1, q.size - 1)), None, Math.min(pn, qn))

    def loop() {
      val edge = S minBy (_.cost)
      S -= edge

      val t1 = F find (_.vs contains edge.n1)
      val t2 = F find (_.vs contains edge.n2)

      (t1, t2) match {
        case (Some(x1), Some(x2)) if x1 != x2 =>
          F -= x1
          F -= x2
          F += Graph((x1.vs ++ x2.vs), x1.es ++ x2.es + edge)
        case _ =>
      }

      if (S.nonEmpty) loop()
    }

    loop()
    (F.toSeq(0).es.toSeq map {_.cost}).sum
  }

  def solve(input: Input): Long = {
    val Input(p, q) = input

    (p.size, q.size) match {
      case (0, _) => q.sum
      case (_, 0) => p.sum
      case _ =>
        val prev = solve(Input(p.init, q.init)) - p.init.sum - q.init.sum
        val b = kruskal(p, q)

        prev + p.sum + q.sum + b
    }
  }

  def parse() = {
    val lines = io.Source.stdin.getLines().toList
    val regex = "(\\d+) (\\d+)".r
    val (w, h) = lines.head match {
      case regex(w, h) => (w.toInt, h.toInt)
    }
    val p = (lines drop 1 take w) map (_.toLong)
    val q = (lines takeRight h) map (_.toLong)

    Input(p, q)
  }

  val input = parse()
  val retval = solve(input)
  println(retval)
}

Score : 500 points

Problem Statement

On an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers.

There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and the difference between the x coordinates is 1.

The cost of paving a road between houses on coordinates (i,j) and (i+1,j) is p_i for any value of j, while the cost of paving a road between houses on coordinates (i,j) and (i,j+1) is q_j for any value of i.

Mr. Takahashi wants to pave some of these roads and be able to travel between any two houses on paved roads only. Find the solution with the minimum total cost.

Constraints

1 ≦ W,H ≦ 10^5

1 ≦ p_i ≦ 10^8(0 ≦ i ≦ W-1)

1 ≦ q_j ≦ 10^8(0 ≦ j ≦ H-1)

p_i (0 ≦ i ≦ W−1) is an integer.

q_j (0 ≦ j ≦ H−1) is an integer.

Input

Inputs are provided from Standard Input in the following form.

W H
p_0
:
p_{W-1}
q_0
:
q_{H-1}

Output

Output an integer representing the minimum total cost.

Sample Input 1

2 2
3
5
2
7

Sample Output 1

29

It is enough to pave the following eight roads.

Road connecting houses at (0,0) and (0,1)

Road connecting houses at (0,1) and (1,1)

Road connecting houses at (0,2) and (1,2)

Road connecting houses at (1,0) and (1,1)

Road connecting houses at (1,0) and (2,0)

Road connecting houses at (1,1) and (1,2)

Road connecting houses at (1,2) and (2,2)

Road connecting houses at (2,0) and (2,1)

Sample Input 2

4 3
2
4
8
1
2
9
3

Sample Output 2

60


import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val str = StdIn.readLine()
    println(str.substring(0, 4) + " " + str.substring(4, 12))
  }
}

Score : 100 points

Problem Statement

This contest is CODE FESTIVAL.
However, Mr. Takahashi always writes it CODEFESTIVAL, omitting the single space between CODE and FESTIVAL.

So he has decided to make a program that puts the single space he omitted.

You are given a string s with 12 letters.
Output the string putting a single space between the first 4 letters and last 8 letters in the string s.

Constraints

s contains exactly 12 letters.

All letters in s are uppercase English letters.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string putting a single space between the first 4 letters and last 8 letters in the string s.
Put a line break at the end.

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE FESTIVAL

Putting a single space between the first 4 letters and last 8 letters in CODEFESTIVAL makes it CODE FESTIVAL.

Sample Input 2

POSTGRADUATE

Sample Output 2

POST GRADUATE

Sample Input 3

ABCDEFGHIJKL

Sample Output 3

ABCD EFGHIJKL


object Main {
  def main(args: Array[String]): Unit = {
    val str = io.StdIn.readLine()
    var k = io.StdIn.readLine().toLong

    val newStr = for (i <- 0 to (str.length - 1)) yield {
      val d = 'z' + 1 - str(i)
      if (d <= k) { k = k - d; 'a' }
      else str(i)
    }

    val lastChar = ((newStr.last + k - 'a') % 26) + 'a'

    val ans = newStr.slice(0, newStr.length - 1).mkString + lastChar.toChar
    println(ans)
  }
}

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    val a: Int = sc.nextLine.toInt
    val b: Int = sc.nextLine.toInt
    val h: Int = sc.nextLine.toInt
    println((a + b) * h / 2)
  }
}

Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

The input is given from Standard Input in the following format:

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val userStrMap = scala.collection.mutable.HashMap(('a', inputs(0)),('b', inputs(1)),('c', inputs(2)))

  println(solve(userStrMap))

  def solve(map: scala.collection.mutable.HashMap[Char, String]): Char = {
    var current = 'a'

    while(map(current).size != 0) {
      val next = map(current).head
      map.update(current, map(current).tail)
      current = next
    }

    current.toUpper
  }
}

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

The input is given from Standard Input in the following format:

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


object Main extends App {
  val sc = new FastScanner(System.in)
  val h, w = sc.nextLong()
  val n = sc.nextInt()
  val ab = List.fill(n)((sc.nextInt(), sc.nextInt()))
  var m = Map[(Int, Int), Int]().withDefaultValue(0)
  for ((a, b) <- ab) {
    for {
      i <- -1 to 1
      j <- -1 to 1
      if 1 < a+i && a+i < h && 1 < b+j && b+j < w
    } {
      m += (a+i, b+j) -> (m((a+i, b+j)) + 1)
    }
  }

  val count = m.values.groupBy(identity).view.mapValues(_.size)
  println((w-2) * (h-2) - count.values.sum)
  for (i <- 1 to 9) {
    println(count.getOrElse(i, 0))
  }
}

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

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

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

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

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

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

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

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

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

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. At first, all cells were painted white.

Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.

Compute the following:

For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the grid contains exactly j black cells, after Snuke painted N cells?

Constraints

3 \leq H \leq 10^9

3 \leq W \leq 10^9

0 \leq N \leq min(10^5,H×W)

1 \leq a_i \leq H (1 \leq i \leq N)

1 \leq b_i \leq W (1 \leq i \leq N)

(a_i, b_i) \neq (a_j, b_j) (i \neq j)

Input

The input is given from Standard Input in the following format:

H W N
a_1 b_1
:
a_N b_N

Output

Print 10 lines.
The (j+1)-th ( 0 \leq j \leq 9 ) line should contain the number of the subrectangles of size 3×3 of the grid that contains exactly j black cells.

Sample Input 1

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

Sample Output 1

0
0
0
2
4
0
0
0
0
0

There are six subrectangles of size 3×3. Two of them contain three black cells each, and the remaining four contain four black cells each.

Sample Input 2

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

Sample Output 2

4
26
22
10
2
0
0
0
0
0

Sample Input 3

1000000000 1000000000 0

Sample Output 3

999999996000000004
0
0
0
0
0
0
0
0
0


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

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

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

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

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

    case class Edge(v: Long, w: Int)

    // 会社に属さないノードは 駅id
    // 会社に属するノードは 会社id * 1e6 + 駅id
    val g: mutable.Map[Long, ArrayBuffer[Edge]] = mutable.Map().withDefaultValue(ArrayBuffer.empty)

    // 方向あるよ
    def joint(from: Long, to: Long, w: Int): Unit = {
      if (!g.contains(from)) g(from) = ArrayBuffer()
      g(from) += Edge(to, w)
    }

    REP(M) { _ =>
      val from, to = ni() - 1
      val c = ni()
      val fromC = from + c * 1e6.toLong
      val toC = to + c * 1e6.toLong

      joint(fromC, toC, 0)
      joint(toC, fromC, 0)
      joint(from, fromC, 1) // 乗るのは1
      joint(fromC, from, 0) // 降りるのは0
      joint(to, toC, 1)
      joint(toC, to, 0)
    }

//    g.toSeq.sortBy(_._1).foreach { case (v, es) =>
//      debug(s"$v ${es.mkString}")
//    }

    val INF = Integer.MAX_VALUE / 2
    def dijk(start: Long, dest: Long): Int = {
      import java.util
      val d = mutable.Map[Long, Int]().withDefaultValue(INF)
      case class Visit(node: Long, cost: Int)
      val queue = new util.ArrayDeque[Visit]()
      d(start) = 0
      queue.add(Visit(start, 0))

      while(!queue.isEmpty) {
        val v = queue.poll()
        if (d(v.node) == v.cost) {
          val es = g(v.node)
          REP(es.length) { i =>
            val e = es(i)
            val next = v.cost + e.w
            if (d(e.v) > next) {
              d(e.v) = next
              if (e.w == 0) queue.addFirst(Visit(e.v, next))
              else queue.addLast(Visit(e.v, next))
            }
          }
        }
      }

//      d.toSeq.sortBy(_._1).foreach { case (v, cost) =>
//          debug(s"$v $cost")
//      }

      d(dest)
    }

    val ans = dijk(0, N - 1)
    if (ans == INF) out.println(-1)
    else out.println(ans)
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

Score : 600 points

Problem Statement

Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.

The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This line is operated by company c_i.

You can change trains at a station where multiple lines are available.

The fare system used in this subway system is a bit strange. When a passenger only uses lines that are operated by the same company, the fare is 1 yen (the currency of Japan). Whenever a passenger changes to a line that is operated by a different company from the current line, the passenger is charged an additional fare of 1 yen. In a case where a passenger who changed from some company A's line to another company's line changes to company A's line again, the additional fare is incurred again.

Snuke is now at station 1 and wants to travel to station N by subway. Find the minimum required fare.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq 2×10^5

1 \leq p_i \leq N (1 \leq i \leq M)

1 \leq q_i \leq N (1 \leq i \leq M)

1 \leq c_i \leq 10^6 (1 \leq i \leq M)

p_i \neq q_i (1 \leq i \leq M)

Input

The input is given from Standard Input in the following format:

N M
p_1 q_1 c_1
:
p_M q_M c_M

Output

Print the minimum required fare. If it is impossible to get to station N by subway, print -1 instead.

Sample Input 1

3 3
1 2 1
2 3 1
3 1 2

Sample Output 1

1

Use company 1's lines: 1 → 2 → 3. The fare is 1 yen.

Sample Input 2

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

Sample Output 2

2

First, use company 1's lines: 1 → 3 → 2 → 5 → 6. Then, use company 5's lines: 6 → 7 → 8. The fare is 2 yen.

Sample Input 3

2 0

Sample Output 3

-1


object Main extends App {

  import scala.io.StdIn._

  val n = readLong()
  val s = readLong()

  val rt = Math.sqrt(n).toLong

  def digitSum(b : Long, n : Long) : Long = if (n < b) n else digitSum(b , n / b) + n % b

  def checkOne = if (n == s) Some(1) else None

  def searchFirstHalf(now : Long):Option[Long] = {
    if (now >= rt)  None
    else if (digitSum(now, n) == s) Some(now)
    else searchFirstHalf(now + 1)
  }

  def searchSecondHalf(now : Long) : Option[Long] = {
    if (now <= 0) None
    else {
      val b = (n + now - s) / now
      if (digitSum(b, n) == s) {
        Some(b)
      }
      else searchSecondHalf(now - 1)
    }
  }

  val calc = if (n < s) None else checkOne orElse searchFirstHalf(2) orElse searchSecondHalf(rt)

  println(calc getOrElse -1)
}

Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

The input is given from Standard Input in the following format:

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1


object Main extends App {
  val scan = new java.util.Scanner(System.in)
  val n = scan.next().toInt
  val a = scan.next().toDouble
  val xs = (1 to n).toArray.map(_ => scan.next().toInt)
  val memo = Array.fill(n+1, n+1,2501)(-1)
  memo(0)(0)(0) = 0
  for (i<-1 to n; j<-0 to n; k<-0 to 2500) {
    if (memo(i-1)(j)(k) != -1) {
      if (memo(i)(j)(k) == -1) memo(i)(j)(k) = 0
      memo(i)(j)(k) = memo(i-1)(j)(k)
    }
    if ((k-xs(i-1)>=0 && j-1>=0 && memo(i-1)(j-1)(k-xs(i-1)) != -1)) {
      if (memo(i)(j)(k) == -1) memo(i)(j)(k) = 0
      memo(i)(j)(k) += 1
    }
  }

  println((for (j<-1 to n; k<-0 to 2500; if memo(n)(j)(k) != -1 && k%j==0 && k/j==a) yield memo(n)(j)(k)).sum)
}

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

The input is given from Standard Input in the following format:

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.


import scala.io.StdIn

object Main {

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

    val Array(n, a) = readIntArray()
    val xs = readIntArray().map(_.toLong).zipWithIndex.toVector

    val alreadyComputed = collection.mutable.Set.empty[Seq[(Long, Int)]]

    def solve(ys: Seq[(Long, Int)]): Long = {
      ys match {
        case Nil =>
          0L
        case head +: Nil =>
          if (head._1 == a && !alreadyComputed(Seq(head))) 1L else 0L
        case head +: tail =>
//          println(s"--- head : ${head}")
          var count = 0
          (1 to tail.length).foreach { i =>
            tail.combinations(i).foreach { cb =>
//              println(s"${i} : ${cb}")
              if ((cb.map(_._1).sum + head._1).toDouble / (1 + i) == a && !alreadyComputed(head +: cb)) {
                count += 1
                alreadyComputed += (head +: cb)
              } else if (cb.map(_._1).sum.toDouble / i == a && !alreadyComputed(cb)) {
                count += 1
                alreadyComputed += cb
              }
            }
          }
//          println(s"::: count : ${count}")
          solve(tail) + count
      }
    }

    println(solve(xs))
  }

  private def readIntArray(): Array[Int] =
    StdIn.readLine().trim.split(' ').filter(_.nonEmpty).map(_.toInt)
}


object Main extends App {
  val str = scala.io.StdIn.readLine.toList
  if ((str.exists { _ == 'N' } == str.exists { _ == 'S' }) && (str.exists { _ == 'W' } == str.exists { _ == 'E' })) println("Yes")
  else println("No")
}

Score : 200 points

Problem Statement

Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip.
At the beginning of Day 1, he is at home. His plan is described in a string S of length N.
On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction:

North if the i-th letter of S is N

West if the i-th letter of S is W

South if the i-th letter of S is S

East if the i-th letter of S is E

He has not decided each day's travel distance. Determine whether it is possible to set each day's travel distance so that he will be back at home at the end of Day N.

Constraints

1 ≦ | S | ≦ 1000

S consists of the letters N, W, S, E.

Input

The input is given from Standard Input in the following format:

S

Output

Print Yes if it is possible to set each day's travel distance so that he will be back at home at the end of Day N. Otherwise, print No.

Sample Input 1

SENW

Sample Output 1

Yes

If Snuke travels a distance of 1 on each day, he will be back at home at the end of day 4.

Sample Input 2

NSNNSNSN

Sample Output 2

Yes

Sample Input 3

NNEW

Sample Output 3

No

Sample Input 4

W

Sample Output 4

No


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  println(List.fill(10)(1 + 1).foldLeft(0){(x, acc) => acc + x + acc + 1})
}

Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

The input is given from Standard Input in the following format:

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


import scala.io.StdIn

object Main extends App {

  val n = StdIn.readLine().toLong

  def fact(before: Long, k: Long): Long = {
    if(k == n) before + n
    else {
      fact(before + k, k + 1)
    }
  }

  println(fact(0, 0))

}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val h, w, a, b = sc.nextInt()
  val mod = 1000000007

  def plus(a: Long, b: Long): Long = (a + b) % mod
  def times(a: Long, b: Long): Long = (a * b) % mod

  def pow(a: Long, n: Int, res: Long = 1): Long = {
    if (n == 0) {
      res
    } else if ((n&1) == 0) {
      pow(times(a,a), n >> 1, res)
    } else {
      pow(times(a,a), n >> 1, times(res,a))
    }
  }

  def inv(a: Long): Long = pow(a, mod-2)

  def initFactTable(n: Int): Array[Long] = {
    (1 to n).scanLeft(1L)(times(_,_)).toArray
  }

  val fact = initFactTable(h + w)

  def initInvFactTable(n: Int): Array[Long] = {
    (1 to n).scanRight(inv(fact(n)))(times(_,_)).toArray
  }

  val invFact = initInvFactTable(h + w)

  def comb(n: Int, k: Int): Long = {
    times(times(fact(n), invFact(k)), invFact(n-k))
  }

  val ans = (0 until (h - a).min(w - b)).map( i =>
    times(comb(b + h - a - 1, b + i), comb(a + w - b - 1, a + i))
  ).reduceLeft(plus)

  println(ans)
}

Score : 400 points

Problem Statement

We have a large square grid with H rows and W columns.
Iroha is now standing in the top-left cell.
She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.

However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there are A×B forbidden cells.) There is no restriction on entering the other cells.

Find the number of ways she can travel to the bottom-right cell.

Since this number can be extremely large, print the number modulo 10^9+7.

Constraints

1 ≦ H, W ≦ 100,000

1 ≦ A < H

1 ≦ B < W

Input

The input is given from Standard Input in the following format:

H W A B

Output

Print the number of ways she can travel to the bottom-right cell, modulo 10^9+7.

Sample Input 1

2 3 1 1

Sample Output 1

2

We have a 2×3 grid, but entering the bottom-left cell is forbidden. The number of ways to travel is two: "Right, Right, Down" and "Right, Down, Right".

Sample Input 2

10 7 3 4

Sample Output 2

3570

There are 12 forbidden cells.

Sample Input 3

100000 100000 99999 99999

Sample Output 3

1

Sample Input 4

100000 100000 44444 55555

Sample Output 4

738162020


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

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

object Main {
  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val H, W, A, B = sc.nextInt()

    val F = Array.ofDim[Long](H + W)
    F(0) = 1
    (1 until F.length) foreach { i =>
      F(i) = F(i - 1) * i % MOD
    }
    val Inv = Array.ofDim[Long](F.length)
    rep(F.length) { i =>
      Inv(i) = powMod(F(i).toInt, MOD - 2, MOD)
    }

    def comb(n: Int, k: Int): Long = {
      F(n) * Inv(n - k) % MOD * Inv(k) % MOD
    }

    var ans = 0L
    rep(W - B) { i =>
      val c1 = {
        val n = H - A - 1 + B + i
        val k = H - A - 1
        comb(n, k)
      }

      val c2 = {
        val n = A - 1 + W - B - 1 - i
        val k = A - 1
        comb(n, k)
      }
      ans = (ans + c1 * c2) % MOD
    }
    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  def powMod(x: Int, n: Int, m: Int): Int = {
    def step(x: Long, n: Int, stack: Long): Long = {
      n match {
        case 0 => stack
        case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
      }
    }
    step(x, n, 1).toInt
  }

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

    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)
  }
  def rep(n: Int)(f: Int => Unit): Unit = {
    var i = 0
    while(i < n) { f(i); i += 1 }
  }
  def rep_r(n: Int)(f: Int => Unit): Unit = {
    var i = n - 1
    while(i >= 0) { 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
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}


object Main extends App {
  val l = io.StdIn.readLine()
  val nums = l.split(" ").map((s) => s.toInt)
  if (nums.count((i) => i == 5) == 2 && nums.count((i) => i == 7) == 1 ) {
    println("YES")
  } else {
    println("NO")
  }
}

Score : 100 points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

1≦A,B,C≦10

Input

The input is given from Standard Input in the following format:

A B C

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  var fee, cols = sc.nextInt
  val xss = List.fill(cols)(sc.nextInt)
  var ten: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  var cash = 0
  var count = 0
  var n = 10000
  var flag = true

  for (i <- 0 to 9) {
    if (xss.contains(i)) {
      ten = ten.filter {
        _ != i
      }
    }
  }

  for (j <- 0 to 3) {
    n /= 10
    flag = true
    for (i <- 0 to 9) {
      if (ten.contains(fee / n + i) && flag && cash < fee) {
        cash += (fee / n + i) * n
        flag = false
      }
    }
    fee /= 10
  }

  print(cash)

}

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

The input is given from Standard Input in the following format:

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999


object Main extends App {

  import scala.io.StdIn.{readInt, readLine}
  val n = readInt()
  val arr = readLine().trim.split(" ").map(_.toInt)
  val sorted = arr.toList.sorted
  var ans = 0
  for (i <- 0 to (sorted.length - 1)) {
    if (i % 2 == 0) ans += sorted(i)
  }
  println(ans)

}

Score : 200 points

Problem Statement

Snuke is having a barbeque party.

At the party, he will make N servings of Skewer Meal.

Example of a serving of Skewer Meal

He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i.
Also, he has an infinite supply of ingredients.

To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers.
Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients.

What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally?

Constraints

1≦N≦100

1≦L_i≦100

For each i, L_i is an integer.

Input

The input is given from Standard Input in the following format:

N
L_1 L_2 ... L_{2N}

Output

Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold.

Sample Input 1

2
1 3 1 2

Sample Output 1

3

If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold 1 and 2 ingredients, for the total of 3.

Sample Input 2

5
100 1 2 3 14 15 58 58 58 29

Sample Output 2

135


object Main extends App {
	import scala.math._

	val N = scala.io.StdIn.readLine.split(" ").map(_.toLong)

	def function(a: Long, b: Long): Long = {
		val aa = min(a,b)
		val bb = max(a,b)

		if(aa == 1L){
			return 2L*bb -1L
		}else{
			return 2L*aa + function(aa,bb-aa)
		}
	}

	println(N(0) + function(N(1), N(0)-N(1)))

}

Score : 500 points

Problem Statement

Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light.

Three mirrors of length N are set so that they form an equilateral triangle.
Let the vertices of the triangle be a, b and c.

Inside the triangle, the rifle is placed at the point p on segment ab such that ap = X.
(The size of the rifle is negligible.)
Now, the rifle is about to fire a ray of Mysterious Light in the direction of bc.

The ray of Mysterious Light will travel in a straight line, and will be reflected by mirrors, in the same ways as "ordinary" light.
There is one major difference, though: it will be also reflected by its own trajectory as if it is a mirror!
When the ray comes back to the rifle, the ray will be absorbed.

The following image shows the ray's trajectory where N = 5 and X = 2.

It can be shown that the ray eventually comes back to the rifle and is absorbed, regardless of the values of N and X.
Find the total length of the ray's trajectory.

Constraints

2≦N≦10^{12}

1≦X≦N-1

N and X are integers.

Partial Points

300 points will be awarded for passing the test set satisfying N≦1000.

Another 200 points will be awarded for passing the test set without additional constraints.

Input

The input is given from Standard Input in the following format:

N X

Output

Print the total length of the ray's trajectory.

Sample Input 1

5 2

Sample Output 1

12

Refer to the image in the Problem Statement section.
The total length of the trajectory is 2+3+2+2+1+1+1 = 12.