import java.util.Scanner

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

    val n = sc.nextInt
    val iSeq = Seq(sc.nextInt, sc.nextInt, sc.nextInt)

    val ll = List.fill(n)(sc.nextInt)

    val target = (1 to Math.pow(4,n).toInt).toArray.map{l => s"%0${n}d".format(l_adic(l,4).mkString.toInt)}.filter{s => s.contains('1') && s.contains('2') && s.contains('3')}

    val res =
      target.foldLeft(Int.MaxValue){ case (min, str) =>
        val temp = str zip ll
        val sum = temp.toArray.filter(t => t._1 != '0').foldLeft( Array((0,0),(0,0),(0,0)) ){case (arr, (i,num)) =>
          i match{
            case '1' => val x = arr(0); arr.update(0, (x._1 + num, x._2 + 1) ) ; arr
            case '2' => val x = arr(1); arr.update(1, (x._1 + num, x._2 + 1) ) ; arr
            case '3' => val x = arr(2); arr.update(2, (x._1 + num, x._2 + 1) ) ; arr
          }
        }
        val sumSeq = sum.map(_._1).toSeq
        val jointNum = sum.map(_._2 - 1).sum
        if( sumSeq.count(_ == 0 ) > 0) min
        else {
          Math.min( (sumSeq zip iSeq).map(t => Math.abs(t._1 - t._2)).sum + 10 * jointNum, min)
        }
      }
    println(res)
  }

  def l_adic(n: Int, l: Int): List[Int] ={
    def loop(m: Int, acc: List[Int]): List[Int] ={
      m match {
        case 0 => acc
        case x => loop( x / l, (x % l) +: acc)
      }
    }
    loop(n,List.empty[Int])
  }
}

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


object Main extends App {
  val AB = io.StdIn.readLine.split(' ')
  val A = AB.head.toInt
  val B = AB.last.toInt

  val out = B % A match {
    case 0 => B + A
    case _ => B - A
  }

  println(out)
}

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

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.

Submitted source-code file size, in bytes.

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

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


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

  val ans = {
    if (b % a == 0) a + b
    else b - a
  }

  println(ans)
}


import scala.math._

object Main extends App {

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

  val input: Array[Array[Int]] = Array.ofDim(6, 6000000)
  ///////////////////////////////////////////

  val sc = new java.util.Scanner(System.in)
  val n, m = sc.nextInt
//  val b = sc.nextInt
//  val a = List.fill(n)(sc.nextInt)
//  val b = List.fill(m)(sc.nextInt)
//  val c = List.fill(n - 1)(sc.nextInt)
//  val list = List.fill(n, 2)(sc.next)

  val a = (1 to n).foldLeft(Seq.empty[Seq[Int]]){ case (acc, _) =>
    val k = sc.nextInt
    acc :+ List.fill(k)(sc.nextInt)
  }.flatten

  val ans = a.groupBy(identity).foldLeft(0){ case (acc, in) => if (in._2.size == n) acc + 1 else acc }

  println(ans)

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

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

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

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

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

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

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

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


object Main{
	def main(A:Array[String]){
		val s = new java.util.Scanner(System.in)
		val n = s.nextInt
		val a = new Array[Int](s.nextInt)
		(1 to n).flatMap(_ => 1 to s.nextInt).foreach(_=>a(s.nextInt-1)+=1)
		println(a.count(i=>i==n))
	}
}


import java.util.Scanner

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

    val n = sc.nextInt
    val m = sc.nextInt

    val l = (1 to n).foldLeft(List.empty[List[Int]]) {(seq, i) =>
      val k = sc.nextInt
      seq :+ List.fill(k)(sc.nextInt)
    }

    val c = l.foldLeft((1 to m).toList)( _ intersect _)

    println(c.size)

  }

}


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.tail.head.split(' ').map(_.toLong).toArray
  val s = ls.sorted.reverse
  val longest = s.head
  val others = s.tail.sum
  val ret = if(longest < others) "YES" else "NO"
  println(ret)
}

Score : 200 points

Problem Statement

Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.

You can use the following theorem:

Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.

Sample Input 2

4
3 8 4 1

Sample Output 2

No

Since 8 \geq 8 = 3 + 4 + 1, it follows from the theorem that such a polygon cannot be drawn on a plane.

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


import scala.io.StdIn._

object Main extends App {

  val Array(n,m) = readLine().split(" ").map(_.toInt)
  val X = readLine().split(" ").map(_.toLong)

  def solve() = {
    val sorted = X.sorted
    (0 until m-1).map { i =>
      sorted(i+1) - sorted(i)
    }.sorted(Ordering[Long].reverse).drop(n-1).sum
  }

  println(solve())

}

Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

Find the minimum number of moves required to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

Find the minimum number of moves required to achieve the objective.

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0


import java.util.Scanner

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
    sc.nextLine
    val ABC = Array.fill(3)(sc.nextLine)

    var n = 0
    for (i <- 0 until N) {
      if (ABC(0)(i) != ABC(1)(i)) {
        n += 1
      }
      if (ABC(0)(i) != ABC(2)(i) && ABC(1)(i) != ABC(2)(i)) {
        n += 1
      }
    }
    n.toString
  }
}

Score : 200 points

Problem Statement

You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.

Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:

Operation: Choose one of the strings A, B and C, and specify an integer i between 1 and N (inclusive). Change the i-th character from the beginning of the chosen string to some other lowercase English letter.

What is the minimum number of operations required to achieve the objective?

Constraints

1 \leq N \leq 100

Each of the strings A, B and C is a string of length N.

Each character in each of the strings A, B and C is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
A
B
C

Output

Print the minimum number of operations required.

Sample Input 1

4
west
east
wait

Sample Output 1

3

In this sample, initially A = west、B = east、C = wait. We can achieve the objective in the minimum number of operations by performing three operations as follows:

Change the second character in A to a. A is now wast.

Change the first character in B to w. B is now wast.

Change the third character in C to s. C is now wast.

Sample Input 2

9
different
different
different

Sample Output 2

0

If A, B and C are already equal in the beginning, the number of operations required is 0.

Sample Input 3

7
zenkoku
touitsu
program

Sample Output 3

13


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 = {
    import java.util
    val N, M = ni()
    val (from, to) = na2(N - 1 + M ,-1)

    // ルートはかならずtoに現れない
    val flg = Array.ofDim[Boolean](N)
    REP(from.length) { i =>
      flg(to(i)) = true
    }
    val rt = flg.indexWhere(!_)
//    debug(rt.toString)

    val g = packDGraph(N, from, to)

    // 子供へのショートカットしかないので最大距離 == 木の上での深さになる
    // DFSしないと再計算がおこる
    // (depth, parents)
    def calcMaxDepth: (Array[Int], Array[Int]) = {
      val d = Array.ofDim[Int](N)
      val p = Array.ofDim[Int](N)

      val stack = mutable.Stack[Int]()
      val ix = Array.ofDim[Int](N)

      def visit(u: Int, v: Int): Unit = {
        if (d(v) + 1 > d(u)) {
          p(u) = v
          d(u) = d(v) + 1
          stack.push(u)
        }
      }

      visit(rt, 0)
      debug(d)
      debug(p)
      while(stack.nonEmpty) {
        val v = stack.top
        val es = g(v)
        if (ix(v) == es.length) stack.pop()
        else {
          val u = es(ix(v))
          visit(u, v)
          ix(v) += 1
        }
      }

      (d, p)
    }

    val (d, p) = calcMaxDepth
    debug(d)
    debug(p)

    REP(N) { i =>
      if (i == rt) out.println(0)
      else out.println(p(i) + 1)
    }
  }

  def packDGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP_r(m) { i => // 順序維持する
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

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

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

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

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

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

Problem Statement

There is a rooted tree (see Notes) with N vertices numbered 1 to N.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex 1.

Takahashi has added M new directed edges to this graph.
Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v.

You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges.
More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

If i \neq j, (A_i, B_i) \neq (A_j, B_j).

The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_{N-1+M} B_{N-1+M}

Output

Print N lines.
In the i-th line, print 0 if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge 1 \rightarrow 3 to the rooted tree 1 \rightarrow 2 \rightarrow 3.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


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 = {
    import java.util
    val N, M = ni()
    val (from, to) = na2(N - 1 + M ,-1)

    // ルートはかならずtoに現れない
    val flg = Array.ofDim[Boolean](N)
    REP(from.length) { i =>
      flg(to(i)) = true
    }
    val rt = flg.indexWhere(!_)
    debug(rt.toString)

    val g = packDGraph(N, from, to)

    // 子供へのショートカットしかないので最大距離 == 木の上での深さになる
    def calcMaxDepth: Array[Int] = {
      val d = Array.ofDim[Int](N)
      val queue = new java.util.ArrayDeque[Int]()
      def visit(v: Int): Unit = {
        g(v).foreach { u =>
          if (d(v) + 1 > d(u)) {
            d(u) = d(v) + 1
            queue.add(u)
          }
        }
      }
      visit(rt)

      while(!queue.isEmpty) {
        val v = queue.poll()
        visit(v)
      }

      d
    }

    val d: Array[Int] = calcMaxDepth
    debug(d)

    case class Visit(parent: Int, v: Int)
    val queue = new util.ArrayDeque[Visit]()
    val p = Array.ofDim[Int](N)

    def addChildren(v: Int, parent: Int): Unit = {
      p(v) = parent
      g(v).foreach { u =>
        queue.add(Visit(v, u))
      }
    }

    addChildren(rt, -1)
    while(!queue.isEmpty) {
      val v = queue.poll()
      if (d(v.parent) + 1 == d(v.v)) {
        addChildren(v.v, v.parent)
      }
    }

    debug(p)

    REP(N) { i =>
      if (i == rt) out.println(0)
      else out.println(p(i) + 1)
    }
  }

  def packDGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP_r(m) { i => // 順序維持する
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

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

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

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

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

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

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

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

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

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

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


import scala.util.control.Breaks

object Main extends App {
  var n = scala.io.StdIn.readInt()
  var s = scala.io.StdIn.readLine()
  var inputArray =  s.split(" ").map(_.toInt)
  var i = 0

  def minusWater(s: Seq[Int]): Seq[Int] = {
    var arrayIndex = Seq.empty[Int]
    val maxIndex = s.indexOf(s.max)
    val b1 = new Breaks
    b1.breakable{
      for(i<-maxIndex to n - 1) {
        if (s(i) == 0) {
          b1.break()
        } else {
          arrayIndex :+= i
        }
      }
    }
    if (maxIndex > 0) {
      val b2 = new Breaks
      b2.breakable{
        for(i<-(maxIndex-1) to 0 by -1) {
          if (s(i) == 0) {
            b2.break()
          } else {
            arrayIndex :+= i
          }
        }
      }
    }

    s.zipWithIndex.map{ h =>
      if (arrayIndex.find(_ == h._2).isDefined) {
        h._1 - 1
      }else {
        h._1
      }
    }
  }

  def judgeSeq(s: Seq[Int]): Unit = {
    i += 1
    val seqAfterWater = minusWater(s)
    if (seqAfterWater.filterNot(_ == 0).isEmpty) {
      println(i)
    } else {
      judgeSeq(seqAfterWater)
    }
  }
  judgeSeq(inputArray)
}

Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


import scala.collection.mutable.Map
import Ordering.Long.reverse
import scala.collection.mutable.PriorityQueue

object Main {
    // type T = PriorityQueue[Long]
    def main(args : Array[String]) = {
        val sc = new java.util.Scanner(System.in)
        val n, k = sc.nextInt
        val sushis = List.fill(n)(sc.nextInt, sc.nextInt).sortWith(_._2 > _._2)
        var kind, ans : Long = 0
        val used = new Array[Boolean](n+1)
        var selected = new PriorityQueue[Long]
        for ((t, d) <- sushis take k) {
            ans += d
            if (used(t)) selected += d
            else {
                used(t) = true
                kind += 1
            }
        }
        val toeat_ : Map[Int, List[Long]] = Map()
        for ((t, d) <- sushis)
            if (toeat_ contains t) toeat_(t) = d :: toeat_(t)
            else toeat_(t) = List(d)
        var toeat : List[List[Long]] = toeat_.filter{case (k, _) => !used(k)}.values.toList
        toeat = toeat.map(_.sorted(reverse)).sortWith(_.head > _.head)
        var candidate : Long = kind * kind + ans
        for (xs <- toeat if selected.size > 0) {
            kind += 1
            ans += (xs.head - selected.dequeue)
            candidate = candidate max (kind * kind + ans)
        }
        println(candidate)
    }
}

Score : 400 points

Problem Statement

There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:

The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".

The base total deliciousness is the sum of the deliciousness of the pieces you eat.

The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat.

You want to have as much satisfaction as possible.
Find this maximum satisfaction.

Constraints

1 \leq K \leq N \leq 10^5

1 \leq t_i \leq N

1 \leq d_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

Output

Print the maximum satisfaction that you can obtain.

Sample Input 1

5 3
1 9
1 7
2 6
2 5
3 1

Sample Output 1

26

If you eat Sushi 1,2 and 3:

The base total deliciousness is 9+7+6=22.

The variety bonus is 2*2=4.

Thus, your satisfaction will be 26, which is optimal.

Sample Input 2

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

Sample Output 2

25

It is optimal to eat Sushi 1,2,3 and 4.

Sample Input 3

6 5
5 1000000000
2 990000000
3 980000000
6 970000000
6 960000000
4 950000000

Sample Output 3

4900000016

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


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val S = sc.next()
  val splited = 1.until("keyence".length).map("keyence".splitAt)
  val isExists = S.startsWith("keyence") || S.endsWith("keyence") ||
    splited.exists { case (l, r) => S.startsWith(l) && S.endsWith(r) }
  println(if (isExists) "YES" else "NO")
}

Score : 200 points

Problem Statement

A string is called a KEYENCE string when it can be changed to keyence by removing its contiguous substring (possibly empty) only once.

Given a string S consisting of lowercase English letters, determine if S is a KEYENCE string.

Constraints

The length of S is between 7 and 100 (inclusive).

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a KEYENCE string, print YES; otherwise, print NO.

Sample Input 1

keyofscience

Sample Output 1

YES

keyence is an abbreviation of key of science.

Sample Input 2

mpyszsbznf

Sample Output 2

NO

Sample Input 3

ashlfyha

Sample Output 3

NO

Sample Input 4

keyence

Sample Output 4

YES


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val S = sc.next()
  val isExists =
    "keyence".inits.toList.tail.zip("keyence".tails.toList.tail.reverse).map {
      case (l, r) => s".*$l.*$r.*"
    }.exists(S.matches)
  println(if (isExists) "YES" else "NO")
}


object Main {
  import java.util.Scanner

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

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

  def solve(implicit sc: Scanner): Unit = {
    val N = readLineLongs(sc)(0)
    val A = readLineLongs
    val B = readLineLongs
    val AmB = A.zip(B).map { case (a, b) => a - b }
    if (AmB.sum < 0) return print(-1)

    val (negatives, positives) = AmB.partition(_ < 0)
    val negSorted = negatives.sorted(implicitly[Ordering[Long]].reverse)
    val posSorted = positives.filter(_ > 0).sorted

    def posUseNumber: Int = {
      var negIndex = 0
      var posMinUnaltered = 0

      while (negIndex < negSorted.length) {
        val a = negSorted(negIndex)

        def search: Option[Int] = {
          for {i <- posSorted.indices} if (posSorted(i) > a) return Some(i)
          None
        }
        search match {
          case Some(index) => {
            posSorted(index) -= a
            negSorted(negIndex) = 0

            negIndex += 1
            posMinUnaltered = Math.max(posMinUnaltered, index + 1)
          }
          case None => {
            var negToFill = negSorted.sum * (-1)
            val (usedPos, unusedPos) = posSorted.splitAt(posMinUnaltered)
            negToFill -= usedPos.sum
            val additionalUse = unusedPos.scan(0L)(_ + _).takeWhile(_ < negToFill).length
            return posMinUnaltered + additionalUse
          }
        }
      }
      posMinUnaltered
    }
    println(negSorted.length + posUseNumber)
  }
}

Score : 400 points

Problem Statement

A university student, Takahashi, has to take N examinations and pass all of them.
Currently, his readiness for the i-th examination is A_{i}, and according to his investigation, it is known that he needs readiness of at least B_{i} in order to pass the i-th examination.

Takahashi thinks that he may not be able to pass all the examinations, and he has decided to ask a magician, Aoki, to change the readiness for as few examinations as possible so that he can pass all of them, while not changing the total readiness.

For Takahashi, find the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the following conditions:

The sum of the sequence A_1, A_2, ..., A_{N} and the sum of the sequence C_1, C_2, ..., C_{N} are equal.

For every i, B_i \leq C_i holds.

If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

A_i and B_i are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N}
B_1 B_2 ... B_{N}

Output

Print the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the conditions.
If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Sample Input 1

3
2 3 5
3 4 1

Sample Output 1

3

(A_1, A_2, A_3) = (2, 3, 5) and (B_1, B_2, B_3) = (3, 4, 1). If nothing is done, he cannot pass the first and second exams.
The minimum possible number of indices i such that A_i and C_i are different, 3, is achieved when:

(C_1, C_2, C_3) = (3, 5, 2)

Sample Input 2

3
2 3 3
2 2 1

Sample Output 2

0

In this case, he has to do nothing in order to pass all the exams.

Sample Input 3

3
17 7 1
25 6 14

Sample Output 3

-1

In this case, no matter what is done, he cannot pass all the exams.

Sample Input 4

12
757232153 372327760 440075441 195848680 354974235 458054863 463477172 740174259 615762794 632963102 529866931 64991604
74164189 98239366 465611891 362739947 147060907 118867039 63189252 78303147 501410831 110823640 122948912 572905212

Sample Output 4

5


object Main extends App {
  val n = scala.io.StdIn.readLine.toInt
  val w = scala.io.StdIn.readLine.toInt
  val h = scala.io.StdIn.readLine.toInt
  println((n-(w-1))*(n-(h-1)))
}

Score : 100 points

Problem Statement

It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board.

The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns.

How many ways are there to choose where to put the notice so that it completely covers exactly HW squares?

Constraints

1 \leq H, W \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
H
W

Output

Print the answer.

Sample Input 1

3
2
3

Sample Output 1

2

There are two ways to put the notice, as follows:

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

Here, # represents a square covered by the notice, and . represents a square not covered.

Sample Input 2

100
1
1

Sample Output 2

10000

Sample Input 3

5
4
2

Sample Output 3

8


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, B = ni()
    val P = na(N)
    val a = P.count(_ <= A)
    val b = P.count(x => A + 1 <= x && x <= B)
    val c = N - a - b
    val ans = min(a, min(b, c))
    out.println(ans)
  }

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

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

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

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

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

Problem Statement

You have written N problems to hold programming contests.
The i-th problem will have a score of P_i points if used in a contest.

With these problems, you would like to hold as many contests as possible under the following condition:

A contest has three problems. The first problem has a score not greater than A points, the second has a score between A + 1 and B points (inclusive), and the third has a score not less than B + 1 points.

The same problem should not be used in multiple contests.
At most how many contests can be held?

Constraints

3 \leq N \leq 100

1 \leq P_i \leq 20 (1 \leq i \leq N)

1 \leq A < B < 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A B
P_1 P_2 ... P_N

Output

Print the answer.

Sample Input 1

7
5 15
1 10 16 2 7 20 12

Sample Output 1

2

Two contests can be held by putting the first, second, third problems and the fourth, fifth, sixth problems together.

Sample Input 2

8
3 8
5 5 5 10 10 10 15 20

Sample Output 2

0

No contest can be held, because there is no problem with a score of A = 3 or less.

Sample Input 3

3
5 6
5 6 10

Sample Output 3

1


import java.util.Scanner

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

  val n = sc.nextInt()

  val happy = Stream.range(0, n)
    .map(_ => (sc.nextLong(), sc.nextLong(), sc.nextLong()))
    .foldLeft(0L, 0L, 0L) {
      case ((am, bm, cm), (ai, bi, ci)) =>
        (
          math.max(bm + ai, cm + ai),
          math.max(cm + bi, am + bi),
          math.max(am + ci, bm + ci)
        )
    }

  println(Seq(happy._1, happy._2, happy._3).max)

}

Score : 100 points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of N days.
For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:

A: Swim in the sea. Gain a_i points of happiness.

B: Catch bugs in the mountains. Gain b_i points of happiness.

C: Do homework at home. Gain c_i points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq a_i, b_i, c_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain 70 + 50 + 90 = 210 points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

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

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.


import scala.io.StdIn

object Main extends App {

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

  val ans = if((a+b) > c) b + c
    else if(b > c) c * 2 + a
    else  b * 2 + a + 1

  println(ans)
}

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


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N = sc.next()
  println(N.count(_ == '2'))
}

Score : 100 points

Problem Statement

You are given an integer N that has exactly four digits in base ten.
How many times does 2 occur in the base-ten representation of N?

Constraints

1000 \leq N \leq 9999

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

1222

Sample Output 1

3

2 occurs three times in 1222. By the way, this contest is held on December 22 (JST).

Sample Input 2

3456

Sample Output 2

0

Sample Input 3

9592

Sample Output 3

1


import scala.annotation.tailrec
import scala.math._

object Main extends App {

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

  val input: Array[Array[Int]] = Array.ofDim(6, 6000000)
  ///////////////////////////////////////////

  val sc = new java.util.Scanner(System.in)
  val s = sc.next
//  val b = sc.nextInt
//  val a = List.fill(n)(sc.nextInt)
//  val b = List.fill(m)(sc.nextInt)

  val aaaa = s.zipWithIndex

  val ans = foldLeftWithNext(s.zipWithIndex)((0, 0)) { case ((acc, count), (sA, indexA), (sB, indexB)) =>
    if ((sA.toString + sB.toString) == "BW") (acc + indexB - count, count + 1)
    else (acc, count)
  } {
    case ((acc, count), (sA, indexA)) =>
      (acc, count)
  }
  println(ans._1)

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

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

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

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

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

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

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

  object +: {
    def unapply[T](s: Seq[T]) =
      s.headOption.map(head => (head, s.tail))
  }

  @tailrec
  def foldLeftWithNext[A, B](seq: Seq[A])(z: B)(op: (B, A, A) => B)(tailOp: (B, A) => B): B = {
    seq match {
      case Nil => z
      case a +: Nil => tailOp(z, a)
      case a +: next +: tail => foldLeftWithNext(next +: tail)(op(z, a, next))(op)(tailOp)
    }
  }
}

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


import scala.io.{StdIn => in}

object Main extends App {
  val s = in.readLine

  val ans = (0 until s.size)./:((0L, 0)) { case ((acc,cnt),i) =>
    if(s(i) == 'W') (acc+(i-cnt), cnt+1)
    else (acc, cnt)
  }._1

  println(ans)
}


object Main extends App {
  val regex = "BW"
  val newStr = "WB"
  println(rep(io.StdIn.readLine()))

  def rep(str: String): Int = {
    if (str.indexOf(regex) == -1) {
      0
    } else {
      rep(str.replaceFirst(regex, newStr)) + 1
    }
  }
}


object Main extends App {

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

  val ballCount = readLine.trim.toInt
  val series = readLine.trim.split(' ').map{_.toLong}.sorted
  var stack: List[Ball] = List(new Ball(series.head, 1))
  for (i ← 1 until series.length){
    if (stack.head.number == series(i)){
      stack.head.count += 1
    }else {
      stack ::= new Ball(series(i), 1)
    }
  }
  val balls = stack.toArray.reverse
  val exp = Array.tabulate(33){_ ⇒ 1L}
  for (i ← 1 until exp.length){
    exp(i) = exp(i - 1) * 2
  }
  var sum: Int = 0
  for (i ← balls.indices.reverse){
    for (e ← exp){
      if (e < balls(i).number * 2 && e > balls(i).number) lowerBound(balls, e - balls(i).number) match {
        case r if balls(r).number + balls(i).number == e && balls(r).count >= 1 ⇒
          val min = math.min(balls(r).count, balls(i).count)
          sum += min
          balls(r).count -= min
        case _ ⇒
      }else if (e == balls(i).number * 2 && balls(i).count >= 2) {
        sum += balls(i).count / 2
      }
    }
  }

  println(sum)
  def lowerBound(balls: Array[Ball], target: Long): Int = {
    var left = 0
    var right = balls.length - 1
    while (left < right){
      val mid = (left + right) / 2
      if (balls(mid).number < target){
        left = mid + 1
      }else {// target <= balls(mid).number
        right = mid
      }
    }
    right
  }
  def upperBound(balls: Array[Ball], target: Long): Int = {
    var left = 0
    var right = balls.length - 1
    while (left < right){
      val mid = (left + right) / 2
      if (balls(mid).number <= target){
        left = mid + 1
      }else {// target < balls(mid).number
        right = mid
      }
    }
    right
  }

  class Ball(val number: Long, var count: Int) {
    override def toString: String = s"Ball($number, $count)"
  }
  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)
  }
}
/*

同じ文字数であれば

 */

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


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N, K = Integer.parseInt(sc.next())
    val h = new Array[Long](N)
    for (i <- 0 until N) {
      h(i) = Integer.parseInt(sc.next())
    }

    println(solve(N, K, h))
  }

  def solve(N: Int, K: Int, h: Array[Long]): String = {
    val sortedH = h.sorted

    var ans = sortedH(N - 1)
    for (i <- 0 to N - K) {
      ans = Math.min(ans, sortedH(K - 1 + i) - sortedH(i))
    }
    ans.toString
  }
}

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


import scala.io.StdIn.readLine

object Main extends App {

  val Array(n, k) = readLine.split(" ").map(_.toInt)
  val hs: List[Int] = (0 until n).map(_ => readLine.toInt).toList

  val sorted = hs.sorted

  val min = (sorted.take(n-k+1) zip sorted.drop(k-1))
    .map({ case (a, b) => b - a})
    .min

  println(min)

}


import scala.io.{StdIn => in}

object Main extends App {
  val x = in.readInt

  val ans = if(x == 7 || x == 5 || x == 3) "YES" else "No"
  println(ans)
}

Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.


object Main {
  def main(args: Array[String]): Unit = {
    val nums     = scala.io.StdIn.readLine.split("")
    val like_num = 753
    var min_diff = 1000000
    for(i <- 0 until nums.length - 2) {
      val num = (nums(i) + nums(i + 1) + nums(i + 2)).toInt
      val diff = Math.abs(like_num - num)
      if( min_diff > diff) {
        min_diff = diff
      }
    }
    println(min_diff)
  }
}

Score : 200 points

Problem Statement

There is a string S consisting of digits 1, 2, ..., 9.
Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)

The master's favorite number is 753. The closer to this number, the better.
What is the minimum possible (absolute) difference between X and 753?

Constraints

S is a string of length between 4 and 10 (inclusive).

Each character in S is 1, 2, ..., or 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible difference between X and 753.

Sample Input 1

1234567876

Sample Output 1

34

Taking out the seventh to ninth characters results in X = 787, and the difference between this and 753 is 787 - 753 = 34. The difference cannot be made smaller, no matter where X is taken from.

Note that the digits cannot be rearranged. For example, taking out 567 and rearranging it to 765 is not allowed.

We cannot take out three digits that are not consecutive from S, either. For example, taking out the seventh digit 7, the ninth digit 7 and the tenth digit 6 to obtain 776 is not allowed.

Sample Input 2

35753

Sample Output 2

0

If 753 itself can be taken out, the answer is 0.

Sample Input 3

1111111111

Sample Output 3

642

No matter where X is taken from, X = 111, with the difference 753 - 111 = 642.


object Main extends App {
  val S = io.StdIn.readLine

  val out =S.sliding(3).map{ss => math.abs(753 - ss.mkString.toInt)}.min

  println(out)

}


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

    def add(a: mutable.Map[Int, Int], b: mutable.Map[Int, Int]): mutable.Map[Int, Int] = {
      val res = mutable.Map[Int, Int]().withDefaultValue(0)
      res ++= a
      b.foreach { case (f, cnt) => res(f) = res(f) + cnt }
      res
    }

    val factors = map(N - 1, 2) { i =>
      factorize(i)
    }.foldLeft(mutable.Map[Int, Int]())(add)

    val C = factors.values.toArray
    var ans = 0

    def count1(a: Int) = {
      C.count(_ >= a - 1)
    }

    // a < b
    def count2(a: Int, b: Int) = {
      val cb = C.count(_ >= b - 1)
      val ca = C.count(_ >= a - 1) - cb

      ca * cb + (if (cb > 1) cb * (cb - 1) else 0)
    }

    // a < b == c
    def count3(a: Int, b: Int) = {
      val cb = C.count(_ >= b - 1)
      val ca = C.count(_ >= a - 1) - cb

      var res = 0
      if (cb > 1) {
        res += ca * cb * (cb - 1) / 2
      }
      if (cb > 2) {
        res += cb * (cb - 1) * (cb - 2) / 2
      }
      res
    }

    ans += count1(75)
    ans += count2(5, 15)
    ans += count2(3, 25)
    ans += count3(3, 5)

    out.println(ans)
  }

  /**
    * *注意* IntをLongにして使わないこと
    */
  def factorize(n: Int): mutable.Map[Int, Int] = {
    import scala.collection.mutable
    val res = mutable.Map[Int, Int]() withDefaultValue 0

    def minFactor(n0: Int, rt: Int, i: Int): Int = {
      if (i > rt) n0 // √n まで見つからなかったら n0は素数か1
      else if (n0 % i == 0) i
      else minFactor(n0, rt, i + 1)
    }

    def step(n0: Int): Unit = {
      minFactor(n0, math.sqrt(n0).toInt, 2) match {
        case 1 =>
        case f =>
          res(f) = res(f) + 1
          step(n0 / f)
      }
    }

    step(n)
    res
  }

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

Problem Statement

You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?

Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.

Note

When a positive integer A divides a positive integer B, A is said to a divisor of B.
For example, 6 has four divisors: 1, 2, 3 and 6.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go numbers that are divisors of N!.

Sample Input 1

9

Sample Output 1

0

There are no Shichi-Go numbers among the divisors of 9! = 1 \times 2 \times ... \times 9 = 362880.

Sample Input 2

10

Sample Output 2

1

There is one Shichi-Go number among the divisors of 10! = 3628800: 32400.

Sample Input 3

100

Sample Output 3

543


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 S = ns(N)
    val Q = ni()
    val K = na(Q)

    val cumD, cumM, cumDM = Array.ofDim[Long](N + 1)
    rep(N) { i =>
      cumD(i + 1) = cumD(i) + (if(S(i) == 'D') 1 else 0)
      cumM(i + 1) = cumM(i) + (if(S(i) == 'M') 1 else 0)
      cumDM(i + 1) = cumDM(i) + (if(S(i) == 'M') cumD(i) else 0)
    }

    val C = {
      var p = 0
      rep(N) { i =>
        if (S(i) == 'C') p += 1
      }
      val res = Array.ofDim[Int](p)
      rep_r(N) { i =>
        if (S(i) == 'C') {
          p -= 1
          res(p) = i
        }
      }
      res
    }

    K.foreach { k =>
      var ans = 0L
      rep(C.length) { i =>
        val c = C(i)
        val dm = if (c >= k) {
          val d = cumD(c - k + 1)
          val m = cumM(c + 1) - cumM(c - k + 1)
          cumDM(c + 1) -  cumDM(c - k + 1) - d * m
        } else {
          cumDM(c + 1)
        }
        ans += dm
      }
      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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

Score : 600 points

Problem Statement

In Dwango Co., Ltd., there is a content distribution system named 'Dwango Media Cluster', and it is called 'DMC' for short.

The name 'DMC' sounds cool for Niwango-kun, so he starts to define DMC-ness of a string.

Given a string S of length N and an integer k (k \geq 3),
he defines the k-DMC number of S as the number of triples (a, b, c) of integers that satisfy the following conditions:

0 \leq a < b < c \leq N - 1

S[a] = D

S[b] = M

S[c] = C

c-a < k

Here S[a] is the a-th character of the string S. Indexing is zero-based, that is, 0 \leq a \leq N - 1 holds.

For a string S and Q integers k_0, k_1, ..., k_{Q-1}, calculate the k_i-DMC number of S for each i (0 \leq i \leq Q-1).

Constraints

3 \leq N \leq 10^6

S consists of uppercase English letters

1 \leq Q \leq 75

3 \leq k_i \leq N

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

N
S
Q
k_{0} k_{1} ... k_{Q-1}

Output

Print Q lines.
The i-th line should contain the k_i-DMC number of the string S.

Sample Input 1

18
DWANGOMEDIACLUSTER
1
18

Sample Output 1

1

(a,b,c) = (0, 6, 11) satisfies the conditions.

Strangely, Dwango Media Cluster does not have so much DMC-ness by his definition.

Sample Input 2

18
DDDDDDMMMMMCCCCCCC
1
18

Sample Output 2

210

The number of triples can be calculated as 6\times 5\times 7.

Sample Input 3

54
DIALUPWIDEAREANETWORKGAMINGOPERATIONCORPORATIONLIMITED
3
20 30 40

Sample Output 3

0
1
2

(a, b, c) = (0, 23, 36), (8, 23, 36) satisfy the conditions except the last one, namely, c-a < k_i.

By the way, DWANGO is an acronym for "Dial-up Wide Area Network Gaming Operation".

Sample Output 4

30
DMCDMCDMCDMCDMCDMCDMCDMCDMCDMC
4
5 10 15 20

Sample Output 4

10
52
110
140


object Main extends App {
  import scala.io.StdIn.{readInt, readLine}

  val elevationRate = 0.006
  def averageTemperature(T: Double)(elevation: Int) : Double = T - elevation * elevationRate

  val _ = readInt()
  val Array(t, a) = readLine().split(' ').map(_.toInt)
  val elevations = readLine().split(' ').map(_.toInt)

  val distancesFromA = elevations.map(averageTemperature(t)(_) - a)

  println(distancesFromA.zipWithIndex.minBy(_._1.abs)._2 + 1)
}

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 extends App {
  val sc = new java.util.Scanner(System.in)
  val N, T, A = sc.nextInt()
  val Hs = List.fill(N)(sc.nextInt())
  val (_, index) :: _ = Hs.zipWithIndex.sortBy { case (h, _) => (A - T + h * 0.006).abs }
  println(index + 1)
}


import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val _ = in.readLine().toInt
    val Array(t, a) = in.readLine().split("\\s+").map(_.toInt)
    val hs = in.readLine().split("\\s+").map(_.toInt)

    val tm = t * 1000
    val am = a * 1000
    out.println(hs.map(h => Math.abs(tm - h * 6 - am)).zipWithIndex.minBy(_._1)._2 + 1)

    out.flush()
  }
}


object Main {

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

    case class City(i: Int, year: Int)
    val prefectures = Array.fill(N+1)(
      new scala.collection.mutable.PriorityQueue[City]()(
        Ordering.by[City, Int](c => c.year)(Ordering.Int.reverse)))
    val result = new Array[String](M)

    (0 until M) foreach { i =>
      val p, y = sc.nextInt()
      prefectures(p).enqueue(City(i, y))
    }

    val format = (n: Int) => "%06d".format(n)

    (1 to N). foreach { p =>
      val prefecture = prefectures(p)
      var i = 1
      while (prefecture.nonEmpty) {
        val city = prefecture.dequeue()
        result(city.i) = s"${format(p)}${format(i)}"
        i += 1
      }
    }

    println(result.mkString("\n"))

  }

}

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 {
	case class Town(val p: Int, val y: Long)

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

 	val pN = new Array[Int](n)
 	val id = new Array[Long](m)

 	val towns = {for(i<-0 until m) yield{
 		val Array(p, y) = scala.io.StdIn.readLine.split(" ")
 		Town(p.toInt, y.toLong)
 	}}.zipWithIndex.sortBy(_._1.y)

 	for((t, i) <- towns){
 		pN(t.p - 1) += 1
 		id(i) = 1000000000000L + t.p*1000000L + pN(t.p - 1)
 	}

 	id.foreach{z => println(z.toString.takeRight(12))}
}


object Main extends App {
  val lines = io.Source.stdin.getLines.toIndexedSeq
  //val N = lines.head.split(' ').map(_.toInt).head
  //val accs = (0 until N).toArray.map(_=>0)
  val line = lines.tail.zipWithIndex.map{ case (e, gi) =>
    val tmp = e.split(' ').map(_.toInt).toArray
    (tmp(0), (tmp(1), gi))
  }
  val maxgi=line.size
  var idMap=Map[Int, String]()
  val groupByP = line.groupBy(_._1).foreach{ case (pgr, ylist) =>
   	ylist.sortBy(_._2).zipWithIndex.foreach{ case (yi, yindex) =>
      val gi = yi._2._2
      val id = "%06d%06d".format(pgr, (yindex+1))
      //println(gi, id)
      idMap = idMap + (gi -> id)
    }
  }
  (0 until maxgi).foreach(i => println(idMap(i)))
}


object Main extends App {

  val (n, m) = readLine.split(" ").map(_.toInt) match {
    case Array(n, m) => (n, m)
  }

  val lines: Seq[(Int, Int)] = (1 to m)
    .map(_ =>
      readLine.split(" ").map(_.toInt) match {
        case Array(p, y) => (p, y)
      })

  val map: Map[Int, Map[Int, Int]] =
    lines
      .groupBy(_._1)
      .mapValues(
        _.sortBy(_._2).zipWithIndex.map {
          case ((p, y), index) => (y, index + 1)
        }.toMap
      )

  def convert(p: Int, order: Int) = f"${p}%06d${order}%06d"
  val pw = new java.io.PrintWriter(System.out)
  lines.map { case (p, y) => convert(p, map(p)(y)) }.foreach{ res =>
    pw.println(res)
  }
  pw.flush
}


object Main extends App {
  val (n, m) = readLine.split(" ").map(_.toInt) match {
    case Array(n, m) => (n, m)
  }

  def convert(p: Int, order: Int) = f"${p}%06d${order}%06d"

  val lines: Array[Array[Int]] = (1 to m).toArray.map(id =>
    readLine.split(" ").map(_.toInt) match { case Array(p, y) => Array(id, p, y) })

  def order(a1: Array[Int], a2: Array[Int]): Boolean =
    if (a1(1) == a1(1)) a1(2) < a1(2) else a1(1) < a1(1)

  var currentP = 0
  var currentIndex = 1

  def next(a: Array[Int]) = {
    if (a(1) == currentP) currentIndex = currentIndex + 1 else {
      currentIndex = 1
      currentP = a(1)
    }
    Array(a(0), a(1), currentIndex)
  }

  lines
    .sortWith(order)
    .map(next)
    .sortBy(_(0))
    .foreach(a => println(convert(a(1), a(2))))

}


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 H, W = in.next().toInt
  val s = new Array[String](H)
  for (i <- 0 until H) {
    s(i) = in.next()
  }

  //
  def manhattan(p1: (Int, Int), p2: (Int, Int)): Int = {
    val (x1, y1) = p1
    val (x2, y2) = p2

    (x1 - x2).abs + (y1 - y2).abs
  }

  var pairs: List[(Int, Int)] = Nil

  for(y <- 0 until H; x <- 0 until W) {
    if(s(y)(x) == '#') {
      pairs = (x+1, y+1) :: pairs
    }
  }

  var ans = 0

  val ar = pairs.toArray
  val l = ar.length
  for(i <- 0 until l-1) {
    for(k <- i+1 until l) {
      val dist = manhattan(ar(i), ar(k))
      for(m <- k+1 until l) {
        if(manhattan(ar(i), ar(m)) == dist && manhattan(ar(k), ar(m)) == dist)
          ans += 1
      }
    }
  }
  println(ans)
}

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

Score : 700 points

Problem Statement

There are some coins in the xy-plane.
The positions of the coins are represented by a grid of characters with H rows and W columns.
If the character at the i-th row and j-th column, s_{ij}, is #, there is one coin at point (i,j); if that character is ., there is no coin at point (i,j). There are no other coins in the xy-plane.

There is no coin at point (x,y) where 1\leq i\leq H,1\leq j\leq W does not hold.
There is also no coin at point (x,y) where x or y (or both) is not an integer.
Additionally, two or more coins never exist at the same point.

Find the number of triples of different coins that satisfy the following condition:

Choosing any two of the three coins would result in the same Manhattan distance between the points where they exist.

Here, the Manhattan distance between points (x,y) and (x',y') is |x-x'|+|y-y'|.
Two triples are considered the same if the only difference between them is the order of the coins.

Constraints

1 \leq H,W \leq 300

s_{ij} is # or ..

Input

Input is given from Standard Input in the following format:

H W
s_{11}...s_{1W}
:
s_{H1}...s_{HW}

Output

Print the number of triples that satisfy the condition.

Sample Input 1

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

Sample Output 1

3

((1,1),(1,3),(2,2)),((1,1),(2,2),(3,1)) and ((1,3),(3,1),(4,4)) satisfy the condition.

Sample Input 2

13 27
......#.........#.......#..
#############...#.....###..
..............#####...##...
...#######......#...#######
...#.....#.....###...#...#.
...#######....#.#.#.#.###.#
..............#.#.#...#.#..
#############.#.#.#...###..
#...........#...#...#######
#..#######..#...#...#.....#
#..#.....#..#...#...#.###.#
#..#######..#...#...#.#.#.#
#..........##...#...#.#####

Sample Output 2

870


object Main{
  def main(args:Array[String]):Unit={
    var MN = readLine
    var S = readLine
    var T = readLine
    var res = new calculate(S,T)

    println(res.calculate())

  }
}

import scala.collection.mutable.ArrayBuffer

class calculate(s:String,t:String){
  var lens = s.length
  var lent = t.length

   def calculate():Int={
    var lcm = getLCM()
    var res = lcm

    var record:Map[Int,String] = Map()

    for(i <- 0 until lens){
      var temp = i*(lcm/lens)+1
      record += (temp -> s.charAt(i).toString)
    }
    var flag = true
    for(i <- 0 until lent if flag){
      var temp = i*(lcm/lent)+1
      var tempRecord = record.getOrElse(temp,"0")
      if(!tempRecord.equals("0") && !tempRecord.equals(t.charAt(i).toString)){
        flag = false
        res = -1
      }
    }
    res
  }

  def getLCM():Int={
    return lens*lent/getGCD
  }

  def getGCD():Int={
    var tempN = lens
    var tempM = lent
    var c = lens % lent
    while(c!=0){
      tempN = tempM
      tempM = c
      c = tempN % tempM
    }
    return tempM
  }
}

Score : 300 points

Problem Statement

You are given a string S of length N and another string T of length M.
These strings consist of lowercase English letters.

A string X is called a good string when the following conditions are all met:

Let L be the length of X. L is divisible by both N and M.

Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \frac{L}{N}+1)-th, ..., ((N-1)\times\frac{L}{N}+1)-th characters of X, without changing the order, results in S.

Concatenating the 1-st, (\frac{L}{M}+1)-th, (2 \times \frac{L}{M}+1)-th, ..., ((M-1)\times\frac{L}{M}+1)-th characters of X, without changing the order, results in T.

Determine if there exists a good string. If it exists, find the length of the shortest such string.

Constraints

1 \leq N,M \leq 10^5

S and T consist of lowercase English letters.

|S|=N

|T|=M

Input

Input is given from Standard Input in the following format:

N M
S
T

Output

If a good string does not exist, print -1; if it exists, print the length of the shortest such string.

Sample Input 1

3 2
acp
ae

Sample Output 1

6

For example, the string accept is a good string.
There is no good string shorter than this, so the answer is 6.

Sample Input 2

6 3
abcdef
abc

Sample Output 2

-1

Sample Input 3

15 9
dnsusrayukuaiia
dujrunuma

Sample Output 3

45


object Main extends App {
    val i = scala.io.StdIn.readLine().toInt

    if (i == 1){
      println("Hello World")
    } else {
      val a = scala.io.StdIn.readLine().toInt
      val b = scala.io.StdIn.readLine().toInt
      println(a+b)
    }
}

Score: 100 points

Problem Statement

In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.

One day, there was an exam where a one-year-old child must write a program that prints Hello World, and a two-year-old child must write a program that receives integers A, B and prints A+B.

Takahashi, who is taking this exam, suddenly forgets his age.

He decides to write a program that first receives his age N (1 or 2) as input, then prints Hello World if N=1, and additionally receives integers A, B and prints A+B if N=2.

Write this program for him.

Constraints

N is 1 or 2.

A is an integer between 1 and 9 (inclusive).

B is an integer between 1 and 9 (inclusive).

Input

Input is given from Standard Input in one of the following formats:

1

2
A
B

Output

If N=1, print Hello World; if N=2, print A+B.

Sample Input 1

1

Sample Output 1

Hello World

As N=1, Takahashi is one year old. Thus, we should print Hello World.

Sample Input 2

2
3
5

Sample Output 2

8

As N=2, Takahashi is two years old. Thus, we should print A+B, which is 8 since A=3 and B=5.


object Main extends App {

  val age = io.StdIn.readLine.toInt

  val out = age match {
    case 1 => "Hello World"
    case 2 => {
      val A = io.StdIn.readLine.toInt
      val B = io.StdIn.readLine.toInt
      (A + B).toString
    }
  }

  println(out)
}


object Main extends App{
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  println (
    if (N==1) "Hello World"
    else {
      val A,B = sc.nextInt()
      A+B
    }
  )
}


import java.util.Scanner

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

    N match {
      case 1 => "Hello World"
      case 2 => Array.fill(2)(sc.nextInt).sum.toString
    }
  }
}


object Main {
  def main(args:Array[String]) {
	val age = scala.io.StdIn.readInt

	if(age == 1) {
	  println("Hello World")
	}
	else if(age == 2) {
      println(scala.io.StdIn.readInt + scala.io.StdIn.readInt)
	}
  }
}


object Main extends App {
  val Array(n, t) = readLine.split(" ").map(_.toInt)
  val cts = for (_ <- 1 to n) yield {
    val Array(c, t) = readLine.split(" ").map(_.toInt)
    (c, t)
  }

  val filteredCts = cts.filter(ct => {
    val c_ = ct._1
    val t_ = ct._2
    t_ <= t
  })
  val ans =
    if (filteredCts.isEmpty) "TLE"
    else filteredCts.minBy(ct => ct._1)._1

  println(ans)
}

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5


object Main extends App {
  val NT = io.StdIn.readLine.split(' ').map(_.toInt)
  val N = NT.head
  val T = NT.last
  val cts = (1 to N).map(i => io.StdIn.readLine.split(' ').map(_.toInt))

  val candidates = cts.filter(cti => cti(1) <= T)

  val out = if (candidates.isEmpty) "TLE" else candidates.map(_.head).min

  println(out)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N,T = sc.nextInt()
  val a = List.fill(N,2)(sc.nextInt()) filter (_(1)<=T)
  println(
    if(a==Nil) "TLE"
    else a.sortBy(_.head).head.head
  )
}


import scala.io.StdIn
object Main extends App {
  val Seq(n, t) : Seq[Int] = StdIn.readLine.split(" ").map(_.toInt)
  val cts = Range(0, n)
    .map(_ => (StdIn.readLine.split(" ").map(_.toInt)))
    .map(s => (s(0), s(1)))
  println(cts.sorted.find(_._2 <= t).map(_._1.toString).getOrElse("TLE"))
}


object Main{
  def main(args:Array[String]):Unit={
    var nm = readLine.split(" ").map(x => x.toInt)
    var n = nm(0)
    var m = nm(1)
    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 extends App {
	val n = scala.io.StdIn.readInt
	println(1110-n)
}

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


import scala.io.StdIn

object Main {
    def main(args: Array[String]) = {
        StdIn.readLine()
        val a = StdIn.readLine().split(" ").toList.map { str: String => str.toInt }

        def getAlternateIndex(intList: List[Int], result: List[Int] = Nil): List[Int] = intList match {
                case Nil => result.reverse
                case int :: tail => getAlternateIndex(tail.drop(1), int :: result)
        }

        val even = getAlternateIndex(a)
        val odd  = getAlternateIndex(a.drop(1))

        def makeMap(key: Set[Int], value: List[Int], map: Map[Int, Int] = Map.empty[Int, Int]): Map[Int, Int] = {
            key.toList match {
                case Nil => map
                case k :: tail => makeMap(tail.toSet, value.filter { v: Int => k != v }, map + (k -> value.count { v: Int => k == v }))
            }
        }

        val evenMap = makeMap(even.toSet, even)
        val oddMap = makeMap(odd.toSet, odd)

        val evenMax = evenMap.maxBy(item => item._2)
        val oddMax  = oddMap.maxBy(item => item._2)

        var evenMaxVal = evenMax._2
        var oddMaxVal  = oddMax._2

        val evenMaxKey = evenMax._1
        val oddMaxKey  = oddMax._1

        var count = even.toSet.size + odd.toSet.size match {
            case x: Int if x < 2 => 0
            case _ =>
                if (evenMaxKey == oddMaxKey) {
                    {
                        if (evenMaxVal < oddMaxVal) {
                            var t = makeMap(even.filter { num: Int => num != oddMaxKey }.toSet, even.filter { num: Int => num != oddMaxKey })
                            evenMaxVal = {
                                if (t == Map.empty) {
                                   0
                                } else {
                                   t.maxBy(item => item._2)._2
                                }
                            }
                        } else {
                            var t = makeMap(odd.filter { num: Int => num != evenMaxKey }.toSet, even.filter { num: Int => num != evenMaxKey })
                            evenMaxVal = {
                                if (t == Map.empty) {
                                    0
                                } else {
                                    t.maxBy(item => item._2)._2
                                }
                            }
                        }
                    }
                }
                even.size - evenMaxVal + odd.size - oddMaxVal
        }
        println(count)
    }
}


object Main extends App {
  val s = new java.util.Scanner(System.in).next
  val m = Map('1' -> '9', '9' -> '1')
  println(s.map(m(_)))
}


object Main extends App{
    import scala.io.StdIn._
    import scala.math.ceil
    val n:Double = readLine().toInt

    println((ceil(n/111)*111).toInt)
}

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{
	def main(args:Array[String]):Unit={
      var input = readLine
      var record:Map[Int,Int] = Map()
      for(i <- input){
        var tmp = i.toString.toInt
        var r = record.getOrElse(tmp,0)
        r+=1
        record+=(tmp -> r)
      }
      var keys = record.keySet.toArray.sorted.reverse
      var flag = true
      var res = ""
      if(keys.length==1){
        for(i <- 0 until 3) res += keys(0).toString
        flag = false
      }
      for(k <- 0 until keys.length if flag){
        if(k==0 && input.charAt(0).toString.toInt==keys(k)){
          for(i <- 0 until 3) res += keys(0).toString
          flag = false
        }
        if(keys(k)==input.charAt(0).toString.toInt){
          for(i <- 0 until 3) res += keys(k-1).toString
          flag = false
        }
      }
      println(res)

    }
}


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


object Main extends App {
	val n : Int = scala.io.StdIn.readInt
    val xxx : Seq[Int] = Range(111,1110,111).toSeq
	println(xxx.find(_ > n).get)
}


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

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

  val map1 = mu.HashMap.empty[Int,Int]
  val map2 = mu.HashMap.empty[Int,Int]
  val set = mu.HashSet.empty[Int]
  for(i <- 0 until n) {
    set += seq(i)
    if(i % 2 == 0) map1.addOrUpdate(seq(i), 1)
    else map2.addOrUpdate(seq(i), 1)
  }

  val max1 = map1.values.max
  val max2 = map2.values.max
  val res1 = (n / 2) - max1
  val res2 = (n - (n / 2)) - max2
  // println(map1.mkString(" "))
  // println(map2.mkString(" "))
  // println(res1 + " " + res2)

  val ans = if(set.size == 1) n / 2 else res1 + res2
  println(ans)

  object MapHelper {
    implicit class AddOrUpdate[A](map:mu.HashMap[Int,Int]) {
      def addOrUpdate(key:Int, value:Int):mu.HashMap[Int,Int] =
      {
        if(map.contains(key)) map(key) += value
        else map += (key -> value)
        map
      }
    }
  }
}

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]){
    val sc=new java.util.Scanner(System.in)
    val n=sc.nextInt()
    val std=mysprit(n,sc).map(x=>(List(0,0)::mysort(x,Nil))).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.sorted match{
      case Nil => r
      case x::xs => {
        val n = xs.indexWhere(_!=x)
        mysort(xs.drop(n), (x :: n+1 :: 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 scala.io.StdIn

object Main {
    def main(args: Array[String]) = {
        StdIn.readLine()
        val a = StdIn.readLine().split(" ").toList.map { str: String => str.toInt }

        def getAlternateIndex(intList: List[Int], result: List[Int] = Nil): List[Int] = intList match {
                case Nil => result.reverse
                case int :: tail => getAlternateIndex(tail.drop(1), int :: result)
        }

        val evenA = getAlternateIndex(a)
        val oddA  = getAlternateIndex(a.drop(1))

        println(evenA.toSet.size-1 + oddA.toSet.size-1 match {
            case x: Int if x < 0 => 0
            case x: Int if (evenA ::: oddA).toSet.size == 1 => evenA.size
        })
    }
}


object Main {
  import java.util.Scanner

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

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

  def solve(implicit sc: Scanner): Unit = {
    val s = readLineStrings(sc)(0).toList.map(_ == '1').toArray
    val n = s.length
    if (!s.head || s.last) {
      println(-1)
      return
    }
    if (!(0 to (n - 2)).forall(i => s(i) == s(n - 2 - i))) {
      println(-1)
      return
    }
    var nodeIndex = 1
    while (nodeIndex < n - 1) {
      if (s(nodeIndex)) {
        println(s"$nodeIndex ${nodeIndex + 1}")
        nodeIndex += 1
      } else {
        var nextNodeIndex = nodeIndex
        while (!s(nextNodeIndex)) nextNodeIndex += 1
        nextNodeIndex += 1
        for (i <- nodeIndex until nextNodeIndex) {
          println(s"$i $nextNodeIndex")
        }
        nodeIndex = nextNodeIndex
      }
    }
    println(s"${n - 1} $n")
  }
}

Score : 700 points

Problem Statement

You are given a string s of length n.
Does a tree with n vertices that satisfies the following conditions exist?

The vertices are numbered 1,2,..., n.

The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.

If the i-th character in s is 1, we can have a connected component of size i by removing one edge from the tree.

If the i-th character in s is 0, we cannot have a connected component of size i by removing any one edge from the tree.

If such a tree exists, construct one such tree.

Constraints

2 \leq n \leq 10^5

s is a string of length n consisting of 0 and 1.

Input

Input is given from Standard Input in the following format:

s

Output

If a tree with n vertices that satisfies the conditions does not exist, print -1.

If a tree with n vertices that satisfies the conditions exist, print n-1 lines.
The i-th line should contain u_i and v_i with a space in between.
If there are multiple trees that satisfy the conditions, any such tree will be accepted.

Sample Input 1

1111

Sample Output 1

-1

It is impossible to have a connected component of size n after removing one edge from a tree with n vertices.

Sample Input 2

1110

Sample Output 2

1 2
2 3
3 4

If Edge 1 or Edge 3 is removed, we will have a connected component of size 1 and another of size 3. If Edge 2 is removed, we will have two connected components, each of size 2.

Sample Input 3

1010

Sample Output 3

1 2
1 3
1 4

Removing any edge will result in a connected component of size 1 and another of size 3.


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  var n = sc.nextInt()
  var x = sc.nextInt()
  sc.useDelimiter("\n")
  val a = sc.next().split(" ").map(_.toInt).toList.sorted
  var i = 0
  var ans = 0
  for (i <- 0 until n) {
    if (a(i) <= x) {
      ans += 1
      x -= a(i)
    }
  }
  println(ans)
}

Score : 200 points

Problem Statement

There are N children, numbered 1, 2, ..., N.

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n, x = sc.nextInt()
    val kids = List.fill(n)(sc.nextInt()).sorted.scan(0)((a, b) => a + b)
    val a = kids.takeWhile(_ <= x).length
//    println(kids, a)
    System.err.println("hahaha")
    a match {
      case 1                     => println(0)
      case m if kids(m - 1) == x => println(m)
      case m if m == kids.length => println(m - 2)
      case m                     => println(m - 1)
    }
  }
}