import scala.annotation.tailrec

object Main extends App {

  val sc = new java.util.Scanner(System.in)
  sc.useDelimiter("\n")
  val N = sc.nextInt()
  val A = sc.next().split(" ").map(_.toLong)
  println(calc(0L, 0, 0L))

  @tailrec
  def calc(prev: Long, index: Int, acc: Long): Long = {
    if (index == A.length) {
      acc
    } else if (prev <= A(index)) {
      calc(A(index), index + 1, acc)
    } else {
      calc(prev, index + 1, acc + prev - A(index))
    }
  }

}

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  var step: List[Int] = List()
  val A = List.fill(N)(sc.nextInt())
  val ans = for ((a, i) <- A.zipWithIndex) yield {
    if (i == 0 || A(i-1)+step(i-1) <= a) {
      step = step :+ 0
    } else {
      step = step :+ A(i-1)+step(i-1) - a
    }
  }
  println(step.sum)

}

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

Submitted source-code file size, in bytes.

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

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


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	pw.println(
		Seq.fill(Scanner.nextInt)(Scanner.nextLong).foldLeft((0L,0L)) { case ((acc, p), ai) =>
			val updated = if (p < ai) ai else p
			(acc + updated - ai, updated)
		}._1
	)
	pw.flush()
}

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

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

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

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

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

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

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


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextLong)

  val z = A.foldLeft((0L, 0L))((z, x) => if (x >= z._2) (z._1, x) else (z._1 + z._2 - x, z._2))._1

  println(z)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val as = List.fill(n)(sc.nextInt())
  var max = as.head
  var ans = 0L
  for (a <- as) {
    if (a < max) {
      ans += max - a
    } else {
      max = a
    }
  }

  println(ans)
}


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

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

object Main {
  val DEBUG = false

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

  def log(message: => Any): Unit = {
    if (DEBUG) {
      debugOut.println(message)
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    inner(n, width - 1)
  }

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

    inner(n % m, p, 1)
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val (h, w) = get[Int, Int]
    val (ch, cw) = get[Int, Int] match {
      case (a, b) => (a - 1, b - 1)
    }
    val (dh, dw) = get[Int, Int] match {
      case (a, b) => (a - 1, b - 1)
    }
    val smap = Array.fill(h) {
      get[String].toCharArray
    }

    @inline
    def xy2i(y: Int, x: Int): Int = {
      y * w + x
    }

    @inline
    def i2xy(i: Int): (Int, Int) = {
      (i / w, i % w)
    }

    log("=== start")

    class UnionFind(size: Int) {
      val roots: Array[Int] = Array.ofDim[Int](size)
      for (i <- 0 until size) {
        roots(i) = i
      }

      val warpable: Array[mutable.HashSet[Int]] = Array.fill(size)(mutable.HashSet.empty[Int])

      def root(a: Int): Int = {
        if (roots(a) == a) {
          a
        } else {
          roots(a) = root(roots(a))
          roots(a)
        }
      }

      def isSameRoot(a: Int, b: Int): Boolean = {
        root(a) == root(b)
      }

      def walkablize(a: Int, b: Int): Unit = {
        log(s"walkablize(${i2xy(a)},${i2xy(b)})")
        if (a != b) {
          val rootA = root(a)
          val rootB = root(b)
          if (rootA != rootB) {
            roots(rootB) = rootA
            warpable(rootA).addAll(warpable(rootB).map(root))
            warpable(rootB).clear()
          }
        }
      }

      def warpablize(a: Int, b: Int): Unit = {
        log(s"warpablize(${i2xy(a)},${i2xy(b)})")
        val rootA = root(a)
        val rootB = root(b)
        if (rootA != rootB) {
          warpable(rootA).add(rootB)
          warpable(rootB).add(rootA)
        }
      }

      def getWarpables(a: Int): mutable.HashSet[Int] = {
        val rootA = root(a)
        warpable(rootA) = warpable(rootA).map(root)

        warpable(rootA)
      }
    }

    val unionFind = new UnionFind(h * w)

    for (y <- 0 until h) {
      for (x <- 0 until w) {
        if (smap(y)(x) == '.') {

          for (dy <- -2 to 2) {
            for (dx <- -2 to 2) {
              val tx = x + dx
              val ty = y + dy

              if (!(dx == 0 && dy == 0) && tx >= 0 && ty >= 0 && tx < w && ty < h) {
                if (smap(ty)(tx) == '.') {
                  if (Math.abs(dx) + Math.abs(dy) == 1) {
                    unionFind.walkablize(xy2i(y, x), xy2i(ty, tx))
                  } else {
                    unionFind.warpablize(xy2i(y, x), xy2i(ty, tx))
                  }
                }
              }
            }
          }
        }
      }
    }

    debug {
      for (y <- 0 until h) {
        for (x <- 0 until w) {
          if (smap(y)(x) == '.') {
            log(s"(${y},${x}) = root->${unionFind.root(xy2i(y, x))}, warpables->${unionFind.getWarpables(xy2i(y, x))}")
          }
        }
      }
    }

    val queue = mutable.Queue.empty[Int]
    queue.enqueue(xy2i(ch, cw))
    val warp = Array.fill(h * w)(-1)
    warp(xy2i(ch, cw)) = 0

    while (queue.nonEmpty) {
      val current = queue.dequeue()
      val currentWarp = warp(current)
      log(s"current = ${current}")
      log(s"currentWarp = ${currentWarp}")

      if (unionFind.isSameRoot(xy2i(dh, dw), current)) {
        out.println(currentWarp)
        out.flush()
        log("=== end")
        debug {
          debugOut.flush()
        }
        return
      } else {
        val warpables = unionFind.getWarpables(current)
        warpables.foreach { w =>
          log(s"-> warpables=${w}")

          if (warp(w) == -1) {
            warp(w) = currentWarp + 1
            queue.enqueue(w)
          }
        }
      }
    }

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

  }
}

Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2


object Main extends App {
  val input = io.StdIn.readLine()
  val score = input match {
    case "RRR" => 0
    case "RRS" => 1
    case "RSR" => 1
    case "RSS" => 2
    case "SRR" => 1
    case "SRS" => 1
    case "SSR" => 2
    case "SSS" => 3
  }
  println(score)
}

Score : 100 points

Problem Statement

We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.

Find the maximum number of consecutive rainy days in this period.

Constraints

|S| = 3

Each character of S is S or R.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of consecutive rainy days in the period.

Sample Input 1

RRS

Sample Output 1

2

We had rain on the 1-st and 2-nd days in the period. Here, the maximum number of consecutive rainy days is 2, so we should print 2.

Sample Input 2

SSS

Sample Output 2

0

It was sunny throughout the period. We had no rainy days, so we should print 0.

Sample Input 3

RSR

Sample Output 3

1

We had rain on the 1-st and 3-rd days - two "streaks" of one rainy day, so we should print 1.


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N = in.nextInt
  val Ls = Array.fill(N)(in.nextInt).sorted
  println((for {
    a <- 0 until Ls.size
    b <- a + 1 until Ls.size
    c <- b + 1 until Ls.size
    if (Ls(a) != Ls(b) && Ls(b) != Ls(c) && Ls(a) + Ls(b) > Ls(c))
  } yield 1).size)
}

Score : 200 points

Problem Statement

We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.

In how many ways can we choose three of the sticks with different lengths that can form a triangle?

That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:

L_i, L_j, and L_k are all different.

There exists a triangle whose sides have lengths L_i, L_j, and L_k.

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 \cdots L_N

Output

Print the number of ways to choose three of the sticks with different lengths that can form a triangle.

Sample Input 1

5
4 4 9 7 5

Sample Output 1

5

The following five triples (i, j, k) satisfy the conditions: (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 4, 5), and (3, 4, 5).

Sample Input 2

6
4 5 4 3 3 5

Sample Output 2

8

We have two sticks for each of the lengths 3, 4, and 5. To satisfy the first condition, we have to choose one from each length.

There is a triangle whose sides have lengths 3, 4, and 5, so we have 2 ^ 3 = 8 triples (i, j, k) that satisfy the conditions.

Sample Input 3

10
9 4 6 1 9 6 10 6 6 8

Sample Output 3

39

Sample Input 4

2
1 1

Sample Output 4

0

No triple (i, j, k) satisfies 1 \leq i < j < k \leq N, so we should print 0.


import scala.util.control.Breaks

object Main extends App {
  val n = scala.io.StdIn.readInt()
  val lInput = scala.io.StdIn.readLine()
  val lArray = lInput.split(" ").map(_.toLong).toVector

  val lArraySorted = lArray.toSet.toVector.sorted
  val sortedLength = lArraySorted.length
  val groupedMap = lArray.groupBy(l => l)
  var result = 0

  def setTriangle(head: Long, tail: Vector[Long]): Unit = {
    tail.zipWithIndex.foreach { t =>
      if (head < t._1) {
        val second = (head, t._1)
        setThirdPosition(second, tail.drop(t._2 + 1))
      }
    }
  }

  def setThirdPosition(nihen: (Long, Long), tail: Vector[Long]): Unit = {
    val b = new Breaks
    b.breakable {
      tail.foreach { t =>
        if ((nihen._1 + nihen._2) > t && t > Math.abs((nihen._1 - nihen._2))) {
          val firstCount = groupedMap.get(nihen._1).get.size
          val secondCount = groupedMap.get(nihen._2).get.size
          val thirdCount = groupedMap.get(t).get.size
          result = result + (firstCount * secondCount * thirdCount)
        } else {
          b.break()
        }
      }
    }
  }

  if (sortedLength > 2) {
    var count = sortedLength
    var tempSortedArray = lArraySorted
    while (count > 2) {
      val head = tempSortedArray.head
      tempSortedArray = tempSortedArray.tail
      setTriangle(head, tempSortedArray)
      count = count - 1
    }
    println(result)
  } else {
    println(0)
  }

}


import scala.io.StdIn

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

  val stickIdCombinations=scala.collection.mutable.Set.empty[Set[Int]]
  for(s1 <- 0 until sticks.length){
    for(s2 <- 0 until sticks.length){
      for(s3 <- 0 until sticks.length){
        val stickLens = List(s1,s2,s3).map(sticks(_)).toSet
        if(stickLens.size == 3){
          stickIdCombinations += Set(s1,s2,s3)
        }
      }
    }
  }

  val ans = (for (stickIds <- stickIdCombinations.toList) yield {
    val List(s1, s2, s3) = stickIds.toList.map(sticks(_))
    if (s1 + s2 > s3 && s2 + s3 > s1 && s3 + s1 > s2)
      1
    else
      0
  }).sum

  println(ans)

}


import scala.math.BigInt.long2bigInt

object Main extends App {
  val params = io.StdIn.readLine().split(" ").map(_.toLong)
  var x = params(0)
  var k = params(1)
  var d = params(2)
  var ans: Long = 0

  x = Math.abs(x)
  val stright : Long = Math.min(k, x / d)
  k -= stright
  x -= stright * d

  if ((k mod 2) == 0)
    ans = x
  else
    ans = Math.abs(x - d)

  println(ans)
}

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n, k = sc.nextInt()
  val p = Array.fill(n)(sc.nextInt()-1)
  val c = Array.fill(n)(sc.nextLong())

  def decompose(a: Array[Int]): Array[Array[Int]] = {
    val n = a.length
    val visited = Array.fill(n)(false)
    var res = Array[Array[Int]]()

    for (i <- 0 until n) {
      var next = i
      var factor = Array[Int]()
      while (!visited(next)) {
        visited(next) = true
        factor :+= next
        next = a(next)
      }
      if (factor.nonEmpty) {
        res :+= factor
      }
    }

    res
  }

  val d = decompose(p).map(_.map(c))

  var ans = Long.MinValue
  for (f <- d) {
    val l = f.length
    val fa = (f ++ f).scanLeft(0L)(_ + _)
    val sum = fa(l) - fa(0)
    if (sum > 0) {
      val x = k / l
      val y = k % l
      val z = if (x == 0) 1 else 0
      for {
        i <- 0 until l
        j <- i+z to i+y
      } {
        ans = ans.max(sum * x + fa(j) - fa(i))
      }

      val w = if (x == 1) 1 else 0
      if (x != 0) {
        for {
          i <- 0 until l
          j <- i+w to i+l
        } {
          ans = ans.max(sum * (x-1) + fa(j) - fa(i))
        }
      }
    } else {
      for {
        i <- 0 until l
        j <- i+1 to i+(k.min(l))
      } {
        ans = ans.max(fa(j) - fa(i))
      }
    }
  }

  println(ans)
}

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N, D = in.nextInt
  val Ps = Array.fill(N)((in.nextLong, in.nextLong))
  val sq = D.toLong * D

  println(Ps.count{case (x, y) => x * x + y * y <= sq})
}

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

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

0 \leq D \leq 2\times 10^5

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6


import scala.io.StdIn._

object Main extends App {

  val Array(n,d) = readLine().split(" ").map(_.toInt)
  val xy = Array.fill(n)(readLine().split(" ").map(_.toLong))

  def solve() = {
    xy.map { l =>
      Math.sqrt(l(0) * l(0) + l(1) * l(1))
    }.count(_ <= d)
  }

  println(solve())

}


object Main {
  def main(args: Array[String]): Unit = {
    val num = scala.io.StdIn.readInt
    var check_num = Array.fill( num )( false )

    if( num%2 == 0 || num%5 == 0 ) println( -1 )
    else {
      var check = 7%num
      var count = 1
      while( check != 0 && !check_num( check ) ) {
        count += 1
        check_num( check ) = true
        check = ( check*10 + 7 )%num
      }

      if( check%num != 0 ) println( -1 )
      else                 println( count )
    }
  }
}

Score : 300 points

Problem Statement

Takahashi loves the number 7 and multiples of K.

Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of K, print -1 instead.

Constraints

1 \leq K \leq 10^6

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print an integer representing the position of the first occurrence of a multiple of K. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

Sample Input 1

101

Sample Output 1

4

None of 7, 77, and 777 is a multiple of 101, but 7777 is.

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of 2.

Sample Input 3

999983

Sample Output 3

999982


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val k = sc.nextInt()
  val res = Array.fill(k)(false)

  var i = 0
  var r = 7 % k
  res(r) = true
  var continue = true
  while (continue) {
    r = (((r * 10) % k) + 7 % k) % k
    if (res(r)) {
      continue = false
    } else {
      res(r) = true
    }
    i += 1
  }

  println(if (res(0)) i else -1)
}


object Main extends App {
  val sc = new FastScanner(System.in)
  val n, q = sc.nextInt()
  val c = Array.fill(n)(sc.nextInt()-1)
  val lr = List.fill(q)((sc.nextInt()-1, sc.nextInt()-1))

  val pre = Array.fill(n)(-1)
  val ps = Array.fill(n)(List[Int]())
  for ((r, idx) <- c.zipWithIndex) {
    val l = pre(r)
    if (l != -1) {
      ps(l) ::= r
    }
    pre(r) = idx
  }

  val qs = Array.fill(n)(List[(Int, Int)]())
  for (((l, r), idx) <- lr.zipWithIndex) {
    qs(l) ::= (r, idx)
  }

  val ans = Array.fill(q)(0)
  val bit = new BinaryIndexedTree(n)

  for (((pys, qys), x) <- ps.zip(qs).zipWithIndex.reverse) {
    for (y <- pys) {
      bit.add(y, 1)
    }
    for ((y, idx) <- qys) {
      ans(idx) = y-x+1 - bit.query(y)
    }
  }

  val pw = new java.io.PrintWriter(Console.out)
  ans.foreach(pw.println)
  pw.flush()
}

class BinaryIndexedTree(n: Int) {
  private val tree = Array.fill(n+1)(0)

  def query(r: Int): Int = {
    var res = 0
    var i = r
    while (i > 0) {
      res += tree(i)
      i -= i & -i
    }
    res
  }

  def add(idx: Int, a: Int): Unit = {
    var i = idx+1
    while (i <= n) {
      tree(i) += a
      i += i & -i
    }
  }
}

class FastScanner(source: java.io.InputStream) {
  val buf = new Array[Byte](1024)
  var now, end = 0

  def isPrintable(b: Byte): Boolean = 33 <= b && b <= 126
  def isNum(b: Byte): Boolean = 48 <= b && b <= 57

  def hasNextByte: Boolean = {
    if (now < end) {
      true
    } else {
      now = 0
      end = source.read(buf)
      end > 0
    }
  }

  def nextByte(): Byte = {
    if (hasNextByte) {
      val b = buf(now)
      now += 1
      b
    } else {
      -1
    }
  }

  def hasNext: Boolean = {
    while (hasNextByte && !isPrintable(buf(now))) {
      now += 1
    }
    hasNextByte
  }

  def next(): String = {
    if (hasNext) {
      val sb = new StringBuilder()
      var b = nextByte()
      while (isPrintable(b)) {
        sb += b.toChar
        b = nextByte()
      }
      sb.toString
    } else {
      throw new NoSuchElementException()
    }
  }

  def nextInt(): Int = {
    nextLong().toInt
  }

  def nextLong(): Long = {
    if (hasNext) {
      var b = nextByte()
      var sign = 1
      var n = 0L
      if (b == '-') {
        sign = -1
        b = nextByte()
      }
      while (isNum(b)) {
        n = n * 10 + (b - 48)
        b = nextByte()
      }
      sign * n
    } else {
      throw new NoSuchElementException()
    }
  }

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

Score : 600 points

Problem Statement

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

1\leq N,Q \leq 5 \times 10^5

1\leq c_i \leq N

1\leq l_i \leq r_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

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

Sample Input 1

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

Sample Output 1

2
3
1

The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.

The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.

The 3-rd ball from the left has the color 1 - just one color.

Sample Input 2

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

Sample Output 2

1
2
2
1
2
2
6
3
3
3


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n, q = sc.nextInt()
  val c = Array.fill(n)(sc.nextInt())
  val lr = Array.fill(q)(sc.nextInt, sc.nextInt)
  lr.map(color).foreach(println)

  def color(v:(Int, Int)): Int = {
    c.slice(v._1 - 1, v._2).distinct.length
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val score = scala.io.StdIn.readInt
    var rate  = 0
    if( 400 <= score && score < 600 )         rate = 8
    else if( 600 <= score && score < 800 )    rate = 7
    else if( 800 <= score && score < 1000 )   rate = 6
    else if( 1000 <= score && score < 1200 )  rate = 5
    else if( 1200 <= score && score < 1400 )  rate = 4
    else if( 1400 <= score && score < 1600 )  rate = 3
    else if( 1600 <= score && score < 1800 )  rate = 2
    else if( 1800 <= score && score < 2000 )  rate = 1

    println( rate )
  }
}

Score: 100 points

Problem Statement

M-kun is a competitor in AtCoder, whose highest rating is X.

In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:

From 400 through 599: 8-kyu

From 600 through 799: 7-kyu

From 800 through 999: 6-kyu

From 1000 through 1199: 5-kyu

From 1200 through 1399: 4-kyu

From 1400 through 1599: 3-kyu

From 1600 through 1799: 2-kyu

From 1800 through 1999: 1-kyu

What kyu does M-kun have?

Constraints

400 \leq X \leq 1999

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the kyu M-kun has, as an integer.
For example, if he has 8-kyu, print 8.

Sample Input 1

725

Sample Output 1

7

M-kun's highest rating is 725, which corresponds to 7-kyu.

Thus, 7 is the correct output.

Sample Input 2

1600

Sample Output 2

2

M-kun's highest rating is 1600, which corresponds to 2-kyu.

Thus, 2 is the correct output.


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

    val n = sc.nextInt
    val k = sc.nextInt
    val a = Array.fill(n)(sc.nextInt)
    for (i <- k until n) {
        println(if (a(i) > a(i-k)) "Yes" else "No")
    }

}

Score: 300 points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into N terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through (K-1)-th terms: not given.

For each of the K-th through N-th terms: the multiplication of the scores in the last K exams, including the exam in the graded term.

M-kun scored A_i in the exam at the end of the i-th term.

For each i such that K+1 \leq i \leq N, determine whether his grade for the i-th term is strictly greater than the grade for the (i-1)-th term.

Constraints

2 \leq N \leq 200000

1 \leq K \leq N-1

1 \leq A_i \leq 10^{9}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 A_3 \ldots A_N

Output

Print the answer in N-K lines.

The i-th line should contain Yes if the grade for the (K+i)-th term is greater than the grade for the (K+i-1)-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

3-rd term: (96 \times 98 \times 95) = 893760

4-th term: (98 \times 95 \times 100) = 931000

5-th term: (95 \times 100 \times 20) = 190000

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the 3-rd term is equal to the grade for the 2-nd term.

Sample Input 3

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

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  var l,r,d = sc.nextInt()
  var ans = 0
  for (i <- l to r){
    if (i % d == 0) ans+=1
  }
  println(ans)
}

Score : 100 points

Problem Statement

How many multiples of d are there among the integers between L and R (inclusive)?

Constraints

All values in input are integers.

1 \leq L \leq R \leq 100

1 \leq d \leq 100

Input

Input is given from Standard Input in the following format:

L R d

Output

Print the number of multiples of d among the integers between L and R (inclusive).

Sample Input 1

5 10 2

Sample Output 1

3

Among the integers between 5 and 10, there are three multiples of 2: 6, 8, and 10.

Sample Input 2

6 20 7

Sample Output 2

2

Among the integers between 6 and 20, there are two multiples of 7: 7 and 14.

Sample Input 3

1 100 1

Sample Output 3

100


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val count = List.fill(sc.nextInt())(sc.nextInt())
    .zipWithIndex
    .count { case (a, i) => a % 2 == 1 && i % 2 == 0 }
  println(count)
}

Score : 200 points

Problem Statement

We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i.

How many squares i satisfy both of the following conditions?

The assigned number, i, is odd.

The written integer is odd.

Constraints

All values in input are integers.

1 \leq N, a_i \leq 100

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \cdots a_N

Output

Print the number of squares that satisfy both of the conditions.

Sample Input 1

5
1 3 4 5 7

Sample Output 1

2

Two squares, Square 1 and 5, satisfy both of the conditions.

For Square 2 and 4, the assigned numbers are not odd.

For Square 3, the written integer is not odd.

Sample Input 2

15
13 76 46 15 50 98 93 77 31 43 84 90 6 24 14

Sample Output 2

3


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val numLength = sc.nextInt
  val numSeq = Seq.fill(numLength)(sc.nextInt).zipWithIndex
    val resultSeq = for{
    n   <- numSeq
    n1  =  if(n._1 % 2 != 0) n._1 else 0
    n2  =  if(n._2 % 2 == 0 || n._2 == 0)n._2  else 0
    res =  if(n1 > 0 && n2 > 0) 1 else 0
  } yield res
  val result = resultSeq.filter(_ > 0).sum
  println(result)
}


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N = in.nextInt
  val X = BigInt(in.next, 2)
  val Zero = BigInt(0)

  def f(n: BigInt, cnt: Int): Int = {
    if (n == Zero) cnt
    else f(n.mod(n.bitCount), cnt + 1)
  }

  val bits = X.bitCount

  println(((N - 1 to 0 by -1).map {i =>
    (bits + (if (X.testBit(i)) -1 else 1)) match {
      case 0 => 0
      case newBits => f(X.flipBit(i).mod(newBits), 1)
    }
  }).mkString("\n"))
}

Score : 400 points

Problem Statement

Let \mathrm{popcount}(n) be the number of 1s in the binary representation of n.
For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.

Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n is divided by \mathrm{popcount}(n)." (It can be proved that, under the constraints of this problem, n always becomes 0 after a finite number of operations.)

For example, when n=7, it becomes 0 after two operations, as follows:

\mathrm{popcount}(7)=3, so we divide 7 by 3 and replace it with the remainder, 1.

\mathrm{popcount}(1)=1, so we divide 1 by 1 and replace it with the remainder, 0.

You are given an integer X with N digits in binary.
For each integer i such that 1 \leq i \leq N, let X_i be what X becomes when the i-th bit from the top is inverted.
Find f(X_1), f(X_2), \ldots, f(X_N).

Constraints

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

X is an integer with N digits in binary, possibly with leading zeros.

Input

Input is given from Standard Input in the following format:

N
X

Output

Print N lines. The i-th line should contain the value f(X_i).

Sample Input 1

3
011

Sample Output 1

2
1
1

X_1 = 7, which will change as follows: 7 \rightarrow 1 \rightarrow 0. Thus, f(7) = 2.

X_2 = 1, which will change as follows: 1 \rightarrow 0. Thus, f(1) = 1.

X_3 = 2, which will change as follows: 2 \rightarrow 0. Thus, f(2) = 1.

Sample Input 2

23
00110111001011011001110

Sample Output 2

2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N = in.nextInt
  val Ss = List.fill(N)(in.next)
  def formatCount(judge: String): String = s"$judge x ${Ss.count(_ == judge)}"
  println(List("AC", "WA", "TLE", "RE").map(formatCount).mkString("\n"))
}

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {

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

    val sq = Array.fill(h)(sc.next().split("").filter(_ != "").map(_ == "#")).flatten

    val wps = powerSet((0 until w).toList)
    val hps = powerSet((0 until h).toList)

    var ans = 0

    wps.foreach { wl =>
      val wp = wl.flatMap(wi => (0 until h).map(i => w * i + wi))
      hps.foreach { hl =>
        val hp = hl.flatMap(hi => (0 until w).map(i => i + hi * w))
        val po = (wp ++ hp).toSet

        var cnt = 0
        (0 until h * w).foreach(i => if (sq(i) && !po.contains(i)) cnt += 1)

        if (cnt == k) ans += 1
      }
    }

    println(ans)
  }

  def powerSet[A](xs: List[A]): List[List[A]] =
    xs.foldLeft(List(Nil: List[A]))((accum, elem) => accum.flatMap(l => Seq(l, elem :: l)))

}

Score : 300 points

Problem Statement

We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is ., and black if c_{i,j} is #.

Consider doing the following operation:

Choose some number of rows (possibly zero), and some number of columns (possibly zero). Then, paint red all squares in the chosen rows and all squares in the chosen columns.

You are given a positive integer K. How many choices of rows and columns result in exactly K black squares remaining after the operation? Here, we consider two choices different when there is a row or column chosen in only one of those choices.

Constraints

1 \leq H, W \leq 6

1 \leq K \leq HW

c_{i,j} is . or #.

Input

Input is given from Standard Input in the following format:

H W K
c_{1,1}c_{1,2}...c_{1,W}
c_{2,1}c_{2,2}...c_{2,W}
:
c_{H,1}c_{H,2}...c_{H,W}

Output

Print an integer representing the number of choices of rows and columns satisfying the condition.

Sample Input 1

2 3 2
..#
###

Sample Output 1

5

Five choices below satisfy the condition.

The 1-st row and 1-st column

The 1-st row and 2-nd column

The 1-st row and 3-rd column

The 1-st and 2-nd column

The 3-rd column

Sample Input 2

2 3 4
..#
###

Sample Output 2

1

One choice, which is choosing nothing, satisfies the condition.

Sample Input 3

2 2 3
##
##

Sample Output 3

0

Sample Input 4

6 6 8
..##..
.#..#.
#....#
######
#....#
#....#

Sample Output 4

208


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N = in.nextInt
  val As = List.fill(N)(in.nextLong).sorted.reverse

  println(As.head + {
    val l = As.tail.take((N - 1)  / 2)
    if (N % 2 == 0) l.sum * 2
    else l.sum * 2 - l.last
  })
}

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


import scala.math.pow

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  var n = sc.nextInt()
  println(n+pow(n,2).toInt+pow(n,3).toInt)
}

Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

Print the value a + a^2 + a^3 as an integer.

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	pw.println(if ((Scanner.next())(0).isUpper) "A" else "a")
	pw.flush()
}

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

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

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

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

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

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

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

Score : 100 points

Problem Statement

An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

Constraints

\alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

α

Output

If \alpha is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N, K = sc.nextInt
  val p = Array.fill(N)(sc.nextInt)

  val z = p.combinations(K).map(_.sum).min
  println(z)
}

Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000


import java.security.KeyStore.TrustedCertificateEntry
import java.util
import java.util.regex.Pattern
import java.util.{ArrayList, Collections, Comparator, List => JList}

import scala.collection.immutable.TreeMap
import scala.math._
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.util.{Failure, Success, Try}

object Main{
  val LINE_SEPARATOR = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LINE_SEPARATOR);
      println(solve(input).trim());
    }
  }

  def init (nRows: Int, nCols: Int, default: Int) = Array.tabulate(nRows,nCols)( (x,y) =>  default)

  def sortIgnoreCase1(list: JList[String]): JList[String] = {
    val r = new ArrayList[String](list)
    Collections.sort(r, new Comparator[String] {
      override def compare(o1: String, o2: String): Int = o1.compareToIgnoreCase(o2)
    })
    r
  }

//  def solve(input: String): String = {
//    val Array(n, q) = input.split(LINE_SEPARATOR).head.split(" ").map(_.toInt)
//    val a = input.split(LINE_SEPARATOR).tail.take(n).map(_.split(" ").head.toInt)
//    val b = input.split(LINE_SEPARATOR).tail.take(n).map(_.split(" ").tail.head.toInt)
//    val c = input.split(LINE_SEPARATOR).drop(n + 1).map(_.split(" ").head.toInt)
//    val d = input.split(LINE_SEPARATOR).drop(n + 1).map(_.split(" ").tail.head.toInt)
//    val k = 2 * pow(10, 5).toInt
//    val INF = pow(10, 9).toInt + 1
//    val pqMap = (0 until k).map(_ => new mutable.TreeMap[Int, Int]).toArray
//    def add(k: Int, ai: Int): Unit = {
//      val count = pqMap(k).getOrElse(ai, 0)
//      pqMap(k) += ai -> (count + 1)
//    }
//    def delete(k: Int, ai: Int): Unit = {
//      val count = pqMap(k).getOrElse(ai, 0)
//      if (count == 1) pqMap(k) -= ai else pqMap(k) += ai -> (count - 1)
//    }
//    val i2k = (0 until n).map{i =>
//      b(i)
//    }.toArray
//    (0 until n).foreach{i =>
//      add(b(i) - 1, a(i))
//    }
//    val maxList = pqMap.map(pq => if (pq.nonEmpty) pq.last._1 else INF)
//
//    (0 until q).map{j =>
//      add(d(j) - 1, a(c(j) - 1))
//      delete(i2k(c(j) - 1) - 1, a(c(j) - 1))
//      maxList(i2k(c(j) - 1) - 1) =
//        if (pqMap(i2k(c(j) - 1) - 1).nonEmpty) pqMap(i2k(c(j) - 1) - 1).last._1 else INF
//      i2k(c(j) - 1) = d(j)
//      maxList(d(j) - 1) = if (pqMap(d(j) - 1).nonEmpty) pqMap(d(j) - 1).last._1 else INF
//      maxList.min
//    }.mkString(LINE_SEPARATOR)
//  }

  def solve(input: String): String = {
    val n = input.toLong
    divideDigits(n, 26L).map(_.toInt).map(i => (i + 96).toChar).mkString
  }

  def divideDigits(num: Long, base: Long = 10L): List[Long] = {
    def proc(num: Long, base: Long, flg: Boolean): List[Long] = {
      var flag = flg
      val quotient = num / base
      val remainder = if (num % base == 0) {
        flag = true
        base
      } else if (flag) {
        flag = false
        val temp = num % base - 1
        if (temp == 0) {
          flag = true
          base
        } else temp
      } else {
        flag = flg
        num % base
      }
      quotient match {
        case 0 =>
          if (flag) {
            List.empty
          } else List(remainder)
        case _ => remainder :: proc(quotient, base, flag)
      }
    }

    proc(num, base, false).reverse//.filterNot(_ == 0)
  }

  def medianCalculator(seq: Seq[Long]): Long = {
    //In order if you are not sure that 'seq' is sorted
    val sortedSeq = seq.sortWith(_ < _)

    if (seq.size % 2 == 1) sortedSeq(sortedSeq.size / 2)
    else {
      val (up, down) = sortedSeq.splitAt(seq.size / 2)
      (up.last + down.head) / 2
    }
  }

  def factorize(x: Long): List[Long] = {
    def foo(x: Long, a: Long = 2, list: List[Long] = Nil): List[Long] = a*a > x match {
      case false if x % a == 0 => foo(x / a, a    , a :: list)
      case false               => foo(x    , a + 1, list)
      case true                => x :: list
    }
    foo(x)
  }

  def divisors(n: Int): Vector[Int] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(n % _ == 0).map(_.toInt)
    val reversedList = if (sqrt(n).floor == sqrt(n)) halfList.reverse.tail.map(n/_) else halfList.reverse.map(n/_)
    halfList ++ reversedList
  }

  def gcd(m: Long, n: Long): Long = n match {
    case 0 => m
    case _ => gcd(n, m % n)
  }
  def lcm(a: Long, b: Long): Long = a * b / gcd(a, b)

  val tests=List(
    """2""".stripMargin -> """b
                                                |
                             |
                                   |
                                      |""".stripMargin
    ,
    """27""".stripMargin -> """aa
                             |""".stripMargin,
    """123456789""" -> """jjddja""",
    """1000000000000001""" -> "test",
    """702""" -> """zz""",
    """26""" -> "z",
    """677""" -> """za""",
    """1353""" -> """aza"""
  )

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

}

Score : 300 points

Problem Statement

1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:

the dogs numbered 1,2,\cdots,26 were respectively given the names a, b, ..., z;

the dogs numbered 27,28,29,\cdots,701,702 were respectively given the names aa, ab, ac, ..., zy, zz;

the dogs numbered 703,704,705,\cdots,18277,18278 were respectively given the names aaa, aab, aac, ..., zzy, zzz;

the dogs numbered 18279,18280,18281,\cdots,475253,475254 were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;

the dogs numbered 475255,475256,\cdots were respectively given the names aaaaa, aaaab, ...;

and so on.

To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:

a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...

Now, Roger asks you:

"What is the name for the dog numbered N?"

Constraints

N is an integer.

1 \leq N \leq 1000000000000001

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer to Roger's question as a string consisting of lowercase English letters.

Sample Input 1

2

Sample Output 1

b

Sample Input 2

27

Sample Output 2

aa

Sample Input 3

123456789

Sample Output 3

jjddja


object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val n = inputs.head.toInt

  println(solve(n))

  def solve(n: Int): String = {
    var dog = n
    val str  = "-abcdefghijklmnopqrstuvwxyz"
    val base = 26
    var name = ""

    while(dog != 0) {
      val p = dog % base
      dog = dog / base
      name = name + str(p.toInt)
    }
    name.reverse
  }
}


import java.security.KeyStore.TrustedCertificateEntry
import java.util
import java.util.regex.Pattern
import java.util.{ArrayList, Collections, Comparator, List => JList}

import scala.collection.immutable.TreeMap
import scala.math._
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.util.{Failure, Success, Try}

object Main{
  val LINE_SEPARATOR = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LINE_SEPARATOR);
      println(solve(input).trim());
    }
  }

  def init (nRows: Int, nCols: Int, default: Int) = Array.tabulate(nRows,nCols)( (x,y) =>  default)

  def sortIgnoreCase1(list: JList[String]): JList[String] = {
    val r = new ArrayList[String](list)
    Collections.sort(r, new Comparator[String] {
      override def compare(o1: String, o2: String): Int = o1.compareToIgnoreCase(o2)
    })
    r
  }

//  def solve(input: String): String = {
//    val Array(n, q) = input.split(LINE_SEPARATOR).head.split(" ").map(_.toInt)
//    val a = input.split(LINE_SEPARATOR).tail.take(n).map(_.split(" ").head.toInt)
//    val b = input.split(LINE_SEPARATOR).tail.take(n).map(_.split(" ").tail.head.toInt)
//    val c = input.split(LINE_SEPARATOR).drop(n + 1).map(_.split(" ").head.toInt)
//    val d = input.split(LINE_SEPARATOR).drop(n + 1).map(_.split(" ").tail.head.toInt)
//    val k = 2 * pow(10, 5).toInt
//    val INF = pow(10, 9).toInt + 1
//    val pqMap = (0 until k).map(_ => new mutable.TreeMap[Int, Int]).toArray
//    def add(k: Int, ai: Int): Unit = {
//      val count = pqMap(k).getOrElse(ai, 0)
//      pqMap(k) += ai -> (count + 1)
//    }
//    def delete(k: Int, ai: Int): Unit = {
//      val count = pqMap(k).getOrElse(ai, 0)
//      if (count == 1) pqMap(k) -= ai else pqMap(k) += ai -> (count - 1)
//    }
//    val i2k = (0 until n).map{i =>
//      b(i)
//    }.toArray
//    (0 until n).foreach{i =>
//      add(b(i) - 1, a(i))
//    }
//    val maxList = pqMap.map(pq => if (pq.nonEmpty) pq.last._1 else INF)
//
//    (0 until q).map{j =>
//      add(d(j) - 1, a(c(j) - 1))
//      delete(i2k(c(j) - 1) - 1, a(c(j) - 1))
//      maxList(i2k(c(j) - 1) - 1) =
//        if (pqMap(i2k(c(j) - 1) - 1).nonEmpty) pqMap(i2k(c(j) - 1) - 1).last._1 else INF
//      i2k(c(j) - 1) = d(j)
//      maxList(d(j) - 1) = if (pqMap(d(j) - 1).nonEmpty) pqMap(d(j) - 1).last._1 else INF
//      maxList.min
//    }.mkString(LINE_SEPARATOR)
//  }

  def solve(input: String): String = {
    val n = input.toLong
    divideDigits(n, 26).map(i => (i.toInt + 96).toChar).mkString
  }

  def divideDigits(num: Long, base: Long = 10): List[Long] = {
    def proc(num: Long, base: Long): List[Long] = {
      val quotient = num / base
      val remainder = num % base
      quotient match {
        case 0 => return List(remainder)
        case _ => remainder :: proc(quotient, base)
      }
    }

    proc(num, base).reverse
  }

  def medianCalculator(seq: Seq[Long]): Long = {
    //In order if you are not sure that 'seq' is sorted
    val sortedSeq = seq.sortWith(_ < _)

    if (seq.size % 2 == 1) sortedSeq(sortedSeq.size / 2)
    else {
      val (up, down) = sortedSeq.splitAt(seq.size / 2)
      (up.last + down.head) / 2
    }
  }

  def factorize(x: Long): List[Long] = {
    def foo(x: Long, a: Long = 2, list: List[Long] = Nil): List[Long] = a*a > x match {
      case false if x % a == 0 => foo(x / a, a    , a :: list)
      case false               => foo(x    , a + 1, list)
      case true                => x :: list
    }
    foo(x)
  }

  def divisors(n: Int): Vector[Int] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(n % _ == 0).map(_.toInt)
    val reversedList = if (sqrt(n).floor == sqrt(n)) halfList.reverse.tail.map(n/_) else halfList.reverse.map(n/_)
    halfList ++ reversedList
  }

  def gcd(m: Long, n: Long): Long = n match {
    case 0 => m
    case _ => gcd(n, m % n)
  }
  def lcm(a: Long, b: Long): Long = a * b / gcd(a, b)

  val tests=List(
    """2""".stripMargin -> """b
                                                |
                             |
                                   |
                                      |""".stripMargin
    ,
    """27""".stripMargin -> """aa
                             |""".stripMargin,
    """123456789""" -> """jjddja"""
  )

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

}


// TLE
object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val size = inputs(0).toInt
  val startNums = inputs(1).split(" ").map(_.toInt)
  val q = inputs(2).toInt
  val bi = inputs.splitAt(3)._2

  solve(size, startNums, q, bi)

  def solve(size: Int, startNums: Seq[Int], q: Int, bi: Seq[String]): Unit = {
    val array = scala.collection.mutable.HashMap.empty[Int, Int]
    var sum = 0
    startNums.foreach { v =>
      sum = sum + v
      array.update(v, array.applyOrElse(v, (n: Int) => 0) + 1)
    }

    // 最終的に数字が何になるのかだけ処理する
    bi.foreach { str =>
      val set = str.split(" ").map(_.toInt)
      val from = set(0)
      val to   = set(1)
      var diff = 0

      if(array.isDefinedAt(from)) {
        diff = (to - from) * array(from)
        array.update(to, array.applyOrElse(to, (n: Int) => 0) + array(from))
        array.remove(from)
      }
      sum = sum + diff

      println(sum)
    }
  }
}

Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}

B_{i} \neq C_{i}

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

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

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

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

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000


import java.util.Scanner

object Main extends App {

  def readALine(c:Int, ac:List[Int]=Nil):List[Int] =
    if (c > 0) readALine(c-1, sc.nextInt::ac) else ac.reverse
  // def readLines(r:Int, c:Int, ac:List[List[Int]]):List[List[Int]] =
  //   if (r > 0) readLines(r-1, c, readALine(c, Nil)::ac) else ac.reverse
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val Ai = readALine(N)

  def solver():List[Int] = {
    def prod(l:List[Int], ac:Int = 0):Int = {
      if (l.isEmpty) ac else prod(l.tail, l.head ^ ac)
    }
    def iter(al:List[Int], bl:List[Int], ac:List[Int]):List[Int] = {
      if (al.isEmpty) ac.reverse else {
        val a0 = al.head
        val a1 = al.tail.head
        val al_ = al.tail.tail
        val others = prod(al_) ^ prod(bl)
        iter(al_,a1::a0::bl, (a0^others)::(a1^others)::ac)
      }
    }
    iter(Ai, Nil, Nil)
  }

  println(solver().mkString(" "))

}

Score : 500 points

Problem Statement

There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.

Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.

Recently, they learned the operation called xor (exclusive OR).

What is xor?

For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows:

When x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~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~\textrm{xor}~5 = 6.

They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf.

We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i.
Using this information, restore the integer written on the scarf of each Snuke Cat.

Constraints

All values in input are integers.

2 \leq N \leq 200000

N is even.

0 \leq a_i \leq 10^9

There exists a combination of integers on the scarfs that is consistent with the given information.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print a line containing N integers separated with space.

The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i.

If there are multiple possible solutions, you may print any of them.

Sample Input 1

4
20 11 9 24

Sample Output 1

26 5 7 22

5~\textrm{xor}~7~\textrm{xor}~22 = 20

26~\textrm{xor}~7~\textrm{xor}~22 = 11

26~\textrm{xor}~5~\textrm{xor}~22 = 9

26~\textrm{xor}~5~\textrm{xor}~7 = 24

Thus, this output is consistent with the given information.


import java.security.KeyStore.TrustedCertificateEntry
import java.util
import java.util.regex.Pattern
import java.util.{ArrayList, Collections, Comparator, List => JList}

import scala.collection.immutable.TreeMap
import scala.math._
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.util.{Failure, Success, Try}

object Main{
  val LINE_SEPARATOR = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LINE_SEPARATOR);
      println(solve(input).trim());
    }
  }

  def init (nRows: Int, nCols: Int, default: Int) = Array.tabulate(nRows,nCols)( (x,y) =>  default)

  def sortIgnoreCase1(list: JList[String]): JList[String] = {
    val r = new ArrayList[String](list)
    Collections.sort(r, new Comparator[String] {
      override def compare(o1: String, o2: String): Int = o1.compareToIgnoreCase(o2)
    })
    r
  }

  def solve(input: String): String = {
    val x = input.split(" ").map(_.toInt)
    var res = 0
    (1 to 5).foreach{i =>
      if (x(i - 1) != i) res = i
    }
    res.toString
  }

  def medianCalculator(seq: Seq[Long]): Long = {
    //In order if you are not sure that 'seq' is sorted
    val sortedSeq = seq.sortWith(_ < _)

    if (seq.size % 2 == 1) sortedSeq(sortedSeq.size / 2)
    else {
      val (up, down) = sortedSeq.splitAt(seq.size / 2)
      (up.last + down.head) / 2
    }
  }

  def factorize(x: Long): List[Long] = {
    def foo(x: Long, a: Long = 2, list: List[Long] = Nil): List[Long] = a*a > x match {
      case false if x % a == 0 => foo(x / a, a    , a :: list)
      case false               => foo(x    , a + 1, list)
      case true                => x :: list
    }
    foo(x)
  }

  def divisors(n: Long): Vector[Long] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(_ % n == 0).map(_.toLong)
    val reversedList = if (sqrt(n).floor == sqrt(n)) halfList.reverse.tail.map(n/_) else halfList.reverse.map(n/_)
    halfList ++ reversedList
  }

  def gcd(m: Long, n: Long): Long = n match {
    case 0 => m
    case _ => gcd(n, m % n)
  }
  def lcm(a: Long, b: Long): Long = a * b / gcd(a, b)

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

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

Score : 100 points

Problem Statement

We have five variables x_1, x_2, x_3, x_4, and x_5.

The variable x_i was initially assigned a value of i.

Snuke chose one of these variables and assigned it 0.

You are given the values of the five variables after this assignment.

Find out which variable Snuke assigned 0.

Constraints

The values of x_1, x_2, x_3, x_4, and x_5 given as input are a possible outcome of the assignment by Snuke.

Input

Input is given from Standard Input in the following format:

x_1 x_2 x_3 x_4 x_5

Output

If the variable Snuke assigned 0 was x_i, print the integer i.

Sample Input 1

0 2 3 4 5

Sample Output 1

1

In this case, Snuke assigned 0 to x_1, so we should print 1.

Sample Input 2

1 2 0 4 5

Sample Output 2

3


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val xs = Seq.fill(5)(sc.nextInt)
  println(xs.indexOf(0) + 1)
}


object Main extends App{
  val sc = new java.util.Scanner(System.in)
  var a , b =sc.nextInt()
  if(b == 0) {print(a);sys.exit()}
  var c = List.fill(b)(sc.nextInt())
  if(c.indexOf(a) == -1){print(a);sys.exit()}
  c :+ a
  c = c.sorted
  var min = 0
  var max = 0
  if (c.indexOf(a) == 0){print(a-1);sys.exit()}
  min = c(c.indexOf(a) - 1)
  if(c.indexOf(a) != b-1) {
    max = c(c.indexOf(a)+1)
  }else{
    max = 105
  }
  var i = a-1
  var j = a+1
  var ans = 0
  while (i == min){
    i-=1
    if(!(c.indexOf(min)-1 == -1)) {
      min = c(c.indexOf(min) - 1)
    }else{
      min = i+1
    }
  }
  while (j == max){
    j+=1
    if(!(c.indexOf(max)+1 > b-1)) {
      max = c(c.indexOf(max) + 1)
    }else{
      max = j+1
    }
  }
  var ia = a-i
  var ja = a-j
  if(ia >= a){print(0);sys.exit()}
  if(math.abs(ia)>math.abs(ja)){
    print(j)
  }else{
    print(i)
  }
}

Score : 300 points

Problem Statement

Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.

Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer.

Constraints

1 \leq X \leq 100

0 \leq N \leq 100

1 \leq p_i \leq 100

p_1, \ldots, p_N are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X N
p_1 ... p_N

Output

Print the answer.

Sample Input 1

6 5
4 7 10 6 5

Sample Output 1

8

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the one nearest to 6 is 8.

Sample Input 2

10 5
4 7 10 6 5

Sample Output 2

9

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the ones nearest to 10 are 9 and 11. We should print the smaller one, 9.

Sample Input 3

100 0

Sample Output 3

100

When N = 0, the second line in the input will be empty. Also, as seen here, X itself can be the answer.


object Main extends App {
  val xn =  scala.io.StdIn.readLine()
  val xnArray = xn.split(" ").map(_.toInt).toSeq
  val x = xnArray(0)
  val n = xnArray(1)

  val pInput =  scala.io.StdIn.readLine()

  if (n == 0) {
    println(x)
  } else {
    val pArray = pInput.split(" ").map(_.toInt).toVector.sorted
    if (pArray.find(_ == x).isEmpty) {
      println(x)
    } else {
      val min = pArray.head - 1
      val minSabun = Math.abs(x - min)
      val max = pArray.last + 1
      val maxSabun = Math.abs(x - max)

      var temp = -999
      var sabun = -999
      var result = -999
      if (minSabun > maxSabun) {
        sabun = maxSabun
        result = max
      } else {
        sabun = minSabun
        result = min
      }
      pArray.zipWithIndex.foreach { p =>
        if (temp == -999) {
          temp = p._1
        } else if (temp + 1 == p._1) {
          temp = p._1
        } else {
          // 現状より一つ前の値
          (temp + 1 to p._1 - 1).foreach { i =>
            val tempSabun = Math.abs(x - i)
            if (tempSabun < sabun) {
              sabun = tempSabun
              result = i
            } else if (tempSabun == sabun && i < result) {
              sabun = tempSabun
              result = i
            }
          }
          temp = p._1
        }
      }
      println(result)
    }
  }
}


import java.util.Scanner

import scala.util.control.Breaks

object Main {

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

    val p = Set.fill(n)(sc.nextInt())

    var ans = x
    var dis = 0
    val b = new Breaks
    b.breakable {
      while (true) {
        if (!p.contains(ans - dis)) {
          ans = ans - dis
          b.break()
        } else if (!p.contains(ans + dis)) {
          ans = ans + dis
          b.break()
        } else {
          dis += 1
        }
      }
    }

    println(ans)

  }

}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val X, N = sc.nextInt
  val p = Set.fill(N)(sc.nextInt)

  var i = 0
  var x = Int.MaxValue
  var z = 0
  do {
    if (!p.contains(X - i) && i < x) {
      x = i
      z = X - i
    } else if (!p.contains(X + i) && i < x) {
      x = i
      z = X + i
    }
    i += 1
  } while (x == Int.MaxValue)
  println(z)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val h, w, k = sc.nextInt()
  val x1, y1, x2, y2 = sc.nextInt()-1
  val c = Array.fill(h)(sc.next()).map(_.map(_ == '@').toArray)

  def compare(a: (Int, Int), b: (Int, Int)): Boolean = {
    if (a._1 == b._1) {
      a._2 < b._2
    } else {
      a._1 < b._1
    }
  }

  def shortestPath(sx: Int, sy: Int): Array[Array[Array[(Int, Int)]]] = {
    val sp = Array.fill(h, w, 4)((-1, 0))
    val dir = Array((1,0), (0,1), (-1,0), (0,-1))
    val heap = new BinaryHeap[(Int,Int,Int), (Int,Int)](4000000, compare)
    sp(sx)(sy)(0) = (0, 0)
    heap.add((sx, sy, 0), (0, 0))

    while (heap.nonEmpty) {
      val ((x1, y1, d1), (a, b)) = heap.pop()

      for (i <- -1 to 1) {
        val d2 = (d1+i+4) % 4
        val (x2, y2) = if (i == 0) {
          (x1 + dir(d2)._1, y1 + dir(d2)._2)
        } else {
          (x1, y1)
        }

        if (i != 0 || (0 <= x2 && x2 < h && 0 <= y2 && y2 < w && !c(x2)(y2))) {
          val costOld = sp(x2)(y2)(d2)
          val costNew = if (i == 0) {
            if (b == k-1) (a+1, 0) else (a, b+1)
          } else {
            if (b == 0) (a, 0) else (a+1, 0)
          }

          if (costOld._1 == -1) {
            sp(x2)(y2)(d2) = costNew
            heap.add((x2, y2, d2), costNew)
          } else if (compare(costNew, costOld)) {
            sp(x2)(y2)(d2) = costNew
            heap.upPriority((x2, y2, d2), costNew)
          }
        }
      }
    }
    sp
  }

  class BinaryHeap[A, P](maxSize: Int, comparator: (P, P) => Boolean) {
    private val heap = Array.ofDim[(A, P)](maxSize)
    private var indexMap = Map[A, Int]()

    var size = 0
    def isEmpty: Boolean = size == 0
    def nonEmpty: Boolean = !isEmpty

    private def par(idx: Int): Int = (idx - 1) / 2
    private def left(idx: Int): Int = 2 * idx + 1
    private def right(idx: Int): Int = 2 * idx + 2

    private def isRoot(idx: Int): Boolean = idx == 0
    private def hasLeft(idx: Int): Boolean = left(idx) < size
    private def hasRight(idx: Int): Boolean = right(idx) < size

    private def swap(i: Int, j: Int): Unit = {
      indexMap += heap(i)._1 -> j
      indexMap += heap(j)._1 -> i

      val t = heap(i)
      heap(i) = heap(j)
      heap(j) = t
    }

    private def upHeap(idx: Int): Unit = {
      if (!isRoot(idx) && comparator(heap(idx)._2, heap(par(idx))._2)) {
        swap(idx, par(idx))
        upHeap(par(idx))
      }
    }

    private def downHeap(idx: Int): Unit = {
      if (hasLeft(idx)) {
        val t = if (hasRight(idx) && comparator(heap(right(idx))._2, heap(left(idx))._2)) {
          right(idx)
        } else {
          left(idx)
        }
        if (comparator(heap(t)._2, heap(idx)._2)) {
          swap(idx, t)
          downHeap(t)
        }
      }
    }

    def add(a: A, p: P): Unit = {
      if (size >= maxSize) {
        throw new UnsupportedOperationException()
      } else {
        size += 1
        heap(size - 1) = (a, p)
        indexMap += a -> (size - 1)
        upHeap(size - 1)
      }
    }

    def pop(): (A, P) = {
      if (isEmpty) {
        throw new UnsupportedOperationException()
      } else {
        val head = heap(0)
        indexMap -= head._1
        heap(0) = heap(size - 1)
        size -= 1
        downHeap(0)
        head
      }
    }

    def upPriority(a: A, p: P): Unit = {
      val idx = indexMap(a)
      heap(idx) = (a, p)
      upHeap(idx)
    }
  }

  val sp = shortestPath(x1, y1)
  println(sp(x2)(y2).map{case (a, b) => a + (if (b == 0) 0 else 1)}.min)
}

Score : 600 points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..

In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

Constraints

1 \leq H,W,K \leq 10^6

H \times W \leq 10^6

1 \leq x_1,x_2 \leq H

1 \leq y_1,y_2 \leq W

x_1 \neq x_2 or y_1 \neq y_2.

c_{i,j} is . or @.

c_{x_1,y_1} = .

c_{x_2,y_2} = .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

H W K
x_1 y_1 x_2 y_2
c_{1,1}c_{1,2} .. c_{1,W}
c_{2,1}c_{2,2} .. c_{2,W}
:
c_{H,1}c_{H,2} .. c_{H,W}

Output

Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:

From (3, 2), go west one square to (3, 1).

From (3, 1), go north two squares to (1, 1).

From (1, 1), go east two squares to (1, 3).

From (1, 3), go east one square to (1, 4).

From (1, 4), go south two squares to (3, 4).

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val A, B = in.nextInt
  println(A * B)
}

Score : 100 points

Problem Statement

Compute A \times B.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the value A \times B as an integer.

Sample Input 1

2 5

Sample Output 1

10

We have 2 \times 5 = 10.

Sample Input 2

100 100

Sample Output 2

10000


//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
import scala.language.postfixOps

/**
  * 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 = {
    println(
      recursive(sc.nextLong())
        .filter(_ >= 2)
        .groupBy(identity)
        .map(_._2.length)
        .map(recursive2(_))
        .sum
    )
  }

  @scala.annotation.tailrec
  def recursive(N: Long, ret: List[Long] = List(), now: Long = 2): List[Long] = {
    if (N < now * now) ret :+ N
    else if (N % now == 0) recursive(N / now, ret :+ now, now)
    else recursive(N, ret, now + 1)
  }

  @scala.annotation.tailrec
  def recursive2(N: Long, now: Long = 1): Long = {
    if (N >= now) recursive2(N - now, now + 1)
    else now - 1
  }

  def flip(A: Array[Boolean], B: Array[(Int, Long)]): Array[(Int, Long)] = {
    B.map { case (index, _) =>
      (index, (if (0 < index && A(index - 1)) B(index - 1)._2 else 0L) + (if (index + 1 < B.length && !A(index + 1)) B(index + 1)._2 else 0L))
    }
  }

  val mod: Long = (1e9 + 7).toLong

  @scala.annotation.tailrec
  def factorial(now: Long, ans: Long = 1): Long = {
    if (now == 0) 0 else if (now == 1) ans else factorial(now - 1, now * ans)
  }

  implicit class implicitInt(val N: Int) {
    def times[B](function: Int => B): IndexedSeq[B] = (0 until N).map(function)
  }

  def calc(input: (Long, Long, Long, Long, Long, Long)): Long = {
    input match {
      case (a, b, c, x, y, z) =>
        var ans: Long = Long.MaxValue
        if (b >= 3 && (a >= 2 || c >= 2)) {
          ans = Math.min(ans, Math.max(a - (b - 1), 0) * x + Math.max(c - Math.min(a - 1, b - 2), 0) * z)
          ans = Math.min(ans, Math.max(a - Math.min(c - 1, b - 2), 0) * x + Math.max(c - (b - 1), 0) * z)
        }
        //        println(ans)
        if (b >= 2 && (a >= b && c >= b + 1)) {
          ans = Math.min(ans, y + Math.max(0, a - (c - 1)) * x)
        }
        //        println(ans)
        if (b >= 2 && (a >= b + 1 && c >= b)) {
          ans = Math.min(ans, y + Math.max(0, c - (a - 1)) * z)
        }
        //        println(ans)
        if (a >= 2 && c >= 2)
          if (a != c)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 1)) * y)
          else if (a >= 3 && c >= 3)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 2)) * y + Math.min(x, z))
        //        println(ans)
        if (ans == Long.MaxValue) ans = -1
        ans
    }
  }

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

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

  def getFibonacci(prevprev: Long = 0, prev: Long = 1): LazyList[Long] =
    LazyList.cons(prevprev, getFibonacci(prev, prevprev + prev))

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: LazyList[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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

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

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

 */

object ArabicRoman {

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

  private val codeTable: List[(Int, String)] = 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 =>

      @scala.annotation.tailrec
      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
    }
    } =>

      @scala.annotation.tailrec
      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 PowMod {
  def naivePowMod(a: Long, k: Long, m: Long): Long = {
    var t: Long = 1
    val aMod: Long = a % m

    for (_ <- 1L to k) {
      t = ((t % m) * aMod) % m
    }
    t.toInt
  }

  def powMod(a: Long, k: Long, m: Long): Long = {
    if (k == 0) 1
    else {
      val t = powMod(a, k / 2, m)
      if ((k % 2) == 0) (t * t) % m else (((t * t) % m) * a) % m
    }
  }
}

Score : 400 points

Problem Statement

Given is a positive integer N. Consider repeatedly applying the operation below on N:

First, choose a positive integer z satisfying all of the conditions below:

z can be represented as z=p^e, where p is a prime number and e is a positive integer;

z divides N;

z is different from all integers chosen in previous operations.

Then, replace N with N/z.

Find the maximum number of times the operation can be applied.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum number of times the operation can be applied.

Sample Input 1

24

Sample Output 1

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=12.)

Choose z=3 (=3^1). (Now we have N=4.)

Choose z=4 (=2^2). (Now we have N=1.)

Sample Input 2

1

Sample Output 2

0

We cannot apply the operation at all.

Sample Input 3

64

Sample Output 3

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=32.)

Choose z=4 (=2^2). (Now we have N=8.)

Choose z=8 (=2^3). (Now we have N=1.)

Sample Input 4

1000000007

Sample Output 4

1

We can apply the operation once by, for example, making the following choice:

z=1000000007 (=1000000007^1). (Now we have N=1.)

Sample Input 5

997764507000

Sample Output 5

7


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

  def factorize(n: Long): List[Long] = {
    if (n == 1) {
      Nil
    } else {
      var i = 2
      var d = 0
      while (i*i <= n && d == 0) {
        if (n % i == 0) d = i
        i += 1
      }
      if (d == 0) List(n) else d::factorize(n/d)
    }
  }

  val factorMap = factorize(n).groupBy(identity).view.mapValues(_.length).toMap
  val counts = factorMap.map{ case (p, k) =>
    var rest = k
    var e = 1
    var ans = 0
    while (e <= rest) {
      ans += 1
      rest -= e
      e += 1
    }
    ans
  }

  println(counts.sum)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val c = IndexedSeq.fill(n)((sc.nextInt(), sc.nextInt()))
  val a = c.map(_._1).sorted
  val b = c.map(_._2).sorted

  val amed = if (n % 2 == 1) a((n-1)/2) else a(n/2 - 1) + a(n/2)
  val bmed = if (n % 2 == 1) b((n-1)/2) else b(n/2 - 1) + b(n/2)
  println(bmed - amed + 1)
}

Score : 500 points

Problem Statement

There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i.
Find the number of different values that the median of X_1, X_2, \cdots, X_N can take.

Notes

The median of X_1, X_2, \cdots, X_N is defined as follows. Let x_1, x_2, \cdots, x_N be the result of sorting X_1, X_2, \cdots, X_N in ascending order.

If N is odd, the median is x_{(N+1)/2};

if N is even, the median is (x_{N/2} + x_{N/2+1}) / 2.

Constraints

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

1 \leq A_i \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

2
1 2
2 3

Sample Output 1

3

If X_1 = 1 and X_2 = 2, the median is \frac{3}{2};

if X_1 = 1 and X_2 = 3, the median is 2;

if X_1 = 2 and X_2 = 2, the median is 2;

if X_1 = 2 and X_2 = 3, the median is \frac{5}{2}.

Thus, the median can take three values: \frac{3}{2}, 2, and \frac{5}{2}.

Sample Input 2

3
100 100
10 10000
1 1000000000

Sample Output 2

9991


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 = in.next().toInt
  val A = new Array[Long](N+1)
  for (i <- 0 to N) {
    A(i) = in.next().toLong
  }

  //
  var flag = true
  val dpMax = new Array[Long](N+1)
  var cnt = 1L
  breakable {
    for (i <- 0 to N) {
      cnt -= A(i)
      if (cnt < 0) {
        flag = false
        break
      }

      dpMax(i) = cnt min (Long.MaxValue / 100)
      cnt *= 2
    }
  }

  if (!flag)
    println(-1)
  else if (N == 0) {
    if (A(0) == 1)
      println(1)
    else
      println(-1)
  }
  else  {
    var ans = 0L
    var nodes = 0L

    breakable {
      for (i <- (0 to N).reverse) {
        val now = A(i)

        if ((nodes+1) / 2 > dpMax(i)) {
          flag = false
          break
        }
        else {
          nodes = (nodes min dpMax(i)) + now
          ans += nodes
        }
      }
    }

    if (!flag)
      println(-1)
    else
      println(ans)
  }
}

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

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 : 600 points

Problem Statement

Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.

Notes

A binary tree is a rooted tree such that each vertex has at most two direct children.

A leaf in a binary tree is a vertex with zero children.

The depth of a vertex v in a binary tree is the distance from the tree's root to v. (The root has the depth of 0.)

The depth of a binary tree is the maximum depth of a vertex in the tree.

Constraints

0 \leq N \leq 10^5

0 \leq A_i \leq 10^{8} (0 \leq i \leq N)

A_N \geq 1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 A_2 \cdots A_N

Output

Print the answer as an integer.

Sample Input 1

3
0 1 1 2

Sample Output 1

7

Below is the tree with the maximum possible number of vertices. It has seven vertices, so we should print 7.

Sample Input 2

4
0 0 1 0 2

Sample Output 2

10

Sample Input 3

2
0 3 1

Sample Output 3

-1

Sample Input 4

1
1 1

Sample Output 4

-1

Sample Input 5

10
0 0 1 1 2 3 5 8 13 21 34

Sample Output 5

264


import java.util.Scanner

import scala.annotation.tailrec

object Main extends App {
  val sc = new Scanner(System.in)
  val N, M = sc.nextInt
  val graph = (0 until M).foldLeft(Vector.fill(N)(Vector.empty[Int])) { (acc, _) =>
    val A, B = sc.nextInt - 1
    acc.updated(A, acc(A) :+ B).updated(B, acc(B) :+ A)
  }

  val ps = loop(Vector.fill(N)(-1).updated(0, 0), graph(0).map(_ -> 0)).tail
  println("Yes")
  ps.foreach(p => println(p + 1))

  @tailrec def loop(acc: Vector[Int], nexts: Vector[(Int, Int)]): Vector[Int] = nexts match {
    case (room, prev) +: rest if acc(room) == -1 =>
      loop(acc.updated(room, prev), rest ++ graph(room).withFilter(r => acc(r) == -1).map(_ -> room))
    case _ +: rest =>
      loop(acc, rest)
    case _ => acc
  }

}

Score: 100 points

Problem Statement

The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.

When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a positive integer N not exceeding 999 is as follows:

hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;

pon when the digit in the one's place of N is 0, 1, 6 or 8;

bon when the digit in the one's place of N is 3.

Given N, print the pronunciation of "本" in the phrase "N 本".

Constraints

N is a positive integer not exceeding 999.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

16

Sample Output 1

pon

The digit in the one's place of 16 is 6, so the "本" in "16 本" is pronounced pon.

Sample Input 2

2

Sample Output 2

hon

Sample Input 3

183

Sample Output 3

bon


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val A, B, H, M = sc.nextDouble()
  val sideLength = (angle: Double) =>
    math.sqrt(A * A + B * B - 2 * A * B * math.cos(math.toRadians(angle)))
  val hourHandAngle = ((360.0 / (12 * 60.0)) * (H * 60 + M)) % 360.0
  val minuteHandAngle = ((360.0 / 60.0) * M) % 360.0
  println {
    math.abs(hourHandAngle - minuteHandAngle) match {
      case 0.0 => math.abs(A - B)
      case 180.0 => A + B
      case angle if 180.0 < angle => sideLength(360.0 - angle)
      case angle => sideLength(angle)
    }
  }
}

Score: 300 points

Problem Statement

Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.

An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to make one full rotation, respectively.

At 0 o'clock, the two hands overlap each other. H hours and M minutes later, what is the distance in centimeters between the unfixed endpoints of the hands?

Constraints

All values in input are integers.

1 \leq A, B \leq 1000

0 \leq H \leq 11

0 \leq M \leq 59

Input

Input is given from Standard Input in the following format:

A B H M

Output

Print the answer without units. Your output will be accepted when its absolute or relative error from the correct value is at most 10^{-9}.

Sample Input 1

3 4 9 0

Sample Output 1

5.00000000000000000000

The two hands will be in the positions shown in the figure below, so the answer is 5 centimeters.

Sample Input 2

3 4 10 40

Sample Output 2

4.56425719433005567605

The two hands will be in the positions shown in the figure below. Note that each hand always rotates at constant angular velocity.