import java.util.Scanner

import scala.collection.mutable

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

  val G = (AB ++ AB.map(_.swap)).groupBy(_._1).toSeq.sortBy(_._1).map(_._2.map(_._2))

  val X = Array.fill(N)(false)
  val Y = Array.fill(N)(-1)

  def BFS(x: Int): Unit = {
    val Q = new mutable.Queue[Int]()
    X(x - 1) = true
    Y(x - 1) = 0
    Q += x
    while (Q.nonEmpty) {
      val v = Q.dequeue
      X(v - 1) = true
      G(v - 1).foreach(i => {
        if (!X(i - 1)) {
          X(i - 1) = true
          Y(i - 1) = v
          Q += i
        }
      })
    }
  }
  BFS(1)

  println("Yes")
  Y.tail.foreach(println)
}

Score: 400 points

Problem Statement

There is a cave.

The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

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

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

A_i \neq B_i\ (1 \leq i \leq M)

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.

Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.

Starting in Room 4, you will reach Room 1 after traversing two passages: (4) \to 2 \to 1. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

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

Sample Output 2

Yes
6
5
5
1
1

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


import math._
import collection.mutable.{Map => MTMap}

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val c = Vector.fill(n)((sc.nextLong, sc.nextLong))

  val mod = 1000000007

  def plus(a: Long, b: Long): Long = (a + b) % mod
  def minus(a: Long, b: Long): Long = (a - b + mod) % mod
  def times(a: Long, b: Long): Long = (a * b) % mod

  def pow(a: Long, n: Long, res: Long = 1): Long = {
    if (n == 0) {
      res
    } else if ((n&1) == 0) {
      pow(times(a,a), n >> 1, res)
    } else {
      pow(times(a,a), n >> 1, times(a,res))
    }
  }

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

  val m = MTMap[(Long,Long), Long]()
  var z = 0

  for ((a,b) <- c) {
    if (a == 0 && b == 0) {
      z += 1
    } else {
      val d = gcd(a.abs, b.abs)
      if (b == 0) {
        m((1, 0)) = m.getOrElse((1, 0), 0L) + 1
      } else if (b > 0) {
        m((a / d, b / d)) = m.getOrElse((a / d, b / d), 0L) + 1
      } else {
        m((-a / d, -b / d)) = m.getOrElse((-a / d, -b / d), 0L) + 1
      }
    }
  }

  val bads = m.toList.collect{
    case ((a, b), l) if a > 0 && m.isDefinedAt((-b, a)) => (l, m((-b, a)))
  }

  val ans = minus(plus(times(
    pow(2, n - z - bads.map{case (x,y) => x+y}.sum),
    bads.map{case (x,y) => minus(plus(pow(2,x), pow(2,y)), 1)}.foldLeft(1L)(times(_,_))
  ), z), 1)

  println(ans)
}

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

Score: 500 points

Problem Statement

We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.

We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.

The i-th and j-th sardines (i \neq j) are on bad terms if and only if A_i \cdot A_j + B_i \cdot B_j = 0.

In how many ways can we choose the set of sardines to put into the cooler? Since the count can be enormous, print it modulo 1000000007.

Constraints

All values in input are integers.

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

-10^{18} \leq A_i, B_i \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the count modulo 1000000007.

Sample Input 1

3
1 2
-1 1
2 -1

Sample Output 1

5

There are five ways to choose the set of sardines, as follows:

The 1-st

The 1-st and 2-nd

The 2-nd

The 2-nd and 3-rd

The 3-rd

Sample Input 2

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

Sample Output 2

479

Submitted source-code file size, in bytes.

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

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


object Main extends App {
  val sc = new FastScanner(System.in)
  val n, m = sc.nextInt()
  var xs, ys = List[Int](0)
  var lx, ly = List[(Int, Int, Int)]()
  for (i <- 1 to n) {
    val a, b, c = sc.nextInt()
    lx ::= (a,b,c)
    xs ::= a
    xs ::= b
    ys ::= c
  }
  for (i <- 1 to m) {
    val d, e, f = sc.nextInt()
    ly ::= (d,e,f)
    xs ::= d
    ys ::= e
    ys ::= f
  }

  val xsSorted = xs.distinct.sorted.toVector
  val ysSorted = ys.distinct.sorted.toVector

  if (xsSorted.length == 1 || ysSorted.length == 1) {
    println("INF")
  } else {
    val h = xsSorted.length
    val w = ysSorted.length
    val xCmp = xsSorted.zipWithIndex.toMap
    val yCmp = ysSorted.zipWithIndex.toMap
    val lxCmp = lx.map{case (x1,x2,y) => (xCmp(x1),xCmp(x2),yCmp(y))}
    val lyCmp = ly.map{case (x,y1,y2) => (xCmp(x),yCmp(y1),yCmp(y2))}
    val xWidth = Array.fill(h-1)(0)
    val yWidth = Array.fill(w-1)(0)
    for (x <- 0 until h - 1) {
      xWidth(x) = xsSorted(x+1) - xsSorted(x)
    }
    for (y <- 0 until w - 1) {
      yWidth(y) = ysSorted(y+1) - xsSorted(y)
    }

    val visited = Array.fill(2 * h - 1, 2 * w - 1)(false)
    for {
      (x1,x2,y) <- lxCmp
      x <- 2 * x1 to 2 * x2
    } {
      visited(x)(y*2) = true
    }
    for {
      (x,y1,y2) <- lyCmp
      y <- 2 * y1 to 2 * y2
    } {
      visited(x*2)(y) = true
    }

    val xInit = xCmp(0) * 2
    val yInit = yCmp(0) * 2

    if (xInit == 0 || xInit == 2 * h - 2 || yInit == 0 || yInit == 2 * w - 2) {
      println("INF")
    } else {
      visited(xInit)(yInit) = true

      var ans = 0L
      var queue = List((xCmp(0) * 2, yCmp(0) * 2))
      val d = List((1,0),(-1,0),(0,1),(0,-1))
      while (queue.nonEmpty) {
        val (x,y) = queue.head
        queue = queue.tail
        for ((dx, dy) <- d) {
          val x1 = x + dx
          val y1 = y + dy
          if (!visited(x1)(y1)) {
            if (x1 == 0 || x1 == 2 * h - 2 || y1 == 0 || y1 == 2 * w - 2) {
              ans = -1
              queue = Nil
            } else {
              queue ::= (x1, y1)
              visited(x1)(y1) = true
              if (x1 % 2 == 1 && y1 % 2 == 1) {
                ans += xWidth(x1 / 2) * yWidth(y1 / 2)
              }
            }
          }
        }
      }

      println(if (ans == -1) "INF" else ans)
    }
  }
}

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

There is a grass field that stretches infinitely.

In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).

There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).

What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print INF instead.

Constraints

All values in input are integers between -10^9 and 10^9 (inclusive).

1 \leq N, M \leq 1000

A_i < B_i\ (1 \leq i \leq N)

E_j < F_j\ (1 \leq j \leq M)

The point (0, 0) does not lie on any of the given segments.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M

Output

If the area of the region the cow can reach is infinite, print INF; otherwise, print an integer representing the area in \mathrm{cm^2}.

(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)

Sample Input 1

5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4

Sample Output 1

13

The area of the region the cow can reach is 13\ \mathrm{cm^2}.

Sample Input 2

6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4

Sample Output 2

INF

The area of the region the cow can reach is infinite.


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N, M, X = sc.nextInt
  val CA = Array.fill(N, M + 1)(sc.nextInt)
  val C = CA.map(_.head)
  val A = CA.map(_.tail)

  val a = (0 until N).foldLeft(Set(Set.empty[Int])) {
    (set, element) => set union (set map (_ + element))
  }
  val b = a.toSeq.filter(xs => {
    xs.map(A(_)).foldLeft(Array.fill(M)(0))((x, y) => {
      (x zip y).map { case (x, y) => x + y }
    }).forall(_ >= X)
  })
  val c = b.map(_.map(C(_)).sum)
  val x = if (c.isEmpty) -1 else c.min
  println(x)
}

Score : 300 points

Problem

Takahashi, who is a novice in competitive programming, wants to learn M algorithms.
Initially, his understanding level of each of the M algorithms is 0.

Takahashi is visiting a bookstore, where he finds N books on algorithms.
The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M).
There is no other way to increase the understanding levels of the algorithms.

Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it.

Constraints

All values in input are integers.

1\leq N, M\leq 12

1\leq X\leq 10^5

1\leq C_i \leq 10^5

0\leq A_{i, j} \leq 10^5

Input

Input is given from Standard Input in the following format:

N M X
C_1 A_{1,1} A_{1,2} \cdots A_{1,M}
C_2 A_{2,1} A_{2,2} \cdots A_{2,M}
\vdots
C_N A_{N,1} A_{N,2} \cdots A_{N,M}

Output

If the objective is not achievable, print -1; otherwise, print the minimum amount of money needed to achieve it.

Sample Input 1

3 3 10
60 2 2 4
70 8 7 9
50 2 3 9

Sample Output 1

120

Buying the second and third books makes his understanding levels of all the algorithms 10 or higher, at the minimum cost possible.

Sample Input 2

3 3 10
100 3 1 4
100 1 5 9
100 2 6 5

Sample Output 2

-1

Buying all the books is still not enough to make his understanding levels of all the algorithms 10 or higher.

Sample Input 3

8 5 22
100 3 7 5 3 1
164 4 5 2 7 8
334 7 2 7 2 9
234 4 7 2 8 2
541 5 4 3 3 6
235 4 8 6 9 7
394 3 6 1 6 2
872 8 4 3 7 2

Sample Output 3

1067


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

  var caVector = Vector.empty[Vector[Int]]
  (1 to n).foreach { _ =>
    val ca =  scala.io.StdIn.readLine()
    val caArray =  ca.split(" ").map(_.toInt).toVector
    caVector :+= caArray
  }

  var resultVector = Vector.empty[Int]
  (1 to n).foreach { i =>
    caVector.combinations(i).foreach { cas =>
      var rikaiSum = scala.collection.mutable.Seq.empty[Int]
      cas.foreach { ca =>
        if (rikaiSum.length == 0) {
          rikaiSum = scala.collection.mutable.ListBuffer(ca.tail: _*)
        } else {
          (0 to m - 1).foreach { i =>
            rikaiSum(i) = rikaiSum(i) + ca(i + 1)
          }
        }

      }
      if (!rikaiSum.exists(r => r < x)) {
        resultVector :+= cas.map(ca => ca.head).sum
      }
    }
  }
  if (resultVector.length == 0) {
    println(-1)
  } else {
    println(resultVector.min)
  }
}


import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object Main extends App {
  val s = readLine
  val ans = if(s == "ARC")"ABC" else "ARC"
  println(ans)                       // 結果を出力する
}

Score : 100 points

Problem Statement

AtCoder Inc. holds a contest every Saturday.

There are two types of contests called ABC and ARC, and just one of them is held at a time.

The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.

Given a string S representing the type of the contest held last week, print the string representing the type of the contest held this week.

Constraints

S is ABC or ARC.

Input

Input is given from Standard Input in the following format:

S

Output

Print the string representing the type of the contest held this week.

Sample Input 1

ABC

Sample Output 1

ARC

They held an ABC last week, so they will hold an ARC this week.


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

  if (s == "ABC") {
    println("ARC")
  } else {
    println("ABC")
  }
}


import java.util.Scanner

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

  val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val sweets = Array.fill(k * 2)(readLine().split(" ").map(_.toInt))
    .zipWithIndex.collect {
    case (list, index) if index % 2 == 1 => list.map(_ - 1)
  }

  def solve() = {
    val hasSweetArr = Array.fill(n)(false)
    sweets.foreach { list =>
      list.foreach { i =>
        if(!hasSweetArr(i)) hasSweetArr(i) = true
      }
    }
    hasSweetArr.count(!_)
  }

  println(solve())

}

Score : 200 points

Problem Statement

N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town.

There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}.

Takahashi will walk around this town and make mischief on the Snukes who have no snacks. How many Snukes will fall victim to Takahashi's mischief?

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 100

1 \leq d_i \leq N

1 \leq A_{i, 1} < \cdots < A_{i, d_i} \leq N

Input

Input is given from Standard Input in the following format:

N K
d_1
A_{1, 1} \cdots A_{1, d_1}
\vdots
d_K
A_{K, 1} \cdots A_{K, d_K}

Output

Print the answer.

Sample Input 1

3 2
2
1 3
1
3

Sample Output 1

1

Snuke 1 has Snack 1.

Snuke 2 has no snacks.

Snuke 3 has Snack 1 and 2.

Thus, there will be one victim: Snuke 2.

Sample Input 2

3 3
1
3
1
3
1
3

Sample Output 2

2


import scala.io.StdIn._

object Helpers {
  def readIntLine = readLine.split(" ").map(_.toInt)
  def readInts(n: Int) = Array.fill(n)(readInt)

  def splitDigits(i: Int): Seq[Int] = i.toString.map(_.asDigit)

  def log[A](x: A): A = {println(x); x}

  implicit class IntImplicits(val i: Int) {
    def isEven = i % 2 == 0
    def isOdd = !isEven
  }
}

object Main extends App {
  import Helpers._

  val Array(n, m) = readIntLine
  val hs: Array[Int] = readIntLine

  var roads = Map[Int, Set[Int]]()
  for (_ <- Range(0, m)) {
    val Array(a, b) = readIntLine
    roads = if (roads.contains(a)) roads + (a -> (roads(a) + b)) else roads + (a -> Set(b))
    roads = if (roads.contains(b)) roads + (b -> (roads(b) + a)) else roads + (b -> Set(a))
  }

  def isGood(x: Int, roads: Map[Int, Set[Int]]): Boolean = {
    if (roads.contains(x + 1)) {
      val h = hs(x)
      !roads(x + 1).exists((a: Int) => (hs(a - 1) >= h))
    } else {
      true
    }
  }

  println(Range(0, n).count(isGood(_, roads)))
}

Score : 300 points

Problem Statement

There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i.
There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.

Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road.
Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road.

How many good observatories are there?

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq H_i \leq 10^9

1 \leq A_i,B_i \leq N

A_i \neq B_i

Multiple roads may connect the same pair of observatories.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
H_1 H_2 ... H_N
A_1 B_1
A_2 B_2
:
A_M B_M

Output

Print the number of good observatories.

Sample Input 1

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

Sample Output 1

2

From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good.

From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good.

From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good.

From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good.

Thus, the good observatories are Obs. 3 and 4, so there are two good observatories.

Sample Input 2

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

Sample Output 2

3


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

  val Array(n,m) = readLine.split(" ").map{_.toInt}.toArray
  val h = readLine.split(" ").map{_.toLong}.toList
  val ab = (for (i <- 1 to m) yield {
    val Array(a,b) = readLine.split(" ").map{_.toInt}.toArray
    (a,b)
  }).toList

  val sortedH = h.zipWithIndex.sortWith((x,y) => x._1 > y._1).map{case (x,y) => (x,y+1)}
  val check = Array.fill(n+1)(false)
  check(0) = true
  var ans = 0

  for (x <- sortedH if check.count{x => !x} != 0) {
    val i = x._2
    if (!check(i)) {
      ans += 1
      check(i) = true
    }
    ab.filter{case (a,b) => a == i || b == i}.map{case (a,b) => if (a == i) b else a}.foreach{i => check(i) = true}
  }

  println(ans)

}


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

object Main extends App with StdInHelper {
  val Array(n, m) = readInts
  val map = readLongs.zipWithIndex.map { case (h, i) => (i + 1, h) }.toMap
  var hs = (1 to n).toIndexedSeq

  var res = 0L
  for (_ <- 1 to m) {
    val Array(a, b) = readInts
    if (map(a) < map(b)) hs = hs.filterNot(_ == a)
    else hs = hs.filterNot(_ == b)
  }
  println(hs.length)
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
}


import java.util.Scanner

object Main extends App {
  val ABC = Array("A", "B", "C")
  def printABC(n: Int): Unit = {
    println(ABC(n))
  }

  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val (a, b, c) = (sc.nextInt(), sc.nextInt(), sc.nextInt())
  val ss = (1 to n).map { _ =>
    val s = sc.next()
    S.find(s)
  }

  var state = State(Array(a, b, c), Nil)
  ss.zipWithIndex.foreach { case (s, idx) =>
    val Array(i, j) = s.target
    if(state(i) + state(j) <= 0) {
      println("No")
      sys.exit(0)
    }
    state = if(state(i) == 0) state.add(i, j)
    else if(state(j) == 0) state.add(j, i)
    else {
      ss.lift(idx + 1).fold { state.add(i, j) } { nextS =>
        if(nextS.target.contains(i)) state.add(i, j) else state.add(j, i)
      }
    }
  }
  println("Yes")
  state.result.reverse.foreach(printABC)

}

case class State(ary: Array[Int], result: List[Int]) {
  def add(incr: Int, decr: Int): State = {
    val nextAry = ary.clone()
    nextAry(incr) += 1
    nextAry(decr) -= 1
    State(nextAry, incr :: result)
  }

  def apply(n: Int): Int = ary(n)
}

sealed abstract class S {
  lazy val name: String = getClass.getSimpleName.init

  def target: Array[Int]

  def dup(s: S): Int = (target.toSet & s.target.toSet).head
}

object S {
  case object AB extends S {
    override val target: Array[Int] = Array(0, 1)
  }

  case object AC extends S {
    override val target: Array[Int] = Array(0, 2)
  }

  case object BC extends S {
    override val target: Array[Int] = Array(1, 2)
  }

  val values: Seq[S] = AB :: AC :: BC :: Nil
  def find(name: String): S = values.find(_.name == name).get
}

Score : 600 points

Problem Statement

There is a game that involves three variables, denoted A, B, and C.

As the game progresses, there will be N events where you are asked to make a choice.
Each of these choices is represented by a string s_i. If s_i is AB, you must add 1 to A or B then subtract 1 from the other; if s_i is AC, you must add 1 to A or C then subtract 1 from the other; if s_i is BC, you must add 1 to B or C then subtract 1 from the other.

After each choice, none of A, B, and C should be negative.

Determine whether it is possible to make N choices under this condition. If it is possible, also give one such way to make the choices.

Constraints

1 \leq N \leq 10^5

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

N, A, B, C are integers.

s_i is AB, AC, or BC.

Input

Input is given from Standard Input in the following format:

N A B C
s_1
s_2
:
s_N

Output

If it is possible to make N choices under the condition, print Yes; otherwise, print No.

Also, in the former case, show one such way to make the choices in the subsequent N lines. The (i+1)-th line should contain the name of the variable (A, B, or C) to which you add 1 in the i-th choice.

Sample Input 1

2 1 3 0
AB
AC

Sample Output 1

Yes
A
C

You can successfully make two choices, as follows:

In the first choice, add 1 to A and subtract 1 from B. A becomes 2, and B becomes 2.

In the second choice, add 1 to C and subtract 1 from A. C becomes 1, and A becomes 1.

Sample Input 2

3 1 0 0
AB
BC
AB

Sample Output 2

No

Sample Input 3

1 0 9 0
AC

Sample Output 3

No

Sample Input 4

8 6 9 1
AC
BC
AB
BC
AC
BC
AB
AB

Sample Output 4

Yes
C
B
B
C
C
B
A
A


import scala.io.StdIn.readLine

object Main extends App {
  val k = readLine.toInt
  val a = readLine.split(" ").map(x => x.toInt)
  println(if ((a(0) - 1) / k != a(1) / k) "OK" else "NG")
}

Score: 100 points

Problem Statement

Takahashi the Jumbo will practice golf.

His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).

If he can achieve the objective, print OK; if he cannot, print NG.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 1000

1 \leq K \leq 1000

Input

Input is given from Standard Input in the following format:

K
A B

Output

If he can achieve the objective, print OK; if he cannot, print NG.

Sample Input 1

7
500 600

Sample Output 1

OK

Among the multiples of 7, for example, 567 lies between 500 and 600.

Sample Input 2

4
5 7

Sample Output 2

NG

No multiple of 4 lies between 5 and 7.

Sample Input 3

1
11 11

Sample Output 3

OK


//import java.util.Scanner

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

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

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

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

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

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

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

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

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

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

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

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

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

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

class IUnionFind(val size: Int) {

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

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

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

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

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

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

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

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

object Main {
  def solve(sc: => Scanner): Unit = {
    println(recursive(sc.nextLong()))
  }

  @scala.annotation.tailrec
  def recursive(X: Long, now: Long = 100, ans: Long = 0): Long = {
    if (now >= X) ans
    else recursive(X, (now * 1.01).toLong, ans + 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 : 200 points

Problem Statement

Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.

The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)

Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or above for the first time?

Constraints

101 \le X \le 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of years it takes for Takahashi's balance to reach X yen or above for the first time.

Sample Input 1

103

Sample Output 1

3

The balance after one year is 101 yen.

The balance after two years is 102 yen.

The balance after three years is 103 yen.

Thus, it takes three years for the balance to reach 103 yen or above.

Sample Input 2

1000000000000000000

Sample Output 2

3760

Sample Input 3

1333333333

Sample Output 3

1706


import java.util.Scanner

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

    val a = (1 to 4).flatMap(_ => 1 to m).combinations(n)

    def f(v: Seq[Int]): Int = {
      qs.map { case (a, b, c, d) =>
        val ba = v(b - 1) - v(a - 1)
        if (ba == c) d else 0
      }.sum
    }

    val res = a.map(f)
    println(res.max)

  }
}

Score : 300 points

Problem Statement

Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).

Consider a sequence A satisfying the following conditions:

A is a sequence of N positive integers.

1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.

Let us define a score of this sequence as follows:

The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)

Find the maximum possible score of A.

Constraints

All values in input are integers.

2 ≤ N ≤ 10

1 \leq M \leq 10

1 \leq Q \leq 50

1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )

0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )

(a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)

1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )

Input

Input is given from Standard Input in the following format:

N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q

Output

Print the maximum possible score of A.

Sample Input 1

3 4 3
1 3 3 100
1 2 2 10
2 3 2 10

Sample Output 1

110

When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110.

Sample Input 2

4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328

Sample Output 2

357500

Sample Input 3

10 10 1
1 10 9 1

Sample Output 3

1


import java.util.Scanner

import scala.collection.mutable
import scala.math._

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

    val sc = new Scanner(System.in)
    val n, m, q = sc.nextInt()
    val qs = Vector.fill(q)((sc.nextInt(), sc.nextInt(), sc.nextInt(), sc.nextInt()))

    val a = (1 to m).combinations(n).map(_.sorted).toSeq

    def f(v: Seq[Int]): Int = {
      qs.map { case (a, b, c, d) =>
        if (v(b - 1) - v(a - 1) == c) d else 0
      }.sum
    }

    val res = a.map(f)
    println(res.max)

  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val m = sc.nextInt
    val q = sc.nextInt
    val a = Array.ofDim[Int](q)
    val b = Array.ofDim[Int](q)
    val c = Array.ofDim[Int](q)
    val d = Array.ofDim[Int](q)
    (0 until q).foreach { i =>
      a(i) = sc.nextInt
      b(i) = sc.nextInt
      c(i) = sc.nextInt
      d(i) = sc.nextInt
    }

    println(new QC(n, m, q, a, b, c, d).solve)
  }
}

class QC(n: Int, m: Int, q: Int, a: Array[Int], b: Array[Int], c: Array[Int], d: Array[Int]) {
  def solve: Int = {
    val array = Array.fill[Int](n)(1)
    var ans = 0
    var break = false

    def countup(index: Int, indexUp: Boolean): Unit = {
      if (array(index) < m) {
        val next = array(index) + 1
        if (indexUp) {
          (index until n).foreach(array(_) = next)
        } else {
          array(index) = next
        }
      } else {
        countup(index - 1, true)
      }
    }

    while (!break) {
      ans = Math.max(ans, calc(array))
      break = array(0) == m
      if(!break) {
        countup(n - 1, false)
      }
    }
    ans
  }

  private def calc(array: Array[Int]) = {
    (0 until q).foldLeft(0) { (acc, cur) =>
      if (array(b(cur) - 1) - array(a(cur) - 1) equals c(cur)) {
        acc + d(cur)
      } else {
        acc
      }
    }
  }
}


import scala.util.control.Breaks

object Main extends App {
  val nmq =  scala.io.StdIn.readLine()
  val nmqArray = nmq.split(" ").map(_.toInt).toSeq
  val n = nmqArray(0)
  val m = nmqArray(1)
  val q = nmqArray(2)

  var abcdVector = Vector.empty[Vector[Int]]
  (1 to q).foreach { _ =>
    val a =  scala.io.StdIn.readLine()
    abcdVector :+= a.split(" ").map(_.toInt).toVector
  }
  val max = abcdVector.map(a => a(3)).sum
  var tempMax = 0

  def getInitialAArray(): scala.collection.mutable.Seq[Int] = {
    var returnSeq = scala.collection.mutable.Seq.empty[Int]
    (1 to n).foreach { _=>
      returnSeq :+= 1
    }
    returnSeq
  }
  var aSeq = getInitialAArray()

  val break = new Breaks
  break.breakable {
    (0 to n - 1).foreach { i =>
      kensyou(i)
    }

    def kensyou(index: Int): Unit = {
      if(index == 0) {
        (1 to m).foreach { i =>
          aSeq(n - 1) = i
          calc(aSeq)
        }
      } else {
        (1 to m).foreach { i =>
          aSeq(n - 1 - index) = i
          kensyou(index - 1)
        }
      }
    }

    def calc(kensyouArray: scala.collection.mutable.Seq[Int]) = {
      var tempCalc = 0
      abcdVector.foreach { abcd =>
        if (kensyouArray(abcd(1) - 1) - kensyouArray(abcd(0) - 1) == abcd(2)) {
          tempCalc = tempCalc + abcd(3)
        }
      }

      if(tempCalc == max) {
        tempMax = tempCalc
        break.break()
      } else if(tempCalc > tempMax) {
        tempMax = tempCalc
      }
    }
  }

  println(tempMax)
}


import java.util.Scanner

import scala.io.StdIn._

object Main extends App {

  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)

  def solve() = {
    val arr = Array.fill(n)(0)
    A.foreach { i =>
      arr(i-1) += 1
    }
    arr.mkString("\n")
  }

  println(solve())

}

Score : 300 points

Problem Statement

A company has N members, who are assigned ID numbers 1, ..., N.

Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number.

When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X.

You are given the information that the immediate boss of the member numbered i is the member numbered A_i. For each member, find how many immediate subordinates it has.

Constraints

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

1 \leq A_i < i

Input

Input is given from Standard Input in the following format:

N
A_2 ... A_N

Output

For each of the members numbered 1, 2, ..., N, print the number of immediate subordinates it has, in its own line.

Sample Input 1

5
1 1 2 2

Sample Output 1

2
2
0
0
0

The member numbered 1 has two immediate subordinates: the members numbered 2 and 3.

The member numbered 2 has two immediate subordinates: the members numbered 4 and 5.

The members numbered 3, 4, and 5 do not have immediate subordinates.

Sample Input 2

10
1 1 1 1 1 1 1 1 1

Sample Output 2

9
0
0
0
0
0
0
0
0
0

Sample Input 3

7
1 2 3 4 5 6

Sample Output 3

1
1
1
1
1
1
0


import java.util.Scanner

object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val a = sc.nextInt //最初の整数が読み込まれる

    var b = 0

    (1 to a).foreach{j =>
      j match{
      	case j if j%15 == 0 => b = b
        case j if j%3 == 0 => b = b
        case j if j%5 == 0 => b = b
        case _ => b = b + j
      }
    }
     println(b)
  }
}

Score : 200 points

Problem Statement

Let us define the FizzBuzz sequence a_1,a_2,... as follows:

If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.

If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.

If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.

If none of the above holds, a_i=i.

Find the sum of all numbers among the first N terms of the FizzBuzz sequence.

Constraints

1 \leq N \leq 10^6

Input

Input is given from Standard Input in the following format:

N

Output

Print the sum of all numbers among the first N terms of the FizzBuzz sequence.

Sample Input 1

15

Sample Output 1

60

The first 15 terms of the FizzBuzz sequence are:

1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}

Among them, numbers are 1,2,4,7,8,11,13,14, and the sum of them is 60.

Sample Input 2

1000000

Sample Output 2

266666333332

Watch out for overflow.


object Main{
	private[this] val s = new java.util.Scanner(System.in)
	def main(args:Array[String]) {
		val n=s.nextInt
		println((1L to n).filter(i => i % 5 != 0 && i % 3 != 0).sum)
	}
}


import scala.io.StdIn._
object Main extends App{
  val N = readLine().toInt

  var sum = 0L
  (1 to N).foreach(i =>{
    if(i % 3 == 0 || i % 5 == 0){
    }else{
      sum = sum + i
    }
  })
  println(sum)
}


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

object Main extends App {
  val arr = readLine.split(" ")
  val n   = arr(0).toLong
  val k   = arr(1).toLong

  require(0 <= n && n <= pow(10, 18))
  require(1 <= k && n <= pow(10, 18))

  val a = n % k
  val b = k - a

  if (a > b) println(b) else print(a)
}

Score : 300 points

Problem Statement

Given any integer x, Aoki can do the operation below.

Operation: Replace x with the absolute difference of x and K.

You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

Constraints

0 ≤ N ≤ 10^{18}

1 ≤ K ≤ 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible value taken by N after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, N=7.

After one operation, N becomes |7-4| = 3.

After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.

Sample Input 2

2 6

Sample Output 2

2

N=2 after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n, k = sc.nextLong()
    println(math.min(n % k, math.abs(n % k - k)))
  }
}


object Main extends App {
  val input = readLine
  val n = input.split(" ")(0).toLong
  val k = input.split(" ")(1).toLong

  if(n == k) println(0)
  else if(n < k) {
    println(Array(n, (n-k).abs).min)
  } else if(k < n) {
    println(Array(n%k, k-(n%k)).min)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn._
    val Array(n, k, c, _*) = readLine().split(' ').map(_.toInt)
    def check(comb: List[Int], pre: Int): Boolean =
      comb match {
        case Nil => true
        case head :: tail =>
          if (head <= pre + c) false
          else check(tail, head)
      }
    val possibleDate = readLine().zipWithIndex.collect {
      case ('o', i) => i + 1
    }
      .combinations(k)
      .collect {
        case comb if check(comb.toList, -c) =>
          comb.toSet
      }
    if (possibleDate.nonEmpty) {
      val dates = possibleDate.reduce(_ intersect _)
      dates.toList.foreach(println)
    }
  }
}

Score : 500 points

Problem Statement

Takahashi has decided to work on K days of his choice from the N days starting with tomorrow.

You are given an integer C and a string S. Takahashi will choose his workdays as follows:

After working for a day, he will refrain from working on the subsequent C days.

If the i-th character of S is x, he will not work on Day i, where Day 1 is tomorrow, Day 2 is the day after tomorrow, and so on.

Find all days on which Takahashi is bound to work.

Constraints

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

1 \leq K \leq N

0 \leq C \leq N

The length of S is N.

Each character of S is o or x.

Takahashi can choose his workdays so that the conditions in Problem Statement are satisfied.

Input

Input is given from Standard Input in the following format:

N K C
S

Output

Print all days on which Takahashi is bound to work in ascending order, one per line.

Sample Input 1

11 3 2
ooxxxoxxxoo

Sample Output 1

6

Takahashi is going to work on 3 days out of the 11 days. After working for a day, he will refrain from working on the subsequent 2 days.

There are four possible choices for his workdays: Day 1,6,10, Day 1,6,11, Day 2,6,10, and Day 2,6,11.

Thus, he is bound to work on Day 6.

Sample Input 2

5 2 3
ooxoo

Sample Output 2

1
5

There is only one possible choice for his workdays: Day 1,5.

Sample Input 3

5 1 0
ooooo

Sample Output 3

There may be no days on which he is bound to work.

Sample Input 4

16 4 3
ooxxoxoxxxoxoxxo

Sample Output 4

11
16


object Main extends App{
    val sc=new java.util.Scanner(System.in)
    val s=sc.next
    val res=if(s(2)==s(3)&&s(4)==s(5))"Yes" else "No"
    println(res)
}

Score : 100 points

Problem Statement

A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.

Given a string S, determine whether it is coffee-like.

Constraints

S is a string of length 6 consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is coffee-like, print Yes; otherwise, print No.

Sample Input 1

sippuu

Sample Output 1

Yes

In sippuu, the 3-rd and 4-th characters are equal, and the 5-th and 6-th characters are also equal.

Sample Input 2

iphone

Sample Output 2

No

Sample Input 3

coffee

Sample Output 3

Yes


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

  	val k = readLine.split(" ").head.toInt;
  	val homes =readLine.split(" ").map(_.toInt).toList;
  	println((k - (homes zip (homes.tail :+ homes.head)).map{case (x, y) => scala.math.abs(y - x)}.max).toString)
}

Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

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

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.


import scala.io.StdIn._

object Main extends App {

  val Array(k, n) = readLine.split(" ").map(_.toInt)

  val points = readLine.split(" ").map(_.toInt)

  val distances = points.zipWithIndex.map { case (pos, idx) =>
      if (idx == 0) (k - points(points.length - 1)) + pos
      else pos - points(idx - 1)
  }

  val maxDis = distances.zipWithIndex.maxBy { case (dis, _) => dis }._1

  println(k - maxDis)
}


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

  println(n * (n - 1) / 2 + m * (m - 1) / 2)
}

Score : 100 points

Problem Statement

We have N+M balls, each of which has an integer written on it.

It is known that:

The numbers written on N of the balls are even.

The numbers written on M of the balls are odd.

Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.

It can be shown that this count does not depend on the actual values written on the balls.

Constraints

0 \leq N,M \leq 100

2 \leq N+M

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

2 1

Sample Output 1

1

For example, let us assume that the numbers written on the three balls are 1,2,4.

If we choose the two balls with 1 and 2, the sum is odd;

If we choose the two balls with 1 and 4, the sum is odd;

If we choose the two balls with 2 and 4, the sum is even.

Thus, the answer is 1.

Sample Input 2

4 3

Sample Output 2

9

Sample Input 3

1 1

Sample Output 3

0

Sample Input 4

13 3

Sample Output 4

81

Sample Input 5

0 3

Sample Output 5

3


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

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

    def isPalindrome(s: String): Boolean = {
      s == s.reverse
    }

    out.println({
      if (isPalindrome(s) &&
        isPalindrome(s.substring(0, (s.length - 1) / 2)) &&
        isPalindrome(s.substring((s.length + 3) / 2 - 1))) {
        "Yes"
      } else {
        "No"
      }
    })

    out.flush()
  }
}

Score : 200 points

Problem Statement

A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied:

S is a palindrome.

Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome.

The string consisting of the (N+3)/2-st through N-th characters of S is a palindrome.

Determine whether S is a strong palindrome.

Constraints

S consists of lowercase English letters.

The length of S is an odd number between 3 and 99 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

If S is a strong palindrome, print Yes;
otherwise, print No.

Sample Input 1

akasaka

Sample Output 1

Yes

S is akasaka.

The string formed by the 1-st through the 3-rd characters is aka.

The string formed by the 5-th through the 7-th characters is aka.
All of these are palindromes, so S is a strong palindrome.

Sample Input 2

level

Sample Output 2

No

Sample Input 3

atcoder

Sample Output 3

No


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N = in.nextInt
  val counts = Array.fill(N + 1)(0L)
  val As = Array.fill(N)(in.nextInt)
  As.foreach(a => counts(a) += 1)
  val pairs = counts.map(c => c * (c - 1) / 2)
  val sum = pairs.sum
  val results = counts.map(c => sum - c * (c - 1) / 2 + (if (c > 0) (c - 1) * (c - 2) / 2 else 0))
  println(As.map(a => results(a)).mkString("\n"))
}

Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

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

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5


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

	val n = Scanner.nextInt()
	val a = Array.fill(n)(Scanner.nextInt() - 1)

	val m = Array.fill(n)(0)
	loop(0, n-1) { i => m(a(i)) += 1 }

	val ans = m.map(e => e * (e-1) / 2).sum

	loop(0, n-1) { i => pw.println(ans - m(a(i)) + 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 scala.math.round

object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val H = sc.nextLong()
  val W = sc.nextLong()

  println(round(H * W / 2))

}

Score : 200 points

Problem Statement

We have a board with H horizontal rows and W vertical columns of squares.
There is a bishop at the top-left square on this board.
How many squares can this bishop reach by zero or more movements?

Here the bishop can only move diagonally.
More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:

r_1 + c_1 = r_2 + c_2

r_1 - c_1 = r_2 - c_2

For example, in the following figure, the bishop can move to any of the red squares in one move:

Constraints

1 \leq H, W \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H \ W

Output

Print the number of squares the bishop can reach.

Sample Input 1

4 5

Sample Output 1

10

The bishop can reach the cyan squares in the following figure:

Sample Input 2

7 3

Sample Output 2

11

The bishop can reach the cyan squares in the following figure:

Sample Input 3

1000000000 1000000000

Sample Output 3

500000000000000000


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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
  import java.util.Arrays.sort

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

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val H, W = nl()
    if (H == 1 || W == 1) out.println(1)
    else {
      val ans = if (H * W % 2 == 1) H * W / 2 + 1 else H * W / 2
      out.println(ans)
    }
  }
}


object Main extends App {
  val in = readLine

  val ptn = "(hi)+".r
  val t = if( in.matches("(hi)+") ) "Yes" else "No"
  println(t)
}

Score : 100 points

Problem Statement

A Hitachi string is a concatenation of one or more copies of the string hi.

For example, hi and hihi are Hitachi strings, while ha and hii are not.

Given a string S, determine whether S is a Hitachi string.

Constraints

The length of S is between 1 and 10 (inclusive).

S is a string consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a Hitachi string, print Yes; otherwise, print No.

Sample Input 1

hihi

Sample Output 1

Yes

hihi is the concatenation of two copies of hi, so it is a Hitachi string.

Sample Input 2

hi

Sample Output 2

Yes

Sample Input 3

ha

Sample Output 3

No


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

  val m = readLine.split(" ")(2).toInt
  val a = readLine.split(" ").map(_.toInt)
  val b = readLine.split(" ").map(_.toInt)

  val coupons = (1 to m).map(x => readLine).map(_.split(" ").map(_.toInt))
  val buys = coupons.map(x => (a(x(0)) + b(x(1)) - x(2)))
  println( ((a.min+b.min) +: buys).min.toString)
}

Score : 200 points

Problem Statement

You are visiting a large electronics store to buy a refrigerator and a microwave.

The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen.

You have M discount tickets. With the i-th ticket ( 1 \le i \le M ), you can get a discount of c_i yen from the total price when buying the x_i-th refrigerator and the y_i-th microwave together. Only one ticket can be used at a time.

You are planning to buy one refrigerator and one microwave. Find the minimum amount of money required.

Constraints

All values in input are integers.

1 \le A \le 10^5

1 \le B \le 10^5

1 \le M \le 10^5

1 \le a_i , b_i , c_i \le 10^5

1 \le x_i \le A

1 \le y_i \le B

c_i \le a_{x_i} + b_{y_i}

Input

Input is given from Standard Input in the following format:

A B M
a_1 a_2 ... a_A
b_1 b_2 ... b_B
x_1 y_1 c_1
\vdots
x_M y_M c_M

Output

Print the answer.

Sample Input 1

2 3 1
3 3
3 3 3
1 2 1

Sample Output 1

5

With the ticket, you can get the 1-st refrigerator and the 2-nd microwave for 3+3-1=5 yen.

Sample Input 2

1 1 2
10
10
1 1 5
1 1 10

Sample Output 2

10

Note that you cannot use more than one ticket at a time.

Sample Input 3

2 2 1
3 5
3 5
2 2 2

Sample Output 3

6

You can get the 1-st refrigerator and the 1-st microwave for 6 yen, which is the minimum amount to pay in this case.
Note that using a ticket is optional.


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val S = sc.next()
  println(if (S == "AAA" || S == "BBB") "No" else "Yes")
}

Score : 100 points

Problem Statement

In AtCoder City, there are three stations numbered 1, 2, and 3.

Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is A, Company A operates Station i; if S_i is B, Company B operates Station i.

To improve the transportation condition, for each pair of a station operated by Company A and one operated by Company B, there will be a bus service connecting them.

Determine if there is a pair of stations that will be connected by a bus service.

Constraints

Each character of S is A or B.

|S| = 3

Input

Input is given from Standard Input in the following format:

S

Output

If there is a pair of stations that will be connected by a bus service, print Yes; otherwise, print No.

Sample Input 1

ABA

Sample Output 1

Yes

Company A operates Station 1 and 3, while Company B operates Station 2.

There will be a bus service between Station 1 and 2, and between Station 2 and 3, so print Yes.

Sample Input 2

BBA

Sample Output 2

Yes

Company B operates Station 1 and 2, while Company A operates Station 3.

There will be a bus service between Station 1 and 3, and between Station 2 and 3, so print Yes.

Sample Input 3

BBB

Sample Output 3

No

Company B operates all the stations. Thus, there will be no bus service, so print No.


object Main extends App {
  val s = io.StdIn.readLine()
  println(if (s.forall(_ == 'A') || s.forall(_ == 'B')) "No" else "Yes")
}


object Main extends App {
  @scala.annotation.tailrec
  def loop(n: Long, a: Long, b: Long, acc: Long): Long =
    if (n <= 0) acc else if (n < a) acc + n else loop(n - a - b, a, b, acc + a)
  val sc = new java.util.Scanner(System.in)
  val N, A, B = sc.nextLong()
  println(if (A == 0) 0 else loop(N, A, B, 0))
}

Score : 200 points

Problem Statement

Takahashi has many red balls and blue balls. Now, he will place them in a row.

Initially, there is no ball placed.

Takahashi, who is very patient, will do the following operation 10^{100} times:

Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.

How many blue balls will be there among the first N balls in the row of balls made this way?

Constraints

1 \leq N \leq 10^{18}

A, B \geq 0

0 < A + B \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of blue balls that will be there among the first N balls in the row of balls.

Sample Input 1

8 3 4

Sample Output 1

4

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

Sample Input 2

8 0 4

Sample Output 2

0

He placed only red balls from the beginning.

Sample Input 3

6 2 4

Sample Output 3

2

Among bbrrrr, there are two blue balls.


object Main extends App {
  import scala.io.StdIn._
  val Array(n,a,b) = readLine().split(" ").map(_.toLong)
  println(n / (a+b)*a + Math.min(a, n%(a+b)))
}


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


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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val a, b = sc.nextInt()

    var ans = 1
    var flg = false
    while (!flg && ans <= 10000) {
      val taxA = (ans * 0.08).toInt
      val taxB = (ans * 0.1).toInt
      if (taxA == a && taxB == b) {
        flg = true
      } else {
        ans += 1
      }
    }

    println(if (flg) ans else -1)
  }
}

Score : 300 points

Problem Statement

Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)

Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.

If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

Constraints

1 \leq A \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

Sample Input 1

2 2

Sample Output 1

25

If the price of a product before tax is 25 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2 yen.

When the consumption tax rate is 10 percent: \lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2 yen.

Thus, the price of 25 yen satisfies the condition. There are other possible prices, such as 26 yen, but print the minimum such price, 25.

Sample Input 2

8 10

Sample Output 2

100

If the price of a product before tax is 100 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 100 \times 0.08 \rfloor = 8 yen.

When the consumption tax rate is 10 percent: \lfloor 100 \times 0.1 \rfloor = 10 yen.

Sample Input 3

19 99

Sample Output 3

-1

There is no price before tax satisfying this condition, so print -1.


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

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    var s = in.readLine()
    val q = in.readLine().toInt

    var reverse = false

    for {
      _ <- 0 until q
    } {
      in.readLine().split("\\s+") match {
        case Array("1") =>
          reverse = !reverse
        case Array("2", f, c) =>
          if (f == "1" && !reverse || f == "2" && reverse) {
            s = "" + c + s
          } else {
            s = s + c
          }
      }
    }

    out.println(
      if (reverse) {
        s.reverse
      } else {
        s
      }
    )
    out.flush()
  }
}

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

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

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


import io.StdIn._

object Main extends App {
  val line1 = readLine.split(" ").map(_.toInt)
  val N = line1(0)
  val P = line1(1)

  val S = readLine.toCharArray.map(_.toInt - 48)

  val d = Array.fill[Int](N + 1)(0)
  var ten = 1
  for (i <- N - 1 to 0 by -1) {
    val a = S(i) * ten % P
    d(i) = (d(i + 1) + a) % P
    ten = ten * 10 % P
  }

  val cnt = Array.fill[Int](P)(0)
  var ans = 0L
  for (i <- N to 0 by -1) {
    ans = ans + cnt(d(i))
    cnt(d(i)) = cnt(d(i)) + 1
  }

  println(ans)
}

Score : 500 points

Problem Statement

Takahashi has a string S of length N consisting of digits from 0 through 9.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

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

S consists of digits.

|S| = N

2 \leq P \leq 10000

P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:

3: divisible by 3.

35: not divisible by 3.

354: divisible by 3.

3543: divisible by 3.

5: not divisible by 3.

54: divisible by 3.

543: divisible by 3.

4: not divisible by 3.

43: not divisible by 3.

3: divisible by 3.

Six of these are divisible by 3, so print 6.

Sample Input 2

4 2
2020

Sample Output 2

10

Here S = 2020. There are ten non-empty (contiguous) substrings of S, all of which are divisible by 2, so print 10.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68


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

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = in.readLine().toInt

    out.println(
      n / 2 + n % 2
    )
    out.flush()
  }
}

Score : 100 points

Problem Statement

Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

N is an integer.

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50


object Main extends App{
    val a = for(_ <- 1 to 3) yield scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val b = for(_ <- 1 to scala.io.StdIn.readInt) yield scala.io.StdIn.readInt
    val a_series = a.reduce(_ ++: _)
    val hit = for(count <- a_series) yield b.contains(count)
    val yoko = hit.grouped(3).map(e1 => e1.forall(e2 => e2 == true)).reduce(_ || _)
    val tate = (0 to 6 by 3).map(hit(_)).forall(_ == true) || (1 to 7 by 3).map(hit(_)).forall(_ == true) || (2 to 8 by 3).map(hit(_)).forall(_ == true)
    val name = (0 to 8 by 4).map(hit(_)).forall(_ == true) || (2 to 6 by 2).map(hit(_)).forall(_ == true)
    if(yoko || tate || name) println("Yes") else println("No")
}

Score : 200 points

Problem Statement

We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.

The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

1 \leq A_{i, j} \leq 100

A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))

1 \leq N \leq 10

1 \leq b_i \leq 100

b_i \neq b_j (i \neq j)

Input

Input is given from Standard Input in the following format:

A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.


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

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

  val N, M, K = in.next().toInt
  val uf = new UnionFind(N)
  val friend = Array.fill[List[Int]](N+1)(Nil)
  for (_ <- 1 to M) {
    val A, B = in.next().toInt
    uf.connect(A, B)
    friend(A) = B :: friend(A)
    friend(B) = A :: friend(B)
  }

  val block = Array.fill[List[Int]](N+1)(Nil)
  for (_ <- 1 to K) {
    val C, D = in.next().toInt
    block(C) = D :: block(C)
    block(D) = C :: block(D)
  }

  //
  val ans = new Array[Int](N+1)
  for (i <- 1 to N) {
    ans(i) = (uf.size(i) - 1) - friend(i).length
    val hoge = friend(i).toSet
    for (e <- block(i)) {
      if (!hoge(e) && uf.isConnect(i, e)) {
        ans(i) -= 1
      }
    }
  }

  println(ans.drop(1).mkString(" "))
}

// O(α(n)) << O(log(n))
// v は頂点数
// ノード番号は 1-origin
class UnionFind(v: Int){
  // 根であれば *そのグループの要素数(負)* が、子であれば親の番号が入る。
  val uni = Array.fill(v+1)(-1)

  // 頂点 v の所属するグループを調べる
  def root(v: Int): Int =
    uni(v) < 0 match{
      case true  =>  // v が親の場合
        return v
      case false =>  // v が子の場合
        uni(v) = root(uni(v))  // 親のrootを調べる
        return uni(v)
    }

  // 頂点 a と頂点 b をつなぐ。もともと同じグループのとき、False を返す
  def connect(a: Int, b: Int): Boolean = {
    // まずはそれぞれ根の番号に置き換える
    var ra = root(a)
    var rb = root(b)
    if(ra == rb)
      return false  // a と b がそもそも同じグループに属しているなら即終了

    // ra を大きなグループにしたいので、逆であれば入れ替える
    if(uni(ra) > uni(rb)) {  // rbの方が要素数が多ければ
      var tmp = ra
      ra = rb
      rb = tmp
    }

    // ra と rb を結合し、rb の親を ra とする
    uni(ra) += uni(rb)
    uni(rb) = ra
    return true
  }

  // 頂点 a, b が同じグループであるかを調べる
  def isConnect(a: Int, b: Int): Boolean =
    root(a) == root(b)

  // 頂点 a を含むグループの頂点数を調べる
  def size(a: Int): Int = -uni(root(a))
}

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

Problem Statement

An SNS has N users - User 1, User 2, \cdots, User N.

Between these N users, there are some relationships - M friendships and K blockships.

For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.

For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.

We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:

a \neq b.

There is not a friendship between User a and User b.

There is not a blockship between User a and User b.

There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.

For each user i = 1, 2, ... N, how many friend candidates does it have?

Constraints

All values in input are integers.

2 ≤ N ≤ 10^5

0 \leq M \leq 10^5

0 \leq K \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

1 \leq C_i, D_i \leq N

C_i \neq D_i

(A_i, B_i) \neq (A_j, B_j) (i \neq j)

(A_i, B_i) \neq (B_j, A_j)

(C_i, D_i) \neq (C_j, D_j) (i \neq j)

(C_i, D_i) \neq (D_j, C_j)

(A_i, B_i) \neq (C_j, D_j)

(A_i, B_i) \neq (D_j, C_j)

Input

Input is given from Standard Input in the following format:

N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

Output

Print the answers in order, with space in between.

Sample Input 1

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

Sample Output 1

0 1 0 1

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.

However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

Sample Input 2

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

Sample Output 2

0 0 0 0 0

Everyone is a friend of everyone else and has no friend candidate.

Sample Input 3

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

Sample Output 3

1 3 5 4 3 3 3 3 1 0


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val m = sc.nextInt()
  val k = sc.nextInt()
  val uf = UnionFind(n)
  val ans = new Array[Int](n)
  for (i <- 0 until m) {
    val a = sc.nextInt() - 1
    val b = sc.nextInt() - 1
    uf.unite(a, b)
    ans(a) = ans(a) - 1
    ans(b) = ans(b) - 1
  }
  for (i <- 0 until n) {
    ans(i) = ans(i) + uf.size(i) - 1
  }
  for (i <- 0 until k) {
    val c = sc.nextInt() - 1
    val d = sc.nextInt() - 1
    if (uf.same(c, d)) {
      ans(c) = ans(c) - 1
      ans(d) = ans(d) - 1
    }
  }
  for (i <- 0 until n) {
    print(ans(i))
    if (i < n - 1) print(" ")
  }
  println()
  case class UnionFind(val n: Int) {
    val par = Array.fill(n)(-1)
    val sz = Array.fill(n)(1)
    def find(x: Int): Int = {
      if (par(x) == -1) par(x) = x
      if (par(x) != x) {
        par(x) = find(par(x))
      }
      par(x)
    }
    def unite(x: Int, y: Int): Unit = {
      val a = find(x)
      val b = find(y)
      if (a == b) return
      if (sz(a) > sz(b)) {
        sz(a) += sz(b)
        par(b) = par(a)
      } else {
        sz(b) += sz(a)
        par(a) = par(b)
      }
    }
    def same(x: Int, y: Int): Boolean = {
      find(x) == find(y)
    }
    def size(x: Int): Int = {
      sz(find(x))
    }
  }
}


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

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

  val friends = Array.fill(n)(Array.empty[Int])
  for (_ <- 0 until m) {
    val Array(a, b) = readLine.split(" ").map(_.toInt - 1)
    friends(a) :+= b
    friends(b) :+= a
  }

  val blocks = Array.fill(n)(Array.empty[Int])
  for (_ <- 0 until k) {
    val Array(a, b) = readLine.split(" ").map(_.toInt - 1)
    blocks(a) :+= b
    blocks(b) :+= a
  }

  val groupToMember = mutable.Map.empty[Int, mutable.Set[Int]]
  val memberToGroup = Array.fill(n)(-1)
  val checked = mutable.Set.empty[Int]
  for (i <- 0 until n) {
    groupToMember.put(i, mutable.Set.empty)
    if (!checked.contains(i)) {
      val stack = mutable.Stack[Int](i +: friends(i):_*)
      while (stack.nonEmpty) {
        val next = stack.pop
        if (!checked.contains(next)) {
          memberToGroup(next) = i
          groupToMember(i).add(next)
          checked.add(next)
          stack.pushAll(friends(next))
        }
      }
    }
  }

  println(groupToMember.map{ case (k, v) => k -> v.toSeq })
  println(memberToGroup.toSeq)

  val ans = Range(0, n).map { i =>
    val gid = memberToGroup(i)
    groupToMember(gid).count(candidate =>
      !(i == candidate || friends(i).contains(candidate) || blocks(i).contains(candidate))
    )
  }

  println(ans.mkString(" "))
}


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

object Main extends App {
  val firstLine = readLine.split(" ").map(_.toInt)
  val N = firstLine(0)
  val M = firstLine(1)
  val K = firstLine(2)

  val friends = Array.fill(N + 1)(Array.empty[Int])
  val blocks = Array.fill(N + 1)(Array.empty[Int])

  for (_ <- 0 until M) {
    val friendship = readLine.split(" ").map(_.toInt)
    val a = friendship(0);
    val b = friendship(1);
    friends(a) :+= b
    friends(b) :+= a
  }

  for (_ <- 0 until K) {
    val blockship = readLine.split(" ").map(_.toInt)
    val a = blockship(0)
    val b = blockship(1)
    blocks(a) :+= b
    blocks(b) :+= a
  }

  val groupNumbered = Array.fill(N + 1)(-1)
  val checked = mutable.Set.empty[Int]

  for (i <- 1 to N) {
    if (!checked.contains(i)) {
      groupNumbered(i) = i
      val stack = mutable.Stack[Int](friends(i):_*)
      while (stack.nonEmpty) {
        val next = stack.pop
        groupNumbered(next) = i
        checked.add(next)
        stack.pushAll(friends(next).filterNot(checked.contains))
      }
      checked.add(i)
    }
  }

  for (i <- 1 to N) {
    val groupId = groupNumbered(i)

    val count = groupNumbered.zipWithIndex.count { case (gid, id) =>
      gid == groupId && // 同じグループ
      id != i && // 自分自身ではなく
      !blocks(i).contains(id) && // ブロック関係でなく
      !friends(i).contains(id) // 直接の友人関係でもない
    }

    print(s"$count ")
  }

  print("\n")
}


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

object Main extends App {
  val firstLine = readLine.split(" ").map(_.toInt)
  val N = firstLine(0)
  val M = firstLine(1)
  val K = firstLine(2)

  val friends = Array.fill(N + 1)(Array.empty[Int])
  val blocks = Array.fill(N + 1)(Array.empty[Int])

  for (_ <- 0 until M) {
    val friendship = readLine.split(" ").map(_.toInt)
    val a = friendship(0);
    val b = friendship(1);
    friends(a) :+= b
    friends(b) :+= a
  }

  for (_ <- 0 until K) {
    val blockship = readLine.split(" ").map(_.toInt)
    val a = blockship(0)
    val b = blockship(1)
    blocks(a) :+= b
    blocks(b) :+= a
  }

  val groupNumbered = Array.fill(N + 1)(-1)
  val checked = mutable.Set.empty[Int]

  for (i <- 1 to N) {
    if (!checked.contains(i)) {
      val stack = mutable.Stack[Int](friends(i):_*)
      while (stack.nonEmpty) {
        val next = stack.pop
        groupNumbered(next) = i
        checked.add(next)
        stack.pushAll(friends(next).filterNot(checked.contains))
      }
      checked.add(i)
    }
  }

  for (i <- 1 to N) {
    val groupId = groupNumbered(i)

    val count = groupNumbered.zipWithIndex.count { case (gid, id) =>
      gid == groupId && // 同じグループ
      id != i && // 自分自身ではなく
      !blocks(i).contains(id) && // ブロック関係でなく
      !friends(i).contains(id) // 直接の友人関係でもない
    }

    print(s"$count ")
  }

  print("\n")
}


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

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val Array(n, m, k) = in.readLine().split("\\s").map(_.toInt)

    val friends = for {
      _ <- 0 until m
    } yield {
      in.readLine().split("\\s").map(_.toInt)
    }

    val blocks = for {
      _ <- 0 until k
    } yield {
      in.readLine().split("\\s").map(_.toInt)
    }

    val person2Cluster = mutable.HashMap.empty[Int, ListBuffer[Int]]
    val person2FriendsSize = mutable.HashMap.empty[Int, Int]
    val clusters = ListBuffer.empty[ListBuffer[Int]]

    @inline
    def myRelations(sets: IndexedSeq[Array[Int]], me: Int) = {
      sets.filter(_ (0) == me).map(_ (1)) ++ sets.filter(_ (1) == me).map(_ (0))
    }

    @inline
    def myFriends(me: Int): IndexedSeq[Int] = {
      myRelations(friends, me)
    }

    @inline
    def myBlocks(me: Int): IndexedSeq[Int] = {
      myRelations(blocks, me)
    }

    for {
      i <- 1 to n
      if !person2Cluster.contains(i)
    } yield {
      val cluster = ListBuffer.empty[Int]
      clusters.append(cluster)
      cluster.append(i)
      person2Cluster.update(i, cluster)

      val edges = new mutable.Stack[Int]
      edges.push(i)

      while (edges.nonEmpty) {
        val p = edges.pop()
        val fs = myFriends(p).toArray
        person2FriendsSize.update(p, fs.length)

        fs.filter { f =>
          !person2Cluster.contains(f)
        }.foreach { f =>
          cluster.append(f)
          edges.push(f)
          person2Cluster.update(f, cluster)
        }
      }
    }

    val cluster2size = clusters.foldLeft(mutable.HashMap.empty[ListBuffer[Int], Int]) { (acc, c) =>
      acc.update(c, c.size)
      acc
    }

    out.println(
      (for {
        p <- 1 to n
      } yield {
        val cluster = person2Cluster(p)
        val friendsSize = person2FriendsSize(p)
        val bs = myBlocks(p).filter { b =>
          cluster.contains(b)
        }
        cluster2size(cluster) - friendsSize - bs.size - 1
      }).mkString(" ")
    )
    out.flush()
  }
}


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

	val n, m = sc.nextInt

	val a = Array.fill(n)(-1)
	var flag = true

	Seq.fill(m)((sc.nextInt-1, sc.nextInt)) foreach { case (s, c) =>
		if (a(s) != -1 && a(s) != c) flag = false
		a(s) = c
	}

	if (n != 1 && a(0) == 0) flag = false
	if (a(0) == -1) a(0) == 1

	pw.println( if (flag) a.map(e => if (e == -1) "0" else s"$e").mkString.toInt else -1 )
	pw.flush()
}


object Main {
  import scala.io.StdIn._
  def main(args: Array[String]): Unit = {
    val Array(a,b) = readLine().split(" ").map(_.toInt)
    println(if(a<10) b+(100*(10-a)) else b)
  }
}

Score : 100 points

Problem Statement

Takahashi is a member of a programming competition site, ButCoder.

Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.

The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests.

Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq R \leq 4111

Input

Input is given from Standard Input in the following format:

N R

Output

Print his Inner Rating.

Sample Input 1

2 2919

Sample Output 1

3719

Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800.

Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.

Sample Input 2

22 3051

Sample Output 2

3051


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

	println(r + (if(n >= 10) 0 else 100 * (10 - n)))
}


import scala.io.StdIn._

object Main extends App {

  val Array(n, k) = readLine().split(" ").map(_.toInt)

  def solve(): Int = {
    var digit = 0
    var num = n
    while(num > 0) {
      num /= k
      digit += 1
    }
    digit
  }

  println(solve())

}

Score : 200 points

Problem Statement

Given is an integer N. Find the number of digits that N has in base K.

Notes

For information on base-K representation, see Positional notation - Wikipedia.

Constraints

All values in input are integers.

1 \leq N \leq 10^9

2 \leq K \leq 10

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of digits that N has in base K.

Sample Input 1

11 2

Sample Output 1

4

In binary, 11 is represented as 1011.

Sample Input 2

1010101 10

Sample Output 2

7

Sample Input 3

314159265 3

Sample Output 3

18


object Main {
  def main(args:Array[String]) {
    val N = readLine().toInt
    var X = readLine().split(' ').map(_.toInt)

    var ans = 99999999//X.map(a => a * a).sum
    for(P <- X.min until X.max) {
      var sum = 0
      for(i <- 0 until X.size) {
        sum += (X(i) - P) * (X(i) - P)
      }
      if(sum < ans) ans = sum
    }
    println(ans)
  }
}

Score : 300 points

Problem Statement

There are N people living on a number line.

The i-th person lives at coordinate X_i.

You are going to hold a meeting that all N people have to attend.

The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate P, the i-th person will spend (X_i - P)^2 points of stamina to attend the meeting.

Find the minimum total points of stamina the N people have to spend.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq X_i \leq 100

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print the minimum total stamina the N people have to spend.

Sample Input 1

2
1 4

Sample Output 1

5

Assume the meeting is held at coordinate 2. In this case, the first person will spend (1 - 2)^2 points of stamina, and the second person will spend (4 - 2)^2 = 4 points of stamina, for a total of 5 points of stamina. This is the minimum total stamina that the 2 people have to spend.

Note that you can hold the meeting only at an integer coordinate.

Sample Input 2

7
14 14 2 13 56 2 37

Sample Output 2

2354


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

	val p = 1000000007L

	var tp = 1L

	val p1 = powMod(2L, n, p)
	val p2 = combi(n, a, p)
	val p3 = combi(n, b, p)

	val ans = p1 - p2 - p3 - 1

	if(ans < 0) println((p + ans)%p)
	else println(ans%p)

	def combi(n: Long, r: Long, p: Long): BigInt = {
		val tp1 = (n - r + 1L to n).foldLeft(1L)((z, i) => z*i % p)
		return (1L to r).foldLeft(BigInt(tp1))((z, i) => BigInt(i).modInverse(p) * z % p)
	}

	def powMod(a: Long, n: Long, p: Long): Long = {
    	def subpowMod(a: Long, n: Long, mul: Long): Long = {
    		n match{
				case 1L => a * mul % p
				case _  => subpowMod(a*a%p, n/2, mul * (if((n&1) == 1) a else 1) % p )
    		}
    	}
    	subpowMod(a, n, 1L).toInt
  	}

}

Score : 400 points

Problem Statement

Akari has n kinds of flowers, one of each kind.

She is going to choose one or more of these flowers to make a bouquet.

However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.

How many different bouquets are there that Akari can make?

Find the count modulo (10^9 + 7).

Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet.

Constraints

All values in input are integers.

2 \leq n \leq 10^9

1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5)

Input

Input is given from Standard Input in the following format:

n a b

Output

Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print 0.)

Sample Input 1

4 1 3

Sample Output 1

7

In this case, Akari can choose 2 or 4 flowers to make the bouquet.

There are 6 ways to choose 2 out of the 4 flowers, and 1 way to choose 4, so there are a total of 7 different bouquets that Akari can make.

Sample Input 2

1000000000 141421 173205

Sample Output 2

34076506

Print the count modulo (10^9 + 7).


import java.util.Scanner

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

  val x = (1 to n).filterNot(i => i == a || i == b)

  val max = 200000
  val mod = 1000000007

  val fac = new Array[Long](max)
  val finv = new Array[Long](max)
  val inv = new Array[Long](max)

  def COMInit(): Unit = {
    fac(0) = 1
    fac(1) = 1
    finv(0) = 1
    finv(1) = 1
    inv(1) = 1
    for (i <- 2 until max) {
      fac(i) = fac(i - 1) * i % mod
      inv(i) = mod - inv(mod % i) * (mod / i) % mod
      finv(i) = finv(i - 1) * inv(i) % mod
    }
  }
  COMInit()

  def COM(n: Int, k: Int): Long = {
    if (n < k) 0L
    else if (n < 0 || k < 0) 0L
    else fac(n) * (finv(k) * finv(n - k) % mod) % mod
  }

  val y = x.map(COM(n, _)).sum

  println(y)
}


import scala.io.StdIn._

object Main extends App {

  val n = readInt()
  val S = Array.fill(n)(readLine())

  def solve() = {
    val strAndCntSeq = S.groupBy(identity).mapValues(_.length).toSeq.sortBy(- _._2)
    val maxCnt = strAndCntSeq.head._2
    strAndCntSeq.foldLeft(Seq.empty[String]) { case (acc, (str, cnt)) =>
      if(cnt == maxCnt) str +: acc else acc
    }.sorted.mkString("\n")
  }

  println(solve())

}

Score: 300 points

Problem Statement

We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.

Print all strings that are written on the most number of votes, in lexicographical order.

Constraints

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

S_i (1 \leq i \leq N) are strings consisting of lowercase English letters.

The length of S_i (1 \leq i \leq N) is between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print all strings in question in lexicographical order.

Sample Input 1

7
beat
vet
beet
bed
vet
bet
beet

Sample Output 1

beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

Sample Input 2

8
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo

Sample Output 2

buffalo

Sample Input 3

7
bass
bass
kick
kick
bass
kick
kick

Sample Output 3

kick

Sample Input 4

4
ushi
tapu
nichia
kun

Sample Output 4

kun
nichia
tapu
ushi


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  val treeMap = new scala.collection.mutable.TreeMap[String, Int]()
  1.to(N).foreach { _ =>
    val x = sc.next()
    val count = treeMap.getOrElseUpdate(x, 0)
    treeMap.update(x, count + 1)
  }
  val max = treeMap.values.max
  treeMap.filter { case (_, count) => count == max }.keys.foreach(println)
}


object Main extends App{
  import scala.io.StdIn._
  val n=readInt()
  var map=scala.collection.mutable.Map[String,Int]()
  for {i <- (0 until(n))}{
    val s=readLine()
    map(s) = if(map.contains(s)) map(s) + 1 else 1
  }
  val m=map.toSeq.sortWith(_._2>_._2)
  val top=m.head._2
  m.collect{case r if r._2 == top => r._1}.sorted.foreach(println(_))
}