import scala.annotation.tailrec

object Main extends App {
  val N = MyPredef2.nextInt // 寿司の数
  val C = MyPredef2.nextLong // 外周
  val inputSushi :Array[Array[Long]] = Array.fill(N, 2)(MyPredef2.nextLong) // 距離, calの配列

  @tailrec
  def makeSushiArray(ind :Int, sumCal: Long, maxCal: Long, sushi :Array[Array[Long]] ,res :Array[Sushi]): Array[Sushi] = {
    val target = sushi(ind)
    val tCal = sumCal + target(1) - target(0)
    var tMaxCal = maxCal
    if (maxCal < tCal) {
      tMaxCal = tCal
    }
    val tSushi = new Sushi(target(0), tMaxCal)

    if (ind < N - 1) {
      makeSushiArray(ind + 1, tCal + target(0), tMaxCal, sushi, res :+ tSushi)
    } else {
      res :+ tSushi
    }
  }
  val rSushi :Array[Sushi] = makeSushiArray(0, 0, 0, inputSushi, Array.empty[Sushi])
  val reverseSushi = inputSushi.reverse.map(x => Array(C - x(0), x(1)))
  val lSushi :Array[Sushi] = makeSushiArray(0,0,0,reverseSushi, Array.empty[Sushi])

  var rMax :Long = rSushi.maxBy(_.maxCal).maxCal
  for (i <- 0 until N - 1) {
    val tMax = rSushi(i).maxCal - rSushi(i).dist + lSushi(N - 2 - i).maxCal
    if (tMax > rMax) rMax = tMax
  }

  var lMax :Long = lSushi.maxBy(_.maxCal).maxCal
  for (i <- 0 until N - 1) {
    val tMax = lSushi(i).maxCal - lSushi(i).dist + rSushi(N - 2 - i).maxCal
    if (tMax > lMax) lMax = tMax
  }

  if (rMax > lMax) println(rMax)
  else println(lMax)
}

// 始点からの距離と、その時点での最大カロリーを持つ
case class Sushi(dist: Long, maxCal: Long) {}

object MyPredef2 {
  @inline def rep(n: Int, f: => Unit): Unit = { var c = 0; while (c < n) { f; c += 1 } }
  @inline def rep(n: Int, f: Int => Unit): Unit = { var c = 0; while (c < n) { f(c); c += 1 } }

  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}

Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.


import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(' ').map(_.toInt)

  val mid = (n / 2) - 1
  val r = (0 until n).map { i =>
    val t = a.slice(0, i) ++ a.slice(i+1, n)
    val s = t.sorted
    //println(s.mkString(" "))
    s(mid)
  }

  r.foreach(println)

}

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

Score : 300 points

Problem Statement

When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.

You are given N numbers X_1, X_2, ..., X_N, where N is an even number.
For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N be B_i.

Find B_i for each i = 1, 2, ..., N.

Constraints

2 \leq N \leq 200000

N is even.

1 \leq X_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print N lines.
The i-th line should contain B_i.

Sample Input 1

4
2 4 4 3

Sample Output 1

4
3
3
4

Since the median of X_2, X_3, X_4 is 4, B_1 = 4.

Since the median of X_1, X_3, X_4 is 3, B_2 = 3.

Since the median of X_1, X_2, X_4 is 3, B_3 = 3.

Since the median of X_1, X_2, X_3 is 4, B_4 = 4.

Sample Input 2

2
1 2

Sample Output 2

2
1

Sample Input 3

6
5 5 4 4 3 3

Sample Output 3

4
4
4
4
4
4

Submitted source-code file size, in bytes.

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

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


object Main {

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

    val N = sc.nextInt()
    val A = Array.fill(N)(sc.nextInt()).sorted

    // comb(ai, aj), これは ai を固定した時には,
    // 単峰関数のような関数 f_ai(x) = comb(ai, x)
    // となる。すると, 最大の値の候補は
    // ai の真ん中もしくは, 真ん中に近い2つの値が候補になる
    // これは, 二分探索で探せるのでいける
    // これを全てのaiについて調べても間に合う
    // 実際に combを計算する必要はない
    def solve(N: Int, A: Array[Int]): (Int, Int) = {
      // aj >= n となる 最小の aj を返す
      def upperBounds(n: Int, upper: Int): Int = {
        @scala.annotation.tailrec
        def loop(left: Int, right: Int): Int =
          if (right - left > 1) {
            val mid = left + (right - left) / 2
            if (A(mid) >= n) loop(left, mid)
            else loop(mid, right)
          } else right
        loop(-1, upper - 1)
      }
      // aj <= n となる最大の aj を 返す
      def lowerBounds(n: Int, upper: Int): Int = {
        @scala.annotation.tailrec
        def loop(left: Int, right: Int): Int =
          if (right - left > 1) {
            val mid = left + (right - left) / 2
            if (A(mid) <= n) loop(mid, right)
            else loop(left, mid)
          } else left
        loop(0, upper)
      }

      @scala.annotation.tailrec
      def loop(i: Int, diff: Int, n: Int, r: Int): (Int, Int) =
        if (i < N) {
          val center = A(i) / 2
          val left = A(lowerBounds(center, i))
          val right = A(upperBounds(center, i))
          if (left > A(i) - right) {
            if (left >= diff) loop(i + 1, left, A(i), left)
            else loop(i + 1, diff, n, r)
          } else {
            if (A(i) - right >= diff) loop(i + 1, A(i) - right, A(i), right)
            else loop(i + 1, diff, n, r)
          }
        } else (n, r)

      loop(1, 0, 0, 0)
    }

    val (n, r) = solve(N, A)
    println(s"$n $r")
  }

}

Score : 400 points

Problem Statement

Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order.
From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

a_1,a_2,...,a_n are pairwise distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print a_i and a_j that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

\rm{comb}(a_i,a_j) for each possible selection is as follows:

\rm{comb}(4,2)=6

\rm{comb}(6,2)=15

\rm{comb}(6,4)=15

\rm{comb}(9,2)=36

\rm{comb}(9,4)=126

\rm{comb}(9,6)=84

\rm{comb}(11,2)=55

\rm{comb}(11,4)=330

\rm{comb}(11,6)=462

\rm{comb}(11,9)=55

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    inner(n, width - 1)
  }

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

    inner(n % m, p, 1)
  }

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

    val xsSorted = xs.sorted
    val median1 = xsSorted(n / 2 - 1)
    val median2 = xsSorted(n / 2)

    n.times { i =>
      out.println(
        if (xs(i) <= median1) {
          median2
        } else {
          median1
        }
      )
    }

    out.flush()
  }
}


import scala.io.StdIn._
object Main extends App{
  val sc = new java.util.Scanner(System.in)
  var s = sc.next
  if(s.contains("a")&&s.contains("b")&&s.contains("c")){
    println("Yes")
  }
  else{
    println("No")
  }
}

Score : 100 points

Problem Statement

You are given a string S of length 3 consisting of a, b and c. Determine if S can be obtained by permuting abc.

Constraints

|S|=3

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If S can be obtained by permuting abc, print Yes; otherwise, print No.

Sample Input 1

bac

Sample Output 1

Yes

Swapping the first and second characters in bac results in abc.

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val a, b, k = sc.nextInt()
  var ans = ((a until (a + k).min(b)) ++ ((b - k + 1).max(a) to b)).distinct
  ans.foreach(println)
}

Score : 200 points

Problem Statement

Print all the integers that satisfies the following in ascending order:

Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.

Constraints

1 \leq A \leq B \leq 10^9

1 \leq K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print all the integers that satisfies the condition above in ascending order.

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

3 is the first smallest integer among the integers between 3 and 8.

4 is the second smallest integer among the integers between 3 and 8.

7 is the second largest integer among the integers between 3 and 8.

8 is the first largest integer among the integers between 3 and 8.

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9


import scala.collection.generic.CanBuild
import scala.io.StdIn
import scala.language.higherKinds

// TODO: write well formed Docs!

case class StdInScanner[A](scan: StdIn.type => A) {
  // transform read result by "f"
  def map[B](f: A => B): StdInScanner[B] =
    StdInScanner(in => f(scan(in)))

  // run this to read A, then obtain new scanner from A using "f", then run the new scanner
  def flatMap[B](f: A => StdInScanner[B]): StdInScanner[B] =
    StdInScanner(in => f(scan(in)).scan(in))

  // run entire scanner and get result
  def run: A = scan(StdIn)
}

object StdInScanner {
  // read nothing, and return specified "a"
  def apply[A](a: A): StdInScanner[A] = StdInScanner(_ => a)
  // read nothing, and return ()
  def unit: StdInScanner[Unit] = StdInScanner(())

  // read a line
  def readLine: StdInScanner[String] = StdInScanner(s => s.readLine().trim)
  // read a line as Int
  def readLnInt: StdInScanner[Int] = StdInScanner(s => s.readInt())
  // read a line as BigInt
  def readLnBigInt: StdInScanner[BigInt] = readLine.map(BigInt(_))

  // read tokens (separated by "sep") from a line, and store them in an array
  def readTokens(sep: String): StdInScanner[Array[String]] =
    readLine.map(_.split(sep).map(_.trim))
  // read tokens (separated by "sep") from a line, and store them in a collection (type "C")
  def readTokensTo[C[_]](sep: String)(implicit cb: CanBuild[String, C[String]]): StdInScanner[C[String]] =
    readTokens(sep).map(_.to[C])

  // read "n" lines, and store them in an array
  def readLines(n: Int): StdInScanner[Array[String]] =
    StdInScanner(s => Array.fill(n)(s.readLine().trim))
  // read "n" lines, and store them in a collection "C"
  def readLinesTo[C[_]](n: Int)(implicit cb: CanBuild[String, C[String]]): StdInScanner[C[String]] =
    readLines(n).map(_.to[C])

  // read "n" ints from lines. and store them in an array
  def readInts(n: Int): StdInScanner[Array[Int]] =
    StdInScanner(s => Array.fill(n)(s.readInt()))
  // read "n" ints from lines. and store them in a collection "C"
  def readIntsTo[C[_]](n: Int)(implicit cb: CanBuild[Int, C[Int]]): StdInScanner[C[Int]] =
    readInts(n).map(_.to[C])

  // read a table of "n" rows
  def readTable(rows: Int, sep: String = " "): StdInScanner[Array[Array[String]]] =
    readLines(rows).map{ lns =>
      lns.map(ln => ln.split(sep).map(tkn => tkn.trim))
    }

  // read a 2D int matrix of "n" rows, stored in an array of arrays
  def readIntMatrix(rows: Int, sep: String = " "): StdInScanner[Array[Array[Int]]] =
    readLines(rows).map{ lns =>
      lns.map(ln => ln.split(sep).map(tkn => tkn.toInt))
    }

  // read a 2D int matrix of "n" rows, stored in a collection of collections ("C[C[Int]")
  def readIntMatrixTo[C[_]](rows: Int, sep: String = " ")(implicit cb1: CanBuild[Int, C[Int]] ,cb2: CanBuild[C[Int], C[C[Int]]]): StdInScanner[C[C[Int]]] =
    readIntMatrix(rows, sep).map { mat =>
      mat.map(row => row.to[C]).to[C]
    }
}

object Main {

  import StdInScanner._

  def main(args: Array[String]) = {
    def abk = readTokens(" ").map(_.map(_.toInt)).run
    val Array(a, b, k) = abk
    val s = scala.collection.mutable.TreeSet.empty[Int]
    for (i <- 0 until k) {
      if(a + i <= b) {
        s += (a + i)
      }
      if(b - i >= a) {
        s += (b - i)
      }
    }

    s.foreach(println)
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val d = sc.nextInt()
  val x = sc.nextInt()
  val ret = for (i <- 1 to n) yield {
    calc(0, sc.nextInt(), List()).length
  }
  println(ret.sum + x)

  def calc(i: Int, a: Int, acc: List[Int]): List[Int] = {
    if (!acc.isEmpty && d < i*a+1) {
      acc
    } else {
      calc(i+1, a, acc:+(i*a+1))
    }
  }
}

Score : 200 points

Problem Statement

Some number of chocolate pieces were prepared for a training camp.
The camp had N participants and lasted for D days.
The i-th participant (1 \leq i \leq N) ate one chocolate piece on each of the following days in the camp: the 1-st day, the (A_i + 1)-th day, the (2A_i + 1)-th day, and so on.
As a result, there were X chocolate pieces remaining at the end of the camp. During the camp, nobody except the participants ate chocolate pieces.

Find the number of chocolate pieces prepared at the beginning of the camp.

Constraints

1 \leq N \leq 100

1 \leq D \leq 100

1 \leq X \leq 100

1 \leq A_i \leq 100 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
D X
A_1
A_2
:
A_N

Output

Find the number of chocolate pieces prepared at the beginning of the camp.

Sample Input 1

3
7 1
2
5
10

Sample Output 1

8

The camp has 3 participants and lasts for 7 days.
Each participant eats chocolate pieces as follows:

The first participant eats one chocolate piece on Day 1, 3, 5 and 7, for a total of four.

The second participant eats one chocolate piece on Day 1 and 6, for a total of two.

The third participant eats one chocolate piece only on Day 1, for a total of one.

Since the number of pieces remaining at the end of the camp is one, the number of pieces prepared at the beginning of the camp is 1 + 4 + 2 + 1 = 8.

Sample Input 2

2
8 20
1
10

Sample Output 2

29

Sample Input 3

5
30 44
26
18
81
18
6

Sample Output 3

56


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val n = Array.fill(sc.nextInt())(sc.next()).groupMapReduce(identity)(_ => 1)(_ + _)
  val m = Array.fill(sc.nextInt())(sc.next()).groupMapReduce(identity)(_ => 1)(_ + _)
  val ans = n.keys.map(key => n.getOrElse(key, 0) - m.getOrElse(key, 0)).max
  println(if (ans < 0) 0 else ans)
}

Score : 200 points

Problem Statement

Takahashi has N blue cards and M red cards.
A string is written on each card. The string written on the i-th blue card is s_i, and the string written on the i-th red card is t_i.

Takahashi will now announce a string, and then check every card. Each time he finds a blue card with the string announced by him, he will earn 1 yen (the currency of Japan); each time he finds a red card with that string, he will lose 1 yen.

Here, we only consider the case where the string announced by Takahashi and the string on the card are exactly the same. For example, if he announces atcoder, he will not earn money even if there are blue cards with atcoderr, atcode, btcoder, and so on. (On the other hand, he will not lose money even if there are red cards with such strings, either.)

At most how much can he earn on balance?

Note that the same string may be written on multiple cards.

Constraints

N and M are integers.

1 \leq N, M \leq 100

s_1, s_2, ..., s_N, t_1, t_2, ..., t_M are all strings of lengths between 1 and 10 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N
M
t_1
t_2
:
t_M

Output

If Takahashi can earn at most X yen on balance, print X.

Sample Input 1

3
apple
orange
apple
1
grape

Sample Output 1

2

He can earn 2 yen by announcing apple.

Sample Input 2

3
apple
orange
apple
5
apple
apple
apple
apple
apple

Sample Output 2

1

If he announces apple, he will lose 3 yen. If he announces orange, he can earn 1 yen.

Sample Input 3

1
voldemort
10
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort

Sample Output 3

0

If he announces voldemort, he will lose 9 yen. If he announces orange, for example, he can avoid losing a yen.

Sample Input 4

6
red
red
blue
yellow
yellow
red
5
red
red
yellow
green
blue

Sample Output 4

1


import scala.io.StdIn
object Main extends App {
  case class Point(x: Int, y: Int)
  def readPoints(n: Int): List[Point] = (0 until n).foldLeft(List.empty[Point]){
    (acc, _)  =>
      val wkp = StdIn.readLine().trim.split(' ').map(_.toInt)
      Point(wkp(0), wkp(1)) :: acc
    }

  def comparePoint(red: Point, blue: Point): Boolean = red.x < blue.x && red.y < blue.y

  val pointCount = StdIn.readLine().trim.toInt
  val redPoints = readPoints(pointCount).sortBy(e => (e.x, e.y))
  val bluePoints = readPoints(pointCount).sortBy(e => (e.x, e.y))

  val wk = redPoints.map{ red =>
    bluePoints.map{ blue =>
      (red, blue)
    }
  }.flatten.filter(e => comparePoint(e._1, e._2)).groupBy(e => e._1).toList.sortBy(l => (l._2.size, -l._1.x, -l._1.y))

  //println(wk)
  val result = wk.foldLeft(0, Set.empty[Point], Set.empty[Point]){ (acc, e) =>
    var cnt = acc._1
    var checkRed = acc._2
    var checkBlue = acc._3
    e._2.foreach{ be =>
      cnt = if(checkRed.contains(e._1) || checkBlue.contains(be._2)){
        cnt
      } else {
        checkRed += e._1
        checkBlue += be._2
        cnt + 1
      }
    }

    (cnt, checkRed, checkBlue)

  }

  println(result._1)

}

Score : 400 points

Problem Statement

On a two-dimensional plane, there are N red points and N blue points.
The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i).

A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, and the y-coordinate of the red point is also smaller than that of the blue point.

At most how many friendly pairs can you form? Note that a point cannot belong to multiple pairs.

Constraints

All input values are integers.

1 \leq N \leq 100

0 \leq a_i, b_i, c_i, d_i < 2N

a_1, a_2, ..., a_N, c_1, c_2, ..., c_N are all different.

b_1, b_2, ..., b_N, d_1, d_2, ..., d_N are all different.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N

Output

Print the maximum number of friendly pairs.

Sample Input 1

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

Sample Output 1

2

For example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).

Sample Input 2

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

Sample Output 2

2

For example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).

Sample Input 3

2
2 2
3 3
0 0
1 1

Sample Output 3

0

It is possible that no pair can be formed.

Sample Input 4

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

Sample Output 4

5

Sample Input 5

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

Sample Output 5

4


object Main extends App{
val cs = for (i<-1 to 3) yield scala.io.StdIn.readLine().toList

val result = for(i<-0 until 3) yield cs(i)(i)

println(result.foldLeft("")((a,b)=>a+b))
}

Score : 100 points

Problem Statement

We have a 3×3 square grid, where each square contains a lowercase English letters.
The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.

Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Constraints

Input consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

c_{11}c_{12}c_{13}
c_{21}c_{22}c_{23}
c_{31}c_{32}c_{33}

Output

Print the string of length 3 that can be obtained by concatenating the letters on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Sample Input 1

ant
obe
rec

Sample Output 1

abc

The letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid are a, b and c from top-right to bottom-left. Concatenate these letters and print abc.

Sample Input 2

edu
cat
ion

Sample Output 2

ean


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 sc: Scanner = new Scanner(input)
    val a,b = sc.nextInt
    var sum = 0
    for (i <- a to b) {
      val is = i.toString
      if (is(0) == is(4) && is(1) == is(3)) sum += 1
    }
    sum.toString
  }

  val tests = List(
    """11009 11332""".stripMargin -> """4""",
    """31415 92653""".stripMargin -> """612"""
  )

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

Score : 200 points

Problem Statement

Find the number of palindromic numbers among the integers between A and B (inclusive).
Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward.

Constraints

10000 \leq A \leq B \leq 99999

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the number of palindromic numbers among the integers between A and B (inclusive).

Sample Input 1

11009 11332

Sample Output 1

4

There are four integers that satisfy the conditions: 11011, 11111, 11211 and 11311.

Sample Input 2

31415 92653

Sample Output 2

612


import scala.io.StdIn.{readLine}

object Main extends App {
  def isPalindromic(s: String): Boolean = {
    val (src, dst) = s.splitAt(s.length / 2 + 1)
    val taked = src.take(dst.length)
    taked == dst.reverse
  }

  def nPalindromic(input: String): Int = {
    val ints = input.split(" ").map(_.toInt)
    nPalindromic(ints(0), ints(1))

  }

  def nPalindromic(start: Int, end: Int):Int = {
    Range(start, end).count(i => isPalindromic(i.toString))
  }

  println(nPalindromic(readLine()))
}


import scala.io.StdIn

object Main extends App {
  var a = StdIn.readLine().split(' ').map(_.toLong).sorted

  val n = a(0)
  val m = a(1)

  println(if (n == 1 && m == 1) 1 else if (n == 1 && m != 1) m - 2 else (n - 2) * (m - 2))

}

Score : 300 points

Problem Statement

There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region.
The front and back sides of these cards can be distinguished, and initially every card faces up.

We will perform the following operation once for each square contains a card:

For each of the following nine squares, flip the card in it if it exists: the target square itself and the eight squares that shares a corner or a side with the target square.

It can be proved that, whether each card faces up or down after all the operations does not depend on the order the operations are performed.
Find the number of cards that face down after all the operations.

Constraints

1 \leq N,M \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of cards that face down after all the operations.

Sample Input 1

2 2

Sample Output 1

0

We will flip every card in any of the four operations. Thus, after all the operations, all cards face up.

Sample Input 2

1 7

Sample Output 2

5

After all the operations, all cards except at both ends face down.

Sample Input 3

314 1592

Sample Output 3

496080


object Main extends App {

  val In = io.StdIn.readLine()
  val A = In.split(" ")

  val max:Int = A.max.toInt
  val min:Int = A.min.toInt

  //var arr = Array.ofDim[Int](A(0).toInt, A(1).toInt)

  var N = 0

  if (min == 1) {
    if (max == 1) {
      N = 1
    }else {
        N = max - 2
    }
  }

  if (min == 2) {
    N = 0
  }

  if (min >= 3){
    N = (A(0).toInt - 2) * (A(1).toInt - 2)
  }

  print(N)

}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, M = sc.nextLong()
  val reverseCount =
    (N, M) match {
      case (1, 1) => 1
      case (1, m) => m - 2
      case (n, 1) => n - 2
      case (n, m) => (n - 2) * (m - 2)
    }
  println(reverseCount)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, M = sc.nextInt()
  val reverseCount =
    N match {
      case 1 => M match {
        case 1 => 1
        case _ => M - 2
      }
      case _ => (N - 2) * (M - 2)
    }
  println(reverseCount)
}


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

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

  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 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 main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val (n, m) = get[Long, Long]

    out.println(
      if (n == 1) {
        if (m == 1) {
          1
        } else {
          m - 2
        }
      } else {
        if (m == 1) {
          n - 2
        } else {
          (m - 2) * (n - 2)
        }
      }
    )

    out.flush()
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, K = sc.nextLong

  var sum :Long = 0
  if (K == 0) {
    println(N * N)
    sys.exit
  }

  for (b <- K + 1 to N) {
    val x = N % b
    if (x >= K) {
      sum += (b - K) * (N / b) + x + 1 - K
    } else {
      sum += (b - K) * (N / b)
    }
  }

  println(sum)
}

Score : 400 points

Problem Statement

Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten.
He remembers that the remainder of a divided by b was greater than or equal to K.
Find the number of possible pairs that he may have had.

Constraints

1 \leq N \leq 10^5

0 \leq K \leq N-1

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of possible pairs that he may have had.

Sample Input 1

5 2

Sample Output 1

7

There are seven possible pairs: (2,3),(5,3),(2,4),(3,4),(2,5),(3,5) and (4,5).

Sample Input 2

10 0

Sample Output 2

100

Sample Input 3

31415 9265

Sample Output 3

287927211


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, A, B = sc.nextInt
  val X = N - A - B

  // A + B > N + 1 のとき実現不可能
  if ((A + B) > (N + 1) | N > A * B) {
    println(-1)
    sys.exit
  }

  // それ以外のとき、実現可能
  var arr = Array.emptyIntArray

  if (B != N) {
    for (i <- 1 to A) arr :+= i
  }

  if (A != N) {
    for (j <- N - B + 1 to N) arr +:= j
  }

  if (A > B) {
    for (k <- A + 1 to N - B) arr +:= k
  } else {
    for (k <- N - B to A + 1 by -1) arr +:= k
  }

  println(arr.mkString(" "))
}

Score : 700 points

Problem Statement

Determine if there exists a sequence obtained by permuting 1,2,...,N that satisfies the following conditions:

The length of its longest increasing subsequence is A.

The length of its longest decreasing subsequence is B.

If it exists, construct one such sequence.

Notes

A subsequence of a sequence P is a sequence that can be obtained by extracting some of the elements in P without changing the order.

A longest increasing subsequence of a sequence P is a sequence with the maximum length among the subsequences of P that are monotonically increasing.

Similarly, a longest decreasing subsequence of a sequence P is a sequence with the maximum length among the subsequences of P that are monotonically decreasing.

Constraints

1 \leq N,A,B \leq 3\times 10^5

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

If there are no sequences that satisfy the conditions, print -1.

Otherwise, print N integers. The i-th integer should be the i-th element of the sequence that you constructed.

Sample Input 1

5 3 2

Sample Output 1

2 4 1 5 3

One longest increasing subsequence of this sequence is {2,4,5}, and one longest decreasing subsequence of it is {4,3}.

Sample Input 2

7 7 1

Sample Output 2

1 2 3 4 5 6 7

Sample Input 3

300000 300000 300000

Sample Output 3

-1


import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine
  val size = StdIn.readLine.split(" ").toList
      .distinct.size

  println(if (size == 3) "Three" else "Four")
}

Score : 200 points

Problem Statement

In Japan, people make offerings called hina arare, colorful crackers, on March 3.

We have a bag that contains N hina arare. (From here, we call them arare.)

It is known that the bag either contains arare in three colors: pink, white and green, or contains arare in four colors: pink, white, green and yellow.

We have taken out the arare in the bag one by one, and the color of the i-th arare was S_i, where colors are represented as follows - pink: P, white: W, green: G, yellow: Y.

If the number of colors of the arare in the bag was three, print Three; if the number of colors was four, print Four.

Constraints

1 \leq N \leq 100

S_i is P, W, G or Y.

There always exist i, j and k such that S_i=P, S_j=W and S_k=G.

Input

Input is given from Standard Input in the following format:

N
S_1 S_2 ... S_N

Output

If the number of colors of the arare in the bag was three, print Three; if the number of colors was four, print Four.

Sample Input 1

6
G W Y P Y W

Sample Output 1

Four

The bag contained arare in four colors, so you should print Four.

Sample Input 2

9
G W W G P W P G G

Sample Output 2

Three

The bag contained arare in three colors, so you should print Three.

Sample Input 3

8
P Y W G Y W Y Y

Sample Output 3

Four


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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    sc.nextLine()
    val s = new Array[String](n)
    val mp = scala.collection.mutable.Map[Char, Int](
      ('M', 0), ('A', 0), ('R', 0), ('C', 0), ('H', 0))
    for (i <- 0 until n) {
      s(i) = sc.nextLine()
      val index = s(i)(0)
      if (index == 'M' || index == 'A' || index == 'R' || index == 'C' || index == 'H') {
        mp(index) += 1
      }
    }

    var ans = 0
    val values = mp.values.toList
    for (i <- 0 until 5; j <- i + 1 until 5; k <- j + 1 until 5) {
      ans += values(i) * values(j) * values(k)
    }

    println(ans)
  }
}

Score : 300 points

Problem Statement

There are N people. The name of the i-th person is S_i.

We would like to choose three people so that the following conditions are met:

The name of every chosen person begins with M, A, R, C or H.

There are no multiple people whose names begin with the same letter.

How many such ways are there to choose three people, disregarding order?

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

Constraints

1 \leq N \leq 10^5

S_i consists of uppercase English letters.

1 \leq |S_i| \leq 10

S_i \neq S_j (i \neq j)

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If there are x ways to choose three people so that the given conditions are met, print x.

Sample Input 1

5
MASHIKE
RUMOI
OBIRA
HABORO
HOROKANAI

Sample Output 1

2

We can choose three people with the following names:

MASHIKE, RUMOI, HABORO

MASHIKE, RUMOI, HOROKANAI

Thus, we have two ways.

Sample Input 2

4
ZZ
ZZZ
Z
ZZZZZZZZZZ

Sample Output 2

0

Note that there may be no ways to choose three people so that the given conditions are met.

Sample Input 3

5
CHOKUDAI
RNG
MAKOTO
AOKI
RINGO

Sample Output 3

7


import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine().toInt
  val linse = (0 until n).map(_ => StdIn.readLine())

  val combis = "MARCH".split("").combinations(3).map(p => p.toList.map(_.charAt(0)))
  //println(combis.mkString(" "))

  val members = linse.filter{p =>
    p.charAt(0) == 'M' || p.charAt(0) == 'A' || p.charAt(0) == 'R' || p.charAt(0) == 'C' || p.charAt(0) == 'H'
  }.groupBy(name => name.charAt(0)).map(a => a._1 -> a._2.size)

  //val combi = members.keys.toList.combinations(3)
  //println(combi.mkString(" "))

  val result = combis.foldLeft(0L){ (acc, l) =>
    acc + (
      members.get(l(0)).getOrElse(0) * members.get(l(1)).getOrElse(0) * members.get(l(2)).getOrElse(0))

  }

  println(result)

}


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

import scala.util.Sorting

object Main {
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val H = sc.nextInt()
    val W = sc.nextInt()
    val D = sc.nextInt()
    val N = H * W
    val A = Array.ofDim[(Int, Int)](N + 1)

    for {
      h <- 1 to H
      w <- 1 to W
    } {
      val x = sc.nextInt()
      A(x) = (h, w)
    }

    def move(s: (Int, Int), t: (Int, Int)) = math.abs(s._1 - t._1) + math.abs(s._2 - t._2)

    // (1 to D-1) から xまでのコスト
    val cost = Array.ofDim[Int](N + 1)
    (1 to D) foreach { d =>  // 最初の地点dから
      var j = 1
      while(j * D + d <= N) {
//      (0 until (N / D) + (if(d <= N % D) 1 else 0)) foreach { j =>  // j回移動する
//        if (j == 0) cost(d) = 0
//        else {
          val next = d + D * j
          val prev = d + D * (j - 1)
          cost(next) = cost(prev) + move(A(prev), A(next))
//        }
        j += 1
      }
    }

    val Q = sc.nextInt()
    (0 until Q) foreach { _ =>
      val L = sc.nextInt()
      val R = sc.nextInt()
      println(cost(R) - cost(L))
    }
  }

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

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

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

    def nextInt(): Int = next.toInt
  }
}

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j).

The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is A_{i,j}.

You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by consuming |x-i|+|y-j| magic points.

You now have to take Q practical tests of your ability as a magical girl.

The i-th test will be conducted as follows:

Initially, a piece is placed on the square where the integer L_i is written.

Let x be the integer written in the square occupied by the piece. Repeatedly move the piece to the square where the integer x+D is written, as long as x is not R_i. The test ends when x=R_i.

Here, it is guaranteed that R_i-L_i is a multiple of D.

For each test, find the sum of magic points consumed during that test.

Constraints

1 \leq H,W \leq 300

1 \leq D \leq H×W

1 \leq A_{i,j} \leq H×W

A_{i,j} \neq A_{x,y} ((i,j) \neq (x,y))

1 \leq Q \leq 10^5

1 \leq L_i \leq R_i \leq H×W

(R_i-L_i) is a multiple of D.

Input

Input is given from Standard Input in the following format:

H W D
A_{1,1} A_{1,2} ... A_{1,W}
:
A_{H,1} A_{H,2} ... A_{H,W}
Q
L_1 R_1
:
L_Q R_Q

Output

For each test, print the sum of magic points consumed during that test.

Output should be in the order the tests are conducted.

Sample Input 1

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

Sample Output 1

5

4 is written in Square (1,2).

6 is written in Square (3,3).

8 is written in Square (3,1).

Thus, the sum of magic points consumed during the first test is (|3-1|+|3-2|)+(|3-3|+|1-3|)=5.

Sample Input 2

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

Sample Output 2

0
0

Note that there may be a test where the piece is not moved at all, and there may be multiple identical tests.

Sample Input 3

5 5 4
13 25 7 15 17
16 22 20 2 9
14 11 12 1 19
10 6 23 8 18
3 21 5 24 4
3
13 13
2 10
13 13

Sample Output 3

0
5
0


import java.util.Scanner
object Main extends App {
  val scanner = new Scanner(System.in)
  val h, w, d = scanner.nextInt
  val table: Map[Int, (Int, Int)] = (for {
        y <- 0 until h
        x <- 0 until w
      } yield scanner.nextInt -> (x, y)).toMap

  (1 to scanner.nextInt).foreach{i =>
    val l, r = scanner.nextInt
    /*
    println(((l to r by d).sliding(2).map{l =>
      val lPos = table(l.head)
      val rPos = table(l.last)
      Math.abs(lPos._1 - rPos._1) + Math.abs(lPos._2 - rPos._2)
    }).sum)
    */
  }
  (1 to 100000).foreach{i => println(0)} // test
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.next()
  if (n.tail.forall(_ == '9')) {
    println(n.toList.map(_.asDigit).sum)
  } else {
    println((n.head.asDigit - 1) + (9 * (n.length - 1)))
  }
}

Score : 300 points

Problem Statement

Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Constraints

1\leq N \leq 10^{16}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Sample Input 1

100

Sample Output 1

18

For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.

Sample Input 2

9995

Sample Output 2

35

For example, the sum of the digits in 9989 is 35, which turns out to be the maximum value.

Sample Input 3

3141592653589793

Sample Output 3

137


import scala.io.StdIn._

object Main {
    def main(args: Array[String]): Unit = {
        val t = readLine.toInt % 500
        println(if (t <= readLine.toInt) {
            "Yes"
        } else {
            "No"
        })
    }
}

Score: 100 points

Problem Statement

E869120 has A 1-yen coins and infinitely many 500-yen coins.

Determine if he can pay exactly N yen using only these coins.

Constraints

N is an integer between 1 and 10000 (inclusive).

A is an integer between 0 and 1000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
A

Output

If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print Yes; otherwise, print No.

Sample Input 1

2018
218

Sample Output 1

Yes

We can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer is Yes.

Sample Input 2

2763
0

Sample Output 2

No

When we have no 1-yen coins, we can only pay a multiple of 500 yen using only 500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.

Sample Input 3

37
514

Sample Output 3

Yes


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

  	val mushi = readLine
  	val cards = readLine.split(" ").map(_.toInt).toList

  	println(cards.sorted.foldLeft(0)((a,b)=> b - a ).toString)
}

Score: 200 points

Problem Statement

We have N cards. A number a_i is written on the i-th card.

Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first.

The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards he/she has taken. When both players take the optimal strategy to maximize their scores, find Alice's score minus Bob's score.

Constraints

N is an integer between 1 and 100 (inclusive).

a_i \ (1 \leq i \leq N) is an integer between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print Alice's score minus Bob's score when both players take the optimal strategy to maximize their scores.

Sample Input 1

2
3 1

Sample Output 1

2

First, Alice will take the card with 3. Then, Bob will take the card with 1.
The difference of their scores will be 3 - 1 = 2.

Sample Input 2

3
2 7 4

Sample Output 2

5

First, Alice will take the card with 7. Then, Bob will take the card with 4. Lastly, Alice will take the card with 2. The difference of their scores will be 7 - 4 + 2 = 5. The difference of their scores will be 3 - 1 = 2.

Sample Input 3

4
20 18 2 18

Sample Output 3

18


import scala.io.StdIn

object Main extends App {
   val n = StdIn.readLine().toInt
   val a = StdIn.readLine().split(' ').map(_.toInt).sorted(Ordering[Int].reverse).zipWithIndex

   //println(a.mkString(" "))
   println(a.foldLeft(0)((acc, p) => if(p._2 % 2 == 0) acc + p._1 else acc - p._1))
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val rowC1 = readLine.split(" ").map(_.toInt)
    val rowC2 = readLine.split(" ").map(_.toInt)
    val rowC3 = readLine.split(" ").map(_.toInt)

    val maxN = 100

    def checkRow(row:Array[Int], a1: Int, a2: Int, a3:Int): Boolean ={
      ((row(0) - a1) == (row(1) - a2)) && ((row(1) - a2) == (row(2) - a3))
    }
    val checklist =
      for(a1 <- 0 to maxN; a2 <- 0 to maxN; a3 <- 0 to maxN) yield {
        val a = checkRow(rowC1, a1, a2, a3) && checkRow(rowC2, a1, a2, a3) && checkRow(rowC3, a1, a2, a3)
        //println("DEBUG" + a)
        a
      }
    val ans = checklist.exists(x => x)

    println(if(ans) "Yes" else "No")
  }

}

Score: 300 points

Problem Statement

We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is equal to a_i + b_j.

Determine if he is correct.

Constraints

c_{i, j} \ (1 \leq i \leq 3, 1 \leq j \leq 3) is an integer between 0 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

c_{1,1} c_{1,2} c_{1,3}
c_{2,1} c_{2,2} c_{2,3}
c_{3,1} c_{3,2} c_{3,3}

Output

If Takahashi's statement is correct, print Yes; otherwise, print No.

Sample Input 1

1 0 1
2 1 2
1 0 1

Sample Output 1

Yes

Takahashi is correct, since there are possible sets of integers such as: a_1=0,a_2=1,a_3=0,b_1=1,b_2=0,b_3=1.

Sample Input 2

2 2 2
2 1 2
2 2 2

Sample Output 2

No

Takahashi is incorrect in this case.

Sample Input 3

0 8 8
0 8 8
0 8 8

Sample Output 3

Yes

Sample Input 4

1 8 6
2 9 7
0 7 7

Sample Output 4

No


import scala.io.StdIn

object Main extends App {
  val seq = Iterator.continually(StdIn.readLine)
    .takeWhile(_ != null)
    .map(_.split(" ").map(_.toInt))
    .toArray

  val y = (0 until 3).map(i => seq(0)(i)).toArray
  val x = (0 until 3).map(i => seq(i)(0)-y(0)).toArray

  val ans = (
    for{
      i <- 0 until 3
      j <- 0 until 3
    } yield { seq(i)(j) == x(i) + y(j) }
  ).forall(_ == true)

  println(if(ans)"Yes"else"No")
}


object Main {
	def main(args: Array[String]) {
		val input = io.Source.stdin.getLines().mkString("\n")
		println(solve(input).trim)
	}

	def solve(input: String): String = {
		val List(a, b, c, x) = input.split("\n").map(_.toInt).toList
		val ay = (0 to a).map(_*500)
		val by = (0 to b).map(_*100)
		val cy = (0 to c).map(_*50)
		ay.flatMap(i => by.flatMap(j => cy.map(k => i+j+k))).filter(_==x).size.toString()
	}

}

Score : 100 points

Problem Statement

You went shopping to buy cakes and donuts with X yen (the currency of Japan).

First, you bought one cake for A yen at a cake shop.
Then, you bought as many donuts as possible for B yen each, at a donut shop.

How much do you have left after shopping?

Constraints

1 \leq A, B \leq 1 000

A + B \leq X \leq 10 000

X, A and B are integers.

Input

Input is given from Standard Input in the following format:

X
A
B

Output

Print the amount you have left after shopping.

Sample Input 1

1234
150
100

Sample Output 1

84

You have 1234 - 150 = 1084 yen left after buying a cake.
With this amount, you can buy 10 donuts, after which you have 84 yen left.

Sample Input 2

1000
108
108

Sample Output 2

28

Sample Input 3

579
123
456

Sample Output 3

0

Sample Input 4

7477
549
593

Sample Output 4

405


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    val x: Int = sc.nextLine.toInt
    val a: Int = sc.nextLine.toInt
    val b: Int = sc.nextLine.toInt
    println((x - a) % b)

  }
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datN) = readLine.split(" ").map(_.toInt)
    val datA = for(i <- 1 to 2) yield (readLine.split(" ").map(_.toInt))

    val ans = (0 until datN).map(x => datA(0).take(x + 1).sum + datA(1).takeRight(datN - x).sum).max
    println(ans)
  }
}

Score : 300 points

Problem Statement

We have a 2 \times N grid. We will denote the square at the i-th row and j-th column (1 \leq i \leq 2, 1 \leq j \leq N) as (i, j).

You are initially in the top-left square, (1, 1).
You will travel to the bottom-right square, (2, N), by repeatedly moving right or down.

The square (i, j) contains A_{i, j} candies.
You will collect all the candies you visit during the travel.
The top-left and bottom-right squares also contain candies, and you will also collect them.

At most how many candies can you collect when you choose the best way to travel?

Constraints

1 \leq N \leq 100

1 \leq A_{i, j} \leq 100 (1 \leq i \leq 2, 1 \leq j \leq N)

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} ... A_{1, N}
A_{2, 1} A_{2, 2} ... A_{2, N}

Output

Print the maximum number of candies that can be collected.

Sample Input 1

5
3 2 2 4 1
1 2 2 2 1

Sample Output 1

14

The number of collected candies will be maximized when you:

move right three times, then move down once, then move right once.

Sample Input 2

4
1 1 1 1
1 1 1 1

Sample Output 2

5

You will always collect the same number of candies, regardless of how you travel.

Sample Input 3

7
3 3 4 5 4 5 3
5 3 4 4 2 3 2

Sample Output 3

29

Sample Input 4

1
2
3

Sample Output 4

5


import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine.toInt
  val seq = Iterator.continually(StdIn.readLine)
    .take(2)
    .map(_.split(" ").map(_.toInt))
    .toArray
  val seq1 = seq(0).scanLeft(0)( (acc, e) => acc + e).tail
  val seq2 = seq(1).scanRight(0)( (e,acc) => acc + e).init
  val ans = (0 until n).map(i => seq1(i) + seq2(i)).max

  println(ans)
}


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

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

  val INF = 1 << 30
  val value = Array.fill(n+1)(INF)
  case class Edge(node:Int, cost:Int)
  val graph = Array.fill(n+1)(mu.ListBuffer.empty[Edge])

  Iterator.continually(in.readLine)
    .take(m)
    .map(_.split(" ").map(_.toInt))
    .foreach(e => {
      val l = e(0) - 1
      val r = e(1) - 1
      val d = e(2)
      graph(l) += new Edge(r,d)
      graph(r) += new Edge(l,-d)
    })

  def bfs(node:Int):Unit = {
    if(graph(node).nonEmpty) {
      graph(node).foreach( edge => {
        if(value(edge.node) == INF) {
          value(edge.node) = value(node) + edge.cost
          bfs(edge.node)
        }
      })
    }
  }

  (0 until n).foreach( i => {
    if(value(i) == INF) {
      value(i) = 0
      bfs(i)
    }
  })

  val valid =
    (0 until n).forall( i => {
      graph(i).forall( edge => {
        value(i) + edge.cost == value(edge.node)
      })
    })

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

Score : 400 points

Problem Statement

There are N people standing on the x-axis.
Let the coordinate of Person i be x_i.
For every i, x_i is an integer between 0 and 10^9 (inclusive).
It is possible that more than one person is standing at the same coordinate.

You will given M pieces of information regarding the positions of these people.
The i-th piece of information has the form (L_i, R_i, D_i).
This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.

It turns out that some of these M pieces of information may be incorrect.
Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.

Constraints

1 \leq N \leq 100 000

0 \leq M \leq 200 000

1 \leq L_i, R_i \leq N (1 \leq i \leq M)

0 \leq D_i \leq 10 000 (1 \leq i \leq M)

L_i \neq R_i (1 \leq i \leq M)

If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).

D_i are integers.

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M

Output

If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print Yes; if it does not exist, print No.

Sample Input 1

3 3
1 2 1
2 3 1
1 3 2

Sample Output 1

Yes

Some possible sets of values (x_1, x_2, x_3) are (0, 1, 2) and (101, 102, 103).

Sample Input 2

3 3
1 2 1
2 3 1
1 3 5

Sample Output 2

No

If the first two pieces of information are correct, x_3 - x_1 = 2 holds, which is contradictory to the last piece of information.

Sample Input 3

4 3
2 1 1
2 3 5
3 4 2

Sample Output 3

Yes

Sample Input 4

10 3
8 7 100
7 9 100
9 8 100

Sample Output 4

No

Sample Input 5

100 0

Sample Output 5

Yes


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

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

  val INF = 1 << 30
  val value = Array.fill(n)(INF)
  case class Edge(node:Int, cost:Int)
  val graph = Array.fill(n)(mu.ListBuffer.empty[Edge])

  Iterator.continually(in.readLine)
    .take(m)
    .map(_.split(" ").map(_.toInt))
    .foreach(e => {
      val l = e(0) - 1
      val r = e(1) - 1
      val d = e(2)
      graph(l) += new Edge(r,d)
      graph(r) += new Edge(l,-d)
    })

  def bfs(node:Int):Unit = {
    if(graph(node).nonEmpty) {
      graph(node).foreach( edge => {
        if(value(edge.node) == INF) {
          value(edge.node) = value(node) + edge.cost
          bfs(edge.node)
        }
      })
    }
  }

  (0 until n).foreach( i => {
    if(value(i) == INF) {
      value(i) = 0
      bfs(i)
    }
  })

  val valid =
    (0 until n).forall( i => {
      graph(i).forall( edge => {
        value(i) + edge.cost == value(edge.node)
      })
    })

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


object Main extends App {
    val input = readLine
    val a = input.split(" ")(0)
    val b = input.split(" ")(1)
    val num = (a + b).toInt
    val sqrt_double = Math.sqrt(num)
    val sqrt_int = sqrt_double.toInt
    val res = if(sqrt_int * sqrt_int - num == 0){"Yes"}else{"No"}
    println(res)
}

Score : 200 points

Problem Statement

AtCoDeer the deer has found two positive integers, a and b.
Determine whether the concatenation of a and b in this order is a square number.

Constraints

1 ≤ a,b ≤ 100

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If the concatenation of a and b in this order is a square number, print Yes; otherwise, print No.

Sample Input 1

1 21

Sample Output 1

Yes

As 121 = 11 × 11, it is a square number.

Sample Input 2

100 100

Sample Output 2

No

100100 is not a square number.

Sample Input 3

12 10

Sample Output 3

No


object Main extends App {
	// your code goes here
	val x = io.StdIn.readLine().replaceAll("[^0-9]+", "").toLong
    val s = math.sqrt(x).round
    (x==s*s) match {
      case true => println("Yes")
      case false => println("No")
    }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val list: Seq[Seq[Int]] = Seq(0,0,0) :: List.fill(n, 3)(sc.nextInt.toInt)

  val check = (term: Int, start: (Int, Int), end: (Int, Int)) => {
    val diffX = math.abs(end._1 - start._1)
    val diffY = math.abs(end._2 - start._2)
    val diff = diffX + diffY

    (diff <= term) && (diff % 2 == term % 2)
  }

  val results: Seq[Boolean] = for (index <- (1 to n)) yield {
    check(list(index)(0) - list(index - 1)(0), (list(index - 1)(1), list(index - 1)(2)), (list(index)(1), list(index)(2)))
  }
  val result = !results.contains(false)

  println(if (result) "Yes" else "No")
}

Score : 300 points

Problem Statement

AtCoDeer the deer is going on a trip in a two-dimensional plane.
In his plan, he will depart from point (0, 0) at time 0, then for each i between 1 and N (inclusive), he will visit point (x_i,y_i) at time t_i.

If AtCoDeer is at point (x, y) at time t, he can be at one of the following points at time t+1: (x+1,y), (x-1,y), (x,y+1) and (x,y-1).
Note that he cannot stay at his place.
Determine whether he can carry out his plan.

Constraints

1 ≤ N ≤ 10^5

0 ≤ x_i ≤ 10^5

0 ≤ y_i ≤ 10^5

1 ≤ t_i ≤ 10^5

t_i < t_{i+1} (1 ≤ i ≤ N-1)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
t_1 x_1 y_1
t_2 x_2 y_2
:
t_N x_N y_N

Output

If AtCoDeer can carry out his plan, print Yes; if he cannot, print No.

Sample Input 1

2
3 1 2
6 1 1

Sample Output 1

Yes

For example, he can travel as follows: (0,0), (0,1), (1,1), (1,2), (1,1), (1,0), then (1,1).

Sample Input 2

1
2 100 100

Sample Output 2

No

It is impossible to be at (100,100) two seconds after being at (0,0).

Sample Input 3

2
5 1 1
100 1 1

Sample Output 3

No


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

  def check(term: Int, start: (Int, Int), end: (Int, Int)): Boolean = {
    val diffX = math.abs(end._1 - start._1)
    val diffY = math.abs(end._2 - start._2)
    val diff = diffX + diffY

    (diff <= term) && (diff % 2 == term % 2)
  }

  val results: Seq[Boolean] = for (index <- (0 to list.length - 1)) yield {
    if (index == 0) check(list(index)(0), (0, 0), (list(index)(1), list(index)(2)))
    else check(list(index)(0) - list(index - 1)(0), (list(index - 1)(1), list(index - 1)(2)), (list(index)(1), list(index)(2)))
  }

  println(if (results.contains(false)) "No" else "Yes")
}


object Main extends App {
  val n = io.StdIn.readLine().toInt
  val list = collection.mutable.ListBuffer[Array[Int]](Array(0 ,0, 0))
  (1 to n).foreach { i =>
    list += io.StdIn.readLine().split(' ').map(_.toInt).toArray
  }
  def f(t: Int, x: Int, y: Int): Boolean = {
    if (t == 0) (x == 0 && y == 0)
    else if(x == 0 && y == 0 && (t & 1) == 0) true
    else if (x < 0 || y < 0 || x > t || y > t || x + y > t) false
    else (f(t - 1, x + 1, y) || f(t - 1, x - 1, y) || f(t - 1, x, y + 1) || f(t - 1, x, y - 1))
  }
  list.zip(list.tail)
  val list2 = list.zip(list.tail).map{case (x1, x2) => (x2(0) - x1(0), Math.abs(x2(1) - x1(1)), Math.abs(x2(2) - x1(2)))}
  print(if(list2.forall{case (t, x, y) => f(t, x, y)}) "Yes" else "No")
}


object Main extends App {
  val Array(n, k) = io.StdIn.readLine().split(' ').map(_.toInt)
  val k2 = k * 2
  val list = collection.mutable.ListBuffer[Array[Int]]()
  var (sum, white) = (0, 0)
  (1 to n).foreach { i =>
    val temp = io.StdIn.readLine().split(' ')
    list += (
      if (temp(2) == "B") {
        sum = sum + 1
        Array(temp(0).toInt % k2, temp(1).toInt % k2, 1)
      }
      else {
        sum = sum - 1
        white = white + 1
        Array(temp(0).toInt % k2, temp(1).toInt % k2, -1)
      }
    )
  }
  val matrix = new Array[Array[Int]](k2)
  (0 to k2 - 1).foreach(i => matrix(i) = new Array[Int](k2))
  def inc(x: Int, y: Int, z: Int) = {
    for {
      i <- (x to k2-1)
      j <- (y to k2-1)
    } {
      matrix(i)(j) = matrix(i)(j) + z
    }
  }
  list.foreach(arr => inc(arr(0), arr(1), arr(2)))
  var max = 0
  for {
    i <- (0 to k-1)
    j <- (0 to k-1)
  } {
    val cnt =
      (matrix(i)(j)) +
      (matrix(i+k)(j+k) - matrix(i+k)(j) - matrix(i)(j+k) + matrix(i)(j)) +
      (matrix(k2-1)(j) - matrix(i+k)(j)) +
      (matrix(i)(k2-1) - matrix(i)(j+k)) +
      (matrix(k2-1)(k2-1) - matrix(k2-1)(j+k) - matrix(i+k)(k2-1) + matrix(i+k)(j+k))
    max = Math.max(Math.max(cnt, sum - cnt), max)
  }
  print(max + white)
}

Score : 500 points

Problem Statement

AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K.
Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K × K square.
Below is an example of a checked pattern of side 3:

AtCoDeer has N desires.
The i-th desire is represented by x_i, y_i and c_i.
If c_i is B, it means that he wants to paint the square (x_i,y_i) black; if c_i is W, he wants to paint the square (x_i,y_i) white.
At most how many desires can he satisfy at the same time?

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 1000

0 ≤ x_i ≤ 10^9

0 ≤ y_i ≤ 10^9

If i ≠ j, then (x_i,y_i) ≠ (x_j,y_j).

c_i is B or W.

N, K, x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1 c_1
x_2 y_2 c_2
:
x_N y_N c_N

Output

Print the maximum number of desires that can be satisfied at the same time.

Sample Input 1

4 3
0 1 W
1 2 W
5 3 B
5 4 B

Sample Output 1

4

He can satisfy all his desires by painting as shown in the example above.

Sample Input 2

2 1000
0 0 B
0 1 W

Sample Output 2

2

Sample Input 3

6 2
1 2 B
2 1 W
2 2 B
1 0 B
0 6 W
4 5 W

Sample Output 3

4


object Main extends App {
  val Array(n, k) = io.StdIn.readLine().split(' ').map(_.toInt)
  val k2 = k * 2
  type Record = (Int, Int)
  val list = collection.mutable.ListBuffer[Record]()
  (1 to n).foreach { i =>
    val temp = io.StdIn.readLine().split(' ')
    list += (
      if (temp(2) == "W")
        (temp(0).toInt % k2, temp(1).toInt % k2)
      else
        (temp(0).toInt % k2, (temp(1).toInt + k) % k2)
    )
  }
  var max = 0
  (1 to k).foreach { i =>
    (1 to k).foreach { j =>
      val cnt = list.count {
        t =>
          val x = (t._1 + i) % k2
          val y = (t._2 + j) % k2
          ( (x < k && y < k) || (x >= k && y >= k))
      }
      max = Math.max(Math.max(cnt, n - cnt), max)
    }
  }
  print(max)
}


object Main extends App {
  val Array(n, k) = io.StdIn.readLine().split(' ').map(_.toInt)
  val k2 = k*2
  val end = k2-1
  // 0 ≦ x,y ≦ 2K に圧縮
  val squares = Array.fill(k2)(Array.fill(k2)(0))
  for (i <- 1 to n) {
    val Array(x, y, color) = io.StdIn.readLine().split(' ')
    // 'W'はY方向にKずらした'B'と同値
    squares(x.toInt % k2)((y.toInt + (if (color == "B") 0 else k)) % k2) += 1
  }
  // 計算量削減のために累積和を事前算出
  for {
    i <- 0 to end
    j <- 1 to end
  } squares(i)(j) += squares(i)(j-1)
  for {
    j <- 0 to end
    i <- 1 to end
  } squares(i)(j) += squares(i-1)(j)
  // ex) k = 2
  //      □ □ ■ ■
  //    k □ □ ■ ■
  //      ■ ■ □ □
  //    0 ■ ■ □ □
  //      0   k
  val cnt =
    (squares(k-1)(k-1)) +
    (squares(end)(end) - squares(k-1)(end) - squares(end)(k-1) + squares(k-1)(k-1))
  var max = Math.max(cnt, n - cnt)
  for {
    i <- 0 to k-1
    j <- 0 to k-1
  } {
    // ex) k = 2
    //      ■ □ □ ■
    //  j+k □ ■ ■ □
    //      □ ■ ■ □
    //    j ■ □ □ ■
    //      i   i+k
    val cnt =
      (squares(i)(j)) +
      (squares(end)(j) - squares(i+k)(j)) +
      (squares(i+k)(j+k) - squares(i+k)(j) - squares(i)(j+k) + squares(i)(j)) +
      (squares(i)(end) - squares(i)(j+k)) +
      (squares(end)(end) - squares(end)(j+k) - squares(i+k)(end) + squares(i+k)(j+k))
    max = Math.max(Math.max(cnt, n - cnt), max)
  }
  print(max)
}


object Main extends App {
  import scala.util.matching.Regex

  val keyValPattern: Regex = "([0-9]+)/([0-9]+)/([0-9]+)".r

  val input: String = readLine

  val patternMatch = keyValPattern.findFirstMatchIn(input)
  patternMatch match {
    case Some(m) => println(s"2018/${m.group(2)}/${m.group(3)}")
    case _ => println("error")
  }
}

Score : 100 points

Problem Statement

On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in yyyy/mm/dd format. For example, January 23, 2018 should be written as 2018/01/23.

After finishing the document, she noticed that she had mistakenly wrote 2017 at the beginning of the date column. Write a program that, when the string that Takaki wrote in the date column, S, is given as input, modifies the first four characters in S to 2018 and prints it.

Constraints

S is a string of length 10.

The first eight characters in S are 2017/01/.

The last two characters in S are digits and represent an integer between 1 and 31 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Replace the first four characters in S with 2018 and print it.

Sample Input 1

2017/01/07

Sample Output 1

2018/01/07

Sample Input 2

2017/01/31

Sample Output 2

2018/01/31


object Main extends App {
	var N = scala.io.StdIn.readLine.toArray
	N(3) = '8'
	println(N.mkString)
}


import scala.io.StdIn._

object Main extends App {
  val n = readInt()
  val inputs = List.fill(n - 1)(readLine().split(" ").map(_.toInt).toList)

  for (i <- 0 until n - 1) {
    var time = 0
    for (j <- i until n - 1) {
      val c = inputs(j).head
      val s = inputs(j)(1)
      val f = inputs(j)(2)
      if (time < s)
        time = s
      else if (time % f != 0)
        time += f - (time % f)
      time += c
    }
    println(time)
  }

  println(0)
}

Score : 300 points

Problem Statement

A railroad running from west to east in Atcoder Kingdom is now complete.

There are N stations on the railroad, numbered 1 through N from west to east.

Tomorrow, the opening ceremony of the railroad will take place.

On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i to Station i+1 in C_i seconds. No other trains will be operated.

The first train from Station i to Station i+1 will depart Station i S_i seconds after the ceremony begins. Thereafter, there will be a train that departs Station i every F_i seconds.

Here, it is guaranteed that F_i divides S_i.

That is, for each Time t satisfying S_i≤t and t％F_i=0, there will be a train that departs Station i t seconds after the ceremony begins and arrives at Station i+1 t+C_i seconds after the ceremony begins, where A％B denotes A modulo B, and there will be no other trains.

For each i, find the earliest possible time we can reach Station N if we are at Station i when the ceremony begins, ignoring the time needed to change trains.

Constraints

1≤N≤500

1≤C_i≤100

1≤S_i≤10^5

1≤F_i≤10

S_i％F_i=0

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
C_1 S_1 F_1
:
C_{N-1} S_{N-1} F_{N-1}

Output

Print N lines. Assuming that we are at Station i (1≤i≤N) when the ceremony begins, if the earliest possible time we can reach Station N is x seconds after the ceremony begins, the i-th line should contain x.

Sample Input 1

3
6 5 1
1 10 1

Sample Output 1

12
11
0

We will travel from Station 1 as follows:

5 seconds after the beginning: take the train to Station 2.

11 seconds: arrive at Station 2.

11 seconds: take the train to Station 3.

12 seconds: arrive at Station 3.

We will travel from Station 2 as follows:

10 seconds: take the train to Station 3.

11 seconds: arrive at Station 3.

Note that we should print 0 for Station 3.

Sample Input 2

4
12 24 6
52 16 4
99 2 2

Sample Output 2

187
167
101
0

Sample Input 3

4
12 13 1
44 17 17
66 4096 64

Sample Output 3

4162
4162
4162
0


object Main {
  def main(args: Array[String]): Unit = {
    val in = readLine.split(" ").map(_.toDouble)
    val X = in(0)
    val Y = in(1)

    val lnOf2 = scala.math.log(2)
    val log = (scala.math.log(Y / X) / lnOf2 + 1.0).floor.toInt

    print(log)
  }
}

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 {
  def main(args: Array[String]): Unit = {
    val in = readLine.split(" ").map(_.toInt)
    val X = in(0)
    val Y = in(1)

    val max = (Y / X).toDouble

    val lnOf2 = scala.math.log(2)
    val log = (scala.math.log(max) / lnOf2 + 1.0).floor.toInt

    print(log)
  }
}


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

	if(ab.sum % 2 == 1){
		println(ab.sum/2 + 1)
	}else{
		println(ab.sum/2)
	}

}

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]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    val s: String = sc.nextLine()
    val t: String = sc.nextLine()

    if (s.sorted < t.sorted.reverse) println("Yes")
    else println("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


object Main extends App {
	val s = scala.io.StdIn.readLine.toList.sorted
	val t = scala.io.StdIn.readLine.toList.sorted.reverse

	def check(a: List[Char], b: List[Char]): Boolean = {
		a match {
			case e::rest => if(e == b.head) check(rest, b.tail)
							else if( e < b.head) true
							else false
			case Nil => b match {
				case Nil => false
				case _   => true
			}
		}
	}

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


// Abx082 C
object Main extends App {
  val sc = new java.util.Scanner(System.in)

  val n = scala.io.StdIn.readLine.toInt
  val list = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val map = list.groupBy(identity).mapValues(_.length).toMap
  var delete_count = 0
  var checked = Map[Int, Boolean]()

  list.foreach({e =>
    if (checked.isDefinedAt(e)) {
    } else {
      if (map(e) > e) {
        delete_count += map(e) - e
      }

      if (map(e) < e) {
        delete_count += map(e)
      }

      checked += (e -> true)
    }
  })
  println(delete_count)
}

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

object Main extends App {

  val sc = new Scanner(System.in)

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

  val containsCounts =
    al.foldLeft(Map.empty[Int, Int]){ case (m, e) =>
      if (m.isDefinedAt(e)) m.updated(e, m(e) + 1)
      else Map(e -> 1) ++ m

      // m で定義されている  =>  mapValue
      // m で定義されていない=>  mapを追加
  }

//  val aDistinct = al.distinct

//  val containsCounts =
//    aDistinct.map{ e =>
//      e -> al.count(_ == e)
//    }

  val res =
    containsCounts.foldLeft(0){case (acc, (e,cnt)) =>
      val added =
        if(e > cnt) cnt else cnt - e
      acc + added
  }

  println(res)
}


import scala.io.StdIn

object Main extends App {

  val n = StdIn.readLine.toInt
  val seq = StdIn.readLine.split(" ").map(_.toInt).sorted.toBuffer
  seq ++= Array(0)

  val ans = {
    seq.foldLeft(0,0,0)((acc,e) => {
      // println(acc._1 + " " + acc._2 + " " + acc._3)
      if(acc._1 != e) {
       if(acc._1 != acc._2) {
         if(acc._2 < acc._1) (e, 1, acc._3 + acc._2)
         else (e, 1, acc._3 + acc._2 - acc._1)
       }
       else (e, 1, acc._3)
      } else {
        (e, acc._2+1, acc._3)
      }
    })._3
  }

  println(ans)
}


import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(' ').map(_.toLong)

  val b = a.groupBy(f => f)
  println(b.foldLeft(0L)( (acc, e) => acc + (if(e._2.length >= e._1) e._2.length - e._1 else e._2.length)))

}


object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in);
    sc.nextLine()
    val line = sc.nextLine().split(" ").map(_.toInt);
    println(calc(line, 0));
  }

  def calc(line:Array[Int], count:Int) : String = {
    if (line.count(_.toInt%2==0) == line.size) {
      calc(line.map(_.toInt/2), count+1);
    } else {
      count.toString
    }
  }
}

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.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}

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

  val N = in.next().toInt
  val a = new Array[Int](N)

  for (i <- 0 until N) {
    a(i) = in.next().toInt
  }

  var mx = a.max
  var mn = a.min

  def printer(ans: List[(Int, Int)]): Unit = {
    pw.println(ans.length)
    for (e <- ans)
      pw.println(s"${e._1} ${e._2}")
    pw.flush()
  }

  var ans: List[(Int, Int)] = List()

  if (Math.abs(mx) == 0 && Math.abs(mn) == 0) {
    println(0)
  }
  else if (Math.abs(mx) > Math.abs(mn)) {
    var ind = 0
    for (i <- 0 until N) {
      if(a(i) == mx)
        ind = i
    }

    for(i <- 1 until N) {
      while(a(i) < a(i-1)) {
        ans = (ind+1, i+1) :: ans
        a(i) += mx
        if(a(i) > mx) {
          mx = a(i)
          ind = i
        }
      }
    }

    printer(ans)
  }
}

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

Score : 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.math._

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

  val ans = min(a * n, b)

  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

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 m = 10
  val f = Array.fill(n * m)(sc.nextInt())
  val p = Array.fill(n * (m+1))(sc.nextInt())

  var ans = Long.MinValue
  for (s <- 1 until 1 << m) {
    var ansSub = 0L
    for (i <- 0 until n) {
      val count = (0 until m).count(j => ((s >> j) & f(i*m + j)) == 1)
      ansSub += p(i*(m+1) + count)
    }

    ans = ans.max(ansSub)
  }

  println(ans)
}

Score : 300 points

Problem Statement

Joisino is planning to open a shop in a shopping street.

Each of the five weekdays is divided into two periods, the morning and the evening. For each of those ten periods, a shop must be either open during the whole period, or closed during the whole period. Naturally, a shop must be open during at least one of those periods.

There are already N stores in the street, numbered 1 through N.

You are given information of the business hours of those shops, F_{i,j,k}. If F_{i,j,k}=1, Shop i is open during Period k on Day j (this notation is explained below); if F_{i,j,k}=0, Shop i is closed during that period. Here, the days of the week are denoted as follows. Monday: Day 1, Tuesday: Day 2, Wednesday: Day 3, Thursday: Day 4, Friday: Day 5. Also, the morning is denoted as Period 1, and the afternoon is denoted as Period 2.

Let c_i be the number of periods during which both Shop i and Joisino's shop are open. Then, the profit of Joisino's shop will be P_{1,c_1}+P_{2,c_2}+...+P_{N,c_N}.

Find the maximum possible profit of Joisino's shop when she decides whether her shop is open during each period, making sure that it is open during at least one period.

Constraints

1≤N≤100

0≤F_{i,j,k}≤1

For every integer i such that 1≤i≤N, there exists at least one pair (j,k) such that F_{i,j,k}=1.

-10^7≤P_{i,j}≤10^7

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
F_{1,1,1} F_{1,1,2} ... F_{1,5,1} F_{1,5,2}
:
F_{N,1,1} F_{N,1,2} ... F_{N,5,1} F_{N,5,2}
P_{1,0} ... P_{1,10}
:
P_{N,0} ... P_{N,10}

Output

Print the maximum possible profit of Joisino's shop.

Sample Input 1

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

Sample Output 1

8

If her shop is open only during the periods when Shop 1 is opened, the profit will be 8, which is the maximum possible profit.

Sample Input 2

2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1

Sample Output 2

-2

Note that a shop must be open during at least one period, and the profit may be negative.

Sample Input 3

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

Sample Output 3

23


import scala.io.StdIn._

object Main extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.next
  if((n(0)==n(1))&&(n(1)==n(2))||(n(1)==n(2))&&(n(2)==n(3))){
    println("Yes")
  }
  else{
    println("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


import java.util.Scanner

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

  val x = sc.nextInt

  val d = x % 10
  val c = x % 100 / 10
  val b = x % 1000 / 100
  val a = x / 1000

  val bins = (0 until 8).map(k => zeroEmbeddingtoString(k.toBinaryString, 3))

  val res = bins.find { bin =>
    a + (if (bin(0) == '0') 1 else -1) * b +(if (bin(1) == '0') 1 else -1) * c +(if (bin(2) == '0') 1 else -1) * d == 7
  }.fold("impossible") { bin =>
    val flg0 = if (bin(0) == '0') "+" else "-"
    val flg1 = if (bin(1) == '0') "+" else "-"
    val flg2 = if (bin(2) == '0') "+" else "-"
    s"$a$flg0$b$flg1$c$flg2$d=7"
  }

  println(res)

  def zeroEmbeddingtoString(str: String, index: Int): String ={
    val l = str.length
    List.fill(index - l)("0").mkString + str
  }

}

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 k = scala.io.StdIn.readLine.split(" ")

	def test(x: String): Int = {
		x match {
			case "A" => 10
			case "B" => 11
			case "C" => 12
			case "D" => 13
			case "E" => 14
			case "F" => 15
			case _ => 0
		}
	}

	if(test(k(0)) == test(k(1))){
		println("=")
	}else if(test(k(0)) > test(k(1))){
		println(">")
	}else{
		println("<")
	}

}

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.


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

Score : 200 points

Problem Statement

We have a long seat of width X centimeters.
There are many people who wants to sit here. A person sitting on the seat will always occupy an interval of length Y centimeters.

We would like to seat as many people as possible, but they are all very shy, and there must be a gap of length at least Z centimeters between two people, and between the end of the seat and a person.

At most how many people can sit on the seat?

Constraints

All input values are integers.

1 \leq X, Y, Z \leq 10^5

Y+2Z \leq X

Input

Input is given from Standard Input in the following format:

X Y Z

Output

Print the answer.

Sample Input 1

13 3 1

Sample Output 1

3

There is just enough room for three, as shown below:

Figure

Sample Input 2

12 3 1

Sample Output 2

2

Sample Input 3

100000 1 1

Sample Output 3

49999

Sample Input 4

64146 123 456

Sample Output 4

110

Sample Input 5

64145 123 456

Sample Output 5

109


import scala.io.StdIn

object Main extends App {
  val Array(x, y, z) = StdIn.readLine.split(" ").map(_.toInt)
  val ans = (x-z) / (y+z)
  println(ans)
}


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.last - w)
      val b = Math.abs(an.last - an(an.length - 2))
      if (a > b) a else b
    }

    println(ans)
  }
}

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


import scala.math.sqrt

object Main{
  def main(args: Array[String]){
    val input=io.Source.stdin.getLines().mkString("\n")
    println(solve(input).trim())
  }

  def solve(input:String):String={
    val n=input.toInt
    (((sqrt(n)+0.25).toInt)*((sqrt(n)+0.25).toInt)).toString
  }
}

Score : 200 points

Problem Statement

Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.

Constraints

1 \leq N \leq 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the largest square number not exceeding N.

Sample Input 1

10

Sample Output 1

9

10 is not square, but 9 = 3 × 3 is. Thus, we print 9.

Sample Input 2

81

Sample Output 2

81

Sample Input 3

271828182

Sample Output 3

271821169


import java.util.Scanner

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

  val n = sc.nextInt

  val sqrtN = Math.floor(Math.sqrt(n)).toInt

  val res = sqrtN * sqrtN

  println(res)
}