object Main extends App {
  var count = readLong
  var a = List(readLong,readLong,readLong,readLong,readLong)
  if(count % a.min != 0)
  	println(count / a.min + 5)
  else
  	println(count / a.min + 4)
}

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

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


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.nextLong
    val ABCDE = Array.fill(5)(sc.nextInt)

    val min = ABCDE.min
    val minIdx = ABCDE.indexOf(min)
    val a = ((N + (min - 1)) / min) + (4 - minIdx) + minIdx
    a.toString
  }
}

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

Submitted source-code file size, in bytes.

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

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


import scala.collection.mutable.ArrayBuffer

object Scanner {
  private val buf = new Array[Byte](1024);
  private var ptr = 0;
  private var len = 0

  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126

  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) {
      ptr = 0; len = System.in.read(buf); len > 0
    } else {
      true
    }

  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }

  @inline private def readByte(): Byte =
    if (hasNextByte()) {
      val res = buf(ptr); ptr += 1; res
    } else {
      -1
    }

  def next(): String = {
    if (!hasNext()) ???
    val sb = new StringBuilder;
    var b = readByte()
    while (isPrintableChar(b)) {
      sb.append(b.toChar); b = readByte()
    }
    sb.toString
  }

  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }

  def nextLong(): Long = {
    if (!hasNext()) ???
    var minus = false;
    var b = readByte()
    if (b == '-') {
      minus = true; b = readByte()
    }

    def go(b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') {
        go(readByte(), n * 10 + b - '0')
      }
      else if (minus) {
        -n
      } else {
        n
      }

    go(b)
  }

  def nextDouble(): Double = next.toDouble
}

object Main extends App {
  val x = Scanner.nextInt()
  val y = Scanner.nextInt()
  val z = Scanner.nextInt()
  val k = Scanner.nextInt()

  val a = Array.fill(x)(Scanner.nextLong()).sorted.reverse
  val b = Array.fill(y)(Scanner.nextLong()).sorted.reverse
  val c = Array.fill(z)(Scanner.nextLong()).sorted.reverse

  val input = Array(a,b,c).sortBy(_.length).reverse

  var i1 = 0
  var i2 = 0
  var i0 = 0

  var answerArray = new ArrayBuffer[Long]
  var min = Long.MaxValue

  while(i0<input(0).length){
    val sum = input(0)(i0)+input(1)(i1)+input(2)(i2)
    if (answerArray.length<k){
      answerArray = answerArray :+ sum
      if (sum < min) {
        min = sum
      }
      i2 = i2 + 1
    } else if ( min < sum ) {
      answerArray(answerArray.zipWithIndex.minBy(_._1)._2) = sum
      min = answerArray.min
      i2 = i2 + 1
    } else {
      i2 = 0
      i1 = i1 + 1
    }
    if (i2>=input(2).length){
      i2 = 0
      i1 = i1 + 1
    }
    if (i1>=input(1).length){
      i1 = 0
      i0 = i0 + 1
    }
  }
  answerArray = answerArray.sortBy(_*(-1))
  val pw = new java.io.PrintWriter(System.out)
  answerArray.foreach(i=>pw.println(i))
  pw.flush()
}

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

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


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

object Main extends App {
  val Array(n, q) = in.readLine.split(" ").map(_.toInt)
  val s = in.readLine
  val op = Iterator.continually(in.readLine)
    .take(q)
    .map(_.split(' ').map(_.head))
    .toArray

  def evalute(pos:Int):Int = {
    def rec(pos:Int, cnt:Int):Int = {
      if(pos < 0 || n <= pos || cnt == q) pos match{
        case p if p < 0 => 0
        case p if 0 <= p && p < n => 1
        case p if n <= p => 2
      }
      else if(s(pos) == op(cnt)(0)) {
        if(op(cnt)(1) == 'L') rec(pos-1, cnt+1)
        else rec(pos+1, cnt+1)
      }
      else rec(pos, cnt+1)
    }
    rec(pos,0)
  }

  def binarySearch(x:Int):Int = {
    var left = 0
    var right = n

    @tailrec
    def loop(left:Int, right:Int):Int = {
      if(right - left < 2) left
      else {
        val mid = (left + right) / 2
        if(evalute(mid) <= x) loop(mid,right)
        else loop(left, mid)
      }
    }
    loop(left, right)
  }

  val l = binarySearch(0)
  val r = binarySearch(1)
  debug(l,r)
  val ans = r - l
  println(ans)

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

Score : 500 points

Problem Statement

There are N squares numbered 1 to N from left to right.
Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.

Snuke cast Q spells to move the golems.

The i-th spell consisted of two characters t_i and d_i, where d_i is L or R.
When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is L, and moved to the square adjacent to the right if d_i is R.

However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.

Find the number of golems remaining after Snuke cast the Q spells.

Constraints

1 \leq N,Q \leq 2 \times 10^{5}

|s| = N

s_i and t_i are uppercase English letters.

d_i is L or R.

Input

Input is given from Standard Input in the following format:

N Q
s
t_1 d_1
\vdots
t_{Q} d_Q

Output

Print the answer.

Sample Input 1

3 4
ABC
A L
B L
B R
A R

Sample Output 1

2

Initially, there is one golem on each square.

In the first spell, the golem on Square 1 tries to move left and disappears.

In the second spell, the golem on Square 2 moves left.

In the third spell, no golem moves.

In the fourth spell, the golem on Square 1 moves right.

After the four spells are cast, there is one golem on Square 2 and one golem on Square 3, for a total of two golems remaining.

Sample Input 2

8 3
AABCBDBA
A L
B R
A R

Sample Output 2

5

After the three spells are cast, there is one golem on Square 2, two golems on Square 4 and two golems on Square 6, for a total of five golems remaining.

Note that a single spell may move multiple golems.

Sample Input 3

10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L

Sample Output 3

3


import java.util.Scanner

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

    if (b == "A") {
      println("T")
      return
    }
    if (b == "C") {
      println("G")
      return
    }
    if (b == "G") {
      println("C")
      return
    }
    println("A")
  }
}

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


class Main {
  def main(args: Array[String]): Unit = {
    val out = io.StdIn.readLine.map {
      _.toString count {
          Set('A', 'C', 'G', 'T').contains(_)
        }
    }
    println(out.head)
  }
}


import scala.io.StdIn

object Main extends App {
  val Array(n, q) = StdIn.readLine().split(" ").map(_.toInt)
  val s = StdIn.readLine()
  val lrs = for {
    _ <- 0 until q
  } yield {
    val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)

    (l, r)
  }

  lrs
    .map { case (l, r) =>
      "AC".r.findAllIn(s.substring(l - 1, r)).size
    }
    .foreach(println)
}

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


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

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val N = sc.nextInt
    val Q = sc.nextInt
    val S = sc.next
    val list = Array.fill(Q, 2)(sc.nextInt)

    list.foreach{ case Array(l, r) =>
        val sub = S.substring(l-1, r)
        var count = 0
        for (i <- 0 until sub.length - 1) {
          val l: String = sub.charAt(i).toString + sub.charAt(i + 1).toString
          if(l == "AC"){
            count = count + 1
          }
        }
        println(count)
    }
  }
}


import java.util.Scanner

import scala.collection.mutable

object Main {

  case class ResidueRing(private val input: Long) {
    val representative: Long = ((input % ResidueRing.mod) + ResidueRing.mod) % ResidueRing.mod

    def +(that: ResidueRing): ResidueRing = ResidueRing(this.representative + that.representative)

    def -(that: ResidueRing): ResidueRing = ResidueRing(this.representative - that.representative)

    def *(that: ResidueRing): ResidueRing = ResidueRing(this.representative * that.representative)

    def unary_- : ResidueRing = ResidueRing(-this.representative)

  }

  object ResidueRing {
    val mod: Long = (1e9 + 7).toLong
    val _0: ResidueRing = ResidueRing(0)
    val _1: ResidueRing = ResidueRing(1)
  }

  def read() = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    n
  }

  def solve(n: Int): Long = {
    // 過去3文字分記憶しておけばいい
    val alphabets = "ATGC"
    val stateList: IndexedSeq[String] =
      for (c1 <- alphabets;
           c2 <- alphabets;
           c3 <- alphabets) yield IndexedSeq(c1, c2, c3).mkString

    def transition(state: String, alphabet: Char): Option[String] = {
      (state(0), state(1), state(2), alphabet) match {
        case (_, 'A', 'G', 'C')
             | (_, 'G', 'A', 'C')
             | (_, 'A', 'C', 'G')
             | ('A', _, 'G', 'C')
             | ('A', 'G', _, 'C') => None
        case _ => Some(IndexedSeq(state(1), state(2), alphabet).mkString)
      }
    }

    val mapAll0: mutable.Map[String, ResidueRing] = mutable.Map.empty
    for (state <- stateList) {
      mapAll0.+=((state, ResidueRing._0))
    }
    val dp: Array[mutable.Map[String, ResidueRing]] = Array.fill(n + 1)(mapAll0.clone)

    dp(0)("TTT") += ResidueRing._1
    for (i <- 0 until n) {
      for (state <- stateList) {
        for (alphabet <- alphabets) {
          val next = transition(state, alphabet)
          next match {
            case Some(nextState) => dp(i + 1)(nextState) += dp(i)(state)
            case None =>
          }

        }
      }
    }
    val result = dp.last.values.foldLeft(ResidueRing._0)(_ + _)
    result.representative
  }

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

Score : 400 points

Problem Statement

You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

61

There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

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


import java.util.Scanner

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

    val Array(totalH, totalW) = sc.nextLine.split(" ").map(_.toInt)
    val Array(h, w) = sc.nextLine.split(" ").map(_.toInt)
    val totalTiles: Int = totalH * totalW
    println(totalTiles - (h * totalW + w * totalH - h * w))
  }
}

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


object Main extends App {
  import scala.io.StdIn._
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val a = new Array[Long](n)
  val map = scala.collection.mutable.HashMap[Long,Long]()
  for(i <- (0 until(n))) {
    val Array(aa, bb) = readLine().split(" ").map(_.toInt)
    a(i) = aa
    map(aa) = if(map.contains(aa)) map(aa) + bb else bb
  }
  val aA = a.sorted
  var ans = 0L
  var ind = 0
  for(i <- (1 to m)){
    if(map(aA(ind)) == 0){
      ind += 1
    }
    ans += aA(ind)
    map(aA(ind)) -= 1
  }
  println(ans)
}

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

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


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    val Array(n, m) = sc.nextLine.split(" ").map(_.toInt)
    val sortedInput = List.fill(n, 2)(sc.nextLong).sortBy(_.head)

    @annotation.tailrec
    def go(m: Long, i: Int, acc: Long): Long = {
      if (m == 0) acc
      else {
        if (m > sortedInput(i)(1)) go(m - sortedInput(i)(1), i + 1, acc + sortedInput(i).head * sortedInput(i)(1))
        else go(0, 0, acc + m * sortedInput(i).head)
      }
    }

    println(go(m, 0, 0))

  }

}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val A, B, K = sc.nextInt()
  println(100.to(1, -1).filter(i => A % i == 0 && B % i == 0)(K - 1))
}

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


object Main extends App {

  val Seq(a,b,k) = scala.io.StdIn.readLine().map(_.toInt)

  def solve(): Int = {
    (1 to Math.min(a, b)).filter { i =>
      a % i == 0 && b % i == 0
    }reverse(k-1)
  }

  println(solve)

}


//import java.util.Scanner

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

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

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

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

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

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

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

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

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

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

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

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

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

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {
  def solve(sc: => Scanner): Unit = {
    val A, B, K = sc.nextInt()
    println(Util.getPermutation(1).take(math.max(A, B)).filter(i => A % i == 0 && B % i == 0).sorted.reverse(K - 1))
  }

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

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

  def recursive(sc: => Scanner, n: Long): Unit = {

  }

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

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

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

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

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

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

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

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

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

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

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

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

object ArabicRoman {

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

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

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

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

      convert(src)
  }

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

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

      convert(src.toUpperCase())
  }
}


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.map(_.split(' ').map(_.toInt).toIndexedSeq).head
  val A = ls(0)
  val B = ls(1)
  val K = ls(2)
  var count = 0
  var i=Math.min(A,B)
  while(count<K){
    if(A%i==0 && B%i==0) count+=1
    i-=1
  }
  val ret = i+1
  println(ret)
}


object Main extends App{
  val sc = new java.util.Scanner(System.in)
  val inputstring = sc.next
  val inputlist = List.tabulate(inputstring.size)(x=>{inputstring(x).toInt - 48})
  val count = inputlist.sum
  val ans = List(count,inputlist.size - count).min * 2
  println(ans)
}

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


object Main extends App {
  /* このあたりはmemoに初期値として登録しておく
   if (ss.length <= 1) {
          memo = memo + (ss -> ss)
          ss
        } else if (ss.length == 2) {
          if (ss == "01" || ss == "10") {
            memo = memo + (ss -> ss)
            ""
          } else {
            ss
          }
        }
   */
  var memo: Map[String, String] = Map("" -> "", "0" -> "0", "1" -> "1", "01" -> "", "10" -> "", "00" -> "00", "11" -> "11")

  val s = scala.io.StdIn.readLine

  def check(ss: String): String = {
    memo.get(ss) match {
      case Some(sss) => sss
      case None =>
        if (ss.forall(_ == '0') || ss.forall(_ == '1')) {
          memo = memo + (ss -> ss)
          return ss
        }

        var ans = ss
        (0 until ss.length - 1).foreach { i =>
          //  println(s"${s}: ${i}")
          if (ss(i) != ss(i + 1)) {
            val tmp = check(ss.substring(0, i) + ss.substring(i + 2))
            if (tmp.length < ans.length) {
              ans = tmp
            }
          }
        }
        memo = memo + (ss -> ans)

        ans

    }

  }

  println(s.length - check(s).length)
}


import java.util.Scanner

object Main {
  def read() = {
    val sc = new Scanner(System.in)
    val cubes = sc.next()
    cubes
  }

  def solve(cubes: String) :Int ={
    var cubesTest = cubes
    while(true){
      val beforeLen = cubesTest.length
      cubesTest = cubesTest.replace("01", "")
      cubesTest = cubesTest.replace("10", "")
      val afterLen = cubesTest.length
      if(beforeLen == afterLen) return cubes.length - afterLen
    }
    -1
  }

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


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n, m = sc.nextInt
  val bs = Array.fill(m)((sc.nextInt - 1, sc.nextInt - 1)).reverse
  val uf = new UnionFind(n)

  val result = bs.scanLeft(n.toLong * (n - 1) / 2){(z, b) =>
    if (uf.find(b._1) != uf.find(b._2)) {
      val inconvenience = uf.size(b._1).toLong * uf.size(b._2)
      uf.union(b._1, b._2)
      z - inconvenience
    } else z
  }.reverse.tail

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

class UnionFind(nodes: Int) {
  val parents = Array.tabulate(nodes)(identity)
  val sizes = Array.fill(nodes)(1)

  // @scala.annotation.tailrec
  /** @retrun (root, rank) */
  def findWithRank(x: Int, rank: Int = 0): (Int, Int) = {
    parents(x) match {
      case p if x == p => (p, rank)
      case p => {
        val (newRoot, newRank) = findWithRank(p, rank + 1)
        parents(x) = newRoot
        (newRoot, newRank)
      }
    }
  }

  def find(x: Int): Int = {
    parents(x) match {
      case p if x == p => p
      case p => {
        val newRoot = find(p)
        parents(x) = newRoot
        newRoot
      }
    }
  }

  def size(x: Int) = sizes(find(x))

  def union(x: Int, y: Int): Int = {
    val (xRoot, xRank) = findWithRank(x)
    val (yRoot, yRank) = findWithRank(y)
    val newRoot = if (xRank < yRank) yRoot else xRoot
    if (xRoot != yRoot) {
      parents(xRoot) = newRoot
      parents(yRoot) = newRoot
      sizes(newRoot) = sizes(xRoot) + sizes(yRoot)
    }
    parents(x) = newRoot
    parents(y) = newRoot
    newRoot
  }
}

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


object Main {

  class UnionFind(par: Array[Int]) {

    def union(x: Int, y: Int): Boolean = {
      val rx = root(x)
      val ry = root(y)
      if (rx != ry) {
        if (size(rx) < size(ry)) {
          par(ry) += par(rx)
          par(rx) = ry
        } else {
          par(rx) += par(ry)
          par(ry) = rx
        }
        true
      } else false
    }

    def root(x: Int): Int =
      if (par(x) < 0) x
      else {
        par(x) = root(par(x))
        par(x)
      }

    def size(x: Int): Int =
      -par(root(x))

  }

  object UnionFind {

    def apply(n: Int): UnionFind =
      new UnionFind(Array.fill(n)(-1))

  }

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

    val N, M = sc.nextInt()
    // 辺をつなぐ処理は簡単、しかし切り離す行為は簡単ではない

    case class Bridge(from: Int, to: Int)

    val Bridges = new Array[Bridge](M)
    (0 until M) foreach { i =>
      val a, b = sc.nextInt()
      Bridges(i) = Bridge(a-1, b-1)
    }

    // 全ての橋が壊れている状態
    // この時の不便さは？
    // 連結!
    // 繋いだ時, 始点から繋がっている数 * 終点から繋がっている数
    // BとCがもともと繋がっていた場合には（同じグループの場合には不便さは変わらない
    // BとCがもともと繋がっていない場合には、快適さが上がる。
    // この橋が落ちた時には, 片方のグループの島と, 片方のグループの島の組み合わせが断絶されることになるので
    // この組み合わせの数だけ不便になることになる。
    // つまり, 始点から繋がっている数 * 終点から繋がっている数
    val unionFind = UnionFind.apply(N)
    val res = new Array[Long](M)
    res(M-1) = N*(N-1)/2

    var i = M - 1
    while (i > 0) {
      val Bridge(a, b) = Bridges(i)
      if (unionFind.root(a) != unionFind.root(b)) {
        res(i-1) = res(i) - unionFind.size(a).toLong * unionFind.size(b).toLong
        unionFind.union(a, b)
      } else {
        res(i-1) = res(i)
      }
      i -= 1
    }

    println(res.mkString("\n"))
  }

}


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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val (from, to) = na2(M, -1)
    var cnt = N.toLong * (N - 1) / 2
    val uf = new UnionFind(N)
    val set = Array.ofDim[mutable.Set[Int]](N)
    REP(N) { i =>
      set(i) = mutable.Set(i)
    }

    debug(set.mkString(" "))

    def merge(id1: Int, id2: Int): mutable.Set[Int] = {
      val s1 = set(id1)
      val s2 = set(id2)
      if (s1.size > s2.size) {
        s1 ++= s2
        s1
      } else {
        s2 ++= s1
        s2
      }
    }

    val ans = ArrayBuffer[Long]()
    REP_r(M) { i =>
      ans += cnt

      val id1 = uf.find(from(i))
      val id2 = uf.find(to(i))

      if (id1 != id2) {
        cnt -= set(id1).size.toLong * set(id2).size
        val merged = merge(id1, id2)
        uf.unite(from(i), to(i))
        set(id1) = merged
      }
//      debug(set.mkString(" "))
    }

    ans.reverse.foreach(out.println)
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

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


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  println {
    List.fill(sc.nextInt())(sc.nextDouble() -> sc.next()).map {
      case (d, "BTC") => d * 380000.0
      case (d, _) => d
    }.sum
  }
}

Score : 200 points

Problem Statement

Takahashi received otoshidama (New Year's money gifts) from N of his relatives.

You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative.

For example, if x_1 = 10000 and u_1 = JPY, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = 0.10000000 and u_2 = BTC, the otoshidama from the second relative is 0.1 bitcoins.

If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?

Constraints

2 \leq N \leq 10

u_i = JPY or BTC.

If u_i = JPY, x_i is an integer such that 1 \leq x_i \leq 10^8.

If u_i = BTC, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).

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

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

The otoshidama from the first relative is 10000 yen. The otoshidama from the second relative is 0.1 bitcoins, which is worth 38000.0 yen if converted at the rate of 380000.0 JPY per 1.0 BTC. The sum of these is 48000.0 yen.

Outputs such as 48000 and 48000.1 will also be judged correct.

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

In this case, outputs such as 138001000 and 1.38e8 will also be judged correct.


import scala.math.abs
object Main extends App {
  val in = new java.util.Scanner(System.in)
  val n, A, B, C = in.nextInt
  val ls = Array.fill(n)(in.nextInt)

  def dfs(i: Int, a: Int, b: Int, c: Int): Int = {
    if (i == n) {
      if (a == 0 || b == 0 || c == 0) 100000000
      else abs(A - a) + abs(B - b) + abs(C -c) - 30
    } else {
      Array(
        dfs(i + 1, ls(i) + a, b, c) + 10,
        dfs(i + 1, a, ls(i) + b, c) + 10,
        dfs(i + 1, a, b, ls(i) + c) + 10,
        dfs(i + 1, a, b, c)).min
    }
  }

  println(dfs(0, 0, 0, 0))
}

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 {
  io.StdIn.readLine.split(" ").map(_.toInt) match {
    case Array(a, b) if b % a == 0 => println(a + b)
    case Array(a, b)               => println(b - a)
  }
}

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.


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val n = in.nextInt
  val as = Array.fill(n)(in.nextInt)
  def gcd(l: Int, r: Int): Int = if (r == 0) l else gcd(r, (l % r))
  println(as.reduceLeft(gcd))
}

Score : 300 points

Problem Statement

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

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


import scala.io.{StdIn => in}

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

  val dMin = ms./:(Int.MaxValue)((acc,i) => {
    val v = i % acc
    (math.min(acc, if(v!=0) v else acc))
  })

  // println(dMin)

  val res = if(dMin == 1) 1
    else ms./:(Int.MaxValue)((acc,i) => {
    val v = i % dMin
    val s = if(v != 0) v else acc
    math.min(acc,s)
  })

  val min = math.min(dMin,res)

  // println(min)

  val ans = math.min(ms.head,min)
  println(ans)
}


object Main {

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

    val N, M = sc.nextInt()
    val A = Array.fill(M)(sc.nextInt())
    val MatchOf = Array(0, 2, 5, 5, 4, 5, 6, 3, 7, 6)

    // i本のマッチ棒を使って作れる整数の中で最大のもの
    // 整数の中で最大のものは, 大きい数順に並べることになる
    // 明らかに, 既に付いている先頭の文字列よりも小さいものが来た場合
    // 最大になることはないので捨てる
    val dp = Array.fill(N+1)("")

    var i = 0
    while (i < M) {
      val matches = MatchOf(A(i))
      dp(matches) = "" + A(i)
      i += 1
    }

    i = 1
    while (i <= N) {
      if (dp(i).nonEmpty) {
        var j = 0
        while (j < M) {
          val matches = MatchOf(A(j))
          if (i + matches <= N) {
            val newValue = dp(i) + A(j)
            if (dp(i + matches).nonEmpty) {
              if (newValue.length == dp(i + matches).length) {
                if (newValue > dp(i + matches))
                  dp(i + matches) = newValue
              } else if (newValue.length > dp(i + matches).length) {
                dp(i + matches) = newValue
              }
            } else {
              dp(i + matches) = newValue
            }
          }
          j += 1
        }
      }
      i += 1
    }

    println(dp(N))
  }

}

Score : 400 points

Problem Statement

Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:

Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).

The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

There exists an integer that can be formed by exactly N matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

The output may not fit into a 64-bit integer type.

Sample Input 3

15 3
5 4 6

Sample Output 3

654


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

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

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

  //
  val map = Map(
    1 -> 2, 2 -> 5, 3 -> 5,
    4 -> 4, 5 -> 5, 6 -> 6,
    7 -> 3, 8 -> 7, 9 -> 6
  )

  val dp = new Array[Int](N+1)
  val init = -1
  for (i <- 0 to N)
    dp(i) = init

  dp(0) = 0
  for (i <- 1 to N) {
    for (e <- A) {
      val diff = i - map(e)
      if (diff >= 0) {
        if (dp(i) == 0)
          dp(i) = dp(diff) + 1
        else
          dp(i) = Math.max(dp(i), dp(diff) + 1)
      }
    }
  }

  var now = N
  var ans = ""
  while (now > 0) {
    breakable {
      for (i <- (1 to 9).reverse) {
        val diff = now - map(i)
        if (A.contains(i) && diff >= 0) {
          if (dp(diff) == dp(now) - 1) {
            now = diff
            ans += i.toString
            break
          }
        }
      }
    }
  }

  println(ans)
}

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


import scala.io.StdIn.readLine

object Main{
  def main(args : Array[String]): Unit ={
    val Array(n, m) : Array[Int] = readLine().split(' ').map(_.toInt)
    val can : Array[Int] = readLine().split(' ').map(_.toInt)
    val SLV = new SOLVE(n, can)
    println(SLV.solve(n))
  }
}

class SOLVE(private val n : Int, private val can : Array[Int]){
  val COST : Array[Int] = Array(0, 2, 5, 5, 4, 5, 6, 3, 7, 6)
  val DP : Array[BigInt] = Array.fill(n + 10)(-1)
  DP(0) = 0
  def solve(k : Int): BigInt ={
    if(DP(k) != -1) DP(k)
    else{
      for(ele <- can){
        val idx = k - COST(ele)
        if(idx >= 0) if(DP(k) < ele + 10 * solve(idx)) DP(k) = ele + 10 * solve(idx)
      }
    }
    DP(k)
  }
}


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

import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object Main {
  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  def get[T1, T2, T3, T4](
                           implicit in: BufferedReader,
                           converter1: String => T1,
                           converter2: String => T2,
                           converter3: String => T3,
                           converter4: String => T4
                         ): (T1, T2, T3, T4) = {
    getArray[String] match {
      case Array(v1, v2, v3, v4) => (converter1(v1), converter2(v2), converter3(v3), converter4(v4))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def primes(n: Long): ArrayBuffer[Long] = {
    val buf = ArrayBuffer.empty[Long]
    val s = Math.sqrt(n).toInt

    var v = n
    for (i <- 2 to s) {
      if (v == 1 || v == 0) {
        return buf
      } else {
        while (v % i == 0) {
          buf.append(i)
          v /= i
        }
      }
    }
    if (v > s) {
      buf.append(v)
    }
    buf
  }

  def divisors(n: Int): ArrayBuffer[Int] = {
    val buf = ArrayBuffer.empty[Int]
    val s = Math.sqrt(n).toInt

    for (i <- 1 to s) {
      if (n % i == 0) {
        buf.append(i)
        if (i != n / i) {
          buf.append(n / i)
        }
      }
    }
    buf
  }

  @tailrec
  def gcd(a: Long, b: Long): Long = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

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

  def toBitArray(n: Int, width: Int): Array[Boolean] = {
    val buf = ArrayBuffer.fill(width)(false)

    @tailrec
    def inner(n: Int, i: Int): Array[Boolean] = {
      buf(i) = (n & 1) == 0
      if (i == 0) {
        buf.toArray
      } else {
        inner(n / 2, i - 1)
      }
    }

    inner(n, width - 1)
  }

  def modpow(n: Long, p: Long, m: Long): Long = {
    @tailrec
    def inner(n: Long, p: Long, acc: Long): Long = {
      if (p == 0) {
        acc
      } else if ((p & 1) == 0) {
        inner(n * n % m, p >> 1, acc)
      } else {
        inner(n * n % m, p >> 1, acc * n % m)
      }
    }

    inner(n % m, p, 1)
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val (n, k) = get[Int, Int]

    out.println(
      if (n >= k * 2 - 1) {
        "YES"
      } else {
        "NO"
      }
    )

    out.flush()
  }
}

Score : 100 points

Problem Statement

Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.

Constraints

1\leq N,K\leq 100

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

If we can choose K integers as above, print YES; otherwise, print NO.

Sample Input 1

3 2

Sample Output 1

YES

We can choose 1 and 3.

Sample Input 2

5 5

Sample Output 2

NO

Sample Input 3

31 10

Sample Output 3

YES

Sample Input 4

10 90

Sample Output 4

NO


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val list = List.fill(n)(sc.nextInt)
    if(list.max < list.sum - list.max){
      println("Yes")
    }
    else{
      println("No")
    }
  }
}

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


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val n, m = in.nextInt
  val xs = Array.fill(m)(in.nextInt).sorted
  val spaces = xs.zip(xs.tail).map(s => s._2 - s._1)
  println(spaces.sorted.reverse.drop(n - 1).sum)
}

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

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

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

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

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

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

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

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

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

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

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

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

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

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

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {

  def solve(sc: => Scanner): Unit = {
    val N, M = sc.nextInt()
    println(if (N < M) Array.fill(M)(sc.nextLong()).sorted.sliding(2).map(a => a(1) - a(0)).toArray.sorted.reverse.drop(N - 1).sum else 0)
  }

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

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

  def recursive(A: Array[Long]): Long = {
    val B = A.dropWhile(x => x == 0)
    if (B.length == 0) 0 else {
      recursive(B.takeWhile(x => x != 0).map(i => i - 1)) + recursive(B.dropWhile(x => x != 0)) + 1
    }
  }

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

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

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

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

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

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

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

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

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

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

object ArabicRoman {

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

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

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

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

      convert(src)
  }

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

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

      convert(src.toUpperCase())
  }
}


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

  val Array(n, m) = readLine.trim.split(' ').map(_.toInt)
  val inEdgeCount = Array.tabulate(n){_ ⇒ 0}
  val edges = Array.tabulate(n){_ ⇒ Nil: List[Int]}
  for (_ ← 1 until n + m){
    val Array(a, b) = readLine.trim.split(' ').map(_.toInt - 1)
    inEdgeCount(b) += 1
    edges(a) ::= b
  }
  val root = inEdgeCount.indexWhere(_ == 0)
  println(bfs(root).mkString("\n"))
  def bfs(root: Int): Array[Int] = {
    val prevs = Array.tabulate(n){_ ⇒ 0}
    val queue = mutable.Queue[Int](root)
    while(queue.nonEmpty){
      val top = queue.dequeue()
      for (next ← edges(top)) {
        queue.enqueue(next)
        prevs(next) = top + 1
      }
    }
    prevs
  }
}

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


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

  val Array(n, m) = readLine.trim.split(' ').map(_.toInt)
  val vertexs = readLine.trim.split(' ').map(_.toLong)
  val union = vertexs.map(w ⇒ new UnionFindTree(w))
  val nodes = Array.tabulate(n){_ ⇒ Nil: List[(Int, Long)]}
  val edges = Array.tabulate(m){_ ⇒
    val Array(a, b, y) = readLine.trim.split(' ').map(_.toInt)
    nodes(a - 1) ::= (b - 1, y)
    nodes(b - 1) ::= (a - 1, y)
    Edge(a - 1, b - 1, y)
  }.sortBy(_.weight)
  val needNotRemove = Array.tabulate(m){_ ⇒ false}
  for (i ← edges.indices){
    union(edges(i).from).merge(union(edges(i).to))
    if (union(edges(i).from).weight >= edges(i).weight) {
      needNotRemove(i) = true
    }
  }
  val max = Array.tabulate(n){_ ⇒ 0L}
  val queue = mutable.Queue[Int]()
  for (i ← needNotRemove.indices if needNotRemove(i)){
    val weight = edges(i).weight
    if (max(edges(i).from) < weight) {
      queue.enqueue(edges(i).from)
      max(edges(i).from) = weight
      while (queue.nonEmpty) {
        val top = queue.dequeue()
        for ((to, w) ← nodes(top) if w <= weight && max(to) < weight) {
          max(to) = weight
          queue.enqueue(to)
        }
      }
    }
  }

  println(edges.count(e ⇒ max(e.from) < e.weight || max(e.to) < e.weight))

  case class Edge(from: Int, to: Int, weight: Long)
  class UnionFindTree(private var mWeight: Long){
    private var mParent: Option[UnionFindTree] = None
    private var mSize: Int = 1
    private def parent: UnionFindTree = {
      mParent.map{_.parent} match {
        case None ⇒ this
        case c@Some(p) ⇒
          mParent = c
          p
      }
    }
    def weight: Long = parent.mWeight
    def size: Int = parent.mSize
    def isTop: Boolean = mParent.isEmpty
    def isSameUnion(that: UnionFindTree): Boolean = {
      parent == that.parent
    }
    def merge(that: UnionFindTree): Unit = {
      if (!isSameUnion(that)){
        val p = parent
        val tp = that.parent
        if (p.mSize > tp.mSize){
          tp.mParent = Some(p)
          p.mSize += tp.mSize
          p.mWeight += tp.mWeight
        }else {
          p.mParent = Some(tp)
          tp.mSize += p.mSize
          tp.mWeight += p.mWeight
        }
      }
    }
  }
}

Score : 800 points

Problem Statement

There is a connected undirected graph with N vertices and M edges.
The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Also, each of these vertices and edges has a specified weight.
Vertex i has a weight of X_i; Edge i has a weight of Y_i and connects Vertex A_i and B_i.

We would like to remove zero or more edges so that the following condition is satisfied:

For each edge that is not removed, the sum of the weights of the vertices in the connected component containing that edge, is greater than or equal to the weight of that edge.

Find the minimum number of edges that need to be removed.

Constraints

1 \leq N \leq 10^5

N-1 \leq M \leq 10^5

1 \leq X_i \leq 10^9

1 \leq A_i < B_i \leq N

1 \leq Y_i \leq 10^9

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

The given graph is connected.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_N
A_1 B_1 Y_1
A_2 B_2 Y_2
:
A_M B_M Y_M

Output

Find the minimum number of edges that need to be removed.

Sample Input 1

4 4
2 3 5 7
1 2 7
1 3 9
2 3 12
3 4 18

Sample Output 1

2

Assume that we removed Edge 3 and 4.
In this case, the connected component containing Edge 1 contains Vertex 1, 2 and 3, and the sum of the weights of these vertices is 2+3+5=10.
The weight of Edge 1 is 7, so the condition is satisfied for Edge 1.
Similarly, it can be seen that the condition is also satisfied for Edge 2.
Thus, a graph satisfying the condition can be obtained by removing two edges.

The condition cannot be satisfied by removing one or less edges, so the answer is 2.

Sample Input 2

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

Sample Output 2

4

Sample Input 3

10 9
81 16 73 7 2 61 86 38 90 28
6 8 725
3 10 12
1 4 558
4 9 615
5 6 942
8 9 918
2 7 720
4 7 292
7 10 414

Sample Output 3

8


object Main extends App {
  var s = scala.io.StdIn.readInt()
  var seqInt = Seq(s)

  def nextJudge(i: Int): Unit = {
    var nextInt = 0
    if(i % 2 == 0) {
      nextInt = i / 2
    } else {
      nextInt = 3 * i + 1
    }
    seqInt.find(_ == nextInt).fold
      {seqInt :+= nextInt
       nextJudge(nextInt)
      }
      {_=> println(seqInt.size + 1)}
  }
  nextJudge(s)
}

Score : 200 points

Problem Statement

A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:

The first term s is given as input.

Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.

a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.

Find the minimum integer m that satisfies the following condition:

There exists an integer n such that a_m = a_n (m > n).

Constraints

1 \leq s \leq 100

All values in input are integers.

It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.

Sample Input 2

7

Sample Output 2

18

a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}.

Sample Input 3

54

Sample Output 3

114


import java.util.Scanner

import scala.annotation.tailrec

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

  val n = sc.nextInt
  val hl = Seq.fill(n)(sc.nextInt)

  val res = cntLoop(hl)
  println(res)

  @tailrec
  def cntLoop(list: Seq[Int] , cnt: Int = 0): Int = {
    if (list.forall(_ == 0) ) cnt
    else cntLoop(elementMinusOne(list), cnt + separate(list).size)
  }

  @tailrec
  def separate(list: Seq[Int], lists: Seq[Seq[Int]] = Seq.empty): Seq[Seq[Int]] = {
    list match {
      case Nil => lists
      case nonEmpty => {
        val target = nonEmpty.dropWhile(_ == 0)
        val (take, drop) = target.span(_ > 0)
        val next = drop.dropWhile(_ == 0)
        separate(next, lists :+ take)
      }
    }
  }

  def elementMinusOne(list: Seq[Int]): Seq[Int] = {
    list.map{
      case 0 => 0
      case e => e - 1
    }
  }
}

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


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 = readLineInts
    if(Seq(1, 7, 9, 4).map(n => N.count(_ == n) == 1).forall(identity)) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

Score : 100 points

Problem Statement

You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974".

Constraints

0 \leq N_1, N_2, N_3, N_4 \leq 9

N_1, N_2, N_3 and N_4 are integers.

Input

Input is given from Standard Input in the following format:

N_1 N_2 N_3 N_4

Output

If N_1, N_2, N_3 and N_4 can be arranged into the sequence of digits "1974", print YES; if they cannot, print NO.

Sample Input 1

1 7 9 4

Sample Output 1

YES

We can get 1974 by swapping N_2 and N_3.

Sample Input 2

1 9 7 4

Sample Output 2

YES

We already have 1974 before doing anything.

Sample Input 3

1 2 9 1

Sample Output 3

NO

Sample Input 4

4 9 0 8

Sample Output 4

NO


object Main{
 def main(args:Array[String]) = {
  val sc = new java.util.Scanner(System.in)
  val list = List.fill(4)(sc.nextInt).sorted
  if(List(1,4,7,9) == list){
    println("YES")
  }
  else{
   println("NO")
  }
}
}


object Main extends App {

  import scala.io.StdIn._
  val numbers = readLine.trim.split(' ').map(_.toInt)
  println(
    if (List(1, 9, 7, 4).forall(i ⇒ numbers.contains(i))) "YES"
    else "NO"
  )
  implicit class Extension[T](value :T){
    @inline
    def let[A](@inline func: T ⇒ A): A = func(value)
    @inline
    def also(@inline func: T ⇒ Unit): T = {func(value); value}
  }
}


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)

  /**
    * @param tpe 0: row, 1: col, 2, どっちも
    */
  case class Restriction(tpe: Int, v: Int)

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

    val inRow = A.toSet
    val inCol = B.toSet
    val restrictions = ArrayBuffer[Restriction]()

    REP(N) { i =>
      val tpe = if (inCol.contains(A(i))) 2 else 0
      restrictions += Restriction(tpe, A(i))
    }

    REP(M) { i =>
      if (!inRow.contains(B(i))) restrictions += Restriction(1, B(i))
    }

    // vの降順でそーとしてある
    var ans = 1L
    var cur = N * M + 1
    val R = restrictions.sortBy(_.v).reverse

    def calc(): Long = {
      var r, c = 0

      // cur+1からuntil手前までシミュレートする
      def place(until: Int): Boolean = {
        var i = cur - 1
        while (i > until) {
          val alreadyPlaced = N * M - i
          val free = r * c - alreadyPlaced
          if (free <= 0) return false
          ans = ans * free % MOD
          i -= 1
        }

        true
      }

      REP(R.length) { i =>
        R(i).tpe match {
          // row
          case 0 =>
            if (!place(R(i).v)) return 0
            ans = (ans * c) % MOD
            cur = R(i).v
            r += 1

          // col
          case 1 =>
            if (!place(R(i).v)) return 0
            ans = (ans * r) % MOD
            cur = R(i).v
            c += 1

          // どっちも
          case 2 =>
            if (!place(R(i).v)) return 0
            cur = R(i).v
            c += 1
            r += 1
        }
      }

      place(0)

      ans
    }

    def validate(X: Array[Int]) = {
      X.max == N * M && X.groupBy(identity).values.forall(_.length == 1)
    }

    if (validate(A) && validate(B)) {
      out.println(calc())
    } else {
      out.println(0)
    }
  }

  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

Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates.
Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions:

The largest among the values in the i-th row (1 \leq i \leq N) is A_i.

The largest among the values in the j-th column (1 \leq j \leq M) is B_j.

For him, find the number of ways to write the numbers under these conditions, modulo 10^9 + 7.

Constraints

1 \leq N \leq 1000

1 \leq M \leq 1000

1 \leq A_i \leq N \times M

1 \leq B_j \leq N \times M

A_i and B_j are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of ways to write the numbers under the conditions, modulo 10^9 + 7.

Sample Input 1

2 2
4 3
3 4

Sample Output 1

2

(A_1, A_2) = (4, 3) and (B_1, B_2) = (3, 4). In this case, there are two ways to write the numbers, as follows:

1 in (1, 1), 4 in (1, 2), 3 in (2, 1) and 2 in (2, 2).

2 in (1, 1), 4 in (1, 2), 3 in (2, 1) and 1 in (2, 2).

Here, (i, j) denotes the square at the i-th row and the j-th column.

Sample Input 2

3 3
5 9 7
3 6 9

Sample Output 2

0

Since there is no way to write the numbers under the condition, 0 should be printed.

Sample Input 3

2 2
4 4
4 4

Sample Output 3

0

Sample Input 4

14 13
158 167 181 147 178 151 179 182 176 169 180 129 175 168
181 150 178 179 167 180 176 169 182 177 175 159 173

Sample Output 4

343772227


object Main extends App {

  import scala.io.StdIn._

  val Array(n, d) = readLine.trim.split(' ').map(_.toInt)
  val cities = readLine.trim.split(' ').map(_.toLong).zipWithIndex
  println(minCost(cities.reverse.toList))
  def minCost(cities: List[(Long, Int)]): Long = {
    def sub(list: List[(Long, Int)], current: Long, result: Long = 0): Long = {
      list match {
        case (a, b)::t if a + b * d > current ⇒ sub(t, current, current + a - b * d + result)
        case (a, b)::t ⇒ sub(t, a + b * d, current + a - b * d + result)
        case Nil ⇒ result
      }
    }
    sub(cities.tail, cities.head.let{case (a, b) ⇒ a + b * d})
  }

  class UnionFindTree{
    private var mParent: Option[UnionFindTree] = None
    private var mSize: Int = 1
    private def parent: UnionFindTree = {
      mParent.map{_.parent} match {
        case None ⇒ this
        case c@Some(p) ⇒
          mParent = c
          p
      }
    }
    def isSameUnion(that: UnionFindTree): Boolean = {
      parent == that.parent
    }
    def merge(that: UnionFindTree): Unit = {
      if (!isSameUnion(that)){
        val p = parent
        val tp = that.parent
        if (p.mSize > tp.mSize){
          tp.mParent = Some(p)
          p.mSize += tp.mSize
        }else {
          p.mParent = Some(tp)
          tp.mSize += p.mSize
        }
      }
    }
  }
  implicit class Extension[T](value :T){
    @inline
    def let[A](@inline func: T ⇒ A): A = func(value)
    @inline
    def also(@inline func: T ⇒ Unit): T = {func(value); value}
  }
}

Score : 600 points

Problem Statement

There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}.
Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.

Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}.
For Takahashi, find the minimum possible total cost to achieve the objective.

Constraints

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

1 \leq D \leq 10^9

1 \leq A_{i} \leq 10^9

A_{i} and D are integers.

Input

Input is given from Standard Input in the following format:

N D
A_1 A_2 ... A_N

Output

Print the minimum possible total cost.

Sample Input 1

3 1
1 100 1

Sample Output 1

106

This cost can be achieved by, for example, building roads connecting City 1, 2 and City 1, 3.

Sample Input 2

3 1000
1 100 1

Sample Output 2

2202

Sample Input 3

6 14
25 171 7 1 17 162

Sample Output 3

497

Sample Input 4

12 5
43 94 27 3 69 99 56 25 8 15 46 8

Sample Output 4

658


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, H, W = ni()
    val ans = (N - H + 1) * (N - W + 1)
    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 : 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


//import java.util.Scanner

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

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

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

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

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

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

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

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

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

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

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

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

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

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {

  def solve(sc: => Scanner): Unit = {
    val N, A, B = sc.nextInt()
    val P = Array.fill(N)(sc.nextInt())
    println(math.min(P.count(x => x <= A), math.min(P.count(x => A < x && x <= B), P.count(x => B < x))))
  }

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

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

  def recursive(N1: Long, N2: Long, M1: Long, M2: Long): Long = {
    println(N1, N2, M1, M2)
    if (N1 + N2 == 0 || M1 + M2 == 0) -1
    else recursive(math.max(0, M1 - math.max(0, N1 + N2 - M2) / 2), math.max(0, M2 - N1 - N2) + math.max(0, N1 + N2 - M2) % 2, N1, N2) + 1
  }

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

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

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

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

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

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

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

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

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

object ArabicRoman {

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

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

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

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

      convert(src)
  }

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

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

      convert(src.toUpperCase())
  }
}

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