object Main extends App {
val n = scala.io.StdIn.readInt()

if (n>999) println("ABD") else println("ABC")
}

Score : 100 points

Problem Statement

Decades have passed since the beginning of AtCoder Beginner Contest.

The contests are labeled as ABC001, ABC002, ... from the first round, but after the 999-th round ABC999, a problem occurred: how the future rounds should be labeled?

In the end, the labels for the rounds from the 1000-th to the 1998-th are decided: ABD001, ABD002, ..., ABD999.

You are given an integer N between 1 and 1998 (inclusive). Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Constraints

1 \leq N \leq 1998

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Sample Input 1

999

Sample Output 1

ABC

The 999-th round of AtCoder Beginner Contest is labeled as ABC999.

Sample Input 2

1000

Sample Output 2

ABD

The 1000-th round of AtCoder Beginner Contest is labeled as ABD001.

Sample Input 3

1481

Sample Output 3

ABD

The 1481-th round of AtCoder Beginner Contest is labeled as ABD482.


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

import scala.collection.mutable
import scala.util.Sorting
import math.{abs, max, min}

object Main {
  val MOD = 1000000007
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val a = sc.nextInt()
    val b = sc.nextInt()
    val d = b - a
    val c = d * (d + 1) / 2
    val ans = c - b
    println(ans)
  }

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

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

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

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

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

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1

Submitted source-code file size, in bytes.

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

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


import scala.io.StdIn
object Main extends App {
  val N = StdIn.readLine().toInt
  val list = for {
    a <- 1 to N - 1
    b = N - a
  } yield a.toString.toList.map(_.asDigit).sum + b.toString.toList.map(_.asDigit).sum
  println(list.min)
}

Score : 200 points

Problem Statement

Takahashi has two positive integers A and B.

It is known that A plus B equals N.
Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).

Constraints

2 ≤ N ≤ 10^5

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B".

Sample Input 1

15

Sample Output 1

6

When A=2 and B=13, the sums of their digits are 2 and 4, which minimizes the value in question.

Sample Input 2

100000

Sample Output 2

10


import java.util.Scanner

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

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

  def solve(sc: Scanner): String = {
    val A = sc.nextInt
    val B = sc.nextInt

    Array(A + B, A - B, A * B).max.toString
  }
}

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest value among A+B, A-B and A \times B.

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


object Main extends App {
	val input = io.Source.stdin.getLines.toIndexedSeq.tail.head
	val wi = input.zipWithIndex.filter(_._1 == 'W')

	val bits = new java.util.BitSet()
	wi.foreach(e => bits.set(e._2, true))

	val ret = (0 until input.length).foldLeft(Int.MaxValue) { (min, i) =>
		val l = bits.get(0, i).cardinality
		val r = input.length - i - bits.get(i, Int.MaxValue).cardinality
		Math.min(min, l + r)
	}
	println(ret)
}

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

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

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


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

    println {
      (0 until n).map(leader =>
        (0 until leader).count(! areE(_)) +
          ((leader + 1) until n).count(areE)
      ).min
    }
  }
}


object Main extends App {
  val Array(a,b,c,k) = io.StdIn.readLine.split(" ").map(_.toLong)

    if (a == b && b == c) println(0)
    else {
        def rec(count: Long, x: Long, y: Long, z: Long): (Long, Long, Long) = {
            if (k == count) (x,y,z)
            else rec(count+1, y+z, x+z, x+y)
        }

        val abc = rec(0, a,b,c) // (high-hashi, mid-hashi, low-hashi
        val result = abc._1 - abc._2

        if (math.pow(10, 18) < result.abs) println("Unfair")
        else println(result)
    }
}

Score : 300 points

Problem Statement

Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively.
After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get:

Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own integer with the result.

However, if the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Constraints

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

0 \leq K \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the integer Takahashi will get minus the integer Nakahashi will get, after repeating the following operation K times.
If the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Sample Input 1

1 2 3 1

Sample Output 1

1

After one operation, Takahashi, Nakahashi and Hikuhashi have 5, 4 and 3, respectively. We should print 5-4=1.

Sample Input 2

2 3 2 0

Sample Output 2

-1

Sample Input 3

1000000000 1000000000 1000000000 1000000000000000000

Sample Output 3

0


object Main extends App {
    val Array(a,b,c,d) = scala.io.StdIn.readLine().split("\\s").map(_.toInt)

    if ((a-c).abs <= d || ((a-b).abs <= d && (b-c).abs<=d)) println("Yes") else println("No")
}

Score : 100 points

Problem Statement

Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the distance between them is at most d meters.
Determine if A and C can communicate, either directly or indirectly.
Here, A and C can indirectly communicate when A and B can directly communicate and also B and C can directly communicate.

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

If A and C can communicate, print Yes; if they cannot, print No.

Sample Input 1

4 7 9 3

Sample Output 1

Yes

A and B can directly communicate, and also B and C can directly communicate, so we should print Yes.

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes


import scala.io.StdIn

object Main extends App {

  val s = StdIn.readLine()
  val K = StdIn.readLine().toInt
  val r = {
    for (i <- 0 until s.size;
         j <- 1 to s.size - i; if j <= K)
      yield s.substring(i, i + j)
  }.distinct.sorted.apply(K - 1)

  println(r)
}


object Main extends App {
	val Array(a,b,c,d) = scala.io.StdIn.readLine.split(" ").map(_.toInt)

	if(math.abs(a-b) <= d && math.abs(b-c) <= d){
		println("Yes")
	}else{
		println("No")
	}

}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val max = sc.nextInt() match {
    case 1 => 1
    case x =>
      val powers = for {
        i <- LazyList.from(2).takeWhile(_ <= x)
        j <- LazyList.from(2).takeWhile(_ <= x)
      } yield {
        math.pow(i, j).toInt
      }
      powers.filter(_ <= x).max
  }
  println(max)
}

Score : 200 points

Problem Statement

You are given a positive integer X.
Find the largest perfect power that is at most X.
Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.

Constraints

1 ≤ X ≤ 1000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the largest perfect power that is at most X.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most 10: 1, 4, 8 and 9.
We should print the largest among them, 9.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961


import java.util.Scanner

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

  def pow(b: Int, p: Int): Int = {
    if (p == 0) {
      1
    } else if (p % 2 == 0) {
      pow(b * b, p / 2)
    } else {
      // p%2 == 1
      b * pow(b * b, p / 2)
    }
  }

  def log(base: Int)(x: Int) = Math.log(x) / Math.log(base)

  def parfectPowerList(base: Int, upperBound: Int) = {
    val maxExponent = log(base)(upperBound).toInt
    (2 to maxExponent).map(x => pow(base, x))
    //↑すべての値はupperBound以下
  }

  def main(args: Array[String]): Unit = {
    val x: Int = read()
    val parfectPowers = (2 to x).flatMap(i => parfectPowerList(i, x))
    val result = parfectPowers.max
    println(result)
  }
}


Score : 300 points

Problem Statement

You are given a string s.
Among the different substrings of s, print the K-th lexicographically smallest one.

A substring of s is a string obtained by taking out a non-empty contiguous part in s.
For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z and an empty string are not.
Also, we say that substrings are different when they are different as strings.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

200 points will be awarded as a partial score for passing the test set satisfying |s| ≤ 50.

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

s has five substrings: a, b, ab, ba and aba.
Among them, we should print the fourth smallest one, b.
Note that we do not count a twice.

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


import java.util.Scanner

import scala.collection.mutable

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

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

  def solve(sc: Scanner): String = {
    val s = sc.next
    val K = sc.nextInt

    val ss = new mutable.HashSet[String]()

    for (i <- 0 until s.length; j <- i + 1 to Array(i + K, s.length).min) {
      ss += s.substring(i, j)
    }

//    ss.toList.sorted.foreach(println)
    ss.toList.sorted.take(K).last
  }
}


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

object Main extends App {
  val s = readLine().split(" ").map(_.toInt).toSeq
  val k = readInt()

  println(s.max * pow(2, k).toInt + s.filterNot(_ == s.max).sum)
}

Score: 200 points

Problem Statement

There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:

Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.

What is the largest possible sum of the integers written on the blackboard after K operations?

Constraints

A, B and C are integers between 1 and 50 (inclusive).

K is an integer between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C
K

Output

Print the largest possible sum of the integers written on the blackboard after K operations by E869220.

Sample Input 1

5 3 11
1

Sample Output 1

30

In this sample, 5, 3, 11 are initially written on the blackboard, and E869120 can perform the operation once.

There are three choices:

Double 5: The integers written on the board after the operation are 10, 3, 11.

Double 3: The integers written on the board after the operation are 5, 6, 11.

Double 11: The integers written on the board after the operation are 5, 3, 22.

If he chooses 3., the sum of the integers written on the board afterwards is 5 + 3 + 22 = 30, which is the largest among 1. through 3.

Sample Input 2

3 3 4
2

Sample Output 2

22

E869120 can perform the operation twice. The sum of the integers eventually written on the blackboard is maximized as follows:

First, double 4. The integers written on the board are now 3, 3, 8.

Next, double 8. The integers written on the board are now 3, 3, 16.

Then, the sum of the integers eventually written on the blackboard is 3 + 3 + 16 = 22.


object Main extends App {
  import scala.io.StdIn.readLine
  val Array(a, b, c) = readLine().split(' ').map(_.toInt)
  val Array(k) = readLine().split(' ').map(_.toInt)

  val values = (0 until k).foldLeft((a,b,c)) { case ((a,b,c), _ ) =>
    val maximumIdx = Seq(a,b,c).zipWithIndex.maxBy(_._1)._2
    maximumIdx match {
      case 0 =>
        (a * 2, b, c)
      case 1 =>
        (a, b * 2, c)
      case 2 =>
        (a, b, c * 2)
    }
  }

  println(Seq(values._1, values._2, values._3).sum)
}


object Main extends App {
  val primes: Stream[Int] = 2 #:: (Stream.from(3, 2) filter {n =>
    primes takeWhile {_ <= Math.sqrt(n).toInt} forall {n % _ != 0}
  })
  println(primes.filter(_ % 5 == 1).take(io.StdIn.readLine.toInt).mkString(" "))
}

Score: 400 points

Problem Statement

Print a sequence a_1, a_2, ..., a_N whose length is N that satisfies the following conditions:

a_i (1 \leq i \leq N) is a prime number at most 55 555.

The values of a_1, a_2, ..., a_N are all different.

In every choice of five different integers from a_1, a_2, ..., a_N, the sum of those integers is a composite number.

If there are multiple such sequences, printing any of them is accepted.

Notes

An integer N not less than 2 is called a prime number if it cannot be divided evenly by any integers except 1 and N, and called a composite number otherwise.

Constraints

N is an integer between 5 and 55 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print N numbers a_1, a_2, a_3, ..., a_N in a line, with spaces in between.

Sample Input 1

5

Sample Output 1

3 5 7 11 31

Let us see if this output actually satisfies the conditions.

First, 3, 5, 7, 11 and 31 are all different, and all of them are prime numbers.

The only way to choose five among them is to choose all of them, whose sum is a_1+a_2+a_3+a_4+a_5=57, which is a composite number.

There are also other possible outputs, such as 2 3 5 7 13, 11 13 17 19 31 and 7 11 5 31 3.

Sample Input 2

6

Sample Output 2

2 3 5 7 11 13

2, 3, 5, 7, 11, 13 are all different prime numbers.

2+3+5+7+11=28 is a composite number.

2+3+5+7+13=30 is a composite number.

2+3+5+11+13=34 is a composite number.

2+3+7+11+13=36 is a composite number.

2+5+7+11+13=38 is a composite number.

3+5+7+11+13=39 is a composite number.

Thus, the sequence 2 3 5 7 11 13 satisfies the conditions.

Sample Input 3

8

Sample Output 3

2 5 7 13 19 37 67 79


import scala.io.Source

object Main extends App {
  val primes = sieve(Stream.from(2))

  def sieve(st: Stream[Int]): Stream[Int] = {
    val x = st.head
    x #:: sieve(st.tail.filter(_ % x != 0))
  }

  val lines: Iterator[String] = Source.stdin.getLines()
  val n = lines.next.toInt
  println(primes.take(n).mkString(" "))
}


import java.util.Scanner

import scala.collection.Searching._
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.immutable._
import scala.io.StdIn.readLine

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {
  val m = (1 << 9) - 1

  def solve(sc: => Scanner): Unit = {
    println(getPrimeList.filter(_ % 5 == 4).drop(100).take(sc.nextInt).force.mkString(" "))
  }

  def recursive(now: Int, A: Array[List[Int]]): Int = {
    if (A(now).size == 0) (now) else {
      val next = A(now).head
      A(now) = A(now).filter(_ != next)
      A(next) = A(next).filter(_ != now)
      recursive(next, A)
    }
  }

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

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

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

  def check(A: Array[List[Int]]): Boolean = {
    A.map(_.size == 0).fold(true)((a, b) => a & b)
  }

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

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

  def calc(v: Long): Long = (v + 1) * v / 2

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

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


import java.util.Scanner

import scala.collection.Searching._
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.immutable._
import scala.io.StdIn.readLine

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {
  val m = (1 << 9) - 1

  def solve(sc: => Scanner): Unit = {
    println(getPrimeList(5555).filter(_ % 5 == 1).take(sc.nextInt).mkString(" "))
  }

  def recursive(now: Int, A: Array[List[Int]]): Int = {
    if (A(now).size == 0) (now) else {
      val next = A(now).head
      A(now) = A(now).filter(_ != next)
      A(next) = A(next).filter(_ != now)
      recursive(next, A)
    }
  }

  def getPrimeList(maxV: Long): List[Long] = {
    getPrimeListRecursive((2L to maxV).toList)
  }

  def getPrimeListRecursive(A: List[Long]): List[Long] = {
    if (A.size == 0) (List[Long]()) else {
      List(A.head) ++ getPrimeListRecursive(A.filter(_ % A.head != 0))
    }
  }

  def check(A: Array[List[Int]]): Boolean = {
    A.map(_.size == 0).fold(true)((a, b) => a & b)
  }

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

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

  def calc(v: Long): Long = (v + 1) * v / 2

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

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


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

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

object Main {
  val DEBUG = false

  lazy val debugOut: PrintWriter = {
    new PrintWriter(new BufferedOutputStream(new FileOutputStream("log.txt", true)))
  }

  def log(message: => String): Unit = {
    if (DEBUG) {
      Console.err.println(message)
    }
  }

  def debug(closure: => Unit): Unit = {
    if (DEBUG) {
      closure
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    inner(n, width - 1)
  }

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

    inner(n % m, p, 1)
  }

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

    log("=== start")

    val n = get[Int]
    val as = getArray[Int]

    val sums = as.scanLeft(0L) {
      case (acc, a) => acc + a
    }

    val map = mutable.HashMap.empty[Long, Long]
    for (sum <- sums) {
      map(sum) = map.getOrElse(sum, 0L) + 1
    }

    var patternNum = 0L
    for (c <- map.values) {
      patternNum += c * (c - 1) / 2
    }

    out.println(patternNum)

    out.flush()
    log("=== end")
    debug {
      debugOut.flush()
    }
  }
}

Score : 200 points

Problem Statement

We have an integer sequence A, whose length is N.

Find the number of the non-empty contiguous subsequences of A whose sums are 0.
Note that we are counting the ways to take out subsequences.
That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

Constraints

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

-10^9 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the number of the non-empty contiguous subsequences of A whose sum is 0.

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

There are three contiguous subsequences whose sums are 0: (1,3,-4), (-4,2,2) and (2,-2).

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

In this case, some subsequences that have the same contents but are taken from different positions are counted individually.
For example, three occurrences of (1, -1) are counted.

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


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 S = Array.ofDim[Char](2*N, 2*N)

  for (y <- 1 to N){
    val s = in.next()
    for (x <- 1 to N){
      S(y)(x) = s(x-1)
    }
  }

  for (y <- N+1 to 2*N-1){
    for (x <- 1 to N){
      S(y)(x) = S(y-N)(x)
    }
  }
  for (y <- 1 to N){
    for (x <- N+1 to 2*N-1){
      S(y)(x) = S(y)(x-N)
    }
  }
  for (y <- N+1 to 2*N-1){
    for (x <- N+1 to 2*N-1){
      S(y)(x) = S(y-N)(x-N)
    }
  }

  // process
  var ans = 0

  val dp = Array.ofDim[Int](2*N, 2*N)
  var tmp = 42
  for(y <- 1 to 2*N-1; x <- y+1 to 2*N-1) {
    if(S(y)(x) == S(x)(y)) {
      dp(y)(x) = tmp
    }
  }
  var flag = true
  val ny = 1; val nx = 1
  for (y <- ny to ny+N-1; x <- y+1 to ny+N-1) {
    if(dp(y)(x) != tmp) {
      flag = false
    }
  }
  if(flag)
    ans += N

  //// for y
  for(sty <- 2 to N) {
    tmp += 1

    for(y <- sty to 2*N-1; x <- 1+(y-sty+1) to 2*N-1 - (sty-1)) {
      if(S(y)(x) == S(x+(sty-1))(y-(sty-1))) {
        dp(y)(x) = tmp
      }
    }

    val ny = sty; val nx = 1
    var flag = true
    for (y <- ny to ny+N-1; x <- nx + y-ny+1 to nx+N-1) {
      if(dp(y)(x) != tmp) {
        flag = false
      }
    }
    if(flag){
      ans += (N - sty + 1)
    }

  }

  //// for x
  for(stx <- 2 to N) {
    tmp += 1

    for(x <- stx to 2*N-1; y <- 1+(x-stx+1) to 2*N-1 - (stx-1)) {
      if(S(y)(x) == S(x-(stx-1))(y+(stx-1))) {
        dp(y)(x) = tmp
      }
    }

    ///
    val nx = stx; val ny = 1
    var flag = true

    for (x <- nx to nx+N-1; y <- ny + x-nx+1 to ny+N-1) {
      if(dp(y)(x) != tmp) {
        flag = false
      }
    }
    if(flag){
      ans += (N - stx + 1)
    }
  }

  println(ans)
}

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

Score : 500 points

Problem Statement

Snuke has two boards, each divided into a grid with N rows and N columns.
For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).

There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.

Snuke will write letters on the second board, as follows:

First, choose two integers A and B ( 0 \leq A, B < N ).

Write one letter in each square on the second board.
Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board.
Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.

After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.

Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Constraints

1 \leq N \leq 300

S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}

Output

Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Sample Input 1

2
ab
ca

Sample Output 1

2

For each pair of A and B, the second board will look as shown below:

The second board is a good board when (A,B) = (0,1) or (A,B) = (1,0), thus the answer is 2.

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

Every possible choice of A and B makes the second board good.

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

No possible choice of A and B makes the second board good.


import scala.io.StdIn
object Main extends App {
  val answer = StdIn.readLine().split("").filter(_=='o').size * 100 + 700
  println(answer)
}

Score : 100 points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when S is given, prints the price of the corresponding bowl of ramen.

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

Print the price of the bowl of ramen corresponding to S.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is 700 + 100 \times 3 = 1000 yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is 700 yen.


import scala.io.StdIn
object Main extends App {
  val answer = StdIn.readLine().split("").filter(_=='o').size * 100 + 900
  println(answer)
}


object Main extends App {
  println(readLine.toSeq.count(_.equals('o')) * 100 + 700)
}


object Main extends App {
	val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
	val a = new Array[Int](n)
	for(i <- 0 until n){
		a(i) = scala.io.StdIn.readInt
	}

	val tp = a.sum
	println(n + (x - tp)/a.min)
}

Score : 200 points

Problem Statement

Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts.

Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition:

For each of the N kinds of doughnuts, make at least one doughnut of that kind.

At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Also, under the constraints of this problem, it is always possible to obey the condition.

Constraints

2 ≤ N ≤ 100

1 ≤ m_i ≤ 1000

m_1 + m_2 + ... + m_N ≤ X ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
m_1
m_2
:
m_N

Output

Print the maximum number of doughnuts that can be made under the condition.

Sample Input 1

3 1000
120
100
140

Sample Output 1

9

She has 1000 grams of Moto and can make three kinds of doughnuts. If she makes one doughnut for each of the three kinds, she consumes 120 + 100 + 140 = 360 grams of Moto. From the 640 grams of Moto that remains here, she can make additional six Doughnuts 2. This is how she can made a total of nine doughnuts, which is the maximum.

Sample Input 2

4 360
90
90
90
90

Sample Output 2

4

Making one doughnut for each of the four kinds consumes all of her Moto.

Sample Input 3

5 3000
150
130
150
130
110

Sample Output 3

26


import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    solve(new Scanner(System.in))
  }

  def solve(sc: Scanner): Unit = {
    val A = sc.nextInt
    val B = sc.nextInt
    val C = sc.nextInt
    var X = sc.nextInt
    var Y = sc.nextInt

    var p = if (A + B > C * 2) {
      val m = List(X, Y).min
      X -= m
      Y -= m
      C * 2 * m
    } else 0
    p += List(A, C * 2).min * X
    p += List(B, C * 2).min * Y
    println(p)
  }
}

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val a, b, c, x, y = sc.nextInt()
  if (a + b <= 2 * c) {
    println(a * x + b * y)
  } else {
    var ans = 0
    if (x <= y) {
      ans += 2 * c * x
      ans += (y - x) * b.min(2 * c)
    } else {
      ans += 2 * c * y
      ans += (x - y) * a.min(2 * c)
    }
    println(ans)
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val x = List.fill(n)(sc.nextInt())
  val sorted = x.sorted
  val med1 = sorted.apply(n/2)
  val med2 = sorted.apply(n/2-1)
  for (i <- 1 to n){
    if (x(i-1)<=med2){
      println(med1)
    } else{
      println(med2)
    }
  }
}

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


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) = {
      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)
      }
      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(-1, upper)
      }
      @scala.annotation.tailrec
      def loop(i: Int, diff: Int, n: Int, r: Int): (Int, Int) =
        if (i < N) {
          val center = (A(i) / 2.toDouble).round.toInt
          val li = lowerBounds(center, i)
          val ri = upperBounds(center, i)
          val left = if (li >= 0) A(li) else 0
          val right = if (ri < A(i)) A(ri) else A(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, A.last, 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.{util => ju}
import scala.collection.{mutable => mu}
import MyPredef._

object Main extends App {
  import java.util.Arrays
  val p = new java.io.PrintWriter(System.out)

  val n = MyPredef.nextInt
  val X = Array.fill(n)(MyPredef.nextInt)
  val Xs = X.clone()
  Arrays.sort(Xs)
  val halfB = Xs(n / 2 - 1) // before
  val halfA = Xs(n / 2) // after

  MyPredef.rep(n, i => {
    if (X(i) <= halfB) {
      p.println(halfA)
    } else {
      p.println(halfB)
    }
  })
  p.flush()
}

object MyPredef {
  @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
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val X = List.fill(n)(sc.nextInt)
  val Xs = X.sorted
  val halfB = Xs(n / 2 - 1) // before
  val halfA = Xs(n / 2) // after

  for (i <- 0 until n) {
    if (X(i) <= halfB) {
      println(halfA)
    } else {
      println(halfB)
    }
  }
}


object Main{
    def main(args: Array[String]){
        val numlist = io.StdIn.readLine().split(" ").map(_.toInt).toList
        val a = numlist(0)
        val b = numlist(1)
        val k = numlist(2)
        (a to b).foreach(i => if (i < a + k || i > b - k) println(i))
    }
}

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{
    def main(args: Array[String]){
        val inputString = io.StdIn.readLine()
        if (inputString.exists(s => s == 'a') && inputString.exists(s => s == 'b') && inputString.exists(s=> s == 'c')) println("Yes") else println("No")
    }
}


object Main extends App {
	val s = scala.io.StdIn.readLine.toList.toSet

	if(s == Set('a', 'b', 'c')){
		println("Yes")
	}else{
		println("No")
	}
}


import scala.io.StdIn

object Main extends App {
  val Array(a, b, k) = StdIn.readLine().trim.split(" ").map(_.toInt)
  val k1 = if(b - a <= k) b - a else k
  val result: Array[Int] = if(a != b) ((a until a + k1).map(i => i) ++ (b - k1 + 1 to b ).map(i => i)).toArray
  else Array(a)

  println(result.distinct.mkString(f"%n"))
}

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


object Main extends App {
  val Array(a,b,c) = readLine.split(" ").map{_.toInt}

  if ((a+b)%2==0&&(b+c)%2==0&&(c+a)%2==0) {
    val Array(aa,bb,cc) = Array(a,b,c).sorted
    println((2*cc-aa-bb)/2)
  } else {
    val even = Array(a,b,c).filter{_%2==0}
    val odd = Array(a,b,c).filter{_%2==1}
    if (even.size==1) {
      val aa = even(0)
      val bb = odd(0)+1
      val cc = odd(1)+1
      val Array(aaa,bbb,ccc) = Array(aa,bb,cc).sorted
      println(1+(2*ccc-aaa-bbb)/2)
    } else {
      val aa = even(0) + 1
      val bb = even(1) + 1
      val cc = odd(0)
      val Array(aaa,bbb,ccc) = Array(aa,bb,cc).sorted
      println(1+(2*ccc-aaa-bbb)/2)
    }
  }
}

Score : 300 points

Problem Statement

You are given three integers A, B and C. Find the minimum number of operations required to make A, B and C all equal by repeatedly performing the following two kinds of operations in any order:

Choose two among A, B and C, then increase both by 1.

Choose one among A, B and C, then increase it by 2.

It can be proved that we can always make A, B and C all equal by repeatedly performing these operations.

Constraints

0 \leq A,B,C \leq 50

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the minimum number of operations required to make A, B and C all equal.

Sample Input 1

2 5 4

Sample Output 1

2

We can make A, B and C all equal by the following operations:

Increase A and C by 1. Now, A, B, C are 3, 5, 5, respectively.

Increase A by 2. Now, A, B, C are 5, 5, 5, respectively.

Sample Input 2

2 6 3

Sample Output 2

5

Sample Input 3

31 41 5

Sample Output 3

23


import scala.io.StdIn

object Main extends App {
  val Array(min, mid, max) = StdIn.readLine().trim.split(" ").map(_.toInt).sorted

  val x = if(((3*max) % 2) == (min + mid + max) % 2){
    max
  } else max + 1

  println((3*x - (min + mid + max)) / 2)
}


object Main extends App {
	val n = scala.io.StdIn.readInt
	val a = new Array[Long](n)
	var bs = Long.MaxValue

	for(i<-0 until n){
		val tp = scala.io.StdIn.readLine.split(" ").map(_.toLong)
		a(i) = tp(0)

		if(tp(0) > tp(1)){
			bs = math.min(bs, tp(1))
		}
	}

	if(bs == Long.MaxValue){
		println(0)
	}else{
		println(a.sum - bs)
	}
}

Score : 700 points

Problem Statement

You are given sequences A and B consisting of non-negative integers.
The lengths of both A and B are N, and the sums of the elements in A and B are equal.
The i-th element in A is A_i, and the i-th element in B is B_i.

Tozan and Gezan repeats the following sequence of operations:

If A and B are equal sequences, terminate the process.

Otherwise, first Tozan chooses a positive element in A and decrease it by 1.

Then, Gezan chooses a positive element in B and decrease it by 1.

Then, give one candy to Takahashi, their pet.

Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible.
Find the number of candies given to Takahashi when both of them perform the operations optimally.

Constraints

1 \leq N \leq 2 × 10^5

0 \leq A_i,B_i \leq 10^9(1\leq i\leq N)

The sums of the elements in A and B are equal.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally.

Sample Input 1

2
1 2
3 2

Sample Output 1

2

When both Tozan and Gezan perform the operations optimally, the process will proceed as follows:

Tozan decreases A_1 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

Tozan decreases A_2 by 1.

Gezan decreases B_1 by 1.

One candy is given to Takahashi.

As A and B are equal, the process is terminated.

Sample Input 2

3
8 3
0 1
4 8

Sample Output 2

9

Sample Input 3

1
1 1

Sample Output 3

0


import java.util.Scanner

import scala.collection.Searching._
import scala.annotation.tailrec
import scala.collection.immutable.{NumericRange, Queue}
import scala.collection.mutable
import scala.io.StdIn.readLine

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {
  def solve(sc: => Scanner): Unit = {
    println(math.min(sc.nextInt, sc.nextInt) + math.min(sc.nextInt, sc.nextInt))
  }

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

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

Score : 100 points

Problem Statement

You planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

1 \leq A \leq 1 000

1 \leq B \leq 1 000

1 \leq C \leq 1 000

1 \leq D \leq 1 000

All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Sample Input 1

600
300
220
420

Sample Output 1

520

The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.

Therefore, the minimum total fare is 300 + 220 = 520 yen.

Sample Input 2

555
555
400
200

Sample Output 2

755

Sample Input 3

549
817
715
603

Sample Output 3

1152


object Main extends App {
  import scala.math.abs
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  var A: Array[Int] = Array.fill(n)(sc.nextInt)
  A = 0 +: A :+ 0
  // 全経路いった場合を計算
  var total = 0
  for (i <- 1 to n + 1) {
      total += abs(A(i) - A(i - 1))
  }
  println(total)
  println()

  // 端折る箇所がi-1 i+1の間だった場合は全経路いった場合と同じ、違った場合はi と i-1の絶対値の2倍の額を合計から引く
  for (i <- 1 to n) {
    val before = A(i - 1)
    val after = A(i + 1)

    println(total - abs(A(i) - before) - abs(after - A(i)) + abs(after - before))
  }
 }

Score : 300 points

Problem Statement

There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N.
Spot i is at the point with coordinate A_i.
It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.

You planned a trip along the axis.
In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.

However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i.
You will visit the remaining spots as planned in the order they are numbered.
You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.

For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.

Constraints

2 \leq N \leq 10^5

-5000 \leq A_i \leq 5000 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N lines.
In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.

Sample Input 1

3
3 5 -1

Sample Output 1

12
8
10

Spot 1, 2 and 3 are at the points with coordinates 3, 5 and -1, respectively.
For each i, the course of the trip and the total cost of travel when the visit to Spot i is canceled, are as follows:

For i = 1, the course of the trip is 0 \rightarrow 5 \rightarrow -1 \rightarrow 0 and the total cost of travel is 5 + 6 + 1 = 12 yen.

For i = 2, the course of the trip is 0 \rightarrow 3 \rightarrow -1 \rightarrow 0 and the total cost of travel is 3 + 4 + 1 = 8 yen.

For i = 3, the course of the trip is 0 \rightarrow 3 \rightarrow 5 \rightarrow 0 and the total cost of travel is 3 + 2 + 5 = 10 yen.

Sample Input 2

5
1 1 1 2 0

Sample Output 2

4
4
4
2
4

Sample Input 3

6
-679 -2409 -3258 3095 -3291 -4462

Sample Output 3

21630
21630
19932
8924
21630
19288


import scala.io._
object Main{
  def main(args: Array[String]) {
    val input = Source.fromInputStream(System.in)
    val lines = input.getLines.toSeq
    println(lines(0)(0)+lines(1)(1)+lines(2)(2))
  }
}

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 scala.io.{StdIn => in}

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

  def check(i:Int):Boolean = {
    val s = String.valueOf(i)
    s(0) == s(4) && s(1) == s(3)
  }
  val ans = (a to b).map(check).count(_ == true)
  println(ans)
}

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

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

  val ans = (n to m).count(i => {
    ( i / 10000) == (i % 10) && (i / 1000 % 10) == (i / 10 % 10)
  })

  println(ans)
}


import scala.io.StdIn
object Main extends App {

  val n = StdIn.readLine().toInt
  val linse = (0 until n).map(_ => StdIn.readLine())

  val combis = List('M','A','R','C','H').combinations(3)

  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).toLong *
      members.get(l(1)).getOrElse(0).toLong * members.get(l(2)).getOrElse(0).toLong)
  }

  println(result)

}

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).toLong *
      members.get(l(1)).getOrElse(0).toLong * members.get(l(2)).getOrElse(0).toLong)
  }

  println(result)
}


object Main extends App {
  val sr = new StdinReader
  val h, w, d = sr.nextInt
  val table: Map[Int, (Int, Int)] = (for {
        y <- 0 until h
        x <- 0 until w
      } yield sr.nextInt -> (x, y)).toMap

  val tbl = new Array[Int](h * w + 1)
  (1 to d).flatMap{dd =>
    ((dd + d) to (h * w) by d).map {p =>
      val lPos = table(p - d)
      val rPos = table(p)
      val mp = Math.abs(lPos._1 - rPos._1) + Math.abs(lPos._2 - rPos._2)
      tbl(p) = mp + tbl(p - d)
    }
  }

  println(
    (1 to sr.nextInt).map{i =>
      val l, r = sr.nextInt
      tbl(r) - tbl(l)
    }.mkString("\n"))

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

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

  // support single byte char only
  def next: String = {
    val sb = new StringBuilder
    var reading = false
    var completed = false
    while(!completed) {
      val b = readByte

      if ('!' <= b && b <= '~') {
        sb.append(b.asInstanceOf[Char])
        reading = true
      } else {
        if (reading) completed = true
      }
    }
    sb.toString
  }

  def nextInt: Int = {
    var i = 0
    var reading = false
    var completed = false
    while(!completed) {
      val b = readByte

      if (b == '-') {
        reading = true
        i *= -1
      } else if ('0' <= b && b <= '9') {
        reading = true
        i = i * 10 + (b - '0')
      } else if (reading) completed = true
    }
    i
  }
}
}

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 scala.io.StdIn
object Main extends App {
  val N = StdIn.readLine().toInt
  val A = StdIn.readLine().toInt
  println(if ((N % 500) <= A) "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{
       val n = scala.io.StdIn.readInt
       val a = scala.io.StdIn.readInt

  	   val b = n%500

       val ans = if((a-b)>= 0){
           "Yes"
        }else{
           "No"
           }
        println(ans)
        }


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt()
  val a = List.fill(N)(sc.nextInt())

  println(calc(N, a))

  def calc(N: Int, a: List[Int]) : Int = {
    a.sorted.foldLeft(0)((alice, bob) => bob - alice)
  }
}

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

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val as = List.fill(n)(sc.nextInt())
    val ass = as.sorted.reverse
    var ans = 0
    for (i <- ass.indices) {
      if (i % 2 == 0) {
        ans += ass(i)
      } else {
        ans -= ass(i)
      }
    }

    println(ans)
  }
}


object Main extends App {
	private val Empty = Int.MaxValue - 1
	private val Wall = Int.MaxValue

	private def pre(inputs: Seq[String]) = {
		val g = inputs.head.split(' ').map(_.toInt)
		val total = g(0) * g(1)
		val w = inputs.map(_.count(_ == '#')).sum //TODO '.'に変えてみる？
		val min = solve(inputs)
		val ret = total - w - min - 1
		//assert(0 <= ret) //FIXME RE
		assert(-1 != ret) //FIXME RE

		//assert(ret < Empty)
		ret
	}

	private def solve(inputs: Seq[String]) = {
		val g = inputs.head.split(' ').map(_.toInt)
		val sy = 1
		val sx = 1
		val gy = g(0)
		val gx = g(1)
		val ffff = inputs.tail.map(_.toCharArray.map(e => if (e == '#') Wall else Empty).toArray).toArray
		val fff = ffff.map(Wall +: _ :+ Wall)
		val wall = fff(0).map(_ => Wall)
		val f = wall +: fff :+ wall

		val q = scala.collection.mutable.Queue[(Int, Int)]()
		q.enqueue((sx, sy))
		f(sy)(sx) = -1
		do {
			val (ny, nx) = q.dequeue()
			if (f(ny)(nx) == -1 || f(ny)(nx) == Empty) {
				//f.foreach(e => println(e.toSeq.filterNot(_ == Empty)))

				f(ny)(nx) = 1 + Math.min(f(ny)(nx),
					Math.min(
						Math.min(f(ny - 1)(nx), f(ny + 1)(nx)),
						Math.min(f(ny)(nx - 1), f(ny)(nx + 1))))

				q.enqueue((ny - 1, nx))
				q.enqueue((ny + 1, nx))
				q.enqueue((ny, nx - 1))
				q.enqueue((ny, nx + 1))

				if (nx == gx && ny == gy) q.clear()
			}
		} while (q.nonEmpty)

		//print("done")
		f(gy)(gx)
	}

	private val s1 =
		"""3 3
			|..#
			|#..
			|...
			|""".stripMargin.split("\r\n")
	private val s2 =
		"""10 37
			|.....................................
			|...#...####...####..###...###...###..
			|..#.#..#...#.##....#...#.#...#.#...#.
			|..#.#..#...#.#.....#...#.#...#.#...#.
			|.#...#.#..##.#.....#...#.#.###.#.###.
			|.#####.####..#.....#...#..##....##...
			|.#...#.#...#.#.....#...#.#...#.#...#.
			|.#...#.#...#.##....#...#.#...#.#...#.
			|.#...#.####...####..###...###...###..
			|.....................................
			|""".stripMargin.split("\r\n")
	private val s3 =
		"""10 37
			|.....................................
			|.....................................
			|.....................................
			|.....................................
			|.....................................
			|.....................................
			|.....................................
			|.....................................
			|.....................................
			|.....................................
			|""".stripMargin.split("\r\n")
	private val s4 =
		"""5 37
			|.....................................
			|####################################.
			|.....................................
			|.####################################
			|.....................................
			|""".stripMargin.split("\r\n")
	assert(pre(s1) == 2)
	assert(pre(s2) == 209)
	assert(pre(s3) == 370 - 10 - 37 + 1)
	assert(pre(s4) == 0)

	println(pre(scala.io.Source.stdin.getLines().toSeq))
}

Score: 400 points

Problem statement

We have an H \times W grid whose squares are painted black or white. The square at the i-th row from the top and the j-th column from the left is denoted as (i, j).

Snuke would like to play the following game on this grid. At the beginning of the game, there is a character called Kenus at square (1, 1). The player repeatedly moves Kenus up, down, left or right by one square. The game is completed when Kenus reaches square (H, W) passing only white squares.

Before Snuke starts the game, he can change the color of some of the white squares to black. However, he cannot change the color of square (1, 1) and (H, W). Also, changes of color must all be carried out before the beginning of the game.

When the game is completed, Snuke's score will be the number of times he changed the color of a square before the beginning of the game. Find the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed, that is, Kenus can never reach square (H, W) regardless of how Snuke changes the color of the squares.

The color of the squares are given to you as characters s_{i, j}. If square (i, j) is initially painted by white, s_{i, j} is .; if square (i, j) is initially painted by black, s_{i, j} is #.

Constraints

H is an integer between 2 and 50 (inclusive).

W is an integer between 2 and 50 (inclusive).

s_{i, j} is . or # (1 \leq i \leq H, 1 \leq j \leq W).

s_{1, 1} and s_{H, W} are ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1}s_{1, 2}s_{1, 3} ... s_{1, W}
s_{2, 1}s_{2, 2}s_{2, 3} ... s_{2, W}
: :
s_{H, 1}s_{H, 2}s_{H, 3} ... s_{H, W}

Output

Print the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed.

Sample Input 1

3 3
..#
#..
...

Sample Output 1

2

The score 2 can be achieved by changing the color of squares as follows:

Sample Input 2

10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
.....................................

Sample Output 2

209


import scala.collection.mutable.{HashSet => MSet}
import scala.io.StdIn._
object Main extends App {
  val Dirs = Seq((-1, 0), (1, 0), (0, -1), (0, 1))
  val checked = MSet[(Int, Int)]()

  val Array(h, w) = readLine.split(" ").map{_.toInt}
  val field: Array[String] = (1 to h).map{i => readLine}.toArray
  val Blacks = field.map{_.count(_ == '#')}.sum

  def valid(x: Int, y: Int): Boolean =
    0 < x && x <= w && 0 < y && y <= h && field(y - 1).charAt(x - 1) == '.' && !checked(x, y)

  @scala.annotation.tailrec
  def check(pos: Set[(Int, Int)], step: Int = 1): Int = {
    val valids = (for {
      (x, y) <- pos
      (dx, dy) <- Dirs if (valid(x + dx, y + dy))
    } yield (x + dx, y + dy)).toSet
    checked ++= valids
    if (checked(w, h)) w * h - (Blacks + step + 1)
    else if (valids.size == 0) -1
    else check(valids, step + 1)
  }

  println(check(Set((1, 1))))
}


object Main {

  def func(a: Long, b: Long): Long = {
    var result = a * 2
    while(true) {
      if (result % b != 0)
        return result
      result += a
    }
    return -1
  }

  def main(args: Array[String]): Unit = {
    val context = Console.readLine()
    val numbers = context.split(" ").map(_.toLong)

    if (numbers(1) % numbers(0) == 0) {
      println("-1")
    } else {
      println(func(numbers(0), numbers(1)))
    }
  }
}

Score : 100 points

Problem Statement

You are given positive integers X and Y.
If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it.
If it does not exist, print -1.

Constraints

1 ≤ X,Y ≤ 10^9

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, or print -1 if it does not exist.

Sample Input 1

8 6

Sample Output 1

16

For example, 16 is a multiple of 8 but not a multiple of 6.

Sample Input 2

3 3

Sample Output 2

-1

A multiple of 3 is a multiple of 3.


import java.util.Scanner

/**
  * Created by 80011714 on 2018/2/5.
  */
object Main {

  def solve(sc: Scanner): Unit = {
    val x, y = sc.nextLong()
    println(if (x % y == 0) (-1) else {
      var i = 1
      while (i * x % y == 0) (i += 1)
      i * x
    })
  }

  def task2(n: Int, left: Array[Long], right: Array[Long]): String = {
    if (n == 1)
      return if (left.head <= right.head) "Yes" else "No"

    if (left.head < right.head) {
      val right_add_count = (right.head - left.head) / 2
      right(1) += right_add_count
    } else if (left.head > right.head) {
      val left_add_count = left.head - right.head
      left(1) += (left_add_count * 2)
    }
    return task2(n - 1, left.tail, right.tail)
  }

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

    val N = scala.io.StdIn.readInt
    val a = scala.io.StdIn.readLine.split(" ").map(_.toLong).toSeq.toArray
    val b = scala.io.StdIn.readLine.split(" ").map(_.toLong).toSeq.toArray

    println(task2(N, a, b))
  }
}

Score : 300 points

Problem Statement

You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N.
Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal.

Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two actions simultaneously:

Add 2 to a_i.

Add 1 to b_j.

Constraints

1 ≤ N ≤ 10 000

0 ≤ a_i,b_i ≤ 10^9 (1 ≤ i ≤ N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 .. a_N
b_1 b_2 .. b_N

Output

If we can repeat the operation zero or more times so that the sequences a and b become equal, print Yes; otherwise, print No.

Sample Input 1

3
1 2 3
5 2 2

Sample Output 1

Yes

For example, we can perform three operations as follows to do our job:

First operation: i=1 and j=2. Now we have a = \{3,2,3\}, b = \{5,3,2\}.

Second operation: i=1 and j=2. Now we have a = \{5,2,3\}, b = \{5,4,2\}.

Third operation: i=2 and j=3. Now we have a = \{5,4,3\}, b = \{5,4,3\}.

Sample Input 2

5
3 1 4 1 5
2 7 1 8 2

Sample Output 2

No

Sample Input 3

5
2 7 1 8 2
3 1 4 1 5

Sample Output 3

No


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

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

object Main {
  val MOD = 1000000007
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val M = sc.nextInt()

    type Node = Int
    type Edge = (Node, Int)
    val E = Array.ofDim[ArrayBuffer[Edge]](N)
    (0 until M) foreach { _ =>
      val l = sc.nextInt() - 1
      val r = sc.nextInt() - 1
      val d = sc.nextInt()
      if (E(l) == null) E(l) = ArrayBuffer.empty
      if (E(r) == null) E(r) = ArrayBuffer.empty
      E(l) += ((r, d))
      E(r) += ((l, -d))
    }

    val d = Array.ofDim[Int](N)
    type Elm = (Node, Int)
    val que = mutable.Queue.empty[Elm]

    (0 until N) foreach { i =>
      if (d(i) == 0) {
        visit(i, 0)
        while(que.nonEmpty) {
          val (cost, v) = que.dequeue()
          if (d(v) == 0) {
            d(v) = cost
            visit(v, cost)
          }
        }
      }
    }

    def visit(v: Int, cost0: Int): Unit = {
      if (E(v) != null) {
        E(v) foreach { case (u, cost) =>
          que.enqueue((cost0 + cost, u))
        }
      }
    }

    var valid = true
    for {
      v <- 0 until N
      j <- Option(E(v)) map (_.indices) getOrElse Seq.empty
    } {
      val (u, cost) = E(v)(j)
      valid &= d(v) + cost == d(u)
    }

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

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

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

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

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

  class UnionFind(n: Int) {
    private val par = Array.iterate(0, n)(_ + 1)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      if (par(x) == x) x
      else {
        par(x) = find(par(x))
        par(x)
      }
    }

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

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


object Main extends App {
  val n = io.StdIn.readLine.toInt
  val arr = Iterator.continually(io.StdIn.readLine.split(" "))
    .take(n)
    .toArray
  val ans = (Array(Array("0","0","0")).toBuffer++arr)
    .zip(arr)
    .forall{case (cur, nex) => {
      val dt =nex(0).toInt - cur(0).toInt
      val dist = (nex(1).toInt - cur(1).toInt).abs +
                 (nex(2).toInt - cur(2).toInt).abs
      dt >= dist && (dist&1) == (dt&1)
    }}

  println(if(ans) "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 n = io.StdIn.readLine.toInt
  val ans = Iterator.continually(io.StdIn.readLine.split(" "))
    .take(n)
    .map(in => {
      val c = in(0).toInt - in(1).toInt - in(2).toInt
      if (c < 0 || (c & 1) == 1) false else true
    })
    .forall(_ == true)
//    .takeWhile(_ == true)
//    .size

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


object Main extends App {
  val n = io.StdIn.readLine.toInt
  val ans = Iterator.continually(io.StdIn.readLine)
      .take(n)
      .map(_.split(" ").map(_.toInt))
      .map(in => {
        val Array(t, x, y) = in
        if (x + y > t) "No"
        else if (((t % (x + y)) & 1) == 1) "No"
        else "Yes"
      })
      .toArray

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


import scala.util.control.Breaks._
import scala.math.abs

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

    var possible = true
    breakable { for (i <- 0 until n) {
      val List(t0, x0, y0) = txys(i)
      val List(t1, x1, y1) = txys(i + 1)
      val res = t1 - t0 - (abs(x1 - x0) + abs(y1 - y0))
      if (res < 0 || res%2 != 0) {
        possible = false
        break
      }
    } }
    println(if (possible) "Yes" else "No")
  }
}


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): Boolean = {
    if (t == 0) (x == 0)
    else if(x == 0) (t & 1) == 0
    else if (x < 0 || x > t) false
    else (f(t - 1, x - 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) => f(t, x)}) "Yes" else "No")
}


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
  }
  val cache = collection.mutable.HashMap[(Int, Int, Int), Boolean]()
  def f(t: Int, x: Int, y: Int): Boolean = {
   val absX = Math.abs(x)
    val absY = Math.abs(y)
    if (t == 0) (x == 0 && y == 0)
    else if (absX > t || absY > t || absX + absY > 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), x2(1) - x1(1), x2(2) - x1(2))}
  print(if(list2.forall{case (t, x, y) => cache.getOrElseUpdate((t, x, y), f(t, x, y))}) "Yes" else "No")
}


object Main extends App {
  val n = io.StdIn.readLine().toInt
  val list: collection.mutable.ListBuffer[Array[Int]] = 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 (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)
 // list.foldLeft(Array(0,0,0)){(acc, x)}
  val list2 = list.zip(list.tail).map{case (x1, x2) => (x2(0)-x1(0), x2(1)-x1(1), x2(2)-x1(2))}
  print(if(list2.forall{case (t, x, y) => f(t, x, y)}) "Yes" else "No")
}


import java.util.Scanner

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

    for (i <- 1 to inum) {
      var num, numx, numy = sc.nextInt
      if (num <= (numx + numy) && !flag) {
        if (num % 2 == 0 && (numx + numy) % 2 == 0) flag=true else flag=false
        if (num % 2 == 1 && (numx + numy) % 2 == 1) flag=true else flag=false
      }
    }

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


object Main extends App {
  val Array(n, k) = io.StdIn.readLine().split(' ').map(_.toInt)
  type Record = (Int, Int, Boolean)
  val list = collection.mutable.ListBuffer[Record]()
  (1 to n).foreach { i =>
    val temp = io.StdIn.readLine().split(' ')
    list += ((temp(0).toInt % (k * 2) , temp(1).toInt % (k * 2), temp(2) == "W"))
  }
  def shift(x: Int): Int = if(x == (k * 2)) 0 else x + 1
  def shift(x: Record): Record = (shift(x._1), shift(x._2), x._3)
  def count(xs: Seq[Record]): Int = xs.count {
    case (x, y, bool) => ( (x < k && y < k) || (x >= k && y >= k) == bool )
  }

  var max = 0
  var shiftList = list

  (0 to k).foreach { i =>
    val cnt = count(shiftList)
    max = Math.max(Math.max(cnt, n - cnt), max)
    shiftList = shiftList.map(shift)
  }
  print(max)

}

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


import java.util.Scanner

import scala.annotation.tailrec

object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val es = Element(0, Position(0, 0)) +: Seq.fill(N)(Element(sc.nextInt, Position(sc.nextInt, sc.nextInt)))

  println(if (solve(es)) "Yes" else "No")

  @tailrec
  private[this] def solve(es: Seq[Element]): Boolean = es match {
    case h +: n +: rest =>
      h.validNext(n) || solve(n +: rest)
    case _ => true
  }
}

case class Element(t: Int, p: Position) {
  def validNext(destination: Element): Boolean = {
    val distance = p.distance(destination.p)
    val dt = destination.t - t
    if (distance > dt) false
    else if (dt - distance % 2 == 0) true
    else false
  }
}

case class Position(x: Int, y: Int) {
  def distance(that: Position): Int =
    Math.abs(that.x - x) + Math.abs(that.y - y)
}


object Main {
  def main(args: Array[String]): Unit = {
    var prev_place = Array(0, 0, 0)
    val n = io.StdIn.readLine().toInt

    var result = true
    var i = 0
    while (i < n && result == true) {
      val place = io.StdIn.readLine().split(' ').map({ _.toInt })
      val time = place(0) - prev_place(0)
      val move = place.zip(prev_place).map({ case (x, y) => x-y }).drop(1)

      if (move.sum > time)
        result = false

      if ((time + move.sum) % 2 == 1)
        result = false

      prev_place = place
      i += 1
    }

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


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)
  val max = (for {
    i <- 0 to k-1
    j <- 0 to k-1
  } yield {
    // 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))
    Math.max(cnt, n - cnt)
  }).max
  print(max)
}


import scala.io.StdIn._

object Main extends App {
  val Array(n, a, b) = readLine().split(" ").map(_.toInt)
  if (math.abs(b - a) % 2 == 1) println("Borys") else println("Alice")
}

Score : 300 points

Problem Statement

A game is played on a strip consisting of N cells consecutively numbered from 1 to N.

Alice has her token on cell A. Borys has his token on a different cell B.

Players take turns, Alice moves first.
The moving player must shift his or her token from its current cell X to the neighboring cell on the left, cell X-1, or on the right, cell X+1.
Note that it's disallowed to move the token outside the strip or to the cell with the other player's token.
In one turn, the token of the moving player must be shifted exactly once.

The player who can't make a move loses, and the other player wins.

Both players want to win. Who wins if they play optimally?

Constraints

2 \leq N \leq 100

1 \leq A < B \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print Alice if Alice wins, Borys if Borys wins, and Draw if nobody wins.

Sample Input 1

5 2 4

Sample Output 1

Alice

Alice can move her token to cell 3.
After that, Borys will be unable to move his token to cell 3, so he will have to move his token to cell 5.
Then, Alice moves her token to cell 4. Borys can't make a move and loses.

Sample Input 2

2 1 2

Sample Output 2

Borys

Alice can't make the very first move and loses.

Sample Input 3

58 23 42

Sample Output 3

Borys


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

	var N = List[Long](2L)

	def test(x: Long, y: List[Long]): List[Long] = {
		var list = y
		for(i<-1L until x){
			list = list ::: y.map(_ + i)
		}
		list
	}

	for(i<-0 until temp){
		N = N.filter(_ >= A(i)).filter(_%A(i) == 0)
		N = test(A(i), N)
	}

	if(N == Nil) println(-1)
	else println(s"${N.min} ${N.max}")
}

Score : 500 points

Problem Statement

An adult game master and N children are playing a game on an ice rink.
The game consists of K rounds.
In the i-th round, the game master announces:

Form groups consisting of A_i children each!

Then the children who are still in the game form as many groups of A_i children as possible.
One child may belong to at most one group.
Those who are left without a group leave the game. The others proceed to the next round.
Note that it's possible that nobody leaves the game in some round.

In the end, after the K-th round, there are exactly two children left, and they are declared the winners.

You have heard the values of A_1, A_2, ..., A_K. You don't know N, but you want to estimate it.

Find the smallest and the largest possible number of children in the game before the start, or determine that no valid values of N exist.

Constraints

1 \leq K \leq 10^5

2 \leq A_i \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

K
A_1 A_2 ... A_K

Output

Print two integers representing the smallest and the largest possible value of N, respectively,
or a single integer -1 if the described situation is impossible.

Sample Input 1

4
3 4 3 2

Sample Output 1

6 8

For example, if the game starts with 6 children, then it proceeds as follows:

In the first round, 6 children form 2 groups of 3 children, and nobody leaves the game.

In the second round, 6 children form 1 group of 4 children, and 2 children leave the game.

In the third round, 4 children form 1 group of 3 children, and 1 child leaves the game.

In the fourth round, 3 children form 1 group of 2 children, and 1 child leaves the game.

The last 2 children are declared the winners.

Sample Input 2

5
3 4 100 3 2

Sample Output 2

-1

This situation is impossible.
In particular, if the game starts with less than 100 children, everyone leaves after the third round.

Sample Input 3

10
2 2 2 2 2 2 2 2 2 2

Sample Output 3

2 3


import scala.io.StdIn._

object Main extends App {
  val n = readInt()
  val d = List.fill(n)(readInt()).sorted.toSet
  println(d.size)
}

Score : 200 points

Problem Statement

An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have a 3-layered kagami mochi; if you put just one mochi, you have a 1-layered kagami mochi.

Lunlun the dachshund has N round mochi, and the diameter of the i-th mochi is d_i centimeters. When we make a kagami mochi using some or all of them, at most how many layers can our kagami mochi have?

Constraints

1 ≤ N ≤ 100

1 ≤ d_i ≤ 100

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
d_1
:
d_N

Output

Print the maximum number of layers in a kagami mochi that can be made.

Sample Input 1

4
10
8
8
6

Sample Output 1

3

If we stack the mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, we have a 3-layered kagami mochi, which is the maximum number of layers.

Sample Input 2

3
15
15
15

Sample Output 2

1

When all the mochi have the same diameter, we can only have a 1-layered kagami mochi.

Sample Input 3

7
50
30
50
100
50
80
30

Sample Output 3

4