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

object Main extends App {
  val Array(h, w) = StdIn.readLine.split(" ").map(_.toInt)
  val table = Iterator.continually(StdIn.readLine)
    .take(h)
    .map(_.map(ch => if(ch == '#') true else false).toArray)
    .toArray

  val ans = {
    val dx = Array(0, 1, 0, -1)
    val dy = Array(-1, 0, 1, 0)
    var res = 0;

    def f(y:Int, x:Int):Int = {
      val visit = Array.ofDim[Boolean](h,w)

      def dfs(ey:Int, ex:Int):Unit = {
        if(table(ey)(ex) != table(y)(x) || visit(ey)(ex)) return
        else {
          visit(ey)(ex) = true
          (0 until 4).foreach(i => {
            val y = ey + dy(i)
            val x = ex + dx(i)
            if(0 <= y && y < h && 0 <= x && x < w) {
              dfs(y, x)
            }
          })
        }
      }

      dfs(y, x)

      val a = for {
        i <- 0 until h
        j <- 0 until w
        if !table(i)(j)
      } { if(visit(i)(j)) res += 1 }
      res
    }

    val ret = for {
      i <- 0 until h
      j <- 0 until w
      if table(i)(j)
    } f(i,j)

    res
  }

  println(ans)
}

Score : 300 points

Problem Statement

There is a grid with H rows and W columns, where each square is painted black or white.

You are given H strings S_1, S_2, ..., S_H, each of length W.
If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is #; if that square is painted white, the j-th character in the string S_i is ..

Find the number of pairs of a black square c_1 and a white square c_2 that satisfy the following condition:

There is a path from the square c_1 to the square c_2 where we repeatedly move to a vertically or horizontally adjacent square through an alternating sequence of black and white squares: black, white, black, white...

Constraints

1 \leq H, W \leq 400

|S_i| = W (1 \leq i \leq H)

For each i (1 \leq i \leq H), the string S_i consists of characters # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

Some of the pairs satisfying the condition are ((1, 2), (3, 3)) and ((3, 1), (3, 2)), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

4 3
###
###
...
###

Sample Output 3

6


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 ar = new Array[Int](N)

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

  //
  val dp = Array.fill[Int](N+1)(-1)

  def calc(i: Int): Int = {
    if(dp(i) == -1) {
      var res = 0
      for(e <- graph(i)){
        calc(e)
        res = Math.max(res, dp(e)+1)
      }
      dp(i) = res
    }
    dp(i)
  }

  for (i <- 1 to N) {
    calc(i)
  }

  println(dp.max)
}

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

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

Score : 100 points

Problem Statement

There is a directed graph G with N vertices and M edges.
The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i.
G does not contain directed cycles.

Find the length of the longest directed path in G.
Here, the length of a directed path is the number of edges in it.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq x_i, y_i \leq N

All pairs (x_i, y_i) are distinct.

G does not contain directed cycles.

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the length of the longest directed path in G.

Sample Input 1

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

Sample Output 1

3

The red directed path in the following figure is the longest:

Sample Input 2

6 3
2 3
4 5
5 6

Sample Output 2

2

The red directed path in the following figure is the longest:

Sample Input 3

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

Sample Output 3

3

The red directed path in the following figure is one of the longest:

Submitted source-code file size, in bytes.

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

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


import scala.collection.mutable

object Main extends App {

  import scala.io.StdIn._

  val Array(n, m) = readLine.trim.split(' ').map(_.toInt)
  val edges = Array.tabulate(n){_ ⇒ Nil: List[Int]}
  val inEdge = Array.tabulate(n){_ ⇒ 0}
  for (_ ← 0 until m){
    val Array(x, y) = readLine.trim.split(' ').map(_.toInt)
    edges(x - 1) ::= y - 1
    inEdge(y - 1) += 1
  }
  val longestPath = Array.tabulate(n){_ ⇒ n}
  val queue = mutable.PriorityQueue()(Ordering.by[(Int, Int), Int](_._2).reverse)
  inEdge.indices.filter(p ⇒ inEdge(p) == 0).foreach(p ⇒ queue.enqueue((p, n)))
  while (queue.nonEmpty){
    val (top, cost) = queue.dequeue()
    if (longestPath(top) == cost) {
      for (next ← edges(top)) {
        if (longestPath(next) > cost - 1) {
          longestPath(next) = cost - 1
          queue.enqueue((next, cost - 1))
        }
      }
    }
  }
  println(n - longestPath.min)
  implicit class Extend[T](value: T){
    def also(func: T ⇒ Unit): T = {func(value); value}
    def let[A](func: T ⇒ A): A = func(value)
  }
}


import scala.collection.mutable.Map
import scala.io.StdIn

object Main {
  val N = StdIn.readLine.toInt
  val Nd = N.toDouble
  val DP = Array.fill(N+2,N+2,N+2)(-1.0)

  def solve(i: Int, j: Int, k: Int): Double = {
    if (DP(i)(j)(k) >= 0.0) return DP(i)(j)(k)
    if (i+j+k == 0) return 0.0
    var res = 0.0
    if (i > 0) res = res + solve(i-1,j,k)*i
    if (j > 0) res = res + solve(i+1,j-1,k)*j
    if (k > 0) res = res + solve(i,j+1,k-1)*k
    res = res+Nd
    res = res/(i+j+k).toDouble
    DP(i)(j)(k) = res
    return res
  }

  def main(args: Array[String]) = {
    val N_inv = 1.0 / N.toDouble
    val INIT = Map(1 -> 0,2 -> 0,3 -> 0)
    for (i <- StdIn.readLine.split(" ").map(_.toInt)) INIT(i) = INIT(i)+1
    println(solve(INIT(1), INIT(2), INIT(3)))
  }
}

Score : 100 points

Problem Statement

There are N dishes, numbered 1, 2, \ldots, N.
Initially, for each i (1 \leq i \leq N), Dish i has a_i (1 \leq a_i \leq 3) pieces of sushi on it.

Taro will perform the following operation repeatedly until all the pieces of sushi are eaten:

Roll a die that shows the numbers 1, 2, \ldots, N with equal probabilities, and let i be the outcome. If there are some pieces of sushi on Dish i, eat one of them; if there is none, do nothing.

Find the expected number of times the operation is performed before all the pieces of sushi are eaten.

Constraints

All values in input are integers.

1 \leq N \leq 300

1 \leq a_i \leq 3

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the expected number of times the operation is performed before all the pieces of sushi are eaten.
The output is considered correct when the relative difference is not greater than 10^{-9}.

Sample Input 1

3
1 1 1

Sample Output 1

5.5

The expected number of operations before the first piece of sushi is eaten, is 1.
After that, the expected number of operations before the second sushi is eaten, is 1.5.
After that, the expected number of operations before the third sushi is eaten, is 3.
Thus, the expected total number of operations is 1 + 1.5 + 3 = 5.5.

Sample Input 2

1
3

Sample Output 2

3

Outputs such as 3.00, 3.000000003 and 2.999999997 will also be accepted.

Sample Input 3

2
1 2

Sample Output 3

4.5

Sample Input 4

10
1 3 2 3 3 2 3 2 1 3

Sample Output 4

54.48064457488221


import scala.collection.mutable.Map
import scala.io.StdIn

object Main {
  def main(args: Array[String]) = {
    val N = StdIn.readLine.toInt
    val N_inv = 1.0 / N.toDouble
    val INIT = Map(1 -> 0,2 -> 0,3 -> 0)
    for (i <- StdIn.readLine.split(" ").map(_.toInt)) INIT(i) = INIT(i)+1
    val DP = Array.fill(2,N+2,N+2,N+2)(0.0)
    DP(0)(INIT(1))(INIT(2))(INIT(3)) = 1.0

    var cnt = 1.0
    var mean = 0.0
    for (l <- 1 until 50*N) {
      DP((l-1)%2)(0)(0)(0) = 0.0
      for {
        i <- 0 to N
        j <- 0 to N
        k <- 0 to N
      } {
        val prev = (l-1)%2
        var calc = DP(prev)(i)(j)(k)*(N-i-j-k) + DP(prev)(i+1)(j)(k)*(i+1)
        if (i > 0) calc = calc + DP(prev)(i-1)(j+1)(k)*(j+1)
        if (j > 0) calc = calc + DP(prev)(i)(j-1)(k+1)*(k+1)
        DP(l%2)(i)(j)(k) = calc*N_inv
      }
      mean = mean + DP(l%2)(0)(0)(0)*cnt
      cnt =  cnt + 1.0
    }

    println(mean)
  }
}


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](N+1)
  for(i <- 1 to N)
    a(i) = in.next().toInt

  //
  import Math.{max, min}
  val memo = Array.ofDim[Long](N+1, N+1)
  val init = Long.MaxValue
  for (a <- 0 to N; b <- 0 to N)
    memo(a)(b) = init

  def solve(bg: Int, ed: Int, turn: Boolean): Long = {
    if(memo(bg)(ed) != init)
      memo(bg)(ed)
    else{
      if(bg == ed) {
        memo(bg)(ed) = a(bg) * (if(turn) 1 else -1)
        memo(bg)(ed)
      }
      else {
        val left = solve(bg+1, ed, !turn)
        val right = solve(bg, ed-1, !turn)
        if(turn)
          memo(bg)(ed) = max(left + a(bg), right + a(ed))
        else
          memo(bg)(ed) = min(left - a(bg), right - a(ed))
        memo(bg)(ed)
      }
    }
  }

  println(solve(1, N, true))
}

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

Problem Statement

Taro and Jiro will play the following game against each other.

Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N).
Until a becomes empty, the two players perform the following operation alternately, starting from Taro:

Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.

Let X and Y be Taro's and Jiro's total score at the end of the game, respectively.
Taro tries to maximize X - Y, while Jiro tries to minimize X - Y.

Assuming that the two players play optimally, find the resulting value of X - Y.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the resulting value of X - Y, assuming that the two players play optimally.

Sample Input 1

4
10 80 90 30

Sample Output 1

10

The game proceeds as follows when the two players play optimally (the element being removed is written bold):

Taro: (10, 80, 90, 30) → (10, 80, 90)

Jiro: (10, 80, 90) → (10, 80)

Taro: (10, 80) → (10)

Jiro: (10) → ()

Here, X = 30 + 80 = 110 and Y = 90 + 10 = 100.

Sample Input 2

3
10 100 10

Sample Output 2

-80

The game proceeds, for example, as follows when the two players play optimally:

Taro: (10, 100, 10) → (100, 10)

Jiro: (100, 10) → (10)

Taro: (10) → ()

Here, X = 10 + 10 = 20 and Y = 100.

Sample Input 3

1
10

Sample Output 3

10

Sample Input 4

10
1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1

Sample Output 4

4999999995

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

Sample Input 5

6
4 2 9 7 1 5

Sample Output 5

2

The game proceeds, for example, as follows when the two players play optimally:

Taro: (4, 2, 9, 7, 1, 5) → (4, 2, 9, 7, 1)

Jiro: (4, 2, 9, 7, 1) → (2, 9, 7, 1)

Taro: (2, 9, 7, 1) → (2, 9, 7)

Jiro: (2, 9, 7) → (2, 9)

Taro: (2, 9) → (2)

Jiro: (2) → ()

Here, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13.


import scala.io.Source
import scala.collection.mutable.Map

object Main {
  def main(args: Array[String]) = {
    val lines = Source.stdin.getLines.toStream
    val inSeq = lines.drop(1).head.split(' ').map(_.toLong)

    println(dp(inSeq))
  }

  def dp(input: Array[Long]): Long = {
    val memo = Array.ofDim[Long](input.length + 1, input.length + 1, 2)

    (1 to input.length).foreach { n =>
      memo(n-1)(n)(0) = input(n-1)
      memo(n-1)(n)(1) = 0
    }

    (2 to input.length).foreach { area =>
      (2 to area).foreach { tgLen =>
        var locMin = Long.MaxValue
        var cost = 0L
        ((area - tgLen + 1) to (area - 1)).reverse.foreach { split =>
          var cand = memo(area - tgLen)(split)(1) + memo(split)(area)(1)
          if (cand <= locMin) {
            locMin = cand
            cost = memo(area - tgLen)(split)(0) + memo(split)(area)(0)
          }
        }
        memo(area - tgLen)(area)(0) = cost
        memo(area - tgLen)(area)(1) = locMin + cost
      }
    }
    memo(0)(input.length)(1)
  }
}

Score : 100 points

Problem Statement

There are N slimes lining up in a row.
Initially, the i-th slime from the left has a size of a_i.

Taro is trying to combine all the slimes into a larger slime.
He will perform the following operation repeatedly until there is only one slime:

Choose two adjacent slimes, and combine them into a new slime. The new slime has a size of x + y, where x and y are the sizes of the slimes before combining them. Here, a cost of x + y is incurred. The positional relationship of the slimes does not change while combining slimes.

Find the minimum possible total cost incurred.

Constraints

All values in input are integers.

2 \leq N \leq 400

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 20 30 40

Sample Output 1

190

Taro should do as follows (slimes being combined are shown in bold):

(10, 20, 30, 40) → (30, 30, 40)

(30, 30, 40) → (60, 40)

(60, 40) → (100)

Sample Input 2

5
10 10 10 10 10

Sample Output 2

120

Taro should do, for example, as follows:

(10, 10, 10, 10, 10) → (20, 10, 10, 10)

(20, 10, 10, 10) → (20, 20, 10)

(20, 20, 10) → (20, 30)

(20, 30) → (50)

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

5000000000

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

Sample Input 4

6
7 6 8 6 1 1

Sample Output 4

68

Taro should do, for example, as follows:

(7, 6, 8, 6, 1, 1) → (7, 6, 8, 6, 2)

(7, 6, 8, 6, 2) → (7, 6, 8, 8)

(7, 6, 8, 8) → (13, 8, 8)

(13, 8, 8) → (13, 16)

(13, 16) → (29)


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()
    val A = na(N)

    val cum = cumSum(A)

    // [L, R)
    val dp = Array.ofDim[Long](N, N + 1)
    REP(N, 1) { r =>
      if (r >= 2) {
        // rの２つ左から
        REP_r(r - 1) { l =>
          var v = Long.MaxValue / 2
          // k: (l, r)
          l + 1 until r foreach { k =>
            val cost = cum(r) - cum(l)
            v = min(v, dp(l)(k) + dp(k)(r) + cost)
          }
          dp(l)(r) = v
//          debug(s"[$l,$r) $v")
        }
      }
    }

    val ans = dp(0)(N)
    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(s: String): Unit = {
    System.err.println(s)
  }

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


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 K = ns()
    val N = K.length
    val M = ni()

    val dp = Array.ofDim[Long](N + 1, 2, M)
    dp(0)(0)(0) = 1
    dp(0)(1)(0) = 1

    REP(N, 1) { i =>
      REP(2) { less =>
        val digit = K(N - i) - '0'
        val len = if (less == 1) 10 else digit + 1
        REP(len) { d =>
          REP(M) { m =>
            val nextLess = less | (if (d < digit) 1 else 0)
//            debug(s"$i $less $nextLess m:$m j:$d")
            dp(i)(less)(m) += dp(i - 1)(nextLess)((M * 10 + m - d) % M)
          }
        }

        // まとめてやる
        REP(M) { m =>
          dp(i)(less)(m) %= MOD
        }

        DEBUG {
          debug(s"i:$i less:$less")
          debug(dp(i)(less))
        }
      }
    }

    val ans = dp(N)(0)(0) - 1 // 0を引く
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

Score : 100 points

Problem Statement

Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7:

The sum of the digits in base ten is a multiple of D.

Constraints

All values in input are integers.

1 \leq K < 10^{10000}

1 \leq D \leq 100

Input

Input is given from Standard Input in the following format:

K
D

Output

Print the number of integers satisfying the condition, modulo 10^9 + 7.

Sample Input 1

30
4

Sample Output 1

6

Those six integers are: 4, 8, 13, 17, 22 and 26.

Sample Input 2

1000000009
1

Sample Output 2

2

Be sure to print the number modulo 10^9 + 7.

Sample Input 3

98765432109876543210
58

Sample Output 3

635270834


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val A, B, C = sc.nextInt()
  println(if (C - 1 <= A + B) C + B else B * 2 + A + 1)
}

Score : 200 points

Problem Statement

Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.

Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death.
As he wants to live, he cannot eat one in such a situation.
Eating a cookie containing antidotes while having a stomachache cures it, and there is no other way to cure stomachaches.

Find the maximum number of tasty cookies that Takahashi can eat.

Constraints

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

A,B and C are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the maximum number of tasty cookies that Takahashi can eat.

Sample Input 1

3 1 4

Sample Output 1

5

We can eat all tasty cookies, in the following order:

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

A tasty cookie containing antidotes

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

Sample Input 2

5 2 9

Sample Output 2

10

Sample Input 3

8 8 1

Sample Output 3

9


import scala.io.StdIn

object Main {

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

    val Array(n, h, w): Array[Int] = StdIn.readLine().split(' ').map(_.toInt)
    val abs: Seq[Seq[Int]] =
      (1 to n).foldLeft(Vector(): Vector[Vector[Int]])((acc, _) =>
        acc :+ StdIn.readLine().split(' ').toVector.map(_.toInt))

    println(solve(h, w, abs))

  }

  def solve(h: Int, w: Int, abs: Seq[Seq[Int]]): Int = {

    abs.foldLeft(0)((acc, ab) => {
      val d = if (ab(0) >= h && ab(1) >= w) 1 else 0
      acc + d
    })

  }
}

Score : 200 points

Problem Statement

There are N rectangular plate materials made of special metal called AtCoder Alloy.
The dimensions of the i-th material are A_i \times B_i (A_i vertically and B_i horizontally).

Takahashi wants a rectangular plate made of AtCoder Alloy whose dimensions are exactly H \times W.
He is trying to obtain such a plate by choosing one of the N materials and cutting it if necessary.
When cutting a material, the cuts must be parallel to one of the sides of the material.
Also, the materials have fixed directions and cannot be rotated.
For example, a 5 \times 3 material cannot be used as a 3 \times 5 plate.

Out of the N materials, how many can produce an H \times W plate if properly cut?

Constraints

1 \leq N \leq 1000

1 \leq H \leq 10^9

1 \leq W \leq 10^9

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N H W
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

3 5 2
10 3
5 2
2 5

Sample Output 1

2

Takahashi wants a 5 \times 2 plate.

The dimensions of the first material are 10 \times 3. We can obtain a 5 \times 2 plate by properly cutting it.

The dimensions of the second material are 5 \times 2. We can obtain a 5 \times 2 plate without cutting it.

The dimensions of the third material are 2 \times 5. We cannot obtain a 5 \times 2 plate, whatever cuts are made. Note that the material cannot be rotated and used as a 5 \times 2 plate.

Sample Input 2

10 587586158 185430194
894597290 708587790
680395892 306946994
590262034 785368612
922328576 106880540
847058850 326169610
936315062 193149191
702035777 223363392
11672949 146832978
779291680 334178158
615808191 701464268

Sample Output 2

8


object Main extends App {

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

  implicit def toWith(value: Long): NumberWithExponent = value.toWithExp
  implicit class Converter(private val value : Long){
    def toWithExp: NumberWithExponent = NumberWithExponent(value, 0)
  }
  val n = readLine.trim.toInt
  val numbers = readLine.trim.split(' ').map(_.toLong)
  val minus = minCountOfSortWithMinusTo(numbers).toList
  val plus = minCountOfSortWithPlusAfter(numbers).toList
  println(
    (0::minus).zip(plus ++ List(0)).map{case (l, r) ⇒ l + r}.min
  )
  def minCountOfSortWithMinusTo(numbers: Array[Long]): Array[Int] = {
    var list = Nil: List[MinusSortedSequence]
    numbers.map{right ⇒
      val (c, n) = addMinus(right, list)
      list = n
      c
    }.also{arr ⇒
      for (i ← 1 until arr.length){
        arr(i) += arr(i - 1)
      }
    }
  }
  def minCountOfSortWithPlusAfter(numbers: Array[Long]): Array[Int] = {
    var list = Nil: List[PlusSortedSequence]
    numbers.reverse.map{left ⇒
      val (c, n) = addPlus(left, list)
      list = n
      c
    }.also{arr ⇒
      for (i ← 1 until arr.length){
        arr(i) += arr(i - 1)
      }
    }.reverse
  }

  def addPlus(addLeft: Long, prev: List[PlusSortedSequence] = Nil): (Int, List[PlusSortedSequence]) = {
    prev match {
      case Nil if addLeft > 0 ⇒ (0, PlusSortedSequence(addLeft, addLeft, 1)::Nil)
      case Nil ⇒ (1, PlusSortedSequence(addLeft * -2, addLeft * -2, 1)::Nil)
      case PlusSortedSequence(left, right, length)::t if left >= addLeft && addLeft >= 0 ⇒
        if (left >= addLeft * 4) (0, PlusSortedSequence(addLeft, addLeft, 1)::prev)
        else (0, PlusSortedSequence(addLeft, right, length + 1)::t)
      case PlusSortedSequence(left, _, _)::_ if left < addLeft ⇒
        val (count, next) = increaseWhile(prev, addLeft)
        addPlus(addLeft, next).let{case (c, n) ⇒ (c + count, n)}
      case _ ⇒ addPlus(addLeft * -2, prev).let{case (c, n) ⇒ (c + 1, n)}
    }
  }
  def addMinus(addRight: Long, prev: List[MinusSortedSequence] = Nil): (Int, List[MinusSortedSequence]) = {
    prev match{
      case Nil if addRight < 0 ⇒ (0, MinusSortedSequence(addRight, addRight, 1)::Nil)
      case Nil ⇒ (1, MinusSortedSequence(addRight * -2, addRight * -2, 1)::Nil)
      case MinusSortedSequence(left, right, length)::t if right <= addRight && addRight <= 0 ⇒
        if (right <= addRight * 4) (0, MinusSortedSequence(addRight, addRight, 1)::prev)
        else (0, MinusSortedSequence(left, addRight, length + 1)::t)
      case MinusSortedSequence(_, right, _)::_ if addRight < right ⇒
        val (count, next) = decreaseWhile(prev, addRight)
        addMinus(addRight, next).let{case (c, n) ⇒ (c + count, n)}
      case _ ⇒ addMinus(addRight * -2, prev).let{case (c, n) ⇒ (c + 1, n)}
    }
  }
  def increaseWhile(list: List[PlusSortedSequence], target: NumberWithExponent): (Int, List[PlusSortedSequence]) = {
    list match {
      case h::_ if h.left < target ⇒ increaseWhile(increase(list), target).let{case (c, l) ⇒ (c + h.length * 2, l)}
      case _ ⇒ (0, list)
    }
  }
  def decreaseWhile(list: List[MinusSortedSequence], target: NumberWithExponent): (Int, List[MinusSortedSequence]) = {
    list match {
      case h::_ if h.right > target ⇒
        decreaseWhile(decrease(list), target).let{case (c, l) ⇒ (c + h.length * 2, l)}
      case _ ⇒ (0, list)
    }
  }
  def increase(list: List[PlusSortedSequence]): List[PlusSortedSequence] = {
    list match {
      case PlusSortedSequence(left, r, len1)::PlusSortedSequence(l, right, len2)::t if r.copy(exponent = r.exponent + 4) > l ⇒ PlusSortedSequence(left.copy(exponent = left.exponent + 2), right, len1 + len2)::t
      case PlusSortedSequence(left, right, length)::t ⇒ PlusSortedSequence(left.copy(exponent = left.exponent + 2), right.copy(exponent = right.exponent + 2), length)::t
      case Nil ⇒ Nil
    }
  }
  def decrease(list: List[MinusSortedSequence]): List[MinusSortedSequence] = {
    list match {
      case MinusSortedSequence(l, right, length)::MinusSortedSequence(left, r, len)::t if l.copy(exponent = l.exponent + 4) > r ⇒ MinusSortedSequence(left, right.copy(exponent = right.exponent + 2), length + len)::t
      case MinusSortedSequence(left, right, length)::t ⇒  MinusSortedSequence(left.copy(exponent = left.exponent + 2), right.copy(exponent = right.exponent + 2), length)::t
      case Nil ⇒ Nil
    }
  }
  case class PlusSortedSequence(left: NumberWithExponent, right: NumberWithExponent, length: Int)
  case class MinusSortedSequence(left: NumberWithExponent, right: NumberWithExponent, length: Int)
  case class NumberWithExponent(value: Long, exponent: Int) extends Ordered[NumberWithExponent] {
    override def compare(that: NumberWithExponent): Int = toLogWithSign.compare(that.toLogWithSign)
    private val sign: Int = math.signum(value).toInt * (if (exponent % 2 == 1) -1:Int else 1: Int)
    private val toLogWithSign: Double = (math.log(math.abs(value)) + math.log(2) * exponent) * sign
  }
  implicit class Extension[T](val value :T){
    def also(func: T ⇒ Unit): T = {
      func(value)
      value
    }
    def let[R](func: T ⇒ R): R = func(value)
  }
}

Score : 800 points

Problem Statement

There are N positive integers A_1, A_2, ..., A_N.
Takahashi can perform the following operation on these integers any number of times:

Choose 1 \leq i \leq N and multiply the value of A_i by -2.

Notice that he multiplies it by minus two.

He would like to make A_1 \leq A_2 \leq ... \leq A_N holds.
Find the minimum number of operations required. If it is impossible, print -1.

Constraints

1 \leq N \leq 200000

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the answer.

Sample Input 1

4
3 1 4 1

Sample Output 1

3

One possible solution is:

Choose i=4 and multiply the value of A_4 by -2. A_1, A_2, A_3, A_4 are now 3, 1, 4, -2.

Choose i=1 and multiply the value of A_1 by -2. A_1, A_2, A_3, A_4 are now -6, 1, 4, -2.

Choose i=4 and multiply the value of A_4 by -2. A_1, A_2, A_3, A_4 are now -6, 1, 4, 4.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

0

A_1 \leq A_2 \leq ... \leq A_N holds before any operation is performed.

Sample Input 3

8
657312726 129662684 181537270 324043958 468214806 916875077 825989291 319670097

Sample Output 3

7


object Main extends App {
  private def func(s:Array[Char]):Int = {
    var count = 0
    var last = 0
    //do{
      var i=0
      while(i < s.size){
        if(s(i)=='W'){
          last += 1
          count += (i - last + 1)
        }
        i+=1
        //println(count, i, find, s.toSeq)
      }
    //} while(false/*find*/)
    count
  }
  println(func(io.Source.stdin.getLines.toIndexedSeq.head.toCharArray))
}

Score : 300 points

Problem Statement

There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string S of length N.
If S_i=B, the i-th piece from the left is showing black;
If S_i=W, the i-th piece from the left is showing white.

Consider performing the following operation:

Choose i (1 \leq i < N) such that the i-th piece from the left is showing black and the (i+1)-th piece from the left is showing white, then flip both of those pieces. That is, the i-th piece from the left is now showing white and the (i+1)-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

1 \leq |S| \leq 2\times 10^5

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


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()
    val A = na(N)
    val C = mutable.Map[Int, Int]().withDefaultValue(0)
    val S = mutable.Set[Int]()
    REP(N) { i =>
      C(A(i)) = C(A(i)) +  1
      S += A(i)
    }

    var ans = 0
    // 大きいほうからどんよくに
    REP_r(4, 1) { k =>
      val sum = 1 << k
      S.foreach { a =>
        val b = sum - a
        if (C(a) > 0 && C(b) > 0) {
          if (a == b) {
            val cnt = C(a) / 2
            ans += cnt
            C(a) = C(a) + cnt
          } else {
            val cnt = min(C(b), C(a))
            ans += cnt
            C(a) = C(a) - 1
            C(b) = C(b) - 1
          }
        }
      }
    }

    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, 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

Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i.
He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2.
Note that a ball cannot belong to multiple pairs.
Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of 2 when it can be written as 2^t using some non-negative integer t.

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of 2.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is 4 by pairing the first and third balls.
Note that we cannot pair the second ball with itself.

Sample Input 2

5
3 11 14 5 13

Sample Output 2

2


object Main {
  val sc = new java.util.Scanner(System.in)

  def sin(n: Int): Seq[Int] = Seq.fill(n)(sc.nextInt())

  def main(args: Array[String]): Unit = {
    val n = sc.nextInt()
    val p = sin(n)
    println(p.sum - p.max / 2)
  }
}

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


//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 java.util.Calendar

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 A = Array.fill(sc.nextInt())(sc.nextLong())
    println(A.sum - A.max / 2)
  }

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

  def calc(N: Long, R: Long, M: Long): Double = {
    math.sqrt(R * R - (R * 2 * ((M * 1.0 / N) - 0.5)) * (R * 2 * ((M * 1.0 / N) - 0.5))) * 2
  }

  def recursive(S: Long, N: Long, check3: Boolean, check5: Boolean, check7: Boolean): Long = {
    if (S > N) (0) else {
      (if (check3 && check5 && check7) (1) else (0)) +
        recursive(S * 10 + 3, N, true, check5, check7) +
        recursive(S * 10 + 5, N, check3, true, check7) +
        recursive(S * 10 + 7, N, check3, check5, true)
    }
  }

  def check(s: String): Boolean = {
    if (s == "0") (true) else (s(0) != '0' && 0 <= s.toInt && s.toInt <= 255)
  }

  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 Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)
    val hs = for (_ <- 1 to n) yield io.StdIn.readInt

    val sorted = hs.sorted
    val tree_sets = sorted.sliding(2)
    val diffs = tree_sets.map(t => t.last-t.head)
    val result = diffs.min
    println(result)
}

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).


object Main extends App {
    val Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)
    val hs = for (_ <- 1 to n) yield io.StdIn.readInt

    val sorted = hs.sorted
    val tree_sets = sorted.sliding(k)
    val diffs = tree_sets.map(t => t.max-t.min)
    val result = diffs.min
    println(result)
}


object Main {
  def main(args: Array[String]): Unit = {
    val factors      = scala.io.StdIn.readLine.split(" ").map{_.toInt}
    var tree_heights = Vector[Int]()

    for(i <- 0 until factors(0)) {
      tree_heights = scala.io.StdIn.readInt +: tree_heights
    }

    val sorted_tree_heights = tree_heights.sorted

    var min_diff = 1000000000
    for(i <- 0 until (factors(0) - factors(1) + 1)) {
      val diff = sorted_tree_heights(i + factors(1) - 1) - sorted_tree_heights(i)
      if (diff < min_diff) min_diff = diff
    }
    println(min_diff)
  }
}


object Main extends App {

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

  val Array(n, k) = readLine.trim.split(' ').map(_.toInt)
  val heights = Array.tabulate(n){_ ⇒ readLine.trim.toInt}.sorted
  println(
    (0 to (n - k)).map{it ⇒ heights(it + k - 1) - heights(it)}.min
  )

  implicit class Extenion[T](val value :T){
    def also(func: T ⇒ Unit): T = {
      func(value)
      value
    }
    def let[R](func: T ⇒ R): R = func(value)
  }
}


import scala.io.StdIn.readLine

object Main{
  def solve(n : Int, x : Long): Long ={
    if(n == 0) x
    else{
      val hSize : Long = (1.toLong << (n + 1)) - 3
      val ps : Long = (1.toLong << n) - 1
      if(x == 0) 0
      else if(x == hSize + 2) ps + 1
      else if(x == 2 * hSize + 3) 2 * ps + 1
      else if(x > hSize + 2) ps + 1 + solve(n - 1, x - hSize - 2)
      else solve(n - 1, x - 1)
    }
  }

  def main(args : Array[String]): Unit ={
    val Array(n, x) = readLine().split(' ')
    println(solve(n.toInt, x.toLong))
  }
}

Score : 400 points

Problem Statement

In some other world, today is Christmas.

Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:

A level-0 burger is a patty.

A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.

For example, a level-1 burger and a level-2 burger look like BPPPB and BBPPPBPBPPPBB (rotated 90 degrees), where B and P stands for a bun and a patty.

The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?

Constraints

1 \leq N \leq 50

1 \leq X \leq ( the total number of layers in a level-N burger )

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.

Sample Input 1

2 7

Sample Output 1

4

There are 4 patties in the bottom-most 7 layers of a level-2 burger (BBPPPBPBPPPBB).

Sample Input 2

1 1

Sample Output 2

0

The bottom-most layer of a level-1 burger is a bun.

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

A level-50 burger is rather thick, to the extent that the number of its layers does not fit into a 32-bit integer.


object Main extends App {
  val input = io.Source.stdin.getLines.toIndexedSeq.map(_.split(' ').map(_.toInt).toIndexedSeq)
  val K = input(0)(1)
  //println(K)
  val in = input(1)
  //println(in)

  var sums=Seq[Long]()
  (0 until in.size).foreach{ i =>
    (i until in.size).foreach{ j =>
      val sub = (i to j).map(k => in(k).toLong).sum
      sums +:= sub
    }
  }
  //println(sums)
  val rs = sums.sorted.reverse
  //println(rs)
  val tk = rs.take(K)
  val and = tk.foldLeft(-1L){ (a,e)=>
    a & e
  }
  println(and)
}

Score : 400 points

Problem Statement

One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N.
He is interested in properties of the sequence a.

For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to know the maximum possible value of the bitwise AND of the beauties of K nonempty contiguous subsequences among all N(N+1)/2 nonempty contiguous subsequences. (Subsequences may share elements.)

Find the maximum possible value for him.

Constraints

2 \leq N \leq 1000

1 \leq a_i \leq 10^9

1 \leq K \leq N(N+1)/2

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the answer.

Sample Input 1

4 2
2 5 2 5

Sample Output 1

12

There are 10 nonempty contiguous subsequences of a. Let us enumerate them:

contiguous subsequences starting from the first element: \{2\}, \{2, 5\}, \{2, 5, 2\}, \{2, 5, 2, 5\}

contiguous subsequences starting from the second element: \{5\}, \{5, 2\}, \{5, 2, 5\}

contiguous subsequences starting from the third element: \{2\}, \{2, 5\}

contiguous subsequences starting from the fourth element: \{5\}

(Note that even if the elements of subsequences are equal, subsequences that have different starting indices are considered to be different.)

The maximum possible bitwise AND of the beauties of two different contiguous subsequences is 12.
This can be achieved by choosing \{5, 2, 5\} (with beauty 12) and \{2, 5, 2, 5\} (with beauty 14).

Sample Input 2

8 4
9 1 8 2 7 5 6 4

Sample Output 2

32


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val X, Y = in.nextInt
  println(X + Y / 2)
}

Score: 100 points

Problem Statement

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

The train fare is 58 ⁄ 2=29 yen with the 50% discount.

Thus, it costs 110 yen to travel from Station A to Station C.

Sample Input 2

4 54

Sample Output 2

31


import scala.io.StdIn

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

    println(X + Y / 2)

  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val candidate_num = scala.io.StdIn.readInt
    val temperatures  = scala.io.StdIn.readLine.split(" ").map{_.toInt}
    val candidate     = scala.io.StdIn.readLine.split(" ").map{_.toInt}
    var diff_min      = 100000.0
    var dicision_num  = 0

    for(i <- 0 until candidate.length) {
      val diff = Math.abs(temperatures(1) - (temperatures(0) - 0.006*candidate(i)))
      if (diff_min > diff) {
        diff_min     = diff
        dicision_num = i + 1
      }
    }
    println(dicision_num)
  }
}

Score: 200 points

Problem Statement

A country decides to build a palace.

In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.

There are N places proposed for the place. The elevation of Place i is H_i meters.

Among them, Princess Joisino orders you to select the place whose average temperature is the closest to A degrees Celsius, and build the palace there.

Print the index of the place where the palace should be built.

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

Print the index of the place where the palace should be built.

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

The average temperature of Place 1 is 12-1000 \times 0.006=6 degrees Celsius.

The average temperature of Place 2 is 12-2000 \times 0.006=0 degrees Celsius.

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


object Main {
  def main(args:Array[String]):Unit={
    var N = readLine.toInt
    var TA = readLine.split(" ")
    var H = readLine.split(" ")
    var res = -1
    var min = scala.Int.MaxValue.toDouble
    for(i <- 0 until N){
      var temp = TA(0).toInt-H(i).toInt*0.006
      var diff = scala.math.abs(TA(1).toInt-temp.toDouble)
      if(diff<min){
        res=i
        min=diff
      }
    }
    println(res+1)
  }

}


object Main extends App {
	val n = scala.io.StdIn.readInt
	val Array(t, a) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
	val h = scala.io.StdIn.readLine.split(" ").map(_.toDouble).map{z => math.abs(t - z*0.006 - a)}

	println(h.indexOf(h.min) + 1)
}


import scala.io.StdIn._
import scala.collection.mutable.{HashMap, ArrayBuffer}
import java.io.PrintWriter
import java.text.DecimalFormat
import java.util.Arrays
object Main extends App {
  val f = new DecimalFormat("000000")
  val sr = new StdinReader
  val n, m = sr.nextInt
  val source = (1 to m).map{i => Array(sr.nextInt, sr.nextInt)}
  val map = new HashMap[Int, ArrayBuffer[Int]]
  source.foreach{case Array(p, y) => map.getOrElseUpdate(p, new ArrayBuffer[Int]) += y}
  val newMap = map.mapValues(_.sorted.toArray)
  val w = new PrintWriter(System.out)
  source.foreach {case Array(p, y) =>
    val i = Arrays.binarySearch(newMap(p), y) + 1
    w.print(f.format(p))
    w.println(f.format(i))
  }
  w.flush
}

class StdinReader {
  val is = System.in
  val buffer = new Array[Byte](1024 * 1024)
  var size = 0
  var pos = 0

  private def readByte: Byte = {
    if (pos >= size) {
      pos = 0;
      size = is.read(buffer);
    }
    if (size < 0) -1
    else {
      val ret = buffer(pos)
      pos += 1
      ret
    }
  }

  def nextInt: Int = {
    @scala.annotation.tailrec
    def r(i: Int, reading: Boolean): Int = {
      readByte match {
        case '-' => r(i * -1, true)
        case b if '0' <= b && b <= '9' => r(i * 10 + (b - '0'), true)
        case _ => if (reading) i else r(i, false)
      }
    }
    r(0, false)
  }
}

Score: 300 points

Problem Statement

In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.

City i is established in year Y_i and belongs to Prefecture P_i.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a 12-digit ID number to each city.

If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.

Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002.

As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001.

As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003


object Main extends App {
	private def zeros(yid: String): String = {
		val len = yid.length
		if (len == 0) "000000"
		else if (len == 1) "00000"
		else if (len == 2) "0000"
		else if (len == 3) "000"
		else if (len == 4) "00"
		else if (len == 5) "0" else ""
	}

	private def str(n: Long): String = {
//		val yid = Integer.toString(yindex)
//		val prey = zeros(yid)
//		val pid = Integer.toString(pgr)
//		val prep = zeros(pid)
//		prep + pid + prey + yid

		java.lang.Long.toString(1000000000000L + n).substring(0,12)
	}

	private def func(lines: Seq[String]) {
		val line = lines.tail.zipWithIndex.map { case (e, gi) =>
			val tmp = e.split(' ').map(_.toInt).toArray
			(tmp(0), (tmp(1), gi))
		}
		val idMap = line.indices.map(_ => -1L).toArray
		line.groupBy(_._1).foreach { case (pgr, ylist) =>
			ylist.toSeq.map(_._2).sortBy(_._1).map(_._2).zipWithIndex.foreach { case (gi, yindex) =>
				//val id = "%06d%06d".format(pgr, (yindex + 1))
				//val id = str(pgr, yindex)
				////println(gi, id)
				////idMap = idMap + (gi -> id)
				//idMap(gi) = id

				idMap(gi) = pgr * 1000000L + (yindex + 1)
			}
		}
		val pw = new java.io.PrintWriter(System.out)
		idMap.foreach(e => pw.println(str(e)))
		pw.flush()
	}

//	val start = System.currentTimeMillis()
//	//func((0 until 100).map(i => (i % 1) + " " + -i))
//	func((0 until 100000).map(i => (i % 1) + " " + i))
//	func((0 until 100000).map(i => (i % 1) + " " + -i))
//	func((0 until 100000).map(i => -i + " " + -i))
//	println(System.currentTimeMillis() - start)

	func(scala.io.Source.stdin.getLines.toSeq)
}


object Main extends App {
	private def zeros(yid: String): String = {
		val len = yid.length
		if (len == 0) "000000"
		else if (len == 1) "00000"
		else if (len == 2) "0000"
		else if (len == 3) "000"
		else if (len == 4) "00"
		else if (len == 5) "0" else ""
	}

	private def str(pgr: Int, yindex: Int): String = {
		//val id = "%06d%06d".format(pgr, (yindex + 1))
		val yid = Integer.toString(yindex + 1)
		val prey = zeros(yid)
		val pid = Integer.toString(pgr)
		val prep = zeros(pid)
		prep + pid + prey + yid
	}

	private def func(lines: Seq[String]) {
		val line = lines.tail.zipWithIndex.map { case (e, gi) =>
			val tmp = e.split(' ').map(_.toInt).toArray
			(tmp(0), (tmp(1), gi))
		}
		val idMap = line.indices.map(_ => Array(-1, -1)).toArray
		line.groupBy(_._1).foreach { case (pgr, ylist) =>
			ylist.toSeq.map(_._2).sortBy(_._1).map(_._2).zipWithIndex.foreach { case (gi, yindex) =>
				//val id = str(pgr, yindex)
				////println(gi, id)
				////idMap = idMap + (gi -> id)
				//idMap(gi) = id

				idMap(gi) = Array(pgr, yindex)
			}
		}
		val pw = new java.io.PrintWriter(System.out)
		idMap.foreach(e => pw.println(str(e(0), e(1))))
		pw.flush()
	}

//	val start = System.currentTimeMillis()
//	//func((0 until 100).map(i => (i % 1) + " " + -i))
//	func((0 until 100000).map(i => (i % 1) + " " + i))
//	func((0 until 100000).map(i => (i % 1) + " " + -i))
//	func((0 until 100000).map(i => -i + " " + -i))
//	println(System.currentTimeMillis() - start)

	func(scala.io.Source.stdin.getLines.toSeq)
}


object Main extends App {

  import scala.io.StdIn._

  val Array(n, m) = readLine.trim.split(' ').map(_.toInt)
  val prefNum = Array.tabulate(n){_ ⇒ 0}
  val id = Array.tabulate(m){_ ⇒ 1000000000000L}
  val towns = Array.tabulate(m){_ ⇒
    val Array(p, y) = readLine.trim.split(' ').map(_.toInt)
    Town(p, y)
  }.zipWithIndex.sortBy(_._1.year)
  for ((town, i) ← towns){
    prefNum(town.pref - 1) += 1
    id(i) += prefNum(town.pref - 1) + town.pref * 1000000
  }
  for (i ← id){
    println(i.toString.takeRight(12))
  }
  case class Town(pref: Int, year: Int)
}


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()
    val cities = Array.ofDim[(Int, Int, Int)](M)
    rep(M) { i =>
      cities(i) = (ni() - 1, ni(), i)
    }
    Sorting.quickSort(cities)(Ordering.by(_._2))
    val cnt = Array.ofDim[Int](N)
    val num = Array.ofDim[Int](M)
    val pref = Array.ofDim[Int](M)
    rep(M) { i =>
      val p = cities(i)._1
      val c = cities(i)._3
      val id = cnt(p)
      num(c) = id
      pref(c) = p
      cnt(p) += 1
    }

    rep(M) { i =>
      val p = pref(i)
      val c = num(i)
      out.println(f"${p+1}%06d${c+1}%06d")
    }
  }

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


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 fact(n: Int): Long = if (n == 0) 1 else n * fact(n - 1)

  def test(arrayLength: Int): Array[Long] = {
    if (arrayLength == 0) return Array(1L)
    val base = Array.fill(arrayLength)(fact(arrayLength))
    for (i <- 0 until arrayLength) {
      val leftLength = i
      if (leftLength != 0) {
        val left = test(leftLength)
        val leftMultiplier = fact(arrayLength - 1) / fact(leftLength)
        for (j <- 0 until leftLength) {
          base(j) += left(j) * leftMultiplier
        }
      }

      val rightLength = arrayLength - i - 1
      if (rightLength != 0) {
        val right = test(rightLength)
        val rightMultiplier = fact(arrayLength - 1) / fact(rightLength)
        for (j <- 0 until rightLength) {
          base(j + i + 1) += right(j) * rightMultiplier
        }
      }
    }

    base
  }

  def solve(implicit sc: Scanner): Unit = {
    val N = sc.nextLine().toInt
    val A = readLineLongs

    println(test(N).zipWithIndex.map { case (e, i) => e * A(i) }.sum % 1000000007)
  }
}

Score : 600 points

Problem Statement

There are N blocks arranged in a row, numbered 1 to N from left to right.
Each block has a weight, and the weight of Block i is A_i.
Snuke will perform the following operation on these blocks N times:

Choose one block that is still not removed, and remove it.
The cost of this operation is the sum of the weights of the blocks that are connected to the block being removed (including itself).
Here, two blocks x and y ( x \leq y ) are connected when, for all z ( x \leq z \leq y ), Block z is still not removed.

There are N! possible orders in which Snuke removes the blocks.
For all of those N! orders, find the total cost of the N operations, and calculate the sum of those N! total costs.
As the answer can be extremely large, compute the sum modulo 10^9+7.

Constraints

1 \leq N \leq 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

For all of the N! orders, find the total cost of the N operations, and print the sum of those N! total costs, modulo 10^9+7.

Sample Input 1

2
1 2

Sample Output 1

9

First, we will consider the order "Block 1 -> Block 2".
In the first operation, the cost of the operation is 1+2=3, as Block 1 and 2 are connected.
In the second operation, the cost of the operation is 2, as only Block 2 remains.
Thus, the total cost of the two operations for this order is 3+2=5.

Then, we will consider the order "Block 2 -> Block 1".
In the first operation, the cost of the operation is 1+2=3, as Block 1 and 2 are connected.
In the second operation, the cost of the operation is 1, as only Block 1 remains.
Thus, the total cost of the two operations for this order is 3+1=4.

Therefore, the answer is 5+4=9.

Sample Input 2

4
1 1 1 1

Sample Output 2

212

Sample Input 3

10
1 2 4 8 16 32 64 128 256 512

Sample Output 3

880971923


object Main{
  def main(args:Array[String]):Unit={
    var n = readInt
    var m = readInt

    var max = m/n
    var flag = true
    for(i <- max until 0 by -1 if flag){
      if(m%i==0){
        println(i)
        flag = false
      }
    }
  }
}

Score : 400 points

Problem Statement

You are given integers N and M.

Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

N \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the maximum possible value of the greatest common divisor of a sequence a_1, a_2, ..., a_N that satisfies the condition.

Sample Input 1

3 14

Sample Output 1

2

Consider the sequence (a_1, a_2, a_3) = (2, 4, 8). Their greatest common divisor is 2, and this is the maximum value.

Sample Input 2

10 123

Sample Output 2

3

Sample Input 3

100000 1000000000

Sample Output 3

10000


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

    var ans = 1
    rep(math.sqrt(M).toInt, 2) { g =>
      val x = M - g.toLong * (N - 1)
      if (x > 0 && x % g == 0) ans = g
    }

    rep_r(math.sqrt(M).toInt, 2) { c =>
      if (M % c == 0 && c >= N) {
        ans = M / c
      }
    }

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


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

    var ans = 1
    rep(math.sqrt(M).toInt, 2) { g =>
      val x = M - g * (N - 1)
      if (x > 0 && x % g == 0) ans = g
    }

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


object Main{
  def main(args:Array[String]):Unit={
    var input = readLine
    var res = ""
    for(i <- input){
      if(i=='1') res += '9'.toString
      else if(i=='9') res+='1'.toString
      else res+=i.toString
    }
    println(res)
  }
}

Score : 100 points

Problem Statement

Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.

You are given a three-digit integer n written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in n.

Constraints

111 \leq n \leq 999

n is an integer consisting of digits 1 and 9.

Input

Input is given from Standard Input in the following format:

n

Output

Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in n.

Sample Input 1

119

Sample Output 1

991

Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.

Sample Input 2

999

Sample Output 2

111


object Main extends App{
  println((new java.util.Scanner(System.in).nextInt()/111).floor*111)
}

Score : 200 points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC N (the N-th ABC ever held).
Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

100 \leq N \leq 999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If the earliest ABC where Kurohashi can make his debut is ABC n, print n.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC 111, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC 112, which means Kurohashi can no longer participate in ABC 111.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC 222.

Sample Input 3

750

Sample Output 3

777


object Main extends App {
  import scala.io.StdIn.{readInt, readLine}
  val _ = readInt()
  val numbers = readLine().split(' ').map(_.toInt)

  val Array(first, second) = numbers.take(2)
  val tail = numbers.tail.tail

  val suggestedChangeSize = if (first == second) {
    0
  } else {
    tail.zipWithIndex.count {
      case (number, i) =>
        if (i == 0) number == first
        else if (i % 2 == 0) number == first
        else number == second
    }
  }

  println(suggestedChangeSize)
}

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.


object Main {

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

    // 偶数番目, 奇数番目の数が, それぞれ全て同じであればいい
    // かつ, どちらも異なる数

    val N = sc.nextInt()
    val Vm = 100000
    val OddN, EvenN = new Array[Int](Vm+1)

    (0 until N) foreach { i =>
      val v = sc.nextInt()
      if (i % 2 == 0) {
        EvenN(v) += 1
      } else  {
        OddN(v) += 1
      }
    }

    // Odd(i) // i番目に出現回数が大きい数
    // OddN(Odd(i)) // i番目に出現回数の大きい数の出現回数

    def solve(): Int = {
      val Odd = (0 to Vm).sortBy(i => OddN(i))(Ordering.Int.reverse)
      val Even = (0 to Vm).sortBy(i => EvenN(i))(Ordering.Int.reverse)

      var i = 0
      var j = 0
      while (i < Vm && j < Vm) {
        val oN = OddN(Odd(i))
        val eN = EvenN(Even(j))

        if (oN == 0)
          return N - eN
        else if (eN == 0)
          return N - oN

        if (Odd(i) != Even(j)) {
          return N - oN - eN
        }

        if (Odd(i+1) > Even(i+1))
          i += 1
        else
          j += 1
      }
      N
    }
    println(solve())
  }

}


//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 A = Array.fill(sc.nextInt())(sc.nextLong())
    println(if (A.groupBy(i => i).size == 1) (A.size / 2) else {
      val X =
        A.zipWithIndex.filter {
          case (_, a) => a % 2 == 1
        }.map {
          case (a, _) => a
        }.groupBy(i => i).toList.sortBy {
          case (_, b) => b.size
        }.reverse

      val Y = A.zipWithIndex.filter {
        case (_, a) => a % 2 == 0
      }.map {
        case (a, _) => a
      }.groupBy(i => i).toList.sortBy {
        case (_, b) => b.size
      }.reverse

      (A.size -
        (if (X.head._1 == Y.head._1) {
          math.max(X.drop(1).head._2.size + Y.head._2.size, X.head._2.size + Y.drop(1).head._2.size)
        } else {
          X.head._2.size + Y.head._2.size
        }))
    })
  }

  def calc(N: Long, R: Long, M: Long): Double = {
    math.sqrt(R * R - (R * 2 * ((M * 1.0 / N) - 0.5)) * (R * 2 * ((M * 1.0 / N) - 0.5))) * 2
  }

  def recursive(X: Long, primeList: Stream[Long]): Long = {
    0
  }

  def check(A: Long): Boolean = {
    if (A < 0) (check(-A)) else if (A % 10 == 0) (check(A / 10)) else (A < 10)
  }

  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{
  def main(args: Array[String]){
    val sc=new java.util.Scanner(System.in)
    val n=sc.nextInt()
    val v=mysprit(n,sc)
    val std=v.map(x=>(List(0,0)::mysort(x,Nil)).sortBy(-_(1)).take(2)).sortBy(l=>l(0)(1)-l(1)(1))
    std match{
      case List(a:List[List[Int]],b:List[List[Int]]) if a(0)(0)==b(0)(0) => println(n-(a(1)(1)+b(0)(1)))
      case List(a:List[List[Int]],b:List[List[Int]]) => println(n-(a(0)(1)+b(0)(1)))
    }
  }
  def mysort(l:List[Int],r:List[List[Int]]) : List[List[Int]] = {
    l match{
      case Nil => r
      case x::xs => mysort(
        xs filter (_!=x),
        (x :: 1+xs.count(_==x) :: Nil) :: r
      )
    }
  }
  def mysprit(n:Int,s:java.util.Scanner):List[List[Int]] = {
    def myspritlocal(c:Int,l1:List[Int],l2:List[Int]) : List[List[Int]] ={
      c match{
        case 0 => List(l1,l2)
        case a:Int => myspritlocal(a-2,s.nextInt()::l1,s.nextInt()::l2)
      }
    }
    myspritlocal(n,Nil,Nil)
  }
}


import java.util.Scanner

import scala.collection.mutable.LinkedHashMap

object Main {
    case class SuspectedMap(key:Int , count:Int)
    implicit def tupleToName(tup: (Int, Int)): SuspectedMap = tup match {
        case (key, count) => SuspectedMap(key, count)
    }

    def main(args: Array[String]): Unit = {
        val scanner = new Scanner(System.in)
        val n: Int = scanner.nextInt
        val vs: List[Int] = List.fill(n)(scanner.nextInt)
        println(calc(vs))
    }

    def calc(nums: List[Int] ): Int ={
        val (evens, odds) = nums.zipWithIndex.partition(_._2 % 2 == 0)
        val (evensFirst, evensSecond) = take2(evens)
        val (oddsFirst, oddsSecond) = take2(odds)

        if (evensSecond.key == -1 && oddsSecond.key == -1){
          if (evensFirst.key != oddsFirst.key) 0
          else nums.sum / 2
        }
        else {
          if (evensFirst.key != oddsFirst.key)
            nums.sum - evensFirst.count - oddsFirst.count
          else
            countMinNumberOfRewrite(nums.sum, evensFirst.count, evensSecond.count, oddsFirst.count, oddsSecond.count)
        }
    }

    def take2(nums: List[(Int, Int)]): ((Int,Int),(Int,Int)) = {
      val sortedNums: Seq[(Int, Int)] = nums.map(_._1).groupBy(n => n).mapValues(_.length).toSeq.sortBy(_.count).reverse
      (sortedNums(0), try{sortedNums(1)}catch{case e :Exception => (-1, Int.MinValue)})
    }

    def countMinNumberOfRewrite(allNums: Int ,e1stCnt: Int, e2ndCnt: Int, o1stCnt: Int, o2ndCnt: Int): Int={
      val count1 = allNums - e1stCnt - o2ndCnt
      val count2 = allNums - e2ndCnt - o1stCnt
      count1.min(count2)
    }
}


import java.util.Scanner

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

object Main {
  def main(args: Array[String]) {
    val result = solve(new Scanner(System.in))
    if (result.length > 0) println(result)
  }

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

  def solve(sc: Scanner): String = {
    val n = sc.nextInt
    val v1 = new mutable.HashMap[Int, Int]()
    val v2 = new mutable.HashMap[Int, Int]()
    for (i <- 0 until n / 2) {
      val k1 = sc.nextInt
      v1(k1) = v1.getOrElse(k1, 0) + 1
      val k2 = sc.nextInt
      v2(k2) = v2.getOrElse(k2, 0) + 1
    }

    val l1 = v1.toList.sortBy(_._2).reverse.take(2)
    val l2 = v2.toList.sortBy(_._2).reverse.take(2)
    if (l1(0)._1 == l2(0)._1) {
      if (l1.length > 1) {
        val m1 = n - l1(0)._2 - l2(1)._2
        val m2 = n - l1(1)._2 - l2(0)._2
        List(m1, m2).min.toString
      } else (n / 2).toString
    } else {
      (n - l1(0)._2 - l2(0)._2).toString
    }
  }
}


import scala.util.control.Breaks._

object Main extends App {
  val s = scala.io.StdIn.readLine()
  val t = scala.io.StdIn.readLine()

  var memo = Map[Char, Char]()

  breakable {
    s.zip(t)
      .foreach({
        case (x, y) =>
          if (memo.isDefinedAt(x)) {
            if (memo(x) != y) {
              println("No")
              break()
            }
          } else {
            memo += (x -> y)
          }
      })

    if (memo.values.size == memo.values.toList.distinct.size) {
      println("Yes")
    } else {
      println("No")
    }
  }
}

Score : 300 points

Problem Statement

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

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

1 \leq |S| \leq 2 \times 10^5

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


import scala.util.control.Breaks._

object Main extends App {
  val s = scala.io.StdIn.readLine()
  val t = scala.io.StdIn.readLine()

  var memo = Map[Char, Char]()
  var never = Map[Char, Boolean]()

  breakable {
    s.zip(t)
      .foreach({
        case (x, y) =>
          memo += (x -> y)
      })

    if (memo.values.size == memo.values.toList.distinct.size) {
      println("Yes")
    } else {
      println("No")
    }
  }
}


object Main {

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

    val S, T = sc.nextLine()
    val to = scala.collection.mutable.Map.empty[Char, Char]
    val res = S.zip(T).forall { case (s, t) =>
      if (to.contains(s)) {
        to(s) == t
      } else {
        to.put(s, t)
        true
      }
    }
    println(if (res) "Yes" else "No")
  }

}


import scala.io.{StdIn => in}

object Main extends App {
  val s = in.readLine
  val t = in.readLine

  val n = 'z'-'a' + 1
  val ts = Array.fill(n)(-1)
  val tt = Array.fill(n)(-1)

  val isPosi = (0 until s.size).forall(i => {
    val a = s(i) - 'a'
    val b = t(i) - 'a'
    if(ts(a) != -1 || tt(b) != -1) {
      if(ts(a) != b || tt(b) != a) false
      else true
    }
    else {
      ts(a) = b
      tt(b) = a
      true
    }
  })

  val ans = if(isPosi) "Yes" else "No"
  println(ans)
}


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

  val mod = 1000000007

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

  def pow(a: Long, n: Int): Long = {
    def pow(a: Long, n: Int, res: Long): 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(a,res))
    }
    pow(a,n,1L)
  }

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

  def factorize(n: Int): List[Int] = {
    if (n == 1) Nil
    else {
      var i = 2
      var d = 0
      while (i*i <= n && d == 0) {
        if (n % i == 0) d = i
        i += 1
      }
      if (d == 0) List(n) else d::factorize(n/d)
    }
  }

  if (m == 1) println(1)
  else {
    val f = factorize(m)
    val bs = f.toSet.toList.map((x: Int) => f.count(_ == x))

    val l = bs.max + n - 1

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

    val fact = factTable(l)

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

    val factInv = factInvTable(l)

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

    println(bs.map(b => comb(b+n-1, b)).reduceLeft(times(_,_)))
  }
}

Score : 400 points

Problem Statement

You are given positive integers N and M.

How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7.

Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of the sequences consisting of positive integers that satisfy the condition, modulo 10^9 + 7.

Sample Input 1

2 6

Sample Output 1

4

Four sequences satisfy the condition: \{a_1, a_2\} = \{1, 6\}, \{2, 3\}, \{3, 2\} and \{6, 1\}.

Sample Input 2

3 12

Sample Output 2

18

Sample Input 3

100000 1000000000

Sample Output 3

957870001


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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val h, w = sc.nextInt
    val m = Array.fill(h, w)(0)
    for (i <- 0 until h; j <- 0 until w) {
      m(i)(j) = sc.nextInt
    }

    // 下右 だけでいいのかな。。。
    val DI = Array(1, 0)
    val DJ = Array(0, 1)

    val pw = new java.io.PrintWriter(System.out)
    for (i <- 0 until h; j <- 0 until w) {
      val n = m(i)(j)
      if (n % 2 != 0) {
        // 奇数だったら配る
        var delivered = false
        var dIndex = 0
        while (!delivered && dIndex < 2) {
          val ni = i + DI(dIndex)
          val nj = j + DJ(dIndex)
          if (ni >= 0 && ni < h && nj >= 0 && nj < w) {
            val nn = m(ni)(nj)
            pw.println(s"${i + 1} ${j + 1} ${ni + 1} ${nj + 1}")

            m(i)(j) -= 1
            m(ni)(nj) += 1

            delivered = true
          }
          dIndex += 1
        }
      }
    }

    pw.flush()
  }
}

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