import scala.io.StdIn

object Main extends App {
  val Array(a, b) = StdIn.readLine().split(' ').map(_.toInt)
  val s = StdIn.readLine()
  val r = s.slice(0, a) + s.slice(a+1, s.length)
  //println(r)
  println(if(s.length == (a + b + 1) && s.charAt(a) == '-' && r.forall(p => p.isDigit)) "Yes" else "No")
}

Score : 200 points

Problem Statement

The postal code in Atcoder Kingdom is A+B+1 characters long, its (A+1)-th character is a hyphen -, and the other characters are digits from 0 through 9.

You are given a string S. Determine whether it follows the postal code format in Atcoder Kingdom.

Constraints

1≤A,B≤5

|S|=A+B+1

S consists of - and digits from 0 through 9.

Input

Input is given from Standard Input in the following format:

A B
S

Output

Print Yes if S follows the postal code format in AtCoder Kingdom; print No otherwise.

Sample Input 1

3 4
269-6650

Sample Output 1

Yes

The (A+1)-th character of S is -, and the other characters are digits from 0 through 9, so it follows the format.

Sample Input 2

1 1
---

Sample Output 2

No

S contains unnecessary -s other than the (A+1)-th character, so it does not follow the format.

Sample Input 3

1 2
7444

Sample Output 3

No


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

  @tailrec
  def gcd(a: Int, b: Int): Int = {
    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 q = get[Int]

    val isPrimes = Array.fill(100001)(true)

    isPrimes(1) = false
    for (i <- 2 to 50000) {
      if (isPrimes(i)) {
        @tailrec
        def erasePrimes(k: Int): Unit = {
          val newI = i * k
          if (newI <= 100000) {
            isPrimes(newI) = false
            erasePrimes(k + 1)
          }
        }

        erasePrimes(2)
      }
    }

    val is2017Likes = Array.fill(100001)(false)
    for (i <- 3 to 100000 by 2) {
      is2017Likes(i) = isPrimes(i) && isPrimes((i + 1) / 2)
    }

    val is2017LikesSum = Array.fill(100001)(0)
    for (i <- 1 until is2017LikesSum.length) {
      if (is2017Likes(i)) {
        is2017LikesSum(i) = is2017LikesSum(i - 1) + 1
      } else {
        is2017LikesSum(i) = is2017LikesSum(i - 1)
      }
    }

    for ((l, r) <- Array.fill(q)(get[Int, Int])) {
      out.println(is2017LikesSum(r) - is2017LikesSum(l - 1))
    }

    out.flush()
  }
}

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

Score : 400 points

Problem Statement

We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime.

You are given Q queries.

In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i ≤ x ≤ r_i.

Constraints

1≤Q≤10^5

1≤l_i≤r_i≤10^5

l_i and r_i are odd.

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line (1≤i≤Q) should contain the response to the i-th query.

Sample Input 1

1
3 7

Sample Output 1

2

3 is similar to 2017, since both 3 and (3+1)/2=2 are prime.

5 is similar to 2017, since both 5 and (5+1)/2=3 are prime.

7 is not similar to 2017, since (7+1)/2=4 is not prime, although 7 is prime.

Thus, the response to the first query should be 2.

Sample Input 2

4
13 13
7 11
7 11
2017 2017

Sample Output 2

1
0
0
1

Note that 2017 is also similar to 2017.

Sample Input 3

6
1 53
13 91
37 55
19 51
73 91
13 49

Sample Output 3

4
4
1
1
1
2

Submitted source-code file size, in bytes.

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

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


import java.util.Scanner

object Main {
  def read() = {
    val sc = new Scanner(System.in)
    val q = sc.nextInt()
    val ranges = for (_ <- 0 until q) yield Range(sc.nextInt(), sc.nextInt())
    (q, ranges)
  }

  case class Range(min: Int, max: Int) {
  }

  val numMax = 100001
  val isPrimeAsTable: Vector[Boolean] = {
    val n = numMax
    val primeBitmap = Array.fill(n)(true)
    primeBitmap(0) = false
    primeBitmap(1) = false

    for (i <- 2 until Math.sqrt(n).toInt) {
      if (primeBitmap(i)) {
        // i is prime
        val multipleOfI = (2 * i until n).filter(j => j % i == 0)
        multipleOfI.foreach(j => primeBitmap(j) = false)
      }
    }
    primeBitmap.toVector
  }

  def isOdd(n: Int) = n % 2 == 1

  def like2017(n: Int): Boolean = isOdd(n) && isPrimeAsTable(n) && isPrimeAsTable((n + 1) / 2)

  val isLike2017AsTable: Vector[Boolean] = {
    val n = numMax
    (0 until n).map(like2017).toVector
  }

  // cumulativeSum(Vector(a_0,a_1,a_2)) =
  // Vector
  // (0,
  // a_0,
  // a_0 + a_1,
  // a_0 + a_1 + a_2)
  def cumulativeSum[T](a: Vector[T])(implicit num: Numeric[T]): Vector[T] = {
    a.scanLeft(num.zero)(num.plus)
  }

  // countLike2017Until(n) = #{k | k<-{0,1,2...,n-1}, kはlike2017}
  val countLike2017Until: Vector[Int] = cumulativeSum(isLike2017AsTable.map(if (_) 1 else 0))

  def countLike2017(range: Range) = {
    countLike2017Until(range.max + 1) - countLike2017Until(range.min)
  }

  def main(args: Array[String]): Unit = {
    val (_, ranges) = read()
    for (range <- ranges) {
      val result = countLike2017(range)
      println(result)
    }
  }
}


import scala.io.StdIn

object Main{

  val line = StdIn.readLine().split(" ").map(_.toInt).toList.splitAt(2)

  def solve(input: (List[Int], List[Int])): String = {
    val result = input._1.sum - input._2.sum
    if(result > 0){
      "Left"
    } else if (result < 0){
      "Right"
    } else {
      "Balanced"
    }
  }

  println(solve(line))
}

Score : 100 points

Problem Statement

A balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R.

Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and placed a mass of weight C and a mass of weight D on the right pan.

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Constraints

1\leq A,B,C,D \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Sample Input 1

3 8 7 1

Sample Output 1

Left

The total weight of the masses on the left pan is 11, and the total weight of the masses on the right pan is 8. Since 11>8, we should print Left.

Sample Input 2

3 4 5 2

Sample Output 2

Balanced

The total weight of the masses on the left pan is 7, and the total weight of the masses on the right pan is 7. Since 7=7, we should print Balanced.

Sample Input 3

1 7 6 4

Sample Output 3

Right

The total weight of the masses on the left pan is 8, and the total weight of the masses on the right pan is 10. Since 8<10, we should print Right.


object Main {
def main(args: Array[String]): Unit = {
    val in = readLine.split(" ").map(_.toInt)
    val a = in(0)
    val b = in(1)
    val c = in(2)
    val d = in(3)

    val lw = a + b
    val rw = c + d
    if (lw > rw){
      print("Left")
    } else if(lw == rw){
      print("Balanced")
    } else{
      print("Right")
    }
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val X, Y = sc.nextLong()
  println(LazyList.from(0).map(math.pow(2, _) * X).takeWhile(_ <= Y).length)
}

Score : 300 points

Problem Statement

As a token of his gratitude, Takahashi has decided to give his mother an integer sequence.
The sequence A needs to satisfy the conditions below:

A consists of integers between X and Y (inclusive).

For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.

Find the maximum possible length of the sequence.

Constraints

1 \leq X \leq Y \leq 10^{18}

All input values are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the maximum possible length of the sequence.

Sample Input 1

3 20

Sample Output 1

3

The sequence 3,6,18 satisfies the conditions.

Sample Input 2

25 100

Sample Output 2

3

Sample Input 3

314159265 358979323846264338

Sample Output 3

31


object Main extends App {
  import scala.math.ceil
  val Array(a,b) = readLine split(" ") map{_.toDouble}
  println(ceil((a+b)/2).toInt)
}

Score : 100 points

Problem Statement

You are given two positive integers a and b.
Let x be the average of a and b.
Print x rounded up to the nearest integer.

Constraints

a and b are integers.

1 \leq a, b \leq 100

Input

Input is given from Standard Input in the following format:

a b

Output

Print x rounded up to the nearest integer.

Sample Input 1

1 3

Sample Output 1

2

The average of 1 and 3 is 2.0, and it will be rounded up to the nearest integer, 2.

Sample Input 2

7 4

Sample Output 2

6

The average of 7 and 4 is 5.5, and it will be rounded up to the nearest integer, 6.

Sample Input 3

5 5

Sample Output 3

5


import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    if (args.length > 0 && args(0) == "TEST") {
      println(test())
    } else {
      val input = io.Source.stdin.getLines().mkString("\n")
      println(solve(input).trim())
    }
  }

  def solve(input: String): String = {
    val s: Scanner = new Scanner(input)
    val a,b = s.nextInt
    ((a + b) / 2.0).ceil.toInt.toString
  }

  val tests = List(
    """1 3""".stripMargin -> """2""",
    """7 4""".stripMargin -> """6""",
    """5 5""" -> "5"
  )

  def test(): String = tests.map { case (i, o) => (i.trim(), o.trim()) }
    .zipWithIndex.map {
    case ((input, outputExpect), i) =>
      val output = solve(input).trim()
      val tnum = i + 1
      s"test$tnum:" + (
        if (output == outputExpect) "Passed"
        else s"Failed\nexpect:\n$outputExpect\noutput:\n$output")
  }
    .mkString("\n")
}


import scala.io.StdIn._

object Main extends App {
  val x = readLine().split(" ").map(_.toInt).sum / 2.0
  println(math.ceil(x).toInt)
}


import scala.io.StdIn

object Main extends App {
  val s = StdIn.readLine().sorted
  val t = StdIn.readLine().sortBy(f => -1*f)

  def loop(sl: String, tl: String): Boolean = {
    if(sl.nonEmpty && tl.isEmpty) false
    else if(sl.isEmpty && tl.nonEmpty) true
    else if(sl.isEmpty && tl.isEmpty) false
    else if(sl.head > tl.head) false
    else if(sl.head < tl.head) true
    else loop(sl.tail, tl.tail)
  }

  println(if(loop(s, t)) "Yes" else "No")
}

Score : 200 points

Problem Statement

You are given strings s and t, consisting of lowercase English letters.
You will create a string s' by freely rearranging the characters in s.
You will also create a string t' by freely rearranging the characters in t.
Determine whether it is possible to satisfy s' < t' for the lexicographic order.

Notes

For a string a = a_1 a_2 ... a_N of length N and a string b = b_1 b_2 ... b_M of length M, we say a < b for the lexicographic order if either one of the following two conditions holds true:

N < M and a_1 = b_1, a_2 = b_2, ..., a_N = b_N.

There exists i (1 \leq i \leq N, M) such that a_1 = b_1, a_2 = b_2, ..., a_{i - 1} = b_{i - 1} and a_i < b_i. Here, letters are compared using alphabetical order.

For example, xy < xya and atcoder < atlas.

Constraints

The lengths of s and t are between 1 and 100 (inclusive).

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If it is possible to satisfy s' < t', print Yes; if it is not, print No.

Sample Input 1

yx
axy

Sample Output 1

Yes

We can, for example, rearrange yx into xy and axy into yxa. Then, xy < yxa.

Sample Input 2

ratcode
atlas

Sample Output 2

Yes

We can, for example, rearrange ratcode into acdeort and atlas into tslaa. Then, acdeort < tslaa.

Sample Input 3

cd
abc

Sample Output 3

No

No matter how we rearrange cd and abc, we cannot achieve our objective.

Sample Input 4

w
ww

Sample Output 4

Yes

Sample Input 5

zzz
zzz

Sample Output 5

No


import scala.collection.mutable.HashMap
import scala.collection.immutable.List

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

    import Function.tupled
    println(List.fill(n)(sc.nextInt)
            .groupBy(identity)
            .mapValues(_.length)
            .map(tupled {(number, count) =>
                       if (count >= number) count - number
                       else count
                       }
               )
            .sum
          )
  }
}

Score : 300 points

Problem Statement

You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N).
Your objective is to remove some of the elements in a so that a will be a good sequence.

Here, an sequence b is a good sequence when the following condition holds true:

For each element x in b, the value x occurs exactly x times in b.

For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.

Find the minimum number of elements that needs to be removed so that a will be a good sequence.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

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 number of elements that needs to be removed so that a will be a good sequence.

Sample Input 1

4
3 3 3 3

Sample Output 1

1

We can, for example, remove one occurrence of 3. Then, (3, 3, 3) is a good sequence.

Sample Input 2

5
2 4 1 4 2

Sample Output 2

2

We can, for example, remove two occurrences of 4. Then, (2, 1, 2) is a good sequence.

Sample Input 3

6
1 2 2 3 3 3

Sample Output 3

0

Sample Input 4

1
1000000000

Sample Output 4

1

Remove one occurrence of 10^9. Then, () is a good sequence.

Sample Input 5

8
2 7 1 8 2 8 1 8

Sample Output 5

5


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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val S = sc.next()
    val x, y = sc.nextInt()

    val X, Y = ArrayBuffer[Int]()
    var h = true
    var move = 0
    rep(S.length) { i =>
      S(i) match {
        case 'F' => move += 1
        case 'T' =>
          (if (h) X else Y) += move
          h ^= true
          move = 0
      }
    }
    if (move > 0) (if (h) X else Y) += move

    def reach(A: ArrayBuffer[Int], p: Int): Boolean = {
      val s = A.sum
      if (A.isEmpty || s == 0) p == 0 // 移動できない
      else {
        var cur, next = Array.ofDim[Boolean](s * 2 + 1)
        cur(s) = true
        rep(A.length) { i =>
          rep(s * 2 + 1) { j =>
            next(j) = cur(j)
            if (j + A(i) <= s * 2) next(j) ||= cur(j + A(i))
            if (j - A(i) >= 0) next(j) ||= cur(j - A(i))
          }
          val tmp = cur
          cur = next
          next = tmp
        }
        cur(s + p)
      }
    }

    val ok = reach(X, x) && reach(Y, y)
    val ans = if (ok) "Yes" else "No"
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

Score : 500 points

Problem Statement

A robot is put at the origin in a two-dimensional plane.
Initially, the robot is facing in the positive x-axis direction.

This robot will be given an instruction sequence s.
s consists of the following two kinds of letters, and will be executed in order from front to back.

F : Move in the current direction by distance 1.

T : Turn 90 degrees, either clockwise or counterclockwise.

The objective of the robot is to be at coordinates (x, y) after all the instructions are executed.
Determine whether this objective is achievable.

Constraints

s consists of F and T.

1 \leq |s| \leq 8 000

x and y are integers.

|x|, |y| \leq |s|

Input

Input is given from Standard Input in the following format:

s
x y

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning clockwise in the second T.

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

The objective can be achieved by, for example, turning clockwise in the first T and turning clockwise in the second T.

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning counterclockwise in the second T.

Sample Input 6

TTTT
1 0

Sample Output 6

No


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

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

  val s = in.next()
  val _x, y = in.next().toInt
  val N = s.length
  var x = _x

  var dir = 0
  var sayuu: List[Int] = Nil
  var updown: List[Int] = Nil

  def calc(com: Char, num: Int): Unit = {
    com match {
      case 'F' =>
        if(dir == 0)
          sayuu = num :: sayuu
        else
          updown = num :: updown
      case 'T' =>
        if(num % 2 == 1)
          dir += 90
        dir %= 180

    }
  }

  var ind = 0
  ////
  breakable {
    while(ind < N) {
      if(s(ind) == 'F') {
        ind += 1
      }
      else
        break
    }
  }

  x -= ind

  while(ind < N) {
    val now = s(ind)
    var r = ind + 1

    breakable {
      while(true) {
        if(r == N || now != s(r)) {
          calc(now, r-ind)
          ind = r
          break
        }
        else {
          r += 1
        }
      }
    }
  }

  // val dplr = new Array[Int](16002)
  // val dpud = new Array[Int](16002)

  var setlr: Set[Int] = Set()

  for(e <- sayuu) {
    var now = Set(e, -e)

    for(e2 <- setlr) {
      now = now + (e2 + e) + (e2 - e)
    }

    setlr = now
  }

  var setud: Set[Int] = Set()
  for(e <- updown) {
    var now = Set(e, -e)

    for(e2 <- setud) {
      now = now + (e2 + e) + (e2 - e)
    }

    setud = now
  }

  if(setlr.contains(x) && setud.contains(y))
    println("Yes")
  else
    println("No")
}

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 java.util.Scanner

import scala.collection.mutable
import scala.collection.immutable

object Main {
  def isOdd(num:Int) = num % 2 != 0
  def isEven(num:Int) = num % 2 == 0

  def main(args: Array[String]) = {
    def func(cand:immutable.Set[Int], move:Int):immutable.Set[Int] = {
      var next_cand = new mutable.HashSet[Int]
      for (x <- cand) {
        next_cand += x + move
        next_cand += x - move
      }

      val ret:immutable.Set[Int] = immutable.Set.empty ++ next_cand
      return ret
    }

    val sc = new Scanner(System.in)
    val moves = sc.nextLine().split("T").map(_.length).zipWithIndex
    val x_moves = moves.collect{
      case x if isEven(x._2) => x._1
    }
    val y_moves = moves.collect{
      case x if isOdd(x._2) => x._1
    }

    val xpos_cand = x_moves.tail.foldLeft(Set(x_moves(0)))(func)
    val ypos_cand = y_moves.foldLeft(Set(0))(func)

    val goal = sc.nextLine().split(" ").map(_.toInt)
    if (xpos_cand.contains(goal(0)) &&
      ypos_cand.contains(goal(1)))
      println("Yes")
    else
      println("No")
  }
}


object Main extends App {

  val n = io.StdIn.readLine().toInt
  val nums = io.StdIn.readLine().split(' ').map(_.toInt)
  calc(nums)

  def calc(nums: Array[Int], cnt: Int = 0): Array[Int] = {
    val t = for (x <- nums) yield {
      if (x % 2 != 0) {
        println(cnt)
        sys.exit
      }
      x / 2
    }
    if (cnt == 10) {
      sys.exit()
    }
    calc(t, cnt + 1)
  }

}

Score : 200 points

Problem Statement

There are N positive integers written on a blackboard: A_1, ..., A_N.

Snuke can perform the following operation when all integers on the blackboard are even:

Replace each integer X on the blackboard by X divided by 2.

Find the maximum possible number of operations that Snuke can perform.

Constraints

1 \leq N \leq 200

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 maximum possible number of operations that Snuke can perform.

Sample Input 1

3
8 12 40

Sample Output 1

2

Initially, [8, 12, 40] are written on the blackboard.
Since all those integers are even, Snuke can perform the operation.

After the operation is performed once, [4, 6, 20] are written on the blackboard.
Since all those integers are again even, he can perform the operation.

After the operation is performed twice, [2, 3, 10] are written on the blackboard.
Now, there is an odd number 3 on the blackboard, so he cannot perform the operation any more.

Thus, Snuke can perform the operation at most twice.

Sample Input 2

4
5 6 8 10

Sample Output 2

0

Since there is an odd number 5 on the blackboard already in the beginning, Snuke cannot perform the operation at all.

Sample Input 3

6
382253568 723152896 37802240 379425024 404894720 471526144

Sample Output 3

8


import java.util.Scanner
object Main {

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

    val t = sc.nextLine().toInt
    val A = sc.nextLine().split(" ").map(_.toInt)

    def two_index(n:Int): Int = {
      var idx = 0
      var num = n
      while (num % 2 == 0){
        num = num / 2
        idx = idx + 1
      }
      return idx
    }

    val two_index_obj = two_index _
    println(A.map(two_index_obj).min)
  }
}


object Main extends App {

	val N = scala.io.StdIn.readInt
	var A = scala.io.StdIn.readLine.split(" ").map(_.toInt)

	var i = 0

	var l1 = List[Int]()
	var l2 = List[Int]()

	do{
		if(A(i) > A(i+1)){
			if(A(i) < 0){
				A(i) = A(i) + A(i+1)
				l1 = (i+2) :: l1
				l2 = (i+1) :: l2
			}else{
				A(i+1) = A(i+1) + A(i)
				l1 = (i+1) :: l1
				l2 = (i+2) :: l2
			}
		}else{
			i = i + 1
		}

	}while(i < (N-1))

	if(l1.size == 0){
		println(0)
	}else{
		println(l1.size)

		l1 = l1.reverse
		l2 = l2.reverse

		for(i<-0 until l1.size){
			println(l1(i) + " " + l2(i))
		}
	}

}

Score : 600 points

Problem Statement

Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}.

He can perform the following operation any number of times:

Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.

He would like to perform this operation between 0 and 2N times (inclusive) so that a satisfies the condition below. Show one such sequence of operations.
It can be proved that such a sequence of operations always exists under the constraints in this problem.

Condition: a_1 \leq a_2 \leq ... \leq a_{N}

Constraints

2 \leq N \leq 50

-10^{6} \leq a_i \leq 10^{6}

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Let m be the number of operations in your solution. In the first line, print m.
In the i-th of the subsequent m lines, print the numbers x and y chosen in the i-th operation, with a space in between.
The output will be considered correct if m is between 0 and 2N (inclusive) and a satisfies the condition after the m operations.

Sample Input 1

3
-2 5 -1

Sample Output 1

2
2 3
3 3

After the first operation, a = (-2,5,4).

After the second operation, a = (-2,5,8), and the condition is now satisfied.

Sample Input 2

2
-1 -3

Sample Output 2

1
2 1

After the first operation, a = (-4,-3) and the condition is now satisfied.

Sample Input 3

5
0 0 0 0 0

Sample Output 3

0

The condition is satisfied already in the beginning.


import scala.io.StdIn

object Main extends App {
   val x = StdIn.readLine().split(' ').map(_.toInt)
   println(scala.math.min(x(0)*x(1), x(2)))
}

Score : 100 points

Problem Statement

You are parking at a parking lot. You can choose from the following two fee plans:

Plan 1: The fee will be A×T yen (the currency of Japan) when you park for T hours.

Plan 2: The fee will be B yen, regardless of the duration.

Find the minimum fee when you park for N hours.

Constraints

1≤N≤20

1≤A≤100

1≤B≤2000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

When the minimum fee is x yen, print the value of x.

Sample Input 1

7 17 120

Sample Output 1

119

If you choose Plan 1, the fee will be 7×17=119 yen.

If you choose Plan 2, the fee will be 120 yen.

Thus, the minimum fee is 119 yen.

Sample Input 2

5 20 100

Sample Output 2

100

The fee might be the same in the two plans.

Sample Input 3

6 18 100

Sample Output 3

100


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val f = n.toString.map(_.toString.toInt).sum
  println(if (n % f == 0) "Yes" else "No")
}

Score : 200 points

Problem Statement

An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.

Given an integer N, determine whether it is a Harshad number.

Constraints

1?N?10^8

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print Yes if N is a Harshad number; print No otherwise.

Sample Input 1

12

Sample Output 1

Yes

f(12)=1+2=3. Since 12 is divisible by 3, 12 is a Harshad number.

Sample Input 2

57

Sample Output 2

No

f(57)=5+7=12. Since 57 is not divisible by 12, 12 is not a Harshad number.

Sample Input 3

148

Sample Output 3

No


object Main extends App {
  var a = readInt
  var b = a
  var sum = 0
  for(i <- 0 until a.toString.size) {
    sum = sum + a%10
    a = a / 10
  }
  print(if(b%sum!=0){"No"} else {"Yes"})
}


import scala.io.StdIn

object Main extends App {

   val s = StdIn.readLine()
   println(
   if(s(0) == s(1) && s(1) == s(2)) "Yes"
   else if(s(1) == s(2) && s(2) == s(3)) "Yes"
   else "No"
   )
}

Score : 100 points

Problem Statement

We call a 4-digit integer with three or more consecutive same digits, such as 1118, good.

You are given a 4-digit integer N. Answer the question: Is N good?

Constraints

1000 ≤ N ≤ 9999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is good, print Yes; otherwise, print No.

Sample Input 1

1118

Sample Output 1

Yes

N is good, since it contains three consecutive 1.

Sample Input 2

7777

Sample Output 2

Yes

An integer is also good when all the digits are the same.

Sample Input 3

1234

Sample Output 3

No


object Main extends App {
  val N = io.StdIn.readLine().split("").toSet
  if (N.size <= 2) println("Yes") else println("No")
}


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val lucas: Stream[Long] = 2L #:: 1L #:: lucas.zip(lucas.tail).map(n => n._1 + n._2)
  println(lucas(n))
}

Score : 200 points

Problem Statement

It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers.

You are given an integer N. Find the N-th Lucas number.

Here, the i-th Lucas number L_i is defined as follows:

L_0=2

L_1=1

L_i=L_{i-1}+L_{i-2} (i≥2)

Constraints

1≤N≤86

It is guaranteed that the answer is less than 10^{18}.

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the N-th Lucas number.

Sample Input 1

5

Sample Output 1

11

L_0=2

L_1=1

L_2=L_0+L_1=3

L_3=L_1+L_2=4

L_4=L_2+L_3=7

L_5=L_3+L_4=11

Thus, the 5-th Lucas number is 11.

Sample Input 2

86

Sample Output 2

939587134549734843


import java.util.Scanner

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

    def go(i: Int, prev: BigInt, post: BigInt): BigInt ={
      if (i == 0) prev
      else{
        go(i-1, post, prev+post)
      }
    }
    println(go(n, 2, 1))
  }
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val numbers = sc.nextLine.split("").map(_.toInt)

    var ans: String = numbers.head.toString

    def go(num: Array[Int], sumValue: Int, res: String): Boolean = {
      if (num.isEmpty) {
        if (sumValue == 7) {
          ans += res + "=7"
          true
        }
        else false
      } else {
        go(num.tail, sumValue + num.head, Array(res, "+", num.head.toString).mkString("")) |
          go(num.tail, sumValue - num.head, Array(res, "-", num.head.toString).mkString(""))
      }
    }

    go(numbers.tail, numbers.head, "")
    println(ans)
  }
}

Score : 300 points

Problem Statement

Sitting in a station waiting room, Joisino is gazing at her train ticket.

The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive).

In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with + or - so that the formula holds.

The given input guarantees that there is a solution. If there are multiple solutions, any of them will be accepted.

Constraints

0≤A,B,C,D≤9

All input values are integers.

It is guaranteed that there is a solution.

Input

Input is given from Standard Input in the following format:

ABCD

Output

Print the formula you made, including the part =7.

Use the signs + and -.

Do not print a space between a digit and a sign.

Sample Input 1

1222

Sample Output 1

1+2+2+2=7

This is the only valid solution.

Sample Input 2

0290

Sample Output 2

0-2+9+0=7

0 - 2 + 9 - 0 = 7 is also a valid solution.

Sample Input 3

3242

Sample Output 3

3+2+4-2=7


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val h, w = sc.nextInt()
  val n = 10
  val c = Array.fill(n, n)(sc.nextInt())
  val a = List.fill(h * w)(sc.nextInt())

  for {
    k <- 0 until n
    i <- 0 until n
    j <- 0 until n
    if c(i)(k) + c(k)(j) < c(i)(j)
  } {
    c(i)(j) = c(i)(k) + c(k)(j)
  }

  val count = a.groupBy(identity).view.mapValues(_.length).toMap.withDefaultValue(0)
  val ans = (2 until n).map(i => c(i)(1) * count(i)).sum
  println(ans)
}

Score : 400 points

Problem Statement

Joisino the magical girl has decided to turn every single digit that exists on this world into 1.

Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).

She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and 9 (inclusive).

You are given A_{i,j} that describes the square at the i-th row from the top and j-th column from the left, as follows:

If A_{i,j}≠-1, the square contains a digit A_{i,j}.

If A_{i,j}=-1, the square does not contain a digit.

Find the minimum total amount of MP required to turn every digit on this wall into 1 in the end.

Constraints

1≤H,W≤200

1≤c_{i,j}≤10^3 (i≠j)

c_{i,j}=0 (i=j)

-1≤A_{i,j}≤9

All input values are integers.

There is at least one digit on the wall.

Input

Input is given from Standard Input in the following format:

H W
c_{0,0} ... c_{0,9}
:
c_{9,0} ... c_{9,9}
A_{1,1} ... A_{1,W}
:
A_{H,1} ... A_{H,W}

Output

Print the minimum total amount of MP required to turn every digit on the wall into 1 in the end.

Sample Input 1

2 4
0 9 9 9 9 9 9 9 9 9
9 0 9 9 9 9 9 9 9 9
9 9 0 9 9 9 9 9 9 9
9 9 9 0 9 9 9 9 9 9
9 9 9 9 0 9 9 9 9 2
9 9 9 9 9 0 9 9 9 9
9 9 9 9 9 9 0 9 9 9
9 9 9 9 9 9 9 0 9 9
9 9 9 9 2 9 9 9 0 9
9 2 9 9 9 9 9 9 9 0
-1 -1 -1 -1
8 1 1 8

Sample Output 1

12

To turn a single 8 into 1, it is optimal to first turn 8 into 4, then turn 4 into 9, and finally turn 9 into 1, costing 6 MP.

The wall contains two 8s, so the minimum total MP required is 6×2=12.

Sample Input 2

5 5
0 999 999 999 999 999 999 999 999 999
999 0 999 999 999 999 999 999 999 999
999 999 0 999 999 999 999 999 999 999
999 999 999 0 999 999 999 999 999 999
999 999 999 999 0 999 999 999 999 999
999 999 999 999 999 0 999 999 999 999
999 999 999 999 999 999 0 999 999 999
999 999 999 999 999 999 999 0 999 999
999 999 999 999 999 999 999 999 0 999
999 999 999 999 999 999 999 999 999 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Sample Output 2

0

Note that she may not need to change any digit.

Sample Input 3

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

Sample Output 3

47


import scala.math._

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val x, y = sc.next

  val ans = if (x < y) "<" else if (x > y) ">" else "="

  println(ans)

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

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

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

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

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

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

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

Score : 100 points

Problem Statement

In programming, hexadecimal notation is often used.

In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters A, B, C, D, E and F are used to represent the values 10, 11, 12, 13, 14 and 15, respectively.

In this problem, you are given two letters X and Y. Each X and Y is A, B, C, D, E or F.

When X and Y are seen as hexadecimal numbers, which is larger?

Constraints

Each X and Y is A, B, C, D, E or F.

Input

Input is given from Standard Input in the following format:

X Y

Output

If X is smaller, print <; if Y is smaller, print >; if they are equal, print =.

Sample Input 1

A B

Sample Output 1

<

10 < 11.

Sample Input 2

E C

Sample Output 2

>

14 > 12.

Sample Input 3

F F

Sample Output 3

=

15 = 15.


import java.util.Scanner

import scala.collection.Searching._
import scala.annotation.tailrec
import scala.collection.immutable.Queue

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {
  def solve(sc: => Scanner): Unit = {
    val X, Y = sc.next
    if (X == Y) {
      println("=")
    } else if (X < Y) {
      println("<")
    } else {
      println(">")
    }
  }

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


object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val X = sc.next().charAt(0)
    val Y = sc.next().charAt(0)
    val r = if (X > Y) '>' else if (X < Y) '<' else '='
    println(r)
  }
}


object Main extends App {
	import scala.math._

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

	val N = NZW(0).toInt

	val a = (NZW(2) - A(N-1)).abs
	val b = (A(N-1) - A(N-2)).abs

	println(max(a,b))

}

Score : 500 points

Problem Statement

We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i.

Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they will alternately perform the following action:

Draw some number of cards from the top of the deck. Then, discard the card in his hand and keep the last drawn card instead. Here, at least one card must be drawn.

The game ends when there is no more card in the deck. The score of the game is the absolute difference of the integers written on the cards in the two players' hand.

X will play the game so that the score will be maximized, and Y will play the game so that the score will be minimized. What will be the score of the game?

Constraints

All input values are integers.

1 \leq N \leq 2000

1 \leq Z, W, a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N Z W
a_1 a_2 ... a_N

Output

Print the score.

Sample Input 1

3 100 100
10 1000 100

Sample Output 1

900

If X draws two cards first, Y will draw the last card, and the score will be |1000 - 100| = 900.

Sample Input 2

3 100 1000
10 100 100

Sample Output 2

900

If X draws all the cards first, the score will be |1000 - 100| = 900.

Sample Input 3

5 1 1
1 1 1 1 1

Sample Output 3

0

Sample Input 4

1 1 1
1000000000

Sample Output 4

999999999


object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val z = sc.nextInt
    val w = sc.nextInt
    val an = List.fill(n)(sc.nextInt)

    val ans = if (an.length == 1) {
      Math.abs(an.head - w)
    } else {
      val a = Math.abs(an.head - w)
      val b = Math.abs(an.last - an(an.length - 1))
      if (a > b) a else b
    }

    println(ans)
  }
}


import scala.collection.mutable

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val k = sc.nextInt()
  var e = List[(Int, Int, Int)]()
  for (i <- 0 until k) {
    if (i % 10 != 9) {
      e ::= (i, (i+1) % k, 1)
    }
    e ::= (i, (10 * i) % k, 0)
  }

  val sp = binaryBfs(1, k, e)
  println(sp(0) + 1)

  def binaryBfs(s: Int, n: Int, edges: Seq[(Int, Int, Int)]): Array[Int] = {
    val adj = Array.fill(n)(List[(Int, Int)]())
    for ((u, v, w) <- edges) {
      adj(u) ::= (v, w)
    }

    val sp = Array.fill(n)(-1)
    sp(s) = 0
    val deque = mutable.ArrayDeque[Int]()
    deque.append(s)
    while (deque.nonEmpty) {
      val u = deque.removeHead()
      for ((v, w) <- adj(u) if (sp(v) == -1 || sp(u) + w < sp(v))) {
        sp(v) = sp(u) + w
        if (w == 0) {
          deque.prepend(v)
        } else {
          deque.append(v)
        }
      }
    }
    sp
  }
}

Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    val r: Int = sc.nextLine.toInt
    val g: Int = sc.nextLine.toInt
    println(2 * g - r)
  }
}

Score : 100 points

Problem Statement

Takahashi is a user of a site that hosts programming contests.

When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows:

Let the current rating of the user be a.

Suppose that the performance of the user in the contest is b.

Then, the new rating of the user will be the avarage of a and b.

For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000.

Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest.

Find the performance required to achieve it.

Constraints

0 \leq R, G \leq 4500

All input values are integers.

Input

Input is given from Standard Input in the following format:

R
G

Output

Print the performance required to achieve the objective.

Sample Input 1

2002
2017

Sample Output 1

2032

Takahashi's current rating is 2002.

If his performance in the contest is 2032, his rating will be the average of 2002 and 2032, which is equal to the desired rating, 2017.

Sample Input 2

4500
0

Sample Output 2

-4500

Although the current and desired ratings are between 0 and 4500, the performance of a user can be below 0.


object Main extends App {
    val scanner = new java.util.Scanner(System.in)
    val n = scanner.next().toInt
    val k = scanner.next().toInt
    println(sim(1, k, n).min)

    def sim(n: Int, k: Int, cnt: Int): List[Int] = {
        if (cnt == 0) {
            List(n)
        } else {
            sim(n+k, k, cnt-1) ::: sim(n*2, k, cnt-1)
        }
    }
}

Score : 200 points

Problem Statement

Square1001 has seen an electric bulletin board displaying the integer 1.
He can perform the following operations A and B to change this value:

Operation A: The displayed value is doubled.

Operation B: The displayed value increases by K.

Square1001 needs to perform these operations N times in total.
Find the minimum possible value displayed in the board after N operations.

Constraints

1 \leq N, K \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the minimum possible value displayed in the board after N operations.

Sample Input 1

4
3

Sample Output 1

10

The value will be minimized when the operations are performed in the following order: A, A, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 7 → 10.

Sample Input 2

10
10

Sample Output 2

76

The value will be minimized when the operations are performed in the following order: A, A, A, A, B, B, B, B, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 8 → 16 → 26 → 36 → 46 → 56 → 66 → 76.

By the way, this contest is AtCoder Beginner Contest 076.


import java.io.{BufferedReader, InputStreamReader}

object Main extends App {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val Array(n, m) = in.readLine.split(" ").map(_.toInt)
  val edges = Iterator.continually(in.readLine)
    .take(m)
    .map(_.split(" ").map(_.toInt))
    .toArray

  val graph = {
    val arr = Array.ofDim[Boolean](n+1,n+1)
    for(edge <- edges) {
      arr(edge(0))(edge(1)) = true
      arr(edge(1))(edge(0)) = true
    }
    arr
  }
  var visit = Array.ofDim[Boolean](n+1)

  def dfs(v:Int):Unit = {
    if(visit(v)) return
    visit(v) = true
    for(i <- 1 to n) {
      if(graph(v)(i)) dfs(i)
    }
  }

  val ans = {
    for(edge <- edges) yield {
      visit = Array.fill(n+1)(false)
      graph(edge(0))(edge(1)) = false
      graph(edge(1))(edge(0)) = false
      dfs(edge(0))
      // println(visit.mkString(" "))
      graph(edge(0))(edge(1)) = true
      graph(edge(1))(edge(0)) = true
      visit.tail.forall(_ == true)
    }
  }

  println(ans.count(_ == false))
}

Score : 300 points

Problem Statement

You are given an undirected connected graph with N vertices and M edges that does not contain self-loops and double edges.

The i-th edge (1 \leq i \leq M) connects Vertex a_i and Vertex b_i.

An edge whose removal disconnects the graph is called a bridge.

Find the number of the edges that are bridges among the M edges.

Notes

A self-loop is an edge i such that a_i=b_i (1 \leq i \leq M).

Double edges are a pair of edges i,j such that a_i=a_j and b_i=b_j (1 \leq i<j \leq M).

An undirected graph is said to be connected when there exists a path between every pair of vertices.

Constraints

2 \leq N \leq 50

N-1 \leq M \leq min(N(N−1)⁄2,50)

1 \leq a_i<b_i \leq N

The given graph does not contain self-loops and double edges.

The given graph is connected.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the edges that are bridges among the M edges.

Sample Input 1

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

Sample Output 1

4

The figure below shows the given graph:

The edges shown in red are bridges. There are four of them.

Sample Input 2

3 3
1 2
1 3
2 3

Sample Output 2

0

It is possible that there is no bridge.

Sample Input 3

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

Sample Output 3

5

It is possible that every edge is a bridge.


object Main{
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val N = sc.nextInt
    val K = sc.nextInt

    val x_ = Array.ofDim[BigInt](N)
    val y_ = Array.ofDim[BigInt](N)
    for(i <- 0 to N-1){
      x_(i) = sc.nextInt
      y_(i) = sc.nextInt
    }

    val x = x_.sorted
    val y = y_.sorted

    println(x.deep)
    println(y.deep)

    var ans : BigInt = (x(N-1)-x(0)) * (y(N-1)-y(0))
    println("ans : " + ans)
    for(xi <- 0 to N-1){
      for(xj <- xi+1 to N-1){
        for(yi <- 0 to N-1){
          for(yj <- yi+1 to N-1){
            val lx = x(xi)
            val rx = x(xj)
            val by = y(yi)
            val uy = y(yj)

            var cnt = 0
            for(i <- 0 to N-1){
              if(lx<=x(i) && x(i)<=rx && by<=y(i) && y(i)<=uy) cnt = cnt + 1
            }

            if((rx-lx)*(uy-by) == 10){
              println(x(xi) + " " + x(xj) + " " + y(yi) + " " + y(yj))
            }
            if(cnt >= K){
              ans = ans.min((rx-lx)*(uy-by))
            }
          }
        }
      }
    }
    assert(ans >= 0)
    println(ans)
  }
}

Score : 400 points

Problem Statement

We have N points in a two-dimensional plane.

The coordinates of the i-th point (1 \leq i \leq N) are (x_i,y_i).

Let us consider a rectangle whose sides are parallel to the coordinate axes that contains K or more of the N points in its interior.

Here, points on the sides of the rectangle are considered to be in the interior.

Find the minimum possible area of such a rectangle.

Constraints

2 \leq K \leq N \leq 50

-10^9 \leq x_i,y_i \leq 10^9 (1 \leq i \leq N)

x_i≠x_j (1 \leq i<j \leq N)

y_i≠y_j (1 \leq i<j \leq N)

All input values are integers. (Added at 21:50 JST)

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1
:
x_{N} y_{N}

Output

Print the minimum possible area of a rectangle that satisfies the condition.

Sample Input 1

4 4
1 4
3 3
6 2
8 1

Sample Output 1

21

One rectangle that satisfies the condition with the minimum possible area has the following vertices: (1,1), (8,1), (1,4) and (8,4).

Its area is (8-1) × (4-1) = 21.

Sample Input 2

4 2
0 0
1 1
2 2
3 3

Sample Output 2

1

Sample Input 3

4 3
-1000000000 -1000000000
1000000000 1000000000
-999999999 999999999
999999999 -999999999

Sample Output 3

3999999996000000001

Watch out for integer overflows.


object Main {

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

    val N = sc.nextInt()
    // 制約から, h, n, w <= 3500を探索することになる
    val (h, n, w) = (for {
      h <- 1 to 3500
      n <- 1 to 3500
      top = N * h * n
      bottom = 4 * h * n - N * n - N * h
      if top % bottom == 0
      w = top / bottom
    } yield (h, n, w)).head

    println(s"$h $n $w")
  }

}

Score : 300 points

Problem Statement

You are given an integer N.

Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.

If there are multiple solutions, any of them will be accepted.

Constraints

It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.

Inputs

Input is given from Standard Input in the following format:

N

Outputs

Print a triple of positive integers h, n and w that satisfies the condition, in the following format:

h n w

Sample Input 1

2

Sample Output 1

1 2 2

4/2 = 1/1 + 1/2 + 1/2.

Sample Input 2

3485

Sample Output 2

872 1012974 1539173474040

It is allowed to use an integer exceeding 3500 in a solution.

Sample Input 3

4664

Sample Output 3

3498 3498 3498


object Main extends App {
  val Array(n, a) = Array(io.StdIn.readLine().toInt, io.StdIn.readLine().toInt)
  println(n * n - a)
}

Score : 100 points

Problem Statement

We have an N \times N square grid.

We will paint each square in the grid either black or white.

If we paint exactly A squares white, how many squares will be painted black?

Constraints

1 \leq N \leq 100

0 \leq A \leq N^2

Inputs

Input is given from Standard Input in the following format:

N
A

Outputs

Print the number of squares that will be painted black.

Sample Input 1

3
4

Sample Output 1

5

There are nine squares in a 3 \times 3 square grid.
Four of them will be painted white, so the remaining five squares will be painted black.

Sample Input 2

19
100

Sample Output 2

261

Sample Input 3

10
0

Sample Output 3

100

As zero squares will be painted white, all the squares will be painted black.


import java.io.{BufferedReader, InputStreamReader}
import java.util.Arrays

object Main extends App {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val Array(a, b, c, d, e, f) = in.readLine.split(" ").map(_.toInt)
  // 入れる水の量 100a 100b
  // 入れる砂糖の量 c d
  // 100gあたりとける量 e
  // ビーカーに入る量 f
  val water = {
    for {
      i <- 0 to f/(a*100)
      j <- 0 to f/(b*100)
      w = 100 * a * i + 100 * b * j
      if(0 < w && w <= f)
    } yield w
  }.distinct.toArray
  val sugar = {
    for {
      i <- 0 to (f-100)/c
      j <- 0 to (f-100)/d
      w = c * i + d * j
      if(0 < w && w <= f)
    } yield w
  }.distinct.toArray

  // println(water.length + " " + sugar.length)

  val ans = {
    var max = (0d, 0, 0)
    for {
      w <- water
      s <- sugar
      weight = w + s
      concent = s.toDouble / (w.toDouble/100d)
      if w + s <= f && concent <= e
    } {
      // println(weight + " " + concent)
      if(concent > max._1)
        max = (concent, weight, s)
    }
    max
  }

  println(ans._2 + " " + ans._3)
}

Score : 300 points

Problem Statement

Snuke is making sugar water in a beaker.
Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.

Operation 1: Pour 100A grams of water into the beaker.

Operation 2: Pour 100B grams of water into the beaker.

Operation 3: Put C grams of sugar into the beaker.

Operation 4: Put D grams of sugar into the beaker.

In our experimental environment, E grams of sugar can dissolve into 100 grams of water.

Snuke will make sugar water with the highest possible density.

The beaker can contain at most F grams of substances (water and sugar combined), and there must not be any undissolved sugar in the beaker.
Find the mass of the sugar water Snuke will make, and the mass of sugar dissolved in it.
If there is more than one candidate, any of them will be accepted.

We remind you that the sugar water that contains a grams of water and b grams of sugar is \frac{100b}{a + b} percent.
Also, in this problem, pure water that does not contain any sugar is regarded as 0 percent density sugar water.

Constraints

1 \leq A < B \leq 30

1 \leq C < D \leq 30

1 \leq E \leq 100

100A \leq F \leq 3 000

A, B, C, D, E and F are all integers.

Inputs

Input is given from Standard Input in the following format:

A B C D E F

Outputs

Print two integers separated by a space.
The first integer should be the mass of the desired sugar water, and the second should be the mass of the sugar dissolved in it.

Sample Input 1

1 2 10 20 15 200

Sample Output 1

110 10

In this environment, 15 grams of sugar can dissolve into 100 grams of water, and the beaker can contain at most 200 grams of substances.

We can make 110 grams of sugar water by performing Operation 1 once and Operation 3 once.
It is not possible to make sugar water with higher density.
For example, the following sequences of operations are infeasible:

If we perform Operation 1 once and Operation 4 once, there will be undissolved sugar in the beaker.

If we perform Operation 2 once and Operation 3 three times, the mass of substances in the beaker will exceed 200 grams.

Sample Input 2

1 2 1 2 100 1000

Sample Output 2

200 100

There are other acceptable outputs, such as:

400 200

However, the output below is not acceptable:

300 150

This is because, in order to make 300 grams of sugar water containing 150 grams of sugar, we need to pour exactly 150 grams of water into the beaker, which is impossible.

Sample Input 3

17 19 22 26 55 2802

Sample Output 3

2634 934


import java.io.{BufferedReader, InputStream, InputStreamReader, PrintWriter}
import java.util.StringTokenizer

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

object Main {
  val MOD = 1000000007
  val out = new PrintWriter(System.out)
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val A, B, C, D, E, F = sc.nextInt()

    def waters: Array[Int] = {
      val set = mutable.HashSet[Int]()
      for {
        a <- 0 to F / A / 100
        b <- 0 to F / B / 100
      } {
        val w = a * A + b * B
        if (w * 100 <= F && w > 0) set += w
      }
      set.toArray
    }

    def sugars: Array[Int] = {
      val set = mutable.HashSet[Int]()
      for {
        c <- 0 to F / C
        d <- 0 to F / D
      } {
        val s = c * C + d * D
        if (s <= F) set += s
      }
      set.toArray
    }

    val (w, s) = (for {
      w <- waters
      s <- sugars
      if w * 100 + s <= F && s <= w * E
    } yield (w * 100, s)).maxBy(x => x._2.toDouble / (x._1 + x._2))

    out.println(s"${s + w} $s")
  }

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

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

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

    def nextInt(): Int = next.toInt
    def nextLong(): Long = next.toLong
    def nextChar(): Char = next.charAt(0)
  }

  private def rep(n: Int)(f: Int => Unit): Unit = (0 until n) foreach f

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

  private implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

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

    def rep(f: A => Unit): Unit = {
      as.indices foreach (i => f(as(i)))
    }

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

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

}


import scala.io.{StdIn => in}

object Main extends App {
  val n = in.readLine.map(_.toString.toInt)
  val ans = if(n.exists(_ == 9)) "Yes" else "No"
  println(ans)
}

Score : 100 points

Problem Statement

It is September 9 in Japan now.

You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N?

Constraints

10≤N≤99

Input

Input is given from Standard Input in the following format:

N

Output

If 9 is contained in the decimal notation of N, print Yes; if not, print No.

Sample Input 1

29

Sample Output 1

Yes

The one's digit of 29 is 9.

Sample Input 2

72

Sample Output 2

No

72 does not contain 9.

Sample Input 3

91

Sample Output 3

Yes


import scala.io.{StdIn => in}

object Main extends App {
  val n = in.readLine.map(_.toString.toInt)
  println(n.mkString(" "))
  val ans = if(n.exists(_ == 9)) "Yes" else "No"
  println(ans)
}


object Main extends App {
	val N = scala.io.StdIn.readInt
	var temp = List[Long]()

	for(i<-0 until N){
		val A = scala.io.StdIn.readLong
		if(temp.contains(A)) temp = temp.filterNot(_==A)
		else temp = A::temp
	}

	println(temp.size)
}

Score : 300 points

Problem Statement

You are playing the following game with Joisino.

Initially, you have a blank sheet of paper.

Joisino announces a number. If that number is written on the sheet, erase the number from the sheet; if not, write the number on the sheet. This process is repeated N times.

Then, you are asked a question: How many numbers are written on the sheet now?

The numbers announced by Joisino are given as A_1, ... ,A_N in the order she announces them. How many numbers will be written on the sheet at the end of the game?

Constraints

1≤N≤100000

1≤A_i≤1000000000(=10^9)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print how many numbers will be written on the sheet at the end of the game.

Sample Input 1

3
6
2
6

Sample Output 1

1

The game proceeds as follows:

6 is not written on the sheet, so write 6.

2 is not written on the sheet, so write 2.

6 is written on the sheet, so erase 6.

Thus, the sheet contains only 2 in the end. The answer is 1.

Sample Input 2

4
2
5
5
2

Sample Output 2

0

It is possible that no number is written on the sheet in the end.

Sample Input 3

6
12
22
16
22
18
12

Sample Output 3

2


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    val Array(x, t) = sc.nextLine.split(" ").map(_.toInt)
    println(Array(0, x-t).max)
  }
}

Score : 100 points

Problem Statement

We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand.

How many grams of sand will the upper bulb contains after t seconds?

Constraints

1≤X≤10^9

1≤t≤10^9

X and t are integers.

Input

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

X t

Output

Print the number of sand in the upper bulb after t second.

Sample Input 1

100 17

Sample Output 1

83

17 out of the initial 100 grams of sand will be consumed, resulting in 83 grams.

Sample Input 2

48 58

Sample Output 2

0

All 48 grams of sand will be gone, resulting in 0 grams.

Sample Input 3

1000000000 1000000000

Sample Output 3

0


object Main extends App {
	val temp = scala.io.StdIn.readLine.split(" ").map(_.toLong)

	val result = temp(0)-temp(1)

	if(result>=0)println(result)
	else println(0)
}


object Main extends App {
  val s = readLine.toArray
  var i = 0
  while (i < s.length) {
    print(s(i))
    i += 2
  }
}

Score : 200 points

Problem Statement

You are given a string s consisting of lowercase English letters. Extract all the characters in the odd-indexed positions and print the string obtained by concatenating them. Here, the leftmost character is assigned the index 1.

Constraints

Each character in s is a lowercase English letter.

1≤|s|≤10^5

Input

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

s

Output

Print the string obtained by concatenating all the characters in the odd-numbered positions.

Sample Input 1

atcoder

Sample Output 1

acdr

Extract the first character a, the third character c, the fifth character d and the seventh character r to obtain acdr.

Sample Input 2

aaaa

Sample Output 2

aa

Sample Input 3

z

Sample Output 3

z

Sample Input 4

fukuokayamaguchi

Sample Output 4

fkoaaauh


object Main extends App {
  val s = readLine.split("")
  println(s.zipWithIndex.filter{case (_,index) => index%2 == 1}.map{case (x,_) => x}.foldLeft(""){_ + _})
}


import java.util.Scanner

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

  val s = sc.next

  val res = s.zipWithIndex.filter(_._2 % 2 == 0).map(_._1).mkString

  println(res)
}


import io.StdIn._
object Main extends App {
    val n = readInt
    val as = readLine.split(" ").map(_.toInt)

    val number = as.distinct
    val counts = number.map(n => as.filter(a => n-1 == a || n == a || n+1 == a).length)

    println(counts.max)
}

Score : 300 points

Problem Statement

You are given an integer sequence of length N, a_1,a_2,...,a_N.

For each 1≤i≤N, you have three choices: add 1 to a_i, subtract 1 from a_i or do nothing.

After these operations, you select an integer X and count the number of i such that a_i=X.

Maximize this count by making optimal choices.

Constraints

1≤N≤10^5

0≤a_i<10^5 (1≤i≤N)

a_i is an integer.

Input

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

N
a_1 a_2 .. a_N

Output

Print the maximum possible number of i such that a_i=X.

Sample Input 1

7
3 1 4 1 5 9 2

Sample Output 1

4

For example, turn the sequence into 2,2,3,2,6,9,2 and select X=2 to obtain 4, the maximum possible count.

Sample Input 2

10
0 1 2 3 4 5 6 7 8 9

Sample Output 2

3

Sample Input 3

1
99999

Sample Output 3

1


import scala.collection.mutable
import java.io.{BufferedReader, InputStreamReader}

object Main extends App {
  val in = new BufferedReader(new InputStreamReader(System.in))
  val map = mutable.HashMap[Int,Int]()

  val n = in.readLine.toInt
  in.readLine.split(" ").map(_.toInt)
    .foreach(e => {
      if(!map.contains(e)) map += e -> 1
      else map(e) +=1
    })

  val x = map.keySet

  val ans = {
    var max = -1
    for {
      i <- x
    } {
      var cnt = 0
      map.foreach(e => {
        if(i-1 <= e._1 && e._1 <= i+1) cnt += e._2
      })

      if(cnt > max) max = cnt
    }
    max
  }

  println(ans)
}


object Main extends App {
	val N = scala.io.StdIn.readInt
	val A = scala.io.StdIn.readLine.split(" ").map(_.toInt)

	val map = scala.collection.mutable.Map[Int,Int]()

	for(x <- A){
		map.put(x - 1, map.getOrElse(x - 1, 0) + 1)
		map.put(x    , map.getOrElse(x    , 0) + 1)
		map.put(x + 1, map.getOrElse(x + 1, 0) + 1)
	}
	println(map.maxBy(_._2)._2)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val as = List.fill(n)(sc.nextInt()+1)
  val b = Array.fill(100002)(0)
  for (a <- as) {
    b(a-1) += 1
    b(a) += 1
    b(a+1) += 1
  }
  println(b.max)
}


import java.util.Scanner

object Main {

  def solve(sc: => Scanner): Unit = {
    val A1 = math.min(sc.nextLong * 4, math.min(sc.nextLong * 2, sc.nextLong))
    val A2 = math.min(A1 * 2, sc.nextLong)
    val N = sc.nextLong
    println((N / 2: Long) * A2 + N % 2 * A1)
  }

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

Score : 300 points

Problem Statement

You've come to your favorite store Infinitesco to buy some ice tea.

The store sells ice tea in bottles of different volumes at different costs.
Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen.
The store has an infinite supply of bottles of each type.

You want to buy exactly N liters of ice tea. How many yen do you have to spend?

Constraints

1 \leq Q, H, S, D \leq 10^8

1 \leq N \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q H S D
N

Output

Print the smallest number of yen you have to spend to buy exactly N liters of ice tea.

Sample Input 1

20 30 70 90
3

Sample Output 1

150

Buy one 2-liter bottle and two 0.5-liter bottles. You'll get 3 liters for 90 + 30 + 30 = 150 yen.

Sample Input 2

10000 1000 100 10
1

Sample Output 2

100

Even though a 2-liter bottle costs just 10 yen, you need only 1 liter.
Thus, you have to buy a 1-liter bottle for 100 yen.

Sample Input 3

10 100 1000 10000
1

Sample Output 3

40

Now it's better to buy four 0.25-liter bottles for 10 + 10 + 10 + 10 = 40 yen.

Sample Input 4

12345678 87654321 12345678 87654321
123456789

Sample Output 4

1524157763907942


import scala.io.StdIn

object Main extends App {

  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(" ")
  val r = a.foldLeft(Map.empty[Int, Int]) { (acc, s) =>
    val key = s.toInt
    if (acc.contains(key)) acc.updated(key, acc(key) + 1)
    else acc + (key -> 1)
  }

  val tar = r.filter(p => 2 <= p._2)
  val keys = tar.keys.toList.sortBy(e => -1 * e)
  val ans = if (tar.isEmpty) {
    0
  }else if (tar.getOrElse(keys.head, 0) >= 4) {
    keys.head * keys.head
  }
  else if (tar.getOrElse(keys.head, 0) >= 2 &&
    tar.getOrElse(keys.tail.head, 0) >= 2) {
    keys.head * keys.tail.head
  } else {
    0
  }
  println (ans)
}

Score : 300 points

Problem Statement

We have N sticks with negligible thickness.
The length of the i-th stick is A_i.

Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides.
Find the maximum possible area of the rectangle.

Constraints

4 \leq N \leq 10^5

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible area of the rectangle.
If no rectangle can be formed, print 0.

Sample Input 1

6
3 1 2 4 2 1

Sample Output 1

2

1 \times 2 rectangle can be formed.

Sample Input 2

4
1 2 3 4

Sample Output 2

0

No rectangle can be formed.

Sample Input 3

10
3 3 3 3 4 4 4 5 5 5

Sample Output 3

20


import java.util.Scanner

object Main extends App {

  val FF = (1 << 26) - 1

  val sc = new Scanner(System.in)

  val str = sc.next()
  var cs = Array.fill(26)(Seq[Int](Int.MaxValue))
  str.zipWithIndex
    .groupBy(_._1)
    .toStream
    .foreach {
      case (c, seq) =>
//        println(c, seq)
        cs(c - 'a') = seq.map(_._2) ++ Seq(Int.MaxValue)
    }

  var bf = 0
  var len = 0
  for (c <- str.reverse) {
    bf = bf | (1 << (c - 'a'))

    if (bf == FF) {
      bf = 0
      len = len + 1
    }
  }

//  cs.foreach(println(_))
//  println("info", len, bf)

  val head = Range(0, 26)
    .find(i => ((bf >> i) & 1) == 0).get
  print(('a' + head).toChar)

  var cur = cs(head)(0)
  for (i <- 1 to len) {
    cur = find(cur, len - i + 2)
  }
  println

  def find(x: Int, k: Int): Int = {
    for (c <- 0 to 25) {
      val t = find(x, cs(c))
//      println("inner", ('a' + c).toChar, k, t, cs(c).length - t)
      if (cs(c).length - t <= k) {
        print(('a' + c).toChar)
        return if (cs(c).isEmpty) 0 else cs(c)(t)
      }
    }
    0
  }

  def find(x: Int, seq: Seq[Int]) = {
    var l = 0
    var r = seq.length
    while (l < r) {
      val m = (l + r) / 2
      if (seq(m) <= x) l = m + 1
      else r = m
    }
    l
  }
}

Score : 600 points

Problem Statement

A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters.
For example, arc, artistic and (an empty string) are all subsequences of artistic; abc and ci are not.

You are given a string A consisting of lowercase English letters.
Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A.
If there are more than one such string, find the lexicographically smallest one among them.

Constraints

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

A consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

A

Output

Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.

Sample Input 1

atcoderregularcontest

Sample Output 1

b

The string atcoderregularcontest contains a as a subsequence, but not b.

Sample Input 2

abcdefghijklmnopqrstuvwxyz

Sample Output 2

aa

Sample Input 3

frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn

Sample Output 3

aca


import java.util.Scanner

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

  val n = sc.nextInt

  val res = if(n / 100 == n % 10) "Yes" else "No"

  println(res)
}

Score : 100 points

Problem Statement

You are given a three-digit positive integer N.

Determine whether N is a palindromic number.

Here, a palindromic number is an integer that reads the same backward as forward in decimal notation.

Constraints

100≤N≤999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a palindromic number, print Yes; otherwise, print No.

Sample Input 1

575

Sample Output 1

Yes

N=575 is also 575 when read backward, so it is a palindromic number. You should print Yes.

Sample Input 2

123

Sample Output 2

No

N=123 becomes 321 when read backward, so it is not a palindromic number. You should print No.

Sample Input 3

812

Sample Output 3

No


import java.util.Scanner

object Main {
  def solve(sc: => Scanner): Unit = {
    val S = sc.next
    println(if (S.reverse.equals(S)) ("Yes") else ("No"))
  }

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


object Main {
    def main(args: Array[String]) : Unit = {
        val sc = new java.util.Scanner(System.in)
        val a, b, c, d  = sc.nextInt
        println(calc(a, b, c, d))
    }
    def calc(a: Int, b: Int, c: Int, d: Int) : Int = {
        var ans = max(b - c, 0)
        if (ans > 0 && b - d > 0) {
            ans -= b - d
        }
        ans
    }
    def max(a: Int, b: Int) : Int = { if (a > b) a else b }
}

Score : 200 points

Problem Statement

Alice and Bob are controlling a robot. They each have one switch that controls the robot.

Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up.

Bob started holding down his button C second after the start-up, and released his button D second after the start-up.

For how many seconds both Alice and Bob were holding down their buttons?

Constraints

0≤A<B≤100

0≤C<D≤100

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.

Sample Input 1

0 75 25 100

Sample Output 1

50

Alice started holding down her button 0 second after the start-up of the robot, and released her button 75 second after the start-up.

Bob started holding down his button 25 second after the start-up, and released his button 100 second after the start-up.

Therefore, the time when both of them were holding down their buttons, is the 50 seconds from 25 seconds after the start-up to 75 seconds after the start-up.

Sample Input 2

0 33 66 99

Sample Output 2

0

Alice and Bob were not holding their buttons at the same time, so the answer is zero seconds.

Sample Input 3

10 90 20 80

Sample Output 3

60


import scala.io.StdIn.readLine

object Main {
    def main(args: Array[String]){
        val intArray= readLine.split(" ").map(_.toInt)
        println(calc(intArray))
    }

    def calc(args: Array[Int]): Int = {
        val a = args(0)
        val b = args(1)
        val c = args(2)
        val d = args(3)

        val e1 = List(a, c).max
        val e2 = List(b, d).min

        if (e2 - e1 < 0) return 0
        return e2 - e1
    }
}


import scala.io.StdIn

import scala.annotation.tailrec

object Main extends App {
  val n = StdIn.readInt

  @tailrec
  def gdc(x:Long, y:Long):Long = {
    if(y == 0) x
    else gdc(y, x % y)
  }

  def lcm(x:Long, y:Long):Long = {
    x * (y / gdc(x, y))
  }

  val ans = Iterator.continually(StdIn.readLine.toLong)
    .take(n)
    ./:(0L,1L)((acc,e) => {
      val a:Long = lcm(acc._2, e)
      (a,e)
    })._1

  println(ans)
}

Score : 300 points

Problem Statement

We have N clocks. The hand of the i-th clock (1≤i≤N) rotates through 360° in exactly T_i seconds.

Initially, the hand of every clock stands still, pointing directly upward.

Now, Dolphin starts all the clocks simultaneously.

In how many seconds will the hand of every clock point directly upward again?

Constraints

1≤N≤100

1≤T_i≤10^{18}

All input values are integers.

The correct answer is at most 10^{18} seconds.

Input

Input is given from Standard Input in the following format:

N
T_1
:
T_N

Output

Print the number of seconds after which the hand of every clock point directly upward again.

Sample Input 1

2
2
3

Sample Output 1

6

We have two clocks. The time when the hand of each clock points upward is as follows:

Clock 1: 2, 4, 6, ... seconds after the beginning

Clock 2: 3, 6, 9, ... seconds after the beginning

Therefore, it takes 6 seconds until the hands of both clocks point directly upward.

Sample Input 2

5
2
5
10
1000000000000000000
1000000000000000000

Sample Output 2

1000000000000000000


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

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

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

  val Q, K = in.next().toInt

  // dfs
  val stack = new scala.collection.mutable.Stack[(Int, Int)] // (nowNode, cost)
  stack.push((K, 0))

  val dp = new Array[Long](N+1)
  dp(K) = 2

  while (!stack.isEmpty) {
    val (now, accCost) = stack.pop
    for((node, cost) <- graph(now)) {
      if(dp(node) == 0) {
        dp(node) = accCost + cost
        stack.push((node, accCost + cost))
      }
    }
  }

  for (_ <- 1 to Q) {
    val x, y = in.next().toInt
    val ans = dp(x) + dp(y)
    pw.println(ans)
  }
  pw.flush()

}

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

Score : 400 points

Problem Statement

You are given a tree with N vertices.

Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.

The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.

You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):

find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.

Constraints

3≤N≤10^5

1≤a_i,b_i≤N (1≤i≤N-1)

1≤c_i≤10^9 (1≤i≤N-1)

The given graph is a tree.

1≤Q≤10^5

1≤K≤N

1≤x_j,y_j≤N (1≤j≤Q)

x_j≠y_j (1≤j≤Q)

x_j≠K,y_j≠K (1≤j≤Q)

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}

Output

Print the responses to the queries in Q lines.

In the j-th line j(1≤j≤Q), print the response to the j-th query.

Sample Input 1

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

Sample Output 1

3
2
4

The shortest paths for the three queries are as follows:

Query 1: Vertex 2 → Vertex 1 → Vertex 2 → Vertex 4 : Length 1+1+1=3

Query 2: Vertex 2 → Vertex 1 → Vertex 3 : Length 1+1=2

Query 3: Vertex 4 → Vertex 2 → Vertex 1 → Vertex 3 → Vertex 5 : Length 1+1+1+1=4

Sample Input 2

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

Sample Output 2

5
14
22

The path for each query must pass Vertex K=2.

Sample Input 3

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

Sample Output 3

17000000000


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val a = List.fill(n)(sc.nextInt)

    val multipleOf4 = a.filter( _ % 4 == 0)
    val multipleOf2 = a.filter( _ % 2 == 0)
    val ans = if (multipleOf4.length <= a.length / 2) {
      if (multipleOf4.length + (multipleOf2.length - multipleOf4.length) / 2 <= a.length / 2) "Yes"
      else "No"
    }
    else "Yes"

    println(ans)
  }
}

Score : 100 points

Problem Statement

In K-city, there are n streets running east-west, and m streets running north-south. Each street running east-west and each street running north-south cross each other. We will call the smallest area that is surrounded by four streets a block. How many blocks there are in K-city?

Constraints

2 ≤ n, m ≤ 100

Input

Input is given from Standard Input in the following format:

n m

Output

Print the number of blocks in K-city.

Sample Input 1

3 4

Sample Output 1

6

There are six blocks, as shown below:

Sample Input 2

2 2

Sample Output 2

1

There are one block, as shown below:


import scala.io.StdIn

object Main extends App {

  val n = StdIn.readInt
  val a = StdIn.readLine.split(" ").map(_.toLong)

  val (odd, even, mlt4) = a./:(0,0,0)((cnt,i) => {
    val odd = if((i&1) == 1) 1 else 0
    val even = if((i&1) == 0) 1 else 0
    val mlt4 = if((i&3) == 0) 1 else 0
    (cnt._1+odd, cnt._2+even, cnt._3+mlt4)
  })

  val ans = if(odd == mlt4+1) {
    if(even == mlt4) "Yes"
    else "No"
  }
  else if(odd <= mlt4) "Yes" else "No"

  println(ans)
}

Score : 400 points

Problem Statement

We have a sequence of length N, a = (a_1, a_2, ..., a_N).
Each a_i is a positive integer.

Snuke's objective is to permute the element in a so that the following condition is satisfied:

For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.

Determine whether Snuke can achieve his objective.

Constraints

2 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If Snuke can achieve his objective, print Yes; otherwise, print No.

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is (1, 100, 10).

Sample Input 2

4
1 2 3 4

Sample Output 2

No

It is impossible to permute a so that the condition is satisfied.

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes


import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val h, w = sc.nextInt
    val n = sc.nextInt
    val as = Vector.fill(n)(sc.nextInt)

    val rows = split(go(1, as, Vector[Vector[Int]]()).flatten, w)
    val ans = reverseOdd(rows)

    ans.foreach{ a =>
      a.foreach { b =>
        printf("%s ", b)
      }
      println()
    }

  }

  @tailrec
  def go(i: Int, seq: Seq[Int], result: Seq[Seq[Int]]): Seq[Seq[Int]] = {
    if (seq.length == 0) result
    else go(i+1, seq.tail, result :+ Seq.fill(seq.head)(i))
  }

  def split(seq: Seq[Int], n: Int): Seq[Seq[Int]] = {
    def go(s: Seq[Int], result: Seq[Seq[Int]]): Seq[Seq[Int]] = {
      if (s.length == 0) result
      else go(s.drop(n), result :+ s.dropRight(s.length - n))
    }
    go(seq, Seq[Seq[Int]]())
  }

  def reverseOdd(seq: Seq[Seq[Int]]): Seq[Seq[Int]] = {
    def go(i: Int, s: Seq[Seq[Int]], result: Seq[Seq[Int]]): Seq[Seq[Int]] = {
      if (s.length == 0) result
      else if (i % 2 == 0) go(i+1, s.tail, result :+ s.head)
      else go(i+1, s.tail, result :+ s.head.reverse)
    }
    go(0, seq, Seq[Seq[Int]]())
  }
}

Score : 400 points

Problem Statement

We have a grid with H rows and W columns of squares.
Snuke is painting these squares in colors 1, 2, ..., N.
Here, the following conditions should be satisfied:

For each i (1 ≤ i ≤ N), there are exactly a_i squares painted in Color i. Here, a_1 + a_2 + ... + a_N = H W.

For each i (1 ≤ i ≤ N), the squares painted in Color i are 4-connected. That is, every square painted in Color i can be reached from every square painted in Color i by repeatedly traveling to a horizontally or vertically adjacent square painted in Color i.

Find a way to paint the squares so that the conditions are satisfied.
It can be shown that a solution always exists.

Constraints

1 ≤ H, W ≤ 100

1 ≤ N ≤ H W

a_i ≥ 1

a_1 + a_2 + ... + a_N = H W

Input

Input is given from Standard Input in the following format:

H W
N
a_1 a_2 ... a_N

Output

Print one way to paint the squares that satisfies the conditions.
Output in the following format:

c_{1 1} ... c_{1 W}
:
c_{H 1} ... c_{H W}

Here, c_{i j} is the color of the square at the i-th row from the top and j-th column from the left.

Sample Input 1

2 2
3
2 1 1

Sample Output 1

1 1
2 3

Below is an example of an invalid solution:

1 2
3 1

This is because the squares painted in Color 1 are not 4-connected.

Sample Input 2

3 5
5
1 2 3 4 5

Sample Output 2

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

Sample Input 3

1 1
1
1

Sample Output 3

1


import scala.io.StdIn

import scala.annotation.tailrec

object Main extends App {
  val n = StdIn.readInt

  @tailrec
  def rec(acc:Int,num:Int):Int = {
    if((num&1) == 1) acc
    else {
      rec(acc+1,num>>1)
    }
  }
  val ans = (1 to n)./:(1,0)((max,i) => {
    val cnt = rec(0,i)
    if(max._2 < cnt) (i,cnt) else max
  })._1
  println(ans)
}

Score : 200 points

Problem Statement

Takahashi loves numbers divisible by 2.

You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique.

Here, the number of times an integer can be divisible by 2, is how many times the integer can be divided by 2 without remainder.

For example,

6 can be divided by 2 once: 6 -> 3.

8 can be divided by 2 three times: 8 -> 4 -> 2 -> 1.

3 can be divided by 2 zero times.

Constraints

1 ≤ N ≤ 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

7

Sample Output 1

4

4 can be divided by 2 twice, which is the most number of times among 1, 2, ..., 7.

Sample Input 2

32

Sample Output 2

32

Sample Input 3

1

Sample Output 3

1

Sample Input 4

100

Sample Output 4

64


import java.util
import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    var ans = 0
    for(i <- 1 to n) {
      var j = i
      var cnt = 0
      while(j%2==0) {
        j /= 2
        cnt += 1
      }
      ans = Math.max(ans, cnt)
    }
    println(ans)
  }
}


object Main extends App {
	val N = scala.io.StdIn.readInt

	if(N<2) println(1)
	else if(N<4) println(2)
	else if(N<8) println(4)
	else if(N<16) println(8)
	else if(N<32) println(16)
	else if(N<64) println(32)
	else println(64)
}


import scala.io.StdIn
import scala.collection.mutable._

object Main extends App {

  val Array(n, m) = StdIn.readLine.split(" ").map(_.toInt)
  val graph = Array.fill(n+1)(ListBuffer.empty[Int])
  Iterator.continually(StdIn.readLine)
    .take(m)
    .map(_.split(" ").map(_.toInt))
    .foreach(e => graph(e(0)) += e(1))

  val visit = Array.ofDim[Boolean](n+1)
  def dfs(pos:Int, cnt:Int):Unit = {
    if(cnt < 0) return
    visit(pos) = true
    // print(pos + " ")
    for(i <- graph(pos)) {
      dfs(i, cnt-1)
    }
  }

  dfs(1,2)
  val ans = if(visit(n)) "POSSIBLE" else "IMPOSSIBLE"
  println(ans)
}

Score : 300 points

Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands.
For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands.
Each service connects two islands. The i-th service connects Island a_i and Island b_i.

Cat Snuke is on Island 1 now, and wants to go to Island N.
However, it turned out that there is no boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

Help him.

Constraints

3 ≤ N ≤ 200 000

1 ≤ M ≤ 200 000

1 ≤ a_i < b_i ≤ N

(a_i, b_i) \neq (1, N)

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

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

POSSIBLE

Sample Input 2

4 3
1 2
2 3
3 4

Sample Output 2

IMPOSSIBLE

You have to use three boat services to get to Island 4.

Sample Input 3

100000 1
1 99999

Sample Output 3

IMPOSSIBLE

Sample Input 4

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

Sample Output 4

POSSIBLE

You can get to Island 5 by using two boat services: Island 1 -> Island 4 -> Island 5.


object Main extends App {
	val NM = scala.io.StdIn.readLine.split(" ").map(_.toInt)

	var a = List[Int]()
	var b = List[Int]()

	for(i<-0 until NM(1)){
		val t = scala.io.StdIn.readLine.split(" ").map(_.toInt)
		if(t(0) == 1) a = t(1)::a
		if(t(1) == NM(0)) b = t(0)::b
	}

	def find(a: List[Int], b: List[Int]): Boolean = {
		for(i<-a){
			if(b.contains(i)) return true
		}
		return false
	}

	if(find(a,b)) println("POSSIBLE")
	else println("IMPOSSIBLE")

}


object Main extends App {
  val in = io.StdIn.readLine().split(" ").map(_.toInt)
  val A = in(0)
  val B = in(1)
  if (A % 3 == 0 || B % 3 == 0 || (A + B) % 3 == 0)
    println("Possible")
  else
    println("Impossible")

}

Score : 100 points

Problem Statement

Snuke is giving cookies to his three goats.

He has two cookie tins. One contains A cookies, and the other contains B cookies. He can thus give A cookies, B cookies or A+B cookies to his goats (he cannot open the tins).

Your task is to determine whether Snuke can give cookies to his three goats so that each of them can have the same number of cookies.

Constraints

1 \leq A,B \leq 100

Both A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If it is possible to give cookies so that each of the three goats can have the same number of cookies, print Possible; otherwise, print Impossible.

Sample Input 1

4 5

Sample Output 1

Possible

If Snuke gives nine cookies, each of the three goats can have three cookies.

Sample Input 2

1 1

Sample Output 2

Impossible

Since there are only two cookies, the three goats cannot have the same number of cookies no matter what Snuke gives to them.


import scala.io.StdIn

object Main extends App {
  val Array(n, k) = StdIn.readLine.split(" ").map(_.toInt)
  val ans = StdIn.readLine.split(" ").map(_.toInt)
    .sorted.takeRight(k).sum
  println(ans)
}

Score : 200 points

Problem Statement

Snuke has N sticks.
The length of the i-th stick is l_i.

Snuke is making a snake toy by joining K of the sticks together.

The length of the toy is represented by the sum of the individual sticks that compose it.
Find the maximum possible length of the toy.

Constraints

1 \leq K \leq N \leq 50

1 \leq l_i \leq 50

l_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
l_1 l_2 l_3 ... l_{N}

Output

Print the answer.

Sample Input 1

5 3
1 2 3 4 5

Sample Output 1

12

You can make a toy of length 12 by joining the sticks of lengths 3, 4 and 5, which is the maximum possible length.

Sample Input 2

15 14
50 26 27 21 41 7 42 35 7 5 5 36 39 1 45

Sample Output 2

386


object Main {

	def main(arg:Array[String]) = {
		var list = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList;
		var l = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList;
		println(l.sorted.takeRight(list(1)).sum);
	}

}


import java.util.Scanner

/**
  * Created by goryudyuma on 2017/07/16.
  */

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

    for (i <- 0 until N) {
      arr(i) = sc.nextInt()
    }

    println(arr.sorted.reverse.splitAt(K)._1.sum)
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val as = Array.fill(n)(sc.nextLong)
  var i = as.sum
  var min = Integer.MAX_VALUE.toLong
  as.drop(1).reverseIterator.foreach { a =>
    i -= a * 2
    if (math.abs(i) < min) min = math.abs(i)
  }
  println(min)
}

Score : 300 points

Problem Statement

Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.

They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards.
Here, both Snuke and Raccoon have to take at least one card.

Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively.
They would like to minimize |x-y|.
Find the minimum possible value of |x-y|.

Constraints

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

-10^{9} \leq a_i \leq 10^{9}

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Print the answer.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

1

If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, x=10, y=11, and thus |x-y|=1. This is the minimum possible value.

Sample Input 2

2
10 -10

Sample Output 2

20

Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, x=10, y=-10, and thus |x-y|=20.


import scala.io.StdIn.readLine

object Main extends App {
  val MOD = 1000000007
  val n = readLine.toInt
  val a = readLine.split(" ").map(_.toLong).sorted

  val s = a.sum
  val half = s  / 2

  def calc(id: Int, curVal: Long, count: Int): Long = {
    if(id >= n - 1 || half < curVal || count == n - 1) math.abs(s - 2 * curVal)
    else {
      val a1 = calc(id + 1, curVal, count)
      val a2 = calc(id + 1, curVal + a(id + 1), count + 1)
      math.min(a1, a2)
    }
  }

  val ans = (for(i <- 0 until n) yield calc(i, a(i), 1)).min
  println(ans)
}


object Main extends App {
	val temp = scala.io.StdIn.readLine.split(" ").map(_.toLong)

	val N = temp(0)
	val A = temp(1)
	val B = temp(2)
	val C = temp(3)
	val D = temp(4)

	println(temp.mkString(" "))

	val sum = B - A

	var resalt = "NO"

	for(i<- 0L until N){
		val under = i * C - (N - 1 - i) * D
		val top = i * D - (N - 1 - i) * C

//		println(s" ${under} < ${sum} < ${top}")

		if(under <= sum && sum <= top){
			resalt = "YES"
		}
	}

	println(resalt)

}

Score : 400 points

Problem Statement

There are N squares in a row.
The leftmost square contains the integer A, and the rightmost contains the integer B. The other squares are empty.

Aohashi would like to fill the empty squares with integers so that the following condition is satisfied:

For any two adjacent squares, the (absolute) difference of the two integers in those squares is between C and D (inclusive).

As long as the condition is satisfied, it is allowed to use arbitrarily large or small integers to fill the squares.
Determine whether it is possible to fill the squares under the condition.

Constraints

3 \leq N \leq 500000

0 \leq A \leq 10^9

0 \leq B \leq 10^9

0 \leq C \leq D \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B C D

Output

Print YES if it is possible to fill the squares under the condition; print NO otherwise.

Sample Input 1

5 1 5 2 4

Sample Output 1

YES

For example, fill the squares with the following integers: 1, -1, 3, 7, 5, from left to right.

Sample Input 2

4 7 6 4 5

Sample Output 2

NO

Sample Input 3

48792 105960835 681218449 90629745 90632170

Sample Output 3

NO

Sample Input 4

491995 412925347 825318103 59999126 59999339

Sample Output 4

YES


object Main {
  def main(args: Array[String]) {
    import scala.io.StdIn.readLine
    val Array(a, b, c) = readLine split " " map (_.toInt)
    println(Seq(a+b, b+c, c+a).max)
  }
}

Score : 100 points

Problem Statement

Snuke is buying a bicycle.
The bicycle of his choice does not come with a bell, so he has to buy one separately.

He has very high awareness of safety, and decides to buy two bells, one for each hand.

The store sells three kinds of bells for the price of a, b and c yen (the currency of Japan), respectively.
Find the minimum total price of two different bells.

Constraints

1 \leq a,b,c \leq 10000

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print the minimum total price of two different bells.

Sample Input 1

700 600 780

Sample Output 1

1300

Buying a 700-yen bell and a 600-yen bell costs 1300 yen.

Buying a 700-yen bell and a 780-yen bell costs 1480 yen.

Buying a 600-yen bell and a 780-yen bell costs 1380 yen.

The minimum among these is 1300 yen.

Sample Input 2

10000 10000 10000

Sample Output 2

20000

Buying any two bells costs 20000 yen.