object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val K, X = ni()
    out.println(map(K * 2 - 1, X - K + 1)(identity).mkString(" "))
  }
}

Score : 200 points

Problem Statement

There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000.

Among them, some K consecutive stones are painted black, and the others are painted white.

Additionally, we know that the stone at coordinate X is painted black.

Print all coordinates that potentially contain a stone painted black, in ascending order.

Constraints

1 \leq K \leq 100

0 \leq X \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K X

Output

Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate 7 is painted black. There are three possible cases:

The three stones painted black are placed at coordinates 5, 6, and 7.

The three stones painted black are placed at coordinates 6, 7, and 8.

The three stones painted black are placed at coordinates 7, 8, and 9.

Thus, five coordinates potentially contain a stone painted black: 5, 6, 7, 8, and 9.

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val groupCounts = Seq.fill(sc.nextInt())(sc.next()).map(_.sorted).groupBy(identity).mapValues(_.size.toLong).values
  println(groupCounts.foldLeft(0L)((acc, i) => acc + i * (i - 1L) / 2L))
}

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

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.

Submitted source-code file size, in bytes.

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

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


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val groupCounts = Seq.fill(sc.nextInt())(sc.next()).map(_.sorted).groupBy(identity).values.map(_.size)
  println(groupCounts.foldLeft(0L)((acc, i) => acc + i * (i - 1) / 2))
}


object Main extends App {
  var n = readInt
  var ss = Range(0,n).map(t=>readLine.split("").sorted.mkString(""))
  val words = collection.mutable.Map[String,Int]()
  ss.foreach{s=>
    words += s -> (words.getOrElse(s,0)+1)
  }
  println(words.values.foldLeft(0l)((a,x)=>a+x*(x-1)/2))
}


object Main extends App {
  var a = readInt
  var b = Array.tabulate(a)(i => (readLine).sorted)
  var sum = 0L
  for(i <- 0 until a - 1;j <- i+1 until a) {
    if(b(i) == b(j)) {
      sum = sum + 1
    }
  }
  print(sum)
}


import scala.collection.mutable.PriorityQueue

case class fuckingJob(days : Int , money : Int)

object Main extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt() //job
  val m = sc.nextInt() //day
  var mwhile = m - 1
  val ab : PriorityQueue[fuckingJob] = PriorityQueue()(Ordering.by(_.money))
  var ans = 0

  for (i <- 0 until n) {
    val a = sc.nextInt()
    val b = sc.nextInt()
    ab.enqueue(fuckingJob(a,b))
  }

  while(mwhile >= 0 && ab.nonEmpty){
    val wara  = ab.dequeue()
    if(wara.days <= mwhile+1){
      ans += wara.money
      mwhile = mwhile - 1
    }

  }

  println(ans)
}

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


object Main{

def main(args: Array[String]): Unit = {
  val arr1 = io.StdIn.readLine().split(' ')
  val a = arr1(0).toInt
  val b = arr1(1).toInt
  val c = arr1(2).toInt

  if (a - b >= c) println(0) else println(c - (a - b) )
}
}

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


import scala.io.StdIn._
object Main extends App {
  val Array(a, b) = readLine.split(" ").map(_.toInt)
  println(if ((a + b) % 2 == 1) "IMPOSSIBLE" else (a + b) / 2)
}

Score: 100 points

Problem Statement

We have two distinct integers A and B.

Print the integer K such that |A - K| = |B - K|.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

0 \leq A,\ B \leq 10^9

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


import java.util.Scanner

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

    var ans = 0

    val enemies = new Array[Int](n + 1)
    for (i <- enemies.indices) {
      enemies(i) = sc.nextInt()
    }

    val hero = new Array[Int](n)
    for (i <- hero.indices) {
      hero(i) = sc.nextInt()

    }

    for (i <- hero.indices) {
      if (hero(i) <= enemies(i)) {
        ans += hero(i)
      } else {
        hero(i) -= enemies(i)
        ans += enemies(i) + math.min(enemies(i + 1), hero(i))
      }
    }

    println(ans)
  }

  def printArray[T](arr: Array[T]): Unit = {
    for (i <- arr.indices) {
      print(s"${arr(i)} ")
    }
    println()
  }
}

Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


import scala.io.StdIn._
object Main extends App {
  val Mod = 1000000007
  val s = readLine

  def dp(rems: Array[Long], digit: Char): Array[Long] = {
    val ret = new Array[Long](13)
    val is = if (digit == '?') (0 to 9) else Seq((digit - '0').toInt)
    for {
      i <- is
      j <- (0 to 12)
    } {
      ret((j * 10 + i) % 13) += rems(j)
      ret((j * 10 + i) % 13) %= Mod
    }
    ret
  }

  val init = s.head match {
    case '?' => Array.tabulate(13)(i => if (i < 10) 1L else 0L)
    case c => Array.tabulate(13)(i => if (i == c - '0') 1L else 0L)
  }

  val result = s.tail.foldLeft(init){(z, d) => dp(z, d)}
  println(result(5))
}

Score : 400 points

Problem Statement

Given is a string S. Each character in S is either a digit (0, ..., 9) or ?.

Among the integers obtained by replacing each occurrence of ? with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.

Since the answer can be enormous, print the count modulo 10^9+7.

Constraints

S is a string consisting of digits (0, ..., 9) and ?.

1 \leq |S| \leq 10^5

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of integers satisfying the condition, modulo 10^9+7.

Sample Input 1

??2??5

Sample Output 1

768

For example, 482305, 002865, and 972665 satisfy the condition.

Sample Input 2

?44

Sample Output 2

1

Only 044 satisfies the condition.

Sample Input 3

7?4

Sample Output 3

0

We may not be able to produce an integer satisfying the condition.

Sample Input 4

?6?42???8??2??06243????9??3???7258??5??7???????774????4?1??17???9?5?70???76???

Sample Output 4

153716888


object Main extends App {

  val r = scala.io.StdIn.readInt()

  def solve(): Int = {
    3 * r * r
  }

  println(solve)

}

Score : 100 points

Problem Statement

It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2.

Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r.

Constraints

1 \leq r \leq 100

r is an integer.

Input

Input is given from Standard Input in the following format:

r

Output

Print an integer representing the area of the regular dodecagon.

Sample Input 1

4

Sample Output 1

48

The area of the regular dodecagon is 3 \times 4^2 = 48.

Sample Input 2

15

Sample Output 2

675

Sample Input 3

80

Sample Output 3

19200


import scala.io.StdIn
object Main extends App {
  val r = StdIn.readLine().toInt
  println(r * r * 3)
}


import java.util.Scanner

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

  val r = sc.nextInt()

  println(3 * r * r)
}


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

    println(Math.ceil(n / ((d * 2) + 1)).toInt)
  }
}

Score : 200 points

Problem Statement

There are N apple trees in a row. People say that one of them will bear golden apples.

We want to deploy some number of inspectors so that each of these trees will be inspected.

Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector deployed under the i-th tree (1 \leq i \leq N) will inspect the trees with numbers between i-D and i+D (inclusive).

Find the minimum number of inspectors that we need to deploy to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq D \leq 20

Input

Input is given from Standard Input in the following format:

N D

Output

Print the minimum number of inspectors that we need to deploy to achieve the objective.

Sample Input 1

6 2

Sample Output 1

2

We can achieve the objective by, for example, placing an inspector under Tree 3 and Tree 4.

Sample Input 2

14 3

Sample Output 2

2

Sample Input 3

20 4

Sample Output 3

3


import scala.io.StdIn

object Main {

  def main(args: Array[String]): Unit = {
    val Array(n, d) = StdIn.readLine().split(' ').map(_.toInt)
    val range = 2 * d + 1
    val remain = if (n % range == 0) 0 else 1
    val ans = n / range + remain
    println(ans)
  }

}


object Main extends App {
  val n = io.StdIn.readInt
  val as = for (_ <- 1 to n) yield io.StdIn.readInt

  for (count <- 0 until n) {
    val deleted = as.take(count) ++ as.drop(count).tail
    println(deleted.max)
  }
}

Score : 300 points

Problem Statement

You are given a sequence of length N: A_1, A_2, ..., A_N.
For each integer i between 1 and N (inclusive), answer the following question:

Find the maximum value among the N-1 elements other than A_i in the sequence.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 200000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print N lines. The i-th line (1 \leq i \leq N) should contain the maximum value among the N-1 elements other than A_i in the sequence.

Sample Input 1

3
1
4
3

Sample Output 1

4
3
4

The maximum value among the two elements other than A_1, that is, A_2 = 4 and A_3 = 3, is 4.

The maximum value among the two elements other than A_2, that is, A_1 = 1 and A_3 = 3, is 3.

The maximum value among the two elements other than A_3, that is, A_1 = 1 and A_2 = 4, is 4.

Sample Input 2

2
5
5

Sample Output 2

5
5


//import java.util.Scanner

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

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

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

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

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

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

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

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

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

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

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

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

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

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {
  def solve(sc: => Scanner): Unit = {
    val A = Array.fill(sc.nextInt())(sc.nextLong())
    val B = A.zipWithIndex.sortWith((a, b) => a._1 > b._1)
    A.indices.foreach(i => println(if (B.head._2 == i) B.drop(1).head._1 else B.head._1))
  }

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

  def calc(A: Array[Long]): Array[String] = {
    if (A.length == 0) Array.fill(0)("")
    else {
      val last = A.zipWithIndex.map(x => (x._1 - x._2, x._1)).takeWhile(x => x._1 == A.head).last._2
      if (last == A.head) "%d".format(A.head) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
      else "%d-%d".format(A.head, last) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
    }
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

  def recursive(xyz: Array[(Long, Long, Long)], M: Long): Long = {
    if (xyz.isEmpty) M else {
      val head = xyz.head
      if (head._1 == 0) {
        if (head._2 == M)
          recursive(xyz.tail, head._3)
        else if (head._3 == M)
          recursive(xyz.tail, head._2)
        else
          recursive(xyz.tail, M)
      } else {
        if (head._2 == M)
          recursive(xyz.tail, head._3)
        else
          recursive(xyz.tail, M)
      }
    }
  }

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

  def check(s: String): Boolean = {
    s.isEmpty ||
      s.startsWith("dream") && check(s.drop(5)) ||
      s.startsWith("dreamer") && check(s.drop(7)) ||
      s.startsWith("erase") && check(s.drop(5)) ||
      s.startsWith("eraser") && check(s.drop(6))
  }

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

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

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

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

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

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

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

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

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

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

object ArabicRoman {

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

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

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

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

      convert(src)
  }

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

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

      convert(src.toUpperCase())
  }
}


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

  val max = a.max
  for (i <- (0 to n - 1)) {
    if (a(i) == max) {
      val tmp = a.splitAt(i)
      println((tmp._1 ++ tmp._2.tail).max)
    } else {
      print(max)
    }
  }
}


object Main extends App {
  val n = io.StdIn.readInt
  val as = (1 to n).map{ _ => io.StdIn.readInt }
  (1 to n)
    .foreach(i => {
      val mx = as.zipWithIndex
        .filter { case (_, ix) => (ix + 1) != i }
        .map{ case (a, _) => a }
        .max
      println(mx)
    })
}


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

    if (A.distinct.length == 1) {
      A.foreach(println)
    } else {
      A.foreach(d => println(A.filter(_ != d).max))
    }
  }
}


import scala.io.StdIn._
object Main extends App {
  val n = readInt
  val as = 0 +: readLine.split(" ").map(_.toInt)
  val ans = new Array[Int](n + 1)

  (n to 1 by -1).foreach {i =>
    val cnt = (i * 2 to n by i).count(j => ans(j) == 1)
    ans(i) = (cnt & 1) ^ as(i)
  }
  val is = ans.zipWithIndex.collect{case (a, i) if a == 1 => i}
  println(is.size)
  println(is.mkString(" "))
}

Score : 400 points

Problem Statement

There are N empty boxes arranged in a row from left to right.
The integer i is written on the i-th box from the left (1 \leq i \leq N).

For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.

We say a set of choices to put a ball or not in the boxes is good when the following condition is satisfied:

For every integer i between 1 and N (inclusive), the total number of balls contained in the boxes with multiples of i written on them is congruent to a_i modulo 2.

Does there exist a good set of choices? If the answer is yes, find one good set of choices.

Constraints

All values in input are integers.

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

a_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If a good set of choices does not exist, print -1.

If a good set of choices exists, print one such set of choices in the following format:

M
b_1 b_2 ... b_M

where M denotes the number of boxes that will contain a ball, and b_1,\ b_2,\ ...,\ b_M are the integers written on these boxes, in any order.

Sample Input 1

3
1 0 0

Sample Output 1

1
1

Consider putting a ball only in the box with 1 written on it.

There are three boxes with multiples of 1 written on them: the boxes with 1, 2, and 3. The total number of balls contained in these boxes is 1.

There is only one box with a multiple of 2 written on it: the box with 2. The total number of balls contained in these boxes is 0.

There is only one box with a multiple of 3 written on it: the box with 3. The total number of balls contained in these boxes is 0.

Thus, the condition is satisfied, so this set of choices is good.

Sample Input 2

5
0 0 0 0 0

Sample Output 2

0

Putting nothing in the boxes can be a good set of choices.


object Main {

  def printArray(arr: Array[Int]): Unit =
    println(arr.mkString("\n"))

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

    // 1以上N以下の任意の整数iについて, iの倍数が書かれた箱に入っている
    // ボールの個数の和を2で割った余りがa_iである

    val N = sc.nextInt()
    val A = Array.fill(N)(sc.nextInt() match {
      case 1 => true
      case 0 => false
    })

    // 言い換えると, 1以上,N以下の任意のiについて
    // iの倍数の個数を2で割った余りがa_iであるかどうか
    val B = new Array[Boolean](N)
    var i = N
    while (i > 0) {
      var j = i + 1
      var s = false
      if (i <= N * 2)
        while (j <= N) {
          if (j % i == 0)
            s ^= A(j-1)
          j += 1
        }
      if (s != A(i-1))
        B(i-1) = true
      i -= 1
    }
    val boxes = B.zipWithIndex.filter(_._1)
    val M = boxes.length
    val results = boxes.map(_._2 + 1).mkString(" ")
    println(M)
    if (M != 0)
      println(results)
  }

}


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

  var data = Set.empty[Int]

  var cnt = n
  while (cnt >= 1) {
    val array_cnt = cnt - 1
    // 偶数 or 奇数
    val odd = data.count { a => a % cnt == 0 } % 2 == 0

    if (odd && a(array_cnt) == 0) {
      // 偶数 & 求めるのも偶数
      //何もしない
    } else if (odd && a(array_cnt) == 1) {
      // 偶数 & 求めるのは奇数
      data += cnt
    } else if (!odd && a(array_cnt) == 0) {
      // 奇数 & 求めるのは偶数
      data += cnt
    } else if (!odd && a(array_cnt) == 1) {
      // 奇数 & 求めるのは奇数
      // なにもしない
    }
    cnt -= 1
  }

  println(data.size)
  if(data.nonEmpty) {
    println(data.mkString(" "))
  }
}


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

    val sc = new java.util.Scanner(System.in)
    val N = sc.nextInt
    val I = List.fill(N)(sc.nextInt)
    sc.close()

    (0 until I.length - 2).forall(i => (I(i) ^ I(i + 1)) == I(i + 2)) match {
      case true => println("Yes")
      case _    => println("No")
    }
  }
}

Score : 300 points

Problem Statement

Snuke has N hats. The i-th hat has an integer a_i written on it.

There are N camels standing in a circle.
Snuke will put one of his hats on each of these camels.

If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print Yes; otherwise, print No.

The bitwise XOR of the numbers written on the hats on both adjacent camels is equal to the number on the hat on itself.

What is XOR?

The bitwise XOR x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows:

- When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3 \oplus 5 = 6.

Constraints

All values in input are integers.

3 \leq N \leq 10^{5}

0 \leq a_i \leq 10^{9}

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_{N}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

Yes

If we put the hats with 1, 2, and 3 in this order, clockwise, the condition will be satisfied for every camel, so the answer is Yes.

Sample Input 2

4
1 2 4 8

Sample Output 2

No

There is no such way to distribute the hats; the answer is No.


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  case class Edge(i: Int, a: Int, b: Int) {
    def oppo(v: Int) = if (a == v) b else a
  }
  case class Entry(v: Int, deg: Int) extends Comparable[Entry] {
    override def compareTo(o: Entry): Int = Integer.compare(deg, o.deg)
  }

  def solve2(): Boolean = {
    val N, M = ni()
    if (M % 2 == 1) return false

    val deg = Array.ofDim[Int](N)
    val E = Array.ofDim[Edge](M)
    val g = Array.fill[mutable.Set[Int]](N)(mutable.Set()) //edge番号
    REP(M) { i =>
      val a, b = ni() - 1
      E(i) = Edge(i, a, b)
      deg(a) += 1
      deg(b) += 1
      g(a) += i
      g(b) += i
    }

    val q = new java.util.PriorityQueue[Entry]
    def addEntry(v: Int): Unit = {
      if (deg(v) > 1) q.add(Entry(v, deg(v)))
    }

    debug(deg)

    REP(N) { i =>
      addEntry(i)
    }

    val ans = ArrayBuffer[(Int, Int)]()

    // v -> e1, v -> e2
    def outward2(v: Int, e1: Edge): Unit = {
      g(v).remove(e1.i)
      g(E(e1.i).oppo(v)).remove(e1.i)
      val e2 = E(g(v).head)
      g(v).remove(e2.i)
      g(E(e2.i).oppo(v)).remove(e2.i)

      debug(s"outward2($v) e1:$e1 e2:$e2")

      deg(v) -= 2
      deg(e1.oppo(v)) -= 1
      deg(e2.oppo(v)) -= 1

      addEntry(v)
      addEntry(e1.oppo(v))
      addEntry(e2.oppo(v))

      ans += v -> e1.oppo(v)
      ans += v -> e2.oppo(v)
    }

    // e1 -> v -> e2
//    def passOver(v: Int): Unit = {
//      val e1 = E(g(v).head)
//      g(v).remove(e1.i)
//      g(E(e1.i).oppo(v)).remove(e1.i)
//      val e2 = E(g(v).head)
//      g(v).remove(e2.i)
//      g(E(e2.i).oppo(v)).remove(e2.i)
//
//      debug(s"passOver($v) e1:$e1 e2:$e2")
//
//      deg(v) -= 2
//      deg(e1.oppo(v)) -= 1
//      deg(e2.oppo(v)) -= 1
//
//      addEntry(v)
//      addEntry(e1.oppo(v))
//      addEntry(e2.oppo(v))
//
//      ans += e1.oppo(v) -> v
//      ans += v -> e2.oppo(v)
//    }

    while(!q.isEmpty) {
      val e = q.poll()
      if (deg(e.v) == e.deg) {
        e.deg match {
//          case 1 =>
//            val edge = E(g(e.v).head)
//            val u = edge.oppo(e.v)
//            outward2(u, edge)

          case _ =>
            outward2(e.v, E(g(e.v).head))

//          case 3 =>
//            passOver(e.v)
        }
      }
    }

    assert(ans.length == M)
    REP(M) { i =>
      val e = ans(i)
      out.println(s"${e._1+1} ${e._2+1}")
    }

    true
  }

  def solve(): Unit = {
    if (!solve2()) out.println(-1)
  }
}

Score : 700 points

Problem Statement

You are given a simple connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge connects Vertex A_i and Vertex B_i.
Takahashi will assign one of the two possible directions to each of the edges in the graph to make a directed graph.
Determine if it is possible to make a directed graph with an even number of edges going out from every vertex. If the answer is yes, construct one such graph.

Notes

An undirected graph is said to be simple when it contains no self-loops or multiple edges.

Constraints

2 \leq N \leq 10^5

N-1 \leq M \leq 10^5

1 \leq A_i,B_i \leq N (1\leq i\leq M)

The given graph is simple and connected.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If it is impossible to assign directions to satisfy the requirement, print -1.
Otherwise, print an assignment of directions that satisfies the requirement, in the following format:

C_1 D_1
:
C_M D_M

Here each pair (C_i, D_i) means that there is an edge directed from Vertex C_i to Vertex D_i. The edges may be printed in any order.

Sample Input 1

4 4
1 2
2 3
3 4
4 1

Sample Output 1

1 2
1 4
3 2
3 4

After this assignment of directions, Vertex 1 and 3 will each have two outgoing edges, and Vertex 2 and 4 will each have zero outgoing edges.

Sample Input 2

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

Sample Output 2

-1


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

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

  val N = in.next().toInt

  var ans = List((1, 2), (2, 3), (N+3, 1), (N+2, N+3), (N+1, N+2))
  if (N <= 2)
    println("No")
  else {
    for (i <- 4 until N by 2) {
      ans = (i, 1) :: (i+1, i) :: (N+i+1, 1) :: (N+i, N+i+1) :: ans
    }

    var flag = false
    if (N % 2 == 0) {
      breakable {
        for (i <- 2 to N-1 if (i ^ (N+1)) < N) {
          ans = (i, N) :: (i ^ (N+1), N+N) :: ans
          flag = true
          break
        }
      }
    }
    else
      flag = true

    if(flag) {
      pw.println("Yes")
      ans.foreach { case (a, b) => pw.println(s"$a $b") }
    }
    else
      pw.println("No")

    pw.flush()
  }

}

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

Score : 700 points

Problem Statement

You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.

Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.

Constraints

N is an integer.

1 \leq N \leq 10^{5}

Input

Input is given from Standard Input in the following format:

N

Output

If there exists a tree satisfying the condition in the statement, print Yes; otherwise, print No.
Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:

a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}

Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.

Sample Input 1

3

Sample Output 1

Yes
1 2
2 3
3 4
4 5
5 6

The sample output represents the following graph:

Sample Input 2

1

Sample Output 2

No

There is no tree satisfying the condition.


import java.util.Scanner

object Main {

  def solve(sc: Scanner): String = {
    val (n, a, b) = (sc.nextInt(), sc.nextInt(), sc.nextInt())

    (if (n * a > b) b else n * a).toString
  }

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val writer = new java.io.PrintWriter(System.out)
    writer.println(solve(sc))
    writer.flush()
  }

  private def debug(x: Any): Unit = {
    if (System.getenv("LOCAL_DEBUG") != null) println(x)
  }
}

Score : 100 points

Problem Statement

N of us are going on a trip, by train or taxi.

The train will cost each of us A yen (the currency of Japan).

The taxi will cost us a total of B yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq A \leq 50

1 \leq B \leq 50

Input

Input is given from Standard Input in the following format:

N A B

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8


import scala.math._

object Main extends App {

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

  val sc = new java.util.Scanner(System.in)
    val n, a, b = sc.nextInt
//  val list = List.fill(3)(sc.nextInt)

  val ans = min(a * n, b)

  println(ans)

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

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

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

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

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

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

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


import java.util.Scanner

object Main {

  def read(): (Int, Int, IndexedSeq[IndexedSeq[Int]]) = {
    val sc = new Scanner(System.in)
    val n, d = sc.nextInt()
    val x: IndexedSeq[IndexedSeq[Int]] = IndexedSeq.fill(n, d)(sc.nextInt())
    (n, d, x)
  }

  def dist(y: IndexedSeq[Int], z: IndexedSeq[Int]): Double = {
    Math.sqrt((y,z).zipped.map((yi, zi) => Math.pow(yi - zi, 2)).sum)
  }

  def solve(n: Int, x: IndexedSeq[IndexedSeq[Int]]): Int = {
    (for {
      i <- 0 until n - 1
      j <- i + 1 until n
    } yield {
      val y = x(i)
      val z = x(j)
      val d = dist(y, z)
      d % 1 == 0
    }).count(identity)
  }

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

}

Score : 200 points

Problem Statement

There are N points in a D-dimensional space.

The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).

The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.

How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?

Constraints

All values in input are integers.

2 \leq N \leq 10

1 \leq D \leq 10

-20 \leq X_{ij} \leq 20

No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.

Input

Input is given from Standard Input in the following format:

N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}

Output

Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

The number of pairs with an integer distance is one, as follows:

The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.

The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.

The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.

Sample Input 2

3 4
-3 7 8 2
-12 1 10 2
-2 8 9 3

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10


import java.util.Scanner

object Main {

  def read() = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = IndexedSeq.fill(n)(sc.nextLong())
    (n, a)
  }

  def solve(n: Int, a: IndexedSeq[Long]): Long = {
    val as0 = IndexedSeq.concat(0 until n by 2, 1 until n by 2, 0 until n by 2, 1 until n by 2).map(a)
    val as1 = IndexedSeq.concat(1 until n by 2, 0 until n by 2, 1 until n by 2, 0 until n by 2).map(a)
    val cumAS0 = as0.scanLeft(0L)(_ + _)
    val cumAS1 = as1.scanLeft(0L)(_ + _)
    val sum = a.sum
    val y0 = IndexedSeq.tabulate(n / 2 + 1)(i =>
      sum/2 - (cumAS0(i + n / 2 + 1) - cumAS0(i + 1))
    )
    val y1 = IndexedSeq.tabulate(n / 2)(i =>
      sum/2 - (cumAS1(i + n / 2 + 1) - cumAS1(i + 1))
    )
    print(y0((n-1)/2) * 2)
    print(" ")
    for(i<- 0 until n-1){
      if(i %2 == 0){
        print(y0(i/2)*2)
      } else{
        print(y1(i/2)*2)
      }
      print(" ")
    }
    println()
    0
  }

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

Score : 400 points

Problem Statement

There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.

Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).

When Mountain i (1 \leq i \leq N) receives 2x liters of rain, Dam i-1 and Dam i each accumulates x liters of water (Dam 0 is Dam N).

One day, each of the mountains received a non-negative even number of liters of rain.

As a result, Dam i (1 \leq i \leq N) accumulated a total of A_i liters of water.

Find the amount of rain each of the mountains received. We can prove that the solution is unique under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 10^5-1

N is an odd number.

0 \leq A_i \leq 10^9

The situation represented by input can occur when each of the mountains receives a non-negative even number of liters of rain.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N integers representing the number of liters of rain Mountain 1, Mountain 2, ..., Mountain N received, in this order.

Sample Input 1

3
2 2 4

Sample Output 1

4 0 4

If we assume Mountain 1, 2, and 3 received 4, 0, and 4 liters of rain, respectively, it is consistent with this input, as follows:

Dam 1 should have accumulated \frac{4}{2} + \frac{0}{2} = 2 liters of water.

Dam 2 should have accumulated \frac{0}{2} + \frac{4}{2} = 2 liters of water.

Dam 3 should have accumulated \frac{4}{2} + \frac{4}{2} = 4 liters of water.

Sample Input 2

5
3 8 7 5 5

Sample Output 2

2 4 12 2 8

Sample Input 3

3
1000000000 1000000000 0

Sample Output 3

0 2000000000 0


object Main {
	def main(args: Array[String]): Unit = {
		val len = io.StdIn.readInt()
		val numsAsStr = io.StdIn.readLine().split(" ")
		val numsAry = new Array[Int](len)

		for (str <- numsAsStr) {
			numsAry(numsAsStr.indexOf(str)) = str.toInt
		}

		var count = 0

		for (num <- 0 until len - 2) {
			if (returnBoolean(Array(numsAry(num), numsAry(num + 1), numsAry(num + 2)))) count += 1
		}

		println(count)
	}

	def returnBoolean(array: Array[Int]): Boolean = {
		array(1) == array.sortWith((x: Int, y: Int) => x < y)(1)
	}
}

Score : 100 points

Problem Statement

You are given a 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.

Constraints

The length of S is 4.

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.

Sample Input 1

ASSA

Sample Output 1

Yes

S consists of A and S which both appear twice in S.

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No


object Main {
  def main(args:Array[String]) = {
    /* 文字列を読み込み、空白で分割して配列にし、Int型にする */
    val in = readLine.split("")
    val retn = if( 2 == in.filter(_  == in(0)).size == in.filter(_  == in(1)).size == in.filter(_  == in(2)).size ){
      "Yes"
    } else{
      "No"
    }
    println (retn)
  }
}


import scala.io.StdIn

object Main extends App {

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


import scala.io.StdIn._
object Main extends App {
  val n = readInt
  val ds = readLine.split(" ").map(_.toInt)
  println(ds.sliding(3).count{case Array(l, m, r) => (l - m) * (r - m) < 0})
}

Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

p is a permutation of {1,\ 2,\ ...,\ n}.

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

Print the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


object Main extends App {
  var get = readInt
  var list = readLine.split(" ")
  var sum = 0
  var i = 0
  while(i < get-2){
    var count = List(list(i),list(i+1),list(i+2)).sorted
    if(list(i+1)==count(1)){
      if(count(0)!=count(1)&&count(1)!=count(2)){
        sum = sum + 1
      }
    }
    i= i + 1
  }
  println(sum)
}


import scala.math._

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

  val ans = p.foldLeft((0, (None, None, None)): (Int, (Option[Int], Option[Int], Option[Int])))((acc, v) => {
      val current = (acc._2._2, acc._2._3, Some(v))
      current match {
        case (Some(v1), Some(v2), Some(v3)) =>
          if ((v1 < v2 && v2 < v3) || (v3 < v2 && v2 < v1)) (acc._1 + 1, current)
          else (acc._1, current)
        case _ =>
          (0, current)
      }
    }
  )._1

  println(ans)

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

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

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

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

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

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


object Main {

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

    val n = sc.nextInt()
    val p = Array.fill(n)(sc.nextInt())
    val count = p.sliding(3, 1).count { case Array(a, b, c) =>
      if ((b >= a && b < c) || (b >= c && b < a)) true
      else false
    }
    println(count)
  }

}


object Main {

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

    val N, K = sc.nextInt()

    // K個の青いボールを回収するために高橋君がちょうどi回操作をする必要がある時
    // 青いボールの置き方と赤いボールの置き方は独立して考えられる
    // N - K個の赤いボールを一列に並べて, N - K + 1個の隙間のどこに青いボールをK個置くかを考える
    // すると, N - K + 1個の隙間から i 個選ぶ選び方は {N-K+1}_C_i 通り
    // その隙間を選んだ後に,　各隙間に何個ボールを入れるかを考えるので
    // K 個のボールの隙間 K - 1 個の中から i - 1 個選ぶのは
    // {K-1}_C_{i-1} 通りあるので, それぞれの掛け合わせで
    // {N-K+1}_C_i * {K-1}_C_{i-1} となる

    def solve(N: Int, K: Int): IndexedSeq[BigInt] = {
      val MAX: Long = Math.pow(10, 9).toLong + 7
      val nCr = Array.fill(N+1, K+1)(BigInt(0L))
      (0 to K).foreach(i => nCr(i)(i) = 1L)
      (0 to N).foreach(i => {nCr(i)(0) = 1L; nCr(i)(1) = i})
      def combinations(n: Int, r: Int): BigInt = {
        if (n >= 0 && r >= 0) {
          if (nCr(n)(r) > 0) nCr(n)(r)
          else {
            nCr(n)(r) = combinations(n-1, r-1) + combinations(n-1, r)
            nCr(n)(r)
          }
        } else 0
      }
      combinations(N, K)
      for {
        i <- 1 to K
      } yield (nCr(N-K+1)(i) * nCr(K-1)(i-1)) % MAX
    }

    println(solve(N, K).mkString("\n"))
  }

}

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

Be sure to print the numbers of arrangements modulo 10^9+7.


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

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

  val N, M = in.next().toInt
  val graph = Array.fill[List[Int]](N+1)(Nil)
  for (_ <- 1 to M) {
    val u, v = in.next().toInt
    graph(u) = v :: graph(u)
  }
  val S, T = in.next().toInt

  //
  val q = new Queue[(Int, Int)]() // (moveNum, node)
  val dp = new Array[Boolean](N+1)

  q.enqueue((0, S))

  var ans = -1
  breakable {
    while (!q.isEmpty) {
      val (cost, now) = q.dequeue

      if (now == T) {
        ans = cost
        break
      }

      dp(now) = true
      var set = Set[Int]()
      set += now

      for (i <- 0 to 3) {
        val nextSet = Set[Int]()
        for (e <- set) {
          if (i == 3 || i == 1) {
            if (!dp(e)) {
              q.enqueue((cost+1, e))
              dp(e) = true
            }
          }

          if (i < 3) {
            for (e2 <- graph(e))
              nextSet += e2
          }
        }

        set = nextSet
      }
    }
  }

  println(ans)

}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.deep))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] 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

Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.

First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.

Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq \min(10^5, N (N-1))

1 \leq u_i, v_i \leq N(1 \leq i \leq M)

u_i \neq v_i (1 \leq i \leq M)

If i \neq j, (u_i, v_i) \neq (u_j, v_j).

1 \leq S, T \leq N

S \neq T

Input

Input is given from Standard Input in the following format:

N M
u_1 v_1
:
u_M v_M
S T

Output

If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1.
If he can, print the minimum number of ken-ken-pa needed to reach vertex T.

Sample Input 1

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

Sample Output 1

2

Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

Sample Input 2

3 3
1 2
2 3
3 1
1 2

Sample Output 2

-1

Any number of ken-ken-pa will bring Ken back to Vertex 1, so he cannot reach Vertex 2, though he can pass through it in the middle of a ken-ken-pa.

Sample Input 3

2 0
1 2

Sample Output 3

-1

Vertex S and Vertex T may be disconnected.

Sample Input 4

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

Sample Output 4

2


//import java.util.Scanner

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

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

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

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

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

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

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

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

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

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

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

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

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

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {
  def solve(sc: => Scanner): Unit = {
    val N, M = sc.nextInt()
    val B = Array.fill(N * 3)(Long.MaxValue / 6)
    val A = Array.fill(N * 3)(Array.fill(0)(0))
    Array.fill(M)(((sc.nextInt() - 1) * 3, (sc.nextInt() - 1) * 3))
      .foreach(x => {
        A(x._1) :+= x._2 + 1
        A(x._1 + 1) :+= x._2 + 2
        A(x._1 + 2) :+= x._2
      })
    val S, T = (sc.nextInt() - 1) * 3
    B(S) = 0
    val que = new mutable.PriorityQueue[(Int, Int)]()
    que.enqueue((0, S))

    while (que.nonEmpty) {
      val now = que.dequeue()
      if (now._1 == B(now._2)) {
        for (nextPoint <- A(now._2)) {
          if (B(nextPoint) > now._1 + 1) {
            B(nextPoint) = now._1 + 1
            que.enqueue((now._1 + 1, nextPoint))
          }
        }
      }
    }
    println(if (B(T + 2) == Long.MaxValue / 6) -1 else B(T + 2))
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

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

  def calc(A: Array[Long]): Array[String] = {
    if (A.length == 0) Array.fill(0)("")
    else {
      val last = A.zipWithIndex.map(x => (x._1 - x._2, x._1)).takeWhile(x => x._1 == A.head).last._2
      if (last == A.head) "%d".format(A.head) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
      else "%d-%d".format(A.head, last) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
    }
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

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

  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  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
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

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

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

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

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

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

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

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

object ArabicRoman {

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

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

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

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

      convert(src)
  }

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

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

      convert(src.toUpperCase())
  }
}


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) extends Runnable {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  override def run(): Unit = {
    val N, M = ni()
    val (to, from) = na2(M, -1) // 方向が逆
    val g = packDGraph(N, from, to)
    val S, T = ni() - 1

    val INF = 1e9.toInt
    val INF2 = 2e9.toInt + 10
    val dp = Array.fill[Int](N, 3)(INF2)
    val visit = Array.ofDim[Boolean](N, 3)
    dp(S)(0) = 0
    def dfs(v: Int, m: Int): Int = {
      if (visit(v)(m)) INF
      else {
        if (dp(v)(m) == INF2) {
          visit(v)(m) = true
          var res = INF
          REP(g(v).length) { i =>
            val u = g(v)(i)
            val add = if (m == 1) 1 else 0
            res = min(res, dfs(u, (3 + m - 1) % 3) + add)
          }
          dp(v)(m) = res
          visit(v)(m) = false
        }
        dp(v)(m)
      }
    }

    REP(3) { i =>
      dfs(T, 0)
    }

    val ans = if (dp(T)(0) == INF) -1 else dp(T)(0)
    out.println(ans)
  }

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

  def solve(): Unit = {
    val th = new Thread(null, this, "solve", 1 << 26)
    th.start()
    th.join()
  }
}


import scala.io.{StdIn => in}

object Main extends App {
  val s = in.readLine.toCharArray
  val ans = if(s(0) != s(1) && s(1) != s(2) && s(2) != s(3)) "Goog" else "Bad"
  println(ans)
}

Score : 100 points

Problem Statement

The door of Snuke's laboratory is locked with a security code.

The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.

Constraints

S is a 4-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

S

Output

If S is hard to enter, print Bad; otherwise, print Good.

Sample Input 1

3776

Sample Output 1

Bad

The second and third digits are the same, so 3776 is hard to enter.

Sample Input 2

8080

Sample Output 2

Good

There are no two consecutive digits that are the same, so 8080 is not hard to enter.

Sample Input 3

1333

Sample Output 3

Bad

Sample Input 4

0024

Sample Output 4

Bad


import java.util.Scanner

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

  def solve(input: String): String = {
    val s: Scanner = new Scanner(input)
    val n,x = s.nextInt
    List.fill(n)(s.nextInt).scan(0)(_ + _).count(_ <= x).toString
  }

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

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

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


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

  def count(position: Int, times: Int): Int =
    if (position <= x && times <= n)
      count(position + in.nextInt, times + 1)
    else
      times - 1

  val answer = count(0, 1)

  println(answer)
}


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 MOD = 1e9.toLong + 7
  val N, M = in.next().toInt
  val S = new Array[Int](N+1)
  val T = new Array[Int](M+1)
  for (i <- 1 to N)
    S(i) = in.next().toInt
  for (i <- 1 to M)
    T(i) = in.next().toInt

  //
  val imos = Array.ofDim[Long](N+1, M+1)
  val dp = Array.ofDim[Long](N+1, M+1)
  for (n <- 1 to N) {
    for (m <- 1 to M) {
      if (S(n) == T(m)) {
        dp(n)(m) = imos(n-1)(m-1) + 1
        dp(n)(m) %= MOD
      }

      imos(n)(m) = imos(n-1)(m) + imos(n)(m-1) - imos(n-1)(m-1)
      if (imos(n)(m) < 0)
        imos(n)(m) += MOD
      imos(n)(m) %= MOD
      imos(n)(m) += dp(n)(m)
      imos(n)(m) %= MOD
    }
  }

  var ans = 0L
  for (n <- 1 to N)
    for (m <- 1 to M) {
      ans += dp(n)(m)
      ans %= MOD
    }

  println((ans + 1) % MOD)
}

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

You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).

In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?

Here the subsequence of A is a sequence obtained by removing zero or more elements from A and concatenating the remaining elements without changing the order.

For both S and T, we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Since the answer can be tremendous, print the number modulo 10^9+7.

Constraints

1 \leq N, M \leq 2 \times 10^3

The length of S is N.

The length of T is M.

1 \leq S_i, T_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
S_1 S_2 ... S_{N-1} S_{N}
T_1 T_2 ... T_{M-1} T_{M}

Output

Print the number of pairs of a subsequence of S and a subsequence of T such that the subsequences are the same in content, modulo 10^9+7.

Sample Input 1

2 2
1 3
3 1

Sample Output 1

3

S has four subsequences: (), (1), (3), (1, 3).

T has four subsequences: (), (3), (1), (3, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 1 \times 1 pair of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (3), for a total of three pairs.

Sample Input 2

2 2
1 1
1 1

Sample Output 2

6

S has four subsequences: (), (1), (1), (1, 1).

T has four subsequences: (), (1), (1), (1, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 2 \times 2 pairs of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (1,1), for a total of six pairs.
Note again that we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Sample Input 3

4 4
3 4 5 6
3 4 5 6

Sample Output 3

16

Sample Input 4

10 9
9 6 5 7 5 9 8 5 6 7
8 6 8 5 5 7 9 9 7

Sample Output 4

191

Sample Input 5

20 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Sample Output 5

846527861

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


import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn._
object Main extends App {
  val MAX = 200000000.0
  val MIN = -MAX
  val n = readInt()
  val coordinates = mutable.Map[Char, List[Coordinate]]().withDefaultValue(Nil)
  for (_ ← 0 until n) {
    val Array(x, y, d) = readLine.trim.split(' ')
    coordinates(d.head) ::= Coordinate(x.toDouble, y.toDouble)
  }
  val constMinX = List('U', 'D').flatMap(coordinates).minByOption(_.x).map(_.x).getOrElse(MAX)
  val constMaxX = List('U', 'D').flatMap(coordinates).maxByOption(_.x).map(_.x).getOrElse(MIN)
  val constMinY = List('L', 'R').flatMap(coordinates).minByOption(_.y).map(_.y).getOrElse(MAX)
  val constMaxY = List('L', 'R').flatMap(coordinates).maxByOption(_.y).map(_.y).getOrElse(MIN)
  val minUp = coordinates('U').minByOption(_.y).map(_.y).getOrElse(MAX)
  val maxUp = coordinates('U').maxByOption(_.y).map(_.y).getOrElse(MIN)
  val minDown = coordinates('D').minByOption(_.y).map(_.y).getOrElse(MAX)
  val maxDown = coordinates('D').maxByOption(_.y).map(_.y).getOrElse(MIN)
  val minRight = coordinates('R').minByOption(_.x).map(_.x).getOrElse(MAX)
  val maxRight = coordinates('R').maxByOption(_.x).map(_.x).getOrElse(MIN)
  val minLeft = coordinates('L').minByOption(_.x).map(_.x).getOrElse(MAX)
  val maxLeft = coordinates('L').maxByOption(_.x).map(_.x).getOrElse(MIN)

  val changeTime = List(0, constMinY - minUp, minDown - constMinY, constMinX - minRight, minLeft - constMinX, constMaxY - maxUp, maxDown - constMaxY, constMaxX - maxRight, maxLeft - constMaxX, (minDown - minUp) / 2, (maxDown - maxUp) / 2, (minLeft - minRight) / 2, (maxLeft - maxRight) / 2).filter(_ >= 0)

  println(
    "%.15f".format(changeTime.map{t ⇒
      val minX = List(constMinX, minRight + t, minLeft - t).min
      val maxX = List(constMaxX, maxRight + t, maxLeft - t).max
      val minY = List(constMinY, minUp + t, minDown - t).min
      val maxY = List(constMaxY, maxUp + t, maxDown - t).max
      (maxX - minX) * (maxY - minY)
    }.min)
  )

  implicit class Scope[T](val receiver: T) extends AnyVal {
    def let[A](@inline func: T ⇒ A): A = func(receiver)
    def tap(@inline func: T ⇒ Unit): T = {
      func(receiver)
      receiver
    }
  }
  implicit class Wrap[T](val receiver: List[T]) extends AnyVal {
    def minByOption[A: Ordering](@inline keySelector: T ⇒ A): Option[T] = {
      receiver match {
        case Nil ⇒ None
        case _ ⇒ Some(receiver.minBy(keySelector))
      }
    }
    def maxByOption[A: Ordering](@inline keySelector: T ⇒ A): Option[T] = {
      receiver match {
        case Nil ⇒ None
        case _ ⇒ Some(receiver.maxBy(keySelector))
      }
    }
  }
}
case class Coordinate(x: Double, y: Double)

Score : 600 points

Problem Statement

There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:

If d_i = R, the i-th point moves in the positive x direction;

If d_i = L, the i-th point moves in the negative x direction;

If d_i = U, the i-th point moves in the positive y direction;

If d_i = D, the i-th point moves in the negative y direction.

You can stop all the points at some moment of your choice after they start moving (including the moment they start moving).
Then, let x_{max} and x_{min} be the maximum and minimum among the x-coordinates of the N points, respectively. Similarly, let y_{max} and y_{min} be the maximum and minimum among the y-coordinates of the N points, respectively.

Find the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}) and print it.

Constraints

1 \leq N \leq 10^5

-10^8 \leq x_i,\ y_i \leq 10^8

x_i and y_i are integers.

d_i is R, L, U, or D.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1 d_1
x_2 y_2 d_2
.
.
.
x_N y_N d_N

Output

Print the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}).

The output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-9}.

Sample Input 1

2
0 3 D
3 0 L

Sample Output 1

0

After three seconds, the two points will meet at the origin. The value in question will be 0 at that moment.

Sample Input 2

5
-7 -10 U
7 -6 U
-8 7 D
-3 3 D
0 -6 R

Sample Output 2

97.5

The answer may not be an integer.

Sample Input 3

20
6 -10 R
-4 -9 U
9 6 D
-3 -2 R
0 7 D
4 5 D
10 -10 U
-1 -8 U
10 -6 D
8 -5 U
6 4 D
0 3 D
7 9 R
9 -4 R
3 10 D
1 9 U
1 -6 U
9 -8 R
6 7 D
7 -3 D

Sample Output 3

273


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

case class Pos(x: Long, y: Long, dir: String) {

  // calc (x, y)
  def calc(t: Double): (Double, Double) = {
    dir match {
      case "R" => (x+t, y)
      case "L" => (x-t, y)
      case "U" => (x, y+t)
      case "D" => (x, y-t)
    }
  }
}

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

  val N = in.next().toInt
  val p = new Array[Pos](N+1)

  for (i <- 1 to N) {
    val x, y = in.next().toLong
    val d = in.next()

    p(i) = Pos(x, y, d)
  }

  //
  def check(n: Double): Double = {
    import Math.{max, min}

    var xmax = -2e8
    var ymax = -2e8
    var xmin = 2e8
    var ymin = 2e8

    for (i <- 1 to N) {
      val (x, y) = p(i).calc(n)

      xmax = max(xmax, x)
      ymax = max(ymax, y)
      xmin = min(xmin, x)
      ymin = min(ymin, y)
    }

    (xmax - xmin) * (ymax - ymin)
  }

  // 下に凸のグラフの最小値
  def ternarySearch(small: Double, big: Double): Double = {
    val END = 5e-3 // 5e-9
    val VOL = 1e-3 // 1e-9  // (END / 2) より小さい
    def func(small: Double, big: Double): Double = {
      val midl = (big + small) / 2
      val midr = midl + VOL
      if (big - small < END) big
      else {
        if (check(midl) >= check(midr))
          func(midl, big)
        else
          func(small, midr)
      }
    }
    func(small, big)
  }

  val time = ternarySearch(0, 1e9)
  val ans = check((time * 10).round / 10.0)

  println(ans)
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.deep))
  }
}

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


object Main {

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

    // p, q の重複の数が一番多い時、その重複の個数だけコスト0になる
    val N = sc.nextInt()
    val P: IndexedSeq[(Long, Long)] =
      (0 until N) map { i =>
        val x, y = sc.nextLong()
        (x, y)
      }

    val (_, cost0) = P.sliding(2).map { slide =>
      val bp = slide(0)
      val np = slide(1)
      val (bx, by) = bp
      val (nx, ny) = np
      (nx - bx, ny - by)
    }. toList. groupBy(identity). mapValues(_.size). maxBy(_._2)

    println(N - cost0)
  }

}

Score : 300 points

Problem Statement

There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).

We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:

Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1.

Find the minimum total cost required to collect all the balls when we optimally choose p and q.

Constraints

1 \leq N \leq 50

|x_i|, |y_i| \leq 10^9

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum total cost required to collect all the balls.

Sample Input 1

2
1 1
2 2

Sample Output 1

1

If we choose p = 1, q = 1, we can collect all the balls at a cost of 1 by collecting them in the order (1, 1), (2, 2).

Sample Input 2

3
1 4
4 6
7 8

Sample Output 2

1

If we choose p = -3, q = -2, we can collect all the balls at a cost of 1 by collecting them in the order (7, 8), (4, 6), (1, 4).

Sample Input 3

4
1 1
1 2
2 1
2 2

Sample Output 3

2


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

object Main extends App {
  import MapHelper._

  val n = in.readInt
  val pb = Iterator.continually(in.readLine)
    .take(n)
    .map(_.split(" ").map(_.toLong))
    .toArray

  val px = pb.sortWith((x, y) => {
      if(x(0) != y(0)) {
        x(0) > y(0)
      } else {
        x(1) > y(1)
      }
    })
  val py = pb.sortWith((x, y) => {
      if(x(1) != y(1)) {
        x(1) > y(1)
      } else {
        x(0) > y(0)
      }
    })
  val mapX = mu.HashMap.empty[(Long,Long),Long]
  val mapY = mu.HashMap.empty[(Long,Long),Long]

  for(i <- 0 until n-1) {
    val x = px(i)(0) - px(i+1)(0)
    val y = px(i)(1) - px(i+1)(1)
    mapX.addOrUpdate((x,y),1)
  }
  val mX = if(mapX.isEmpty) 0 else mapX.maxBy(m => m._2)._2
  // println(mX)
  for(i <- 0 until n-1) {
    val x = py(i)(0) - py(i+1)(0)
    val y = py(i)(1) - py(i+1)(1)
    mapY.addOrUpdate((x,y),1)
  }
  val mY = if(mapY.isEmpty) 0 else mapY.maxBy(m => m._2)._2
  // println(mY)

  val t = mX max mY

  val ans = n - t
  println(ans)

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


object Main{
	def main(args:Array[String]){
		val s = new java.util.Scanner(System.in)
		val a,b,c=s.nextInt
		println(math.min(a+b,math.min(b+c,c+a)))
	}
}

Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, m = sc.nextInt
    val stairs = Array.fill[Boolean](n + 1)(true)
    for (i <- 0 until m) {
      val a = sc.nextInt
      stairs(a) = false
    }

    val mod = 1000000007
    val dp = Array.fill[Int](n + 1)(0)
    dp(0) = 1
    for (i <- 0 to n) {
      for (j <- 1 to 2) {
        val next = i + j
        if (next <= n && stairs(next) == true) {
          dp(next) += dp(i)
          dp(next) = dp(next) % mod
        }
      }

    }
    println(dp(n))
  }
}

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


import java.util.Scanner

object MyMath {

  def mpow(m: Long)(b: Long, e: Long): Long = {
    def doMpow(r: Long, b: Long, e: Long): Long = {
      if (e == 0) r
      else {
        val r1 = if ((e & 1) == 1) (r * b) % m else r
        doMpow(r1, (b * b) % m, e >> 1)
      }
    }
    doMpow(1, b, e)
  }

  def mfact(m: Long)(n: Long, nend: Long = 1): Long = {
    def doMfact(n: Long, r: Long): Long = {
      if (n < nend) r
      else doMfact(n - 1, (r * n) % m)
    }
    doMfact(n, 1)
  }

  def mconb(m: Long)(n: Long, k: Long): Long = {
    def pow: (Long, Long) => Long = mpow(m)
    def fact: (Long, Long) => Long = mfact(m)

    (fact(n, n - k + 1) * pow(fact(k, 1), m - 2)) % m
  }

}

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

  val mod = 1000000007L
  def comb: (Long, Long) => Long = MyMath.mconb(mod)

  def calcSteps(stairs: Long, twoSteps: Long): Long = comb(stairs - twoSteps, twoSteps)
  def calcPatterns(stairs: Long): Long = {
    if (stairs < 0) 0
    else {
      var sum: Long = 0
      (0L to stairs / 2).foreach(twoSteps => sum = (sum + calcSteps(stairs, twoSteps)) % mod)
      sum
    }
  }

  def solve(input: String): String = {
    val s: Scanner = new Scanner(input)
    val n, m = s.nextInt
    var aprev = -1L
    var p = 1L
    var a = 0L
    for (_ <- 1 to m) {
      a = s.nextInt
      p = (p * calcPatterns(a - 2 - aprev)) % mod
      aprev = a
    }
    p = (p * calcPatterns((n + 1) - 2 - aprev)) % mod
    p.toString
  }

  val tests = List(
    """6 1
      |3
    """.stripMargin -> """4""",
    """10 2
      |4
      |5
    """.stripMargin -> """0""",
    """100 5
      |1
      |23
      |45
      |67
      |89
    """.stripMargin -> """608200469"""
  )

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