object Main {
  // 標準入力
  import scala.io.StdIn._
  def readints: Array[Long] = readLine split " " map (_.toLong)
  //
  def main(args: Array[String]) = {
    val Array(a, b) = readints
    val la = (a * 12.5).ceil.toLong
    val ua = ((a + 1) * 12.5).ceil.toLong
    val lb = (b * 10).ceil.toLong
    val ub = ((b + 1) * 10).ceil.toLong
    val lc = Math.max(la, lb)
    val uc = Math.min(ua, ub)
    if (lc < uc) {
      println(s"$lc")
    } else {
      println(s"-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 scala.util.control.Breaks

object Main extends App {
  val abInput = scala.io.StdIn.readLine()
  val abArray = abInput.split(" ").map(_.toInt).toSeq
  val a = abArray(0)
  val b = abArray(1)
  val break = new Breaks

  var result = -1
  break.breakable {
    (10 to 10000).foreach { i =>
      val aResult = (i * 0.08).toInt
      val bResult = (i * 0.1).toInt

      if(a == aResult && b == bResult) {
        result = i
        break.break()
      }
    }
  }
  println(result)
}

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

Submitted source-code file size, in bytes.

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

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


object Main extends App {
  val buf = new StringBuilder
  val tmp = new StringBuilder
  val s = io.StdIn.readLine()
  val q = io.StdIn.readLine().toInt
  var reverse = false
  buf.append(s)
  for (_ <- 0 until q) {
    val query = io.StdIn.readLine().split(' ')
    val t = query(0).toInt
    if (t == 1) {
      if (tmp.nonEmpty) {buf.append(tmp.reverse); tmp.clear()}
      reverse = !reverse
    }
    else if (t == 2) {
      val f = query(1).toInt
      val c = query(2)
      if (f == 1) {
        if (reverse) {
          buf.append(c)
      } else {
        tmp.append(c)
      }
      } else {
        if (reverse) {
          tmp.append(c)
        } else {
          buf.append(c)
        }
      }
    }
  }

  println(if (reverse) tmp.append(buf).toString() else tmp.append(buf.reverse).toString())
}

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

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt
    val ans =
      if (N % 2 == 0) N / 2
      else (N / 2) + 1
    println(ans)
  }
}

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 {
  def main(args: Array[String]): Unit = {
    solve
  }

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

    println((n + 1) / 2)
  }
}


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val A = Array.fill(9)(in.nextInt)
  val N = in.nextInt

  (1 to N).foreach {i =>
    val b = in.nextInt
    A.indexWhere(_ == b) match {
      case -1 =>
      case n => A(n) = 0
    }
  }

  val bingos: Seq[Seq[Int]] =
    Seq(0, 4, 8) :: Seq(2, 4, 6) :: (0 to 2).flatMap { i =>
      Seq((0 to 2).map(j => j + i * 3), (0 to 2).map(j => j * 3 + i))
    }.toList

  println(if (bingos.exists(_.forall(A(_) == 0))) "Yes" else "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.


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

		if(a(0).contains(b)){
			a(0)(a(0).indexOf(b)) = 0
		}

		if(a(1).contains(b)){
			a(1)(a(1).indexOf(b)) = 0
		}

		if(a(2).contains(b)){
			a(2)(a(2).indexOf(b)) = 0
		}
	}

	var flag = false

	if(a(0).sum == 0 || a(1).sum == 0 || a(2).sum == 0) flag = true

	for(i<-0 until 3){
		if(a(0)(i) + a(1)(i) + a(2)(i) == 0) flag = true
	}

	if(a(0)(0) + a(1)(1) + a(2)(2) == 0) flag = true
	if(a(0)(2) + a(1)(1) + a(2)(0) == 0) flag = true

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

}


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

  val ans = Range(0, n).map { i =>
    val gid = memberToGroup(i)
    val blocked = blocks(i).count(b => memberToGroup(b) == gid)
    groupToMember(gid).size - (1 + friends(i).size + blocked)
  }

  println(ans.mkString(" "))
}

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


import io.StdIn._

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

  val uf = UnionFind.of(N)
  val friendCount = Array.fill(N)(0)
  val blocks = Array.fill(N)(Array.empty[Int])

  for (_ <- 0 until M) {
    val friendship = readLine.split(" ").map(_.toInt - 1) // 入力は 1始まり、プログラム上は0始まり
    val a = friendship(0);
    val b = friendship(1);
    uf.unite(a, b)
    friendCount(a) = friendCount(a) + 1
    friendCount(b) = friendCount(b) + 1
  }
  for (_ <- 0 until K) {
    val blockship = readLine.split(" ").map(_.toInt - 1)
    val a = blockship(0)
    val b = blockship(1)
    blocks(a) = blocks(a) :+ b
    blocks(b) = blocks(b) :+ a
  }

  for (i <- 0 until N) {
    val blockCount = blocks(i).count(block => uf.same(i, block))
    val ans = uf.size(i) - 1 - friendCount(i) - blockCount
    print(s"${ans} ")
  }
  print("\n")
}

/**
 * d(x) == a として
 * x がツリーの根であれば: a はツリーのサイズ（ノード数) に -1 をかけた数
 * x がツリーの根でなければ: a は関連ノードのインデックス番号
 *
 * @param d
 */
case class UnionFind(d: Array[Int]) {
  def root(x: Int): Int = if (d(x) < 0) x else {
    val rt = root(d(x))
    d(x) = rt // memoization
    rt
  }

  def unite(x: Int, y: Int): Boolean = {
    val xRoot = root(x)
    val yRoot = root(y)

    if (xRoot == yRoot) false
    else {
      if (xRoot < yRoot) {
        d(xRoot) = d(xRoot) + d(yRoot)
        d(yRoot) = xRoot
      } else {
        d(yRoot) = d(yRoot) + d(xRoot)
        d(xRoot) = yRoot
      }
      true
    }
  }

  def same(x: Int, y: Int): Boolean = root(x) == root(y)

  def size(x: Int): Int = -1 * d(root(x))
}

object UnionFind {
  def of(n: Int) = UnionFind(Array.fill[Int](n)(-1))
}


import scala.collection.mutable.ArrayBuffer

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

  def solve2(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, m, k = sc.nextInt()
    val users = Array.fill[User](n)(User(new ArrayBuffer[Int](), new ArrayBuffer[Int]()))
    val uf = new UnionFind(n)

    for (i <- 0 until m) {
      val a = sc.nextInt() - 1
      val b = sc.nextInt() - 1
      users(a).friends.append(b)
      users(b).friends.append(a)

      uf.unite(a, b)
    }
    for (i <- 0 until k) {
      val c = sc.nextInt() - 1
      val d = sc.nextInt() - 1
      users(c).blocks.append(d)
      users(d).blocks.append(c)
    }

    val pw = new java.io.PrintWriter(System.out)
    for (i <- 0 until n) {

      // 連結成分の数 - 自分自身 - 友達の数
      var ans = uf.size(i) - 1 - users(i).friends.size
      for (block <- users(i).blocks) {
        if (uf.same(i, block)) {
          // ブロック対象が同じ連結成分に存在したら、友達候補から減算する
          ans -= 1
        }
      }
      pw.println(ans)
    }
    pw.flush()
  }

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, m, k = sc.nextInt()
    val users = Array.fill[User](n)(User(new ArrayBuffer[Int](), new ArrayBuffer[Int]()))

    for (i <- 0 until m) {
      val a = sc.nextInt() - 1
      val b = sc.nextInt() - 1
      users(a).friends.append(b)
      users(b).friends.append(a)
    }
    for (i <- 0 until k) {
      val c = sc.nextInt() - 1
      val d = sc.nextInt() - 1
      users(c).blocks.append(d)
      users(d).blocks.append(c)
    }

    val pw = new java.io.PrintWriter(System.out)
    for (i <- 0 until n) {
      val ans = search(i, users)
      pw.println(ans)
    }
    pw.flush()
  }

  def search(target: Int, users: Array[User]): Int = {
    val queue = scala.collection.mutable.Queue[Int]()
    val checked = new ArrayBuffer[Int]()
    val friends = users(target).friends
    val blocks = users(target).blocks
    var ans = 0

    users(target).friends.foreach(queue.enqueue(_))

    while (!queue.isEmpty) {
      val num = queue.dequeue()
      if (target != num && !checked.contains(num)) {
        if (!friends.contains(num) && !blocks.contains(num)) {
          ans += 1
        }

        checked.append(num)
        users(num).friends.foreach { f =>
          if (f != target && !checked.contains(f)) {
            queue.enqueue(f)
          }
        }
      }
    }

    return ans
  }

  case class User(friends: ArrayBuffer[Int], blocks: ArrayBuffer[Int])

}

class UnionFind(n: Int) {
  private val d: ArrayBuffer[Int] = ArrayBuffer.fill[Int](n)(-1)

  def find(x: Int): Int = {
    if (d(x) < 0) {
      return x
    }
    else {
      d(x) = find(d(x))
      return d(x)
    }
  }

  def unite(x: Int, y: Int): Boolean = {
    // 根同士をくっつけるため根を取得
    val tmpX = find(x)
    val tmpY = find(y)
    if (tmpX == tmpY) {
      // 同じ連結成分内にどちらも存在するため、連結不要！
      return false
    }

    if (d(tmpX) < d(tmpY)) {
      // x方が集合が大きい場合、y->xの向きにくっつける
      d(tmpX) += d(tmpY)
      d(tmpY) = tmpX
    } else {
      // その逆
      d(tmpY) += d(tmpX)
      d(tmpX) = tmpY
    }

    return true
  }

  def same(x: Int, y: Int): Boolean = {
    find(x) == find(y)
  }

  def size(x: Int): Int = {
    -d(find(x))
  }
}


import scala.collection.mutable.ArrayBuffer

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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, m, k = sc.nextInt()
    val users = Array.fill[User](n)(User(new ArrayBuffer[Int](), new ArrayBuffer[Int]()))

    for (i <- 0 until m) {
      val a = sc.nextInt() - 1
      val b = sc.nextInt() - 1
      users(a).friends.append(b)
      users(b).friends.append(a)
    }
    for (i <- 0 until k) {
      val c = sc.nextInt() - 1
      val d = sc.nextInt() - 1
      users(c).blocks.append(d)
      users(d).blocks.append(c)
    }

    val pw = new java.io.PrintWriter(System.out)
    for (i <- 0 until n) {
      val ans = dfs(i, users)
      pw.println(ans)
    }
    pw.flush()
  }

  def dfs(target: Int, users: Array[User]): Int = {
    val queue = scala.collection.mutable.Queue[Int]()
    val checked = new ArrayBuffer[Int]()
    val friends = users(target).friends
    val blocks = users(target).blocks
    var ans = 0

    users(target).friends.foreach(queue.enqueue(_))

    while (!queue.isEmpty) {
      val num = queue.dequeue()
      if (target != num && !checked.contains(num)) {
        if (!friends.contains(num) && !blocks.contains(num)) {
          ans += 1
        }

        checked.append(num)
        users(num).friends.foreach(queue.enqueue(_))
      }
    }

    return ans
  }

  case class User(friends: ArrayBuffer[Int], blocks: ArrayBuffer[Int])

}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, R = sc.nextInt()
  println(R + (10 - N).max(0) * 100)
}

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 N = scala.io.StdIn.readInt
	val X = scala.io.StdIn.readLine.split(" ").map(_.toInt)

	println(X.map(z => z*z).sum - (X.sum)*(X.sum)/N)
}

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{
  import scala.io.StdIn._
  def main(args: Array[String]): Unit = {
    val a = readLine().split(" ").distinct.length
    println(if(a == 2) "Yes" else "No")
  }
}

Score: 100 points

Problem Statement

A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers.

You will be given three integers A, B, and C. If this triple is poor, print Yes; otherwise, print No.

Constraints

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

Input

Input is given from Standard Input in the following format:

A B C

Output

If the given triple is poor, print Yes; otherwise, print No.

Sample Input 1

5 7 5

Sample Output 1

Yes

A and C are equal, but B is different from those two numbers, so this triple is poor.

Sample Input 2

4 4 4

Sample Output 2

No

A, B, and C are all equal, so this triple is not poor.

Sample Input 3

4 9 6

Sample Output 3

No

Sample Input 4

3 3 4

Sample Output 4

Yes


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val isApprovable = List.fill(sc.nextInt())(sc.nextInt())
    .forall(i => i % 2 == 1 || i % 3 == 0 || i % 5 == 0)
  println(if (isApprovable) "APPROVED" else "DENIED")
}

Score: 200 points

Problem Statement

You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.

According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is satisfied:

All even numbers written on the document are divisible by 3 or 5.

If the immigrant should be allowed entry according to the regulation, output APPROVED; otherwise, print DENIED.

Notes

The condition in the statement can be rephrased as "If x is an even number written on the document, x is divisible by 3 or 5".
Here "if" and "or" are logical terms.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

If the immigrant should be allowed entry according to the regulation, print APPROVED; otherwise, print DENIED.

Sample Input 1

5
6 7 9 10 31

Sample Output 1

APPROVED

The even numbers written on the document are 6 and 10.

All of them are divisible by 3 or 5, so the immigrant should be allowed entry.

Sample Input 2

3
28 27 24

Sample Output 2

DENIED

28 violates the condition, so the immigrant should not be allowed entry.


import scala.io.StdIn._

object Main extends App {

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

  def solve() = {
    val isValid = A.map { num =>
      if(num % 2 == 0 && num % 5 == 0 || num % 3 == 0) true else true
    }.forall(identity)
    if(isValid) "APPROVED" else "DENIED"
  }

  println(solve())

}


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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = sc.nextInt()
    }

    var approved = true
    for (num <- a.filter(_ % 2 == 0)) {
      if (num % 3 != 0 && num % 5 != 0) {
        approved = false
      }
    }

    if (approved) println("APPROVED ")
    else println("DENIED ")
  }
}


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

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 s, t = sc.next()
  val a, b = sc.nextInt()
  val u = sc.next()
  var num_s = -1
  var num_t = -1
  if (s==u) {
    println("red")
    num_s = a - 1
    num_t = b
  } else {
    println("blue")
    num_s = a
    num_t = b - 1
  }
  println(s"$num_s $num_t")
}

Score : 100 points

Problem Statement

We have A balls with the string S written on each of them and B balls with the string T written on each of them.

From these balls, Takahashi chooses one with the string U written on it and throws it away.

Find the number of balls with the string S and balls with the string T that we have now.

Constraints

S, T, and U are strings consisting of lowercase English letters.

The lengths of S and T are each between 1 and 10 (inclusive).

S \not= T

S=U or T=U.

1 \leq A,B \leq 10

A and B are integers.

Input

Input is given from Standard Input in the following format:

S T
A B
U

Output

Print the answer, with space in between.

Sample Input 1

red blue
3 4
red

Sample Output 1

2 4

Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string S and four balls with the string T.

Sample Input 2

red blue
5 5
blue

Sample Output 2

5 4

Takahashi chose a ball with blue written on it and threw it away.
Now we have five balls with the string S and four balls with the string T.


object Main extends App {
  val stInput =  scala.io.StdIn.readLine()
  val stArray = stInput.split(" ").toSeq
  val abInput =  scala.io.StdIn.readLine()
  val abArray = abInput.split(" ").map(_.toInt).toSeq
  val u =  scala.io.StdIn.readLine()
  if(u == stArray(0)) {
    println((abArray(0) - 1) + " " + abArray(1))
  } else {
    println(abArray(0) + " " + (abArray(1) - 1))
  }

}


import java.util.Scanner

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

  val s = sc.next

  val res = List.fill(s.length)("x").mkString
  println(res)
}

Score : 200 points

Problem Statement

Given is a string S. Replace every character in S with x and print the result.

Constraints

S is a string consisting of lowercase English letters.

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

Input

Input is given from Standard Input in the following format:

S

Output

Replace every character in S with x and print the result.

Sample Input 1

sardine

Sample Output 1

xxxxxxx

Replacing every character in S with x results in xxxxxxx.

Sample Input 2

xxxx

Sample Output 2

xxxx

Sample Input 3

gone

Sample Output 3

xxxx


object Main extends App{
  import scala.io.StdIn._
  println("x"*readLine().length)
}


import scala.io.StdIn.readLine

object Main extends App {

  val s = readLine()

  println(s.map(_ => 'x'))
}


object Main extends App {
  def getExpect(i: Int): Double = {
    var expect = 0d
    (1 to i).foreach(k => expect = expect + k.toDouble / i.toDouble)
    expect
  }
  val nkInput =  scala.io.StdIn.readLine()
  val nkArray = nkInput.split(" ").map(_.toInt).toSeq
  val n = nkArray(0)
  val k = nkArray(1)
  val pInput =  scala.io.StdIn.readLine()
  val pArray = pInput.split(" ").map(p => getExpect(p.toInt)).toVector

  var maxSum = -1d
  var sumTotal = 0

  (0 to n - 1).foreach { i =>
    if (i >= k - 1) {
      var tempSum = 0d
      (0 to k - 1).foreach { j =>
        tempSum = tempSum + pArray(i - j)
      }
      if(maxSum < tempSum) {
        maxSum = tempSum
      }
    }
  }

  println(maxSum)

}

Score : 400 points

Problem Statement

We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown.

We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this sum.

Constraints

1 ≤ K ≤ N ≤ 200000

1 ≤ p_i ≤ 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 ... p_N

Output

Print the maximum possible value of the expected value of the sum of the numbers shown.

Your output will be considered correct when its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

5 3
1 2 2 4 5

Sample Output 1

7.000000000000

When we throw the third, fourth, and fifth dice from the left, the expected value of the sum of the numbers shown is 7. This is the maximum value we can achieve.

Sample Input 2

4 1
6 6 6 6

Sample Output 2

3.500000000000

Regardless of which die we choose, the expected value of the number shown is 3.5.

Sample Input 3

10 4
17 13 13 12 15 20 10 13 17 11

Sample Output 3

32.000000000000


object Main extends App {
  val Array(n, k) = io.StdIn.readLine().split(' ').map(_.toInt)
  val pn = io.StdIn.readLine().split(' ').map(_.toInt)
  var max: Double = 0
  var l = Array.empty[Int]
  for (i <- 0 to n-k) {
    val sub = pn.slice(i, i+k)
    val sum = sub.sum
    if (max < sum) {max = sum; l = sub}
  }

  val exp = l.map(x => (1 to x).sum / x.toDouble).sum
  println(exp)
}


object Main extends App {
    val num = readLine
    val h = num.split(" ")(0).toInt
    val a = num.split(" ")(1).toInt

    val result = if (h%a==0) (h/a) else ((h/a)+1)
    println(result);
}

Score : 100 points

Problem Statement

Serval is fighting with a monster.

The health of the monster is H.

In one attack, Serval can decrease the monster's health by A.
There is no other way to decrease the monster's health.

Serval wins when the monster's health becomes 0 or below.

Find the number of attacks Serval needs to make before winning.

Constraints

1 \leq H \leq 10^4

1 \leq A \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H A

Output

Print the number of attacks Serval needs to make before winning.

Sample Input 1

10 4

Sample Output 1

3

After one attack, the monster's health will be 6.

After two attacks, the monster's health will be 2.

After three attacks, the monster's health will be -2.

Thus, Serval needs to make three attacks to win.

Sample Input 2

1 10000

Sample Output 2

1

Sample Input 3

10000 1

Sample Output 3

10000


//import java.util.Scanner

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

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

/**
  * 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(if (sc.nextLong() <= Array.fill(sc.nextInt())(sc.nextLong()).sum) "Yes" else "No")
  }

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

  @scala.annotation.tailrec
  def recursive(H: Long, monsterCount: Long, attackCount: Long): Long = {
    if (H == 0) attackCount else recursive(H / 2, monsterCount * 2, attackCount + monsterCount)
  }

  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): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

object ArabicRoman {

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

  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

Raccoon is fighting with a monster.

The health of the monster is H.

Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i.
There is no other way to decrease the monster's health.

Raccoon wins when the monster's health becomes 0 or below.

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Constraints

1 \leq H \leq 10^9

1 \leq N \leq 10^5

1 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H N
A_1 A_2 ... A_N

Output

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Sample Input 1

10 3
4 5 6

Sample Output 1

Yes

The monster's health will become 0 or below after, for example, using the second and third moves.

Sample Input 2

20 3
4 5 6

Sample Output 2

No

Sample Input 3

210 5
31 41 59 26 53

Sample Output 3

Yes

Sample Input 4

211 5
31 41 59 26 53

Sample Output 4

No


object Main extends App {
  val hn = scala.io.StdIn.readLine()
  val hnArray = hn.split(" ").map(_.toLong).toVector
  val h = hnArray(0)
  val n = hnArray(1)
  val a = scala.io.StdIn.readLine()
  val aArray = a.split(" ").map(_.toLong).toVector
  val aArraySum = aArray.sum

  println(if(aArraySum >= h) "Yes" else "No")
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, K = sc.nextInt()
  println(List.fill(N)(sc.nextLong()).sorted(Ordering[Long].reverse).drop(K).sum)
}

Score : 300 points

Problem Statement

Fennec is fighting with N monsters.

The health of the i-th monster is H_i.

Fennec can do the following two actions:

Attack: Fennec chooses one monster. That monster's health will decrease by 1.

Special Move: Fennec chooses one monster. That monster's health will become 0.

There is no way other than Attack and Special Move to decrease the monsters' health.

Fennec wins when all the monsters' healths become 0 or below.

Find the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning when she can use Special Move at most K times.

Constraints

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

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

1 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 ... H_N

Output

Print the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning.

Sample Input 1

3 1
4 1 5

Sample Output 1

5

By using Special Move on the third monster, and doing Attack four times on the first monster and once on the second monster, Fennec can win with five Attacks.

Sample Input 2

8 9
7 9 3 2 3 8 4 6

Sample Output 2

0

She can use Special Move on all the monsters.

Sample Input 3

3 0
1000000000 1000000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.


import scala.io.StdIn._
object Main extends App {
  val h = readLong

  def solve(n: Long): Long = n match {
    case 0 => 0
    case 1 => 1
    case n => 2 * solve(n / 2) + 1
  }

  println(solve(h))
}

Score : 400 points

Problem Statement

Caracal is fighting with a monster.

The health of the monster is H.

Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens:

If the monster's health is 1, it drops to 0.

If the monster's health, X, is greater than 1, that monster disappears. Then, two new monsters appear, each with the health of \lfloor X/2 \rfloor.

(\lfloor r \rfloor denotes the greatest integer not exceeding r.)

Caracal wins when the healths of all existing monsters become 0 or below.

Find the minimum number of attacks Caracal needs to make before winning.

Constraints

1 \leq H \leq 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H

Output

Find the minimum number of attacks Caracal needs to make before winning.

Sample Input 1

2

Sample Output 1

3

When Caracal attacks the initial monster, it disappears, and two monsters appear, each with the health of 1.

Then, Caracal can attack each of these new monsters once and win with a total of three attacks.

Sample Input 2

4

Sample Output 2

7

Sample Input 3

1000000000000

Sample Output 3

1099511627775


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

Score : 100 points

Problem Statement

Takahashi is participating in a programming contest, AXC001. He has just submitted his code to Problem A.

The problem has N test cases, all of which must be passed to get an AC verdict.

Takahashi's submission has passed M cases out of the N test cases.

Determine whether Takahashi's submission gets an AC.

Constraints

1 \leq N \leq 100

0 \leq M \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

If Takahashi's submission gets an AC, print Yes; otherwise, print No.

Sample Input 1

3 3

Sample Output 1

Yes

All three test cases have been passed, so his submission gets an AC.

Sample Input 2

3 2

Sample Output 2

No

Only two out of the three test cases have been passed, so his submission does not get an AC.

Sample Input 3

1 1

Sample Output 3

Yes


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

  println(if (n == m) "Yes" else "No")
}


object Main extends App {
  val n = scala.io.StdIn.readInt()
  val pInput = scala.io.StdIn.readLine()
  val pArray = pInput.split(" ").map(_.toInt).toVector
  var target = pArray.head
  var compareArray = pArray.tail
  var tempResult = 0

  var maxKey = 0
  var result = 1

  compareArray.foreach { p =>
    if (target > p) {
      result = result + 1
      target = p
    }
  }
  println(result)
}

Score : 300 points

Problem Statement

Given is a permutation P_1, \ldots, P_N of 1, \ldots, N.
Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:

For any integer j (1 \leq j \leq i), P_i \leq P_j.

Constraints

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

P_1, \ldots, P_N is a permutation of 1, \ldots, N.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 ... P_N

Output

Print the number of integers i that satisfy the condition.

Sample Input 1

5
4 2 5 1 3

Sample Output 1

3

i=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j holds for j = 1.

Similarly, i=5 does not satisfy the condition, either. Thus, there are three integers that satisfy the condition.

Sample Input 2

4
4 3 2 1

Sample Output 2

4

All integers i (1 \leq i \leq N) satisfy the condition.

Sample Input 3

6
1 2 3 4 5 6

Sample Output 3

1

Only i=1 satisfies the condition.

Sample Input 4

8
5 7 4 2 6 8 1 3

Sample Output 4

4

Sample Input 5

1
1

Sample Output 5

1


import scala.collection.mutable.ArrayBuffer

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

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

	pw.println( (0 until n).filter(i => (0 until i) forall (j => p(i) <= p(j))).length )
	pw.flush()
}


import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new Abc152(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

    @inline private[this] final 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
  }
}

class Abc152(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val a = na(n)
    prePrimes()
//    out.println(primes.length)
//    println(primes.mkString(" "))
    val cnt = Array.fill[Int](N)(0)
    REP(n) { i =>
      var x = a(i)
      var run = true
      var id = 0
      while (run && id < primes.length) {
        if(!mrk(x) && cnt(x) < 1)  {
          cnt(x) = 1
          x = 1
        } else {
          var c = 0
          while (x % primes(id) == 0) {
            c += 1
            x /= primes(id)
          }
          if(c > cnt(primes(id))) cnt(primes(id)) = c
        }
        if(x <= 1) run = false
        id += 1
      }
      primes.foreach { f =>
        if(x % f == 0) {
          var c = 0
          while (x % f == 0) {
            c += 1
            x /= f
          }
          if(cnt(f) < c) cnt(f) = c
        }
      }
    }
    var lm = 1L
    REP(N) { i =>
      if(cnt(i) > 0) {
        lm = lm * pow(i, cnt(i))
        lm %= MOD
      }
    }

    var ans = 0L
    REP(n) { i =>
      ans += (lm * modInv(a(i))) % MOD
      ans %= MOD
    }

    out.println(ans)
  }

  val N: Int = (1e6 + 1).toInt
  val MOD: Int = (1e9 + 7).toInt
  var primes: Array[Int] = _
  var mrk: Array[Boolean] = _

  def prePrimes(): Unit = {
    mrk = Array.fill[Boolean](N)(false)
    mrk(0) = true
    mrk(1) = true
    REP(N) { i =>
      if(i >= 2 && !mrk(i)) {
        i*2 until N by i foreach(j => mrk(j) = true)
      }
    }
    primes = mrk.zipWithIndex.filter(!_._1).map(_._2)
  }

  def pow(u: Long, n: Int): Long = {
    var ans = 1L
    var v = n
    var ret = u.toLong
    while (v > 0) {
      if(v % 2 != 0) {
        ans = ans * ret
        ans %= MOD
      }
      ret = ret * ret
      ret %= MOD
      v /= 2
    }
    ans
  }

  def modInv(x: Long): Long = {
    pow(x, MOD-2)
  }
}

Score : 500 points

Problem Statement

Given are N positive integers A_1,...,A_N.

Consider positive integers B_1, ..., B_N that satisfy the following condition.

Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds.

Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N.

Since the answer can be enormous, print the sum modulo (10^9 +7).

Constraints

1 \leq N \leq 10^4

1 \leq A_i \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the minimum possible value of B_1 + ... + B_N for B_1,...,B_N that satisfy the condition, modulo (10^9 +7).

Sample Input 1

3
2 3 4

Sample Output 1

13

Let B_1=6, B_2=4, and B_3=3, and the condition will be satisfied.

Sample Input 2

5
12 12 12 12 12

Sample Output 2

5

We can let all B_i be 1.

Sample Input 3

3
1000000 999999 999998

Sample Output 3

996989508

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


import scala.annotation.tailrec

object Main{
  // 定数関係
  final private val mod : Int = 1e9.toInt + 7

  @tailrec
  def gcd(a : BigInt, b : BigInt): BigInt = {
      if(b == 0) a
      else if(a < b) gcd(b, a)
      else gcd(a % b, b)
  }
  def lcm(a : BigInt, b : BigInt): BigInt = a / gcd(a, b) * b

  type INTEGER = Long
  def power(a : Int, n : Int): Int = {
      val hd = 32 - java.lang.Integer.numberOfLeadingZeros(n)
      var isMATCH = 1 << hd
      var ans : INTEGER = 1

      while(isMATCH != 0){
          ans = ans * ans % mod
          if((n & isMATCH) != 0){
              ans = a * ans % mod
          }
          isMATCH >>>= 1
      }
      ans.toInt
  }
  def inv(n : Int): Int = power(n, mod - 2)

  // main 関数本体
  def main(args : Array[String]): Unit = {
      val n = scala.io.StdIn.readLine().toInt
      val A = scala.io.StdIn.readLine().split(' ').map(_.toInt)
      var sumInv : Int = 0
      var LCM : BigInt = 1
      for(ele <- A){
          LCM = lcm(ele, LCM)
          sumInv += inv(ele)
          if(sumInv >= mod) sumInv -= mod
      }
      val lcmMod : Long = (LCM % mod).toLong
      val ans = lcmMod * sumInv.toLong % mod
      println(ans)
  }
}


object Main extends App{
    val Array(n, m) = io.StdIn.readLine().split(' ').map(_.toInt)
    val acs = Iterator.continually(io.StdIn.readLine().split(' ')).take(m).map {
        case Array(p, s) => (p.toInt, s)
    }.toSeq.groupBy(_._1).map {
        case (p, ss) => ss.map(_._2)
    }.filter(_.exists(_ == "AC")).toSeq

    val correct = acs.length
    val penalty = if (correct == 0)
        0
    else
        acs.map(_.takeWhile(_ == "WA").length).sum

    println(s"$correct $penalty")

}

Score : 300 points

Problem Statement

Takahashi participated in a contest on AtCoder.

The contest had N problems.

Takahashi made M submissions during the contest.

The i-th submission was made for the p_i-th problem and received the verdict S_i (AC or WA).

The number of Takahashi's correct answers is the number of problems on which he received an AC once or more.

The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem.

Find the numbers of Takahashi's correct answers and penalties.

Constraints

N, M, and p_i are integers.

1 \leq N \leq 10^5

0 \leq M \leq 10^5

1 \leq p_i \leq N

S_i is AC or WA.

Input

Input is given from Standard Input in the following format:

N M
p_1 S_1
:
p_M S_M

Output

Print the number of Takahashi's correct answers and the number of Takahashi's penalties.

Sample Input 1

2 5
1 WA
1 AC
2 WA
2 AC
2 WA

Sample Output 1

2 2

In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem.

In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem.

Thus, he has two correct answers and two penalties.

Sample Input 2

100000 3
7777 AC
7777 AC
7777 AC

Sample Output 2

1 0

Note that it is pointless to get an AC more than once on the same problem.

Sample Input 3

6 0

Sample Output 3

0 0


object Main extends App {
  val Array(n, m) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  var ACseq = Map.empty[Int, Int]
  var wacnt = Map.empty[Int, Int]

  (1 to m).foreach { i =>
   // println(ACseq)
   // println(wacnt)
    val Array(p, s) = scala.io.StdIn.readLine.split(" ")
    val pp = p.toInt

    if (!ACseq.isDefinedAt(pp)) {
      if (s == "AC") {
        val wacnt_tmp = wacnt.getOrElse(pp, 0)
        ACseq += (pp -> wacnt_tmp)
      } else {
        val wacnt_tmp = wacnt.getOrElse(pp, 0)
        wacnt += (pp -> (wacnt_tmp + 1))
      }
    }
  }
  println(ACseq.size + " " + wacnt.foldLeft(0)(_ + _._2))
}


import java.io.{BufferedReader, InputStreamReader}

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

    val pss = (1 to m).map { _ =>
      in.readLine().split("\\s+") match {
        case Array(p, s) => (p.toInt, s)
      }
    }

    var penalties = 0
    var acs = 0
    val results = Array.ofDim[Int](n)

    pss.foreach {
      case (p, s) =>
        if (results(p - 1) != -1) {
          if (s == "AC") {
            penalties += results(p - 1)
            results(p - 1) = -1
            acs += 1
          } else {
            results(p - 1) += 1
          }
        }
    }

    System.out.println(List(acs, penalties).mkString(" "))
  }
}


import scala.collection.immutable.Queue

object Main {

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

    val H, W = sc.nextInt(); sc.nextLine()
    val S = Array.fill(H)(sc.nextLine().trim.toCharArray)
    // スタートの決定にO(H*W)
    // ゴールの決定にO(H*W)
    // 最短路の探索にO(H*W)
    // 全探索するとO(H^3*W^3)
    // 64 * 10^6で間に合わない
    // dist(y)(x)(y')(x') := マスy,xからマスy',x'への最短路としておく
//    def solve(H: Int, W: Int, S: Array[Array[Char]]): Int = {
//      val MAX = Int.MaxValue
//      val dist = Array.fill(H, W, H, W)(MAX)
//      val dx = Array(0, 0, -1, 1)
//      val dy = Array(-1, 1, 0, 0)
//
//      def bfs(sx: Int, sy: Int, ex: Int, ey: Int): Int = {
//        val UNREACHED = 401
//        val arr = Array.fill(H, W)(MAX)
//        arr(sy)(sx) = 0
//        def loop(queue: Queue[(Int, Int)], min: Int): Int = {
//          if (queue.nonEmpty) {
//            val (x, y) = queue.head
//            if (x == ex && y == ey) {
//              val d = min min arr(ey)(ex)
//              dist(sy)(sx)(y)(x) = d
//              dist(y)(x)(sy)(sx) = d
//              d
//            } else if (dist(y)(x)(ey)(ex) != MAX) {
//              loop(queue.tail, min min (arr(y)(x) + dist(y)(x)(ey)(ex)))
//            } else {
//              if (min == UNREACHED) {
//                dist(sy)(sx)(y)(x) = arr(y)(x)
//                dist(y)(x)(sy)(sx) = arr(y)(x)
//              }
//              loop((0 to 3).foldLeft(queue.tail) { (queue, i) =>
//                val nx = x + dx(i)
//                val ny = y + dy(i)
//                if (nx >= 0 && nx < W &&
//                  ny >= 0 && ny < H &&
//                  S(ny)(nx) == '.' &&
//                  arr(ny)(nx) == MAX) {
//                  arr(ny)(nx) = arr(y)(x) + 1
//                  queue.enqueue((nx, ny))
//                } else queue
//              }, min)
//            }
//          } else min
//        }
//        loop(Queue((sx, sy)), UNREACHED)
//      }
//
//      (for {
//        sy <- 0 until H
//        sx <- 0 until W
//        if (S(sy)(sx) == '.')
//        ey <- (0 until H).reverse
//        ex <- (0 until W).reverse
//        if (S(ey)(ex) == '.')
//        if ey > sy || (ey == sy && ex > sx)
//      } yield bfs(sx, sy, ex, ey)).max
//    }

    // 開始地点と終了地点を全探索していたが, そもそも開始地点を確定させて
    // BFSをすると, 一回探索した時に全ての終了地点までの最短経路が求まるので
    // 開始地点の列挙O(HW)に、BFSで最後まで探索した時の距離 O(HW）を求め、その最大を求めればいい
    def solve(H: Int, W: Int, S: Array[Array[Char]]): Int = {
      val dx = Array(0, 0, -1, 1)
      val dy = Array(1, -1, 0, 0)
      def bfs(sx: Int, sy: Int): Int = {
        val visited = Array.fill(H, W)(false)
        def loop(queue: Queue[((Int, Int), Int)], max: Int): Int =
          if (queue.nonEmpty) {
            val ((x, y), dist) = queue.head
            loop((0 until 4).foldLeft(queue.tail)((queue, i) => {
              val nx = x + dx(i)
              val ny = y + dy(i)
              if (nx >= 0 && nx < W &&
                  ny >= 0 && ny < H &&
                  S(ny)(nx) == '.' &&
                  !visited(ny)(nx)) {
                visited(ny)(nx) = true
                queue.enqueue(((nx, ny), dist + 1))
              } else queue
            }), max max dist)
          } else max
        loop(Queue(((sx, sy), 0)), 0)
      }

      (for {
        sy <- 0 until H
        sx <- 0 until W
        if S(sy)(sx) == '.'
      } yield bfs(sx, sy)).max
    }

    println(solve(H, W, S))
  }

}

Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

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

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.


import scala.collection.immutable.Queue

object Main {

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

    val H, W = sc.nextInt(); sc.nextLine()
    val S = Array.fill(H)(sc.nextLine().trim.toCharArray)
    // スタートの決定にO(H*W)
    // ゴールの決定にO(H*W)
    // 最短路の探索にO(H*W)
    // 全探索するとO(H^3*W^3)
    // 64 * 10^6で間に合わない
    // dist(y)(x)(y')(x') := マスy,xからマスy',x'への最短路としておく
    def solve(H: Int, W: Int, S: Array[Array[Char]]): Int = {
      val MAX = Int.MaxValue
      val dist = Array.fill(H, W, H, W)(MAX)
      val dx = Array(0, 0, -1, 1)
      val dy = Array(-1, 1, 0, 0)

      def bfs(sx: Int, sy: Int, ex: Int, ey: Int): Int = {
        val UNREACHED = 401
        val arr = Array.fill(H, W)(MAX)
        arr(sy)(sx) = 0
        def loop(queue: Queue[(Int, Int)], min: Int): Int = {
          if (queue.nonEmpty) {
            val (x, y) = queue.head
            if (x == ex && y == ey) {
              val d = min min arr(ey)(ex)
              dist(sy)(sx)(y)(x) = d
              dist(y)(x)(sy)(sx) = d
              d
            } else if (dist(y)(x)(ey)(ex) != MAX) {
              loop(queue.tail, min min (arr(y)(x) + dist(y)(x)(ey)(ex)))
            } else {
              if (min == UNREACHED) {
                dist(sy)(sx)(y)(x) = arr(y)(x)
                dist(y)(x)(sy)(sx) = arr(y)(x)
              }
              loop((0 to 3).foldLeft(queue.tail) { (queue, i) =>
                val nx = x + dx(i)
                val ny = y + dy(i)
                if (nx >= 0 && nx < W &&
                  ny >= 0 && ny < H &&
                  S(ny)(nx) == '.' &&
                  arr(ny)(nx) == MAX) {
                  arr(ny)(nx) = arr(y)(x) + 1
                  queue.enqueue((nx, ny))
                } else queue
              }, min)
            }
          } else min
        }
        loop(Queue((sx, sy)), UNREACHED)
      }

      val xRange = (0 until W)
      val yRange = (0 until H)
      val xRangeRev = (0 until W).reverse
      val yRangeRev = (0 until H).reverse
      (for {
        sy <- yRange
        sx <- xRange
        if (S(sy)(sx) == '.')
        ey <- yRangeRev
        ex <- xRangeRev
        if (S(ey)(ex) == '.')
      } yield bfs(sx, sy, ex, ey)).max
    }

    println(solve(H, W, S))
  }

}


import scala.collection.immutable.Queue

object Main {

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

    val H, W = sc.nextInt(); sc.nextLine()
    val S = Array.fill(H)(sc.nextLine().trim.toCharArray)
    // スタートの決定にO(H*W)
    // ゴールの決定にO(H*W)
    // 最短路の探索にO(H*W)
    // 全探索するとO(H^3*W^3)
    // 64 * 10^6で間に合わない
    // dist(y)(x)(y')(x') := マスy,xからマスy',x'への最短路としておく
    def solve(H: Int, W: Int, S: Array[Array[Char]]): Int = {
      val MAX = Int.MaxValue
      val dist = Array.fill(H, W, H, W)(MAX)
      val dx = Array(0, 0, -1, 1)
      val dy = Array(-1, 1, 0, 0)

      def bfs(sx: Int, sy: Int, ex: Int, ey: Int): Int = {
        val UNREACHED = 401
        val arr = Array.fill(H, W)(MAX)
        arr(sy)(sx) = 0
        def loop(queue: Queue[(Int, Int)], min: Int): Int = {
          if (queue.nonEmpty) {
            val (x, y) = queue.head
            if (x == ex && y == ey) {
              val d = min min arr(ey)(ex)
              dist(sy)(sx)(y)(x) = d
              dist(y)(x)(sy)(sx) = d
              d
            } else if (dist(y)(x)(ey)(ex) != MAX) {
              loop(queue.tail, min min (arr(y)(x) + dist(y)(x)(ey)(ex)))
            } else {
              if (min == UNREACHED) {
                dist(sy)(sx)(y)(x) = arr(y)(x)
                dist(y)(x)(sy)(sx) = arr(y)(x)
              }
              loop((0 to 3).foldLeft(queue.tail) { (queue, i) =>
                val nx = x + dx(i)
                val ny = y + dy(i)
                if (nx >= 0 && nx < W &&
                  ny >= 0 && ny < H &&
                  S(ny)(nx) == '.' &&
                  arr(ny)(nx) == MAX) {
                  arr(ny)(nx) = arr(y)(x) + 1
                  queue.enqueue((nx, ny))
                } else queue
              }, min)
            }
          } else min
        }
        loop(Queue((sx, sy)), UNREACHED)
      }

      (for {
        sy <- 0 until H
        sx <- 0 until W
        if (S(sy)(sx) == '.')
        ey <- 0 until H
        ex <- 0 until W
        if (S(ey)(ex) == '.')
      } yield bfs(sx, sy, ex, ey)).max
    }

    println(solve(H, W, S))
  }

}


import scala.collection.immutable.Queue

object Main {

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

    val H, W = sc.nextInt(); sc.nextLine()
    val S = Array.fill(H)(sc.nextLine().trim.toCharArray)
    // スタートの決定にO(H*W)
    // ゴールの決定にO(H*W)
    // 最短路の探索にO(H*W)
    // 全探索するとO(H^3*W^3)
    // 64 * 10^6で間に合わない
    // dist(y)(x)(y')(x') := マスy,xからマスy',x'への最短路としておく
    def solve(H: Int, W: Int, S: Array[Array[Char]]): Int = {
      val MAX = Int.MaxValue
      val dist = Array.fill(H, W, H, W)(MAX)
      val dx = Array(0, 0, -1, 1)
      val dy = Array(-1, 1, 0, 0)

      def bfs(sx: Int, sy: Int, ex: Int, ey: Int): Int = {
        val UNREACHED = 401
        val arr = Array.fill(H, W)(MAX)
        arr(sy)(sx) = 0
        def loop(queue: Queue[(Int, Int)], min: Int): Int = {
          if (queue.nonEmpty) {
            val (x, y) = queue.head
            if (x == ex && y == ey) {
              min min arr(ey)(ex)
            } else if (dist(y)(x)(ey)(ex) != MAX) {
              loop(queue.tail, min min (arr(y)(x) + dist(y)(x)(ey)(ex)))
            } else {
              dist(sy)(sx)(y)(x) = dist(sy)(sx)(y)(x) min arr(y)(x)
              dist(y)(x)(sy)(sx) = dist(y)(x)(sy)(sx) min arr(y)(x)
              loop((0 to 3).foldLeft(queue.tail) { (queue, i) =>
                val nx = x + dx(i)
                val ny = y + dy(i)
                if (nx >= 0 && nx < W &&
                  ny >= 0 && ny < H &&
                  S(ny)(nx) == '.' &&
                  arr(ny)(nx) == MAX) {
                  arr(ny)(nx) = arr(y)(x) + 1
                  queue.enqueue((nx, ny))
                } else queue
              }, min)
            }
          } else min
        }
        loop(Queue((sx, sy)), UNREACHED)
      }

      (for {
        sy <- 0 until H
        sx <- 0 until W
        if (S(sy)(sx) == '.')
        ey <- 0 until H
        ex <- 0 until W
        if (S(ey)(ex) == '.')
      } yield bfs(sx, sy, ex, ey)).max
    }

    println(solve(H, W, S))
  }

}


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 H, W = in.next().toInt
  val S = new Array[String](H)
  for (i <- 0 until H)
    S(i) = in.next()

  //
  var ans = 0
  val q = new Queue[((Int, Int), Int)]
  val dp = Array.ofDim[Boolean](H, W)

  for (ny <- 0 until H)
    for (nx <- 0 until W) {
      for (y <- 0 until H; x <- 0 until W) {
        dp(y)(x) = false
      }

      q.enqueue(((nx, ny), 0))
      while (!q.isEmpty) {
        val ((x, y), d) = q.dequeue()
        if (!dp(y)(x) && S(y)(x) == '.') {
          dp(y)(x) = true
          ans = ans max d

          Seq((x-1, y), (x+1, y), (x, y-1), (x, y+1))
            .filter { case (x, y) => 0 <= x && x < W && 0 <= y && y < H }
            .foreach { p =>
              q.enqueue((p, d+1))
            }
        }
      }
    }

  println(ans)

}

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

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


object Main extends App {
  val n = scala.io.StdIn.readInt()
  var playList = Vector.empty[(String, Int)]
  (1 to n).foreach { _ =>
    val stInput = scala.io.StdIn.readLine()
    val stInputArray = stInput.split(" ")
    val title = stInputArray(0)
    val time = stInputArray(1).toInt
    playList :+= (title, time)
  }
  val sleepTitle = scala.io.StdIn.readLine()
  var sleepTitleFind = false
  var sleepTime = 0
  playList.foreach { p =>
    if (sleepTitleFind) {
      sleepTime = sleepTime + p._2
    } else {
      if (p._1 == sleepTitle) {
        sleepTitleFind = true
      }
    }
  }
  println(sleepTime)
}

Score : 200 points

Problem Statement

Niwango created a playlist of N songs.
The title and the duration of the i-th song are s_i and t_i seconds, respectively.
It is guaranteed that s_1,\ldots,s_N are all distinct.

Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, without any pause in between.)
However, he fell asleep during his work, and he woke up after all the songs were played.
According to his record, it turned out that he fell asleep at the very end of the song titled X.

Find the duration of time when some song was played while Niwango was asleep.

Constraints

1 \leq N \leq 50

s_i and X are strings of length between 1 and 100 (inclusive) consisting of lowercase English letters.

s_1,\ldots,s_N are distinct.

There exists an integer i such that s_i = X.

1 \leq t_i \leq 1000

t_i is an integer.

Input

Input is given from Standard Input in the following format:

N
s_1 t_1
\vdots
s_{N} t_N
X

Output

Print the answer.

Sample Input 1

3
dwango 2
sixth 5
prelims 25
dwango

Sample Output 1

30

While Niwango was asleep, two songs were played: sixth and prelims.

The answer is the total duration of these songs, 30.

Sample Input 2

1
abcde 1000
abcde

Sample Output 2

0

No songs were played while Niwango was asleep.

In such a case, the total duration of songs is 0.

Sample Input 3

15
ypnxn 279
kgjgwx 464
qquhuwq 327
rxing 549
pmuduhznoaqu 832
dagktgdarveusju 595
wunfagppcoi 200
dhavrncwfw 720
jpcmigg 658
wrczqxycivdqn 639
mcmkkbnjfeod 992
htqvkgkbhtytsz 130
twflegsjz 467
dswxxrxuzzfhkp 989
szfwtzfpnscgue 958
pmuduhznoaqu

Sample Output 3

6348


object Main extends App {
  val Array(k,x) = readLine.split(" ").map{_.toInt}
  println(if (k*500 >= x) "Yes" else "No")
}

Score : 100 points

Problem Statement

Takahashi has K 500-yen coins. (Yen is the currency of Japan.)
If these coins add up to X yen or more, print Yes; otherwise, print No.

Constraints

1 \leq K \leq 100

1 \leq X \leq 10^5

Input

Input is given from Standard Input in the following format:

K X

Output

If the coins add up to X yen or more, print Yes; otherwise, print No.

Sample Input 1

2 900

Sample Output 1

Yes

Two 500-yen coins add up to 1000 yen, which is not less than X = 900 yen.

Sample Input 2

1 501

Sample Output 2

No

One 500-yen coin is worth 500 yen, which is less than X = 501 yen.

Sample Input 3

4 2000

Sample Output 3

Yes

Four 500-yen coins add up to 2000 yen, which is not less than X = 2000 yen.


object Main {
  def main(args: Array[String]): Unit = {
    val nums = io.StdIn.readLine.split(" ").map{_.toInt}
    if(500*nums(0) >= nums(1)) println("Yes")
    else                      println("No")
  }
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val k = sc.nextInt
  val x = sc.nextInt
  if(k * 500 >= x){
    println("Yes")
  }else{
    println("No")
  }
}


import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
  val n = sc.nextLine().toInt
  val s = sc.nextLine()

  println(m(0, 0))

  def m(i: Int, count: Int): Int = {
    s.indexOf("ABC", i) match {
      case -1 => count
      case ni => m(ni + 1, count + 1)
    }
  }

}

Score : 200 points

Problem Statement

We have a string S of length N consisting of uppercase English letters.

How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)?

Constraints

3 \leq N \leq 50

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print number of occurrences of ABC in S as contiguous subsequences.

Sample Input 1

10
ZABCDBABCQ

Sample Output 1

2

Two contiguous subsequences of S are equal to ABC: the 2-nd through 4-th characters, and the 7-th through 9-th characters.

Sample Input 2

19
THREEONEFOURONEFIVE

Sample Output 2

0

No contiguous subsequences of S are equal to ABC.

Sample Input 3

33
ABCCABCBABCCABACBCBBABCBCBCBCABCB

Sample Output 3

5


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  val s = sc.next
  val replaced = s.replace("ABC","").length
  println((n - replaced) / 3 )
}


import scala.math.abs

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  val P = Vector.fill(N)(sc.nextInt())
  val Q = Vector.fill(N)(sc.nextInt())
  val permutations = (1 to N).permutations.toList
  val a = permutations.indexOf(P) + 1
  val b = permutations.indexOf(Q) + 1
  println(abs(a - b))
}

Score : 300 points

Problem Statement

We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N)).

There are N! possible permutations of size N. Among them, let P and Q be the a-th and b-th lexicographically smallest permutations, respectively. Find |a - b|.

Notes

For two sequences X and Y, X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k.

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 ... P_N
Q_1 Q_2 ... Q_N

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

There are 6 permutations of size 3: (1,~2,~3), (1,~3,~2), (2,~1,~3), (2,~3,~1), (3,~1,~2), and (3,~2,~1). Among them, (1,~3,~2) and (3,~1,~2) come 2-nd and 5-th in lexicographical order, so the answer is |2 - 5| = 3.

Sample Input 2

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

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0


object Main {
  def main(args: Array[String]): Unit = {
    val factors = io.StdIn.readLine.split(" ").map{_.toLong}
    val nums    = io.StdIn.readLine.split(" ").map{_.toLong}

    var least_common_multiple = 1L

    nums.foreach { i =>
      least_common_multiple *= i/2L/calcGcd(least_common_multiple, i/2L)
    }

    var count = 0
    var flag  = true

    while(flag) {
      val check_num = (2*count + 1)*least_common_multiple
      if(check_num <= factors(1)) count += 1
      else flag = false
    }

    println(count)

  }

    def calcGcd(num1: Long, num2: Long): Long = {
    var a = num1
    var b = num2
    if(a > b) {
      val tmp = a
      a = b
      b = tmp
    }
    var r = b%a

    while(r != 0L) {
      b = a
      a = r
      r = b%a
    }
    return a
  }
}

Score : 400 points

Problem Statement

Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.

Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):

There exists a non-negative integer p such that X= a_k \times (p+0.5).

Find the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^9

2 \leq a_i \leq 10^9

a_i is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 a_2 ... a_N

Output

Print the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Sample Input 1

2 50
6 10

Sample Output 1

2

15 = 6 \times 2.5

15 = 10 \times 1.5

45 = 6 \times 7.5

45 = 10 \times 4.5

Thus, 15 and 45 are semi-common multiples of A. There are no other semi-common multiples of A between 1 and 50, so the answer is 2.

Sample Input 2

3 100
14 22 40

Sample Output 2

0

The answer can be 0.

Sample Input 3

5 1000000000
6 6 2 6 2

Sample Output 3

166666667


object Main extends App {
  val Array(s,t) = readLine.split(" ")

  println(s"$t$s")
}

Score : 100 points

Problem Statement

Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string.

Constraints

S and T are strings consisting of lowercase English letters.

The lengths of S and T are between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S T

Output

Print the resulting string.

Sample Input 1

oder atc

Sample Output 1

atcoder

When S = oder and T = atc, concatenating T and S in this order results in atcoder.

Sample Input 2

humu humu

Sample Output 2

humuhumu


object Main extends App{
  import scala.io.StdIn._
  val Array(a,b,k)=readLine().split(" ").map(_.toLong)
  println(if(k>a) s"0 ${Math.max(b - (k - a),0)}"else s"${a-k} ${b}")
}

Score : 200 points

Problem Statement

Takahashi has A cookies, and Aoki has B cookies.
Takahashi will do the following action K times:

If Takahashi has one or more cookies, eat one of his cookies.

Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies.

If they both have no cookies, do nothing.

In the end, how many cookies will Takahashi and Aoki have, respectively?

Constraints

0 \leq A \leq 10^{12}

0 \leq B \leq 10^{12}

0 \leq K \leq 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the numbers of Takahashi's and Aoki's cookies after K actions.

Sample Input 1

2 3 3

Sample Output 1

0 2

Takahashi will do the following:

He has two cookies, so he eats one of them.

Now he has one cookie left, and he eats it.

Now he has no cookies left, but Aoki has three, so Takahashi eats one of them.

Thus, in the end, Takahashi will have 0 cookies, and Aoki will have 2.

Sample Input 2

500000000000 500000000000 1000000000000

Sample Output 2

0 0

Watch out for overflows.


object Main {

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

    val A, B, K = sc.nextLong()

    val (a, b) = if (K <= A) {
      (A - K, B)
    } else {
      (0, (B - (K - A) max 0))
    }
    println(s"$a $b")
  }

}


import scala.io.StdIn._

object Main extends App {

  val x = readInt()

  def solve(): Int = {
    var ans = x
    while(!isPrime(ans)) ans += 1
    ans
  }

  def isPrime(num: Int): Boolean = {
    if(num <= 1) false
    else if(num == 2) true
    else (2 until num).forall(num % _ != 0)
  }

  println(solve())

}

Score: 300 points

Problem Statement

Find the minimum prime number greater than or equal to X.

Notes

A prime number is an integer greater than 1 that cannot be evenly divided by any positive integer except 1 and itself.

For example, 2, 3, and 5 are prime numbers, while 4 and 6 are not.

Constraints

2 \le X \le 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the minimum prime number greater than or equal to X.

Sample Input 1

20

Sample Output 1

23

The minimum prime number greater than or equal to 20 is 23.

Sample Input 2

2

Sample Output 2

2

X itself can be a prime number.

Sample Input 3

99992

Sample Output 3

100003


import java.util.Scanner

import scala.collection.mutable.ListBuffer

object PrimeInt {
  val ps: Stream[Int] = 2 #:: Stream.from(3).filter(i => ps.takeWhile(j => j * j <= i).forall(k => i % k > 0))

  def isPrime(n: Int): Boolean = ps.takeWhile(_ <= n).contains(n)
}

object Primes extends Iterable[Long] {
  var checked = 2L
  val xs = ListBuffer(2L)

  def contains(i: Long): Boolean = xs.takeWhile(_ <= i).contains(i)

  def apply(i: Int): Long = {
    while (xs.length <= i) {
      var n = checked + 1
      while (xs.takeWhile(j => j * j <= n).exists(n % _ == 0)) {
        n += 1
      }
      xs.append(n)
      checked = n
    }
    xs(i)
  }

  override def iterator: Iterator[Long] = new Iterator[Long] {
    var i = 0

    override def hasNext: Boolean = true

    override def next(): Long = {
      val x = apply(i); i += 1; x
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val result = solve(new Scanner(System.in))
    if (result.length > 0) println(result)
  }

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

  def prime(n: Int, primes: Seq[Int]) = primes.forall(p => n % p != 0)

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

    var i = X
    while (!PrimeInt.isPrime(i)) i += 1

    i.toString
  }
}


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

    val n = sc.nextInt()
    val k = sc.nextInt()
    val r = sc.nextInt()
    val s = sc.nextInt()
    val p = sc.nextInt()
    sc.nextLine()
    val str = sc.nextLine().toCharArray
    val qd = new QD(n, k, r, s, p)
    println(qd.ans(str))
  }
}

class QD(n: Int, k: Int, r: Long, s: Long, p: Long) {
  def judge(c: Char):Long = {
    if(c.equals('r')) {
      this.p
    } else if(c.equals('s')) {
      this.r
    } else if(c.equals('p')) {
      this.s
    } else {
      0
    }
  }

  def ans(str: Array[Char]): Long = {
    var result = 0L
    for(i <- Range(0, this.n)) {
      if(i >= k && str(i).equals(str(i-k))) {
        str(i) = '_'
      } else {
        result += judge(str(i))
      }
    }
    result
  }
}

Score : 400 points

Problem Statement

At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:

The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)

Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):

R points for winning with Rock;

S points for winning with Scissors;

P points for winning with Paper.

However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)

Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.

The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively.

What is the maximum total score earned in the game by adequately choosing the hand to play in each round?

Notes

In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.

If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;

if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;

if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;

if both players play the same hand, it is a draw.

Constraints

2 \leq N \leq 10^5

1 \leq K \leq N-1

1 \leq R,S,P \leq 10^4

N,K,R,S, and P are all integers.

|T| = N

T consists of r, p, and s.

Input

Input is given from Standard Input in the following format:

N K
R S P
T

Output

Print the maximum total score earned in the game.

Sample Input 1

5 2
8 7 6
rsrpr

Sample Output 1

27

The machine will play {Rock, Scissors, Rock, Paper, Rock}.

We can, for example, play {Paper, Rock, Rock, Scissors, Paper} against it to earn 27 points.
We cannot earn more points, so the answer is 27.

Sample Input 2

7 1
100 10 1
ssssppr

Sample Output 2

211

Sample Input 3

30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr

Sample Output 3

4996


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

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

  val N, M = in.next().toInt
  val _A = Array.fill[Int](N+1)(Int.MaxValue)
  for (i <- 1 to N) {
    _A(i) = in.next().toInt
  }

  //
  val A = _A.sorted.reverse

  val accs = new Array[Long](N+1)
  accs(1) = A(1)
  for (i <- 2 to N)
    accs(i) = A(i) + A(i-1)

  // 条件を満たす最大の値を返す
  def bs(_min: Int, _max: Int, i: Int, m: Int): Int = {
    def check(t: Int): Boolean = {
      A(t) + A(i) >= m
    }

    def func(min: Int, max: Int): Int = {
      val mid: Int = (max + min) / 2;
      (max - min) match {
        case 0 | 1 =>
          check(max) match {
            case true  => max
            case false => min
          }
        case _ =>
          (check(mid)) match {
            case true  => func(mid, max)
            case false => func(min, mid)
          }
      }
    }

    func(_min, _max)
  }

  // 条件を満たす最大の値を返す
  def binarySearch(_min: Int, _max: Int): Int = {
    def check(m: Int): Boolean = {
      var res = 0
      for (i <- 1 to N) {
        val b = bs(0, N, i, m)
        res += b
      }
      res >= M
    }

    def func(min: Int, max: Int): Int = {
      val mid: Int = (max + min) / 2;
      (max - min) match {
        case 0 | 1 =>
          check(max) match {
            case true  => max
            case false => min
          }
        case _ =>
          (check(mid)) match {
            case true  => func(mid, max)
            case false => func(min, mid)
          }
      }
    }

    func(_min, _max)
  }

  val maxPair = binarySearch(1, 1e5.toInt * 2)
  var ans = 0L
  for (i <- 1 to N) {
    val ind = bs(0, N, i, maxPair)
    ans += accs(ind) + A(i) * ind
  }

  println(ans)
}

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

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

Score : 500 points

Problem Statement

Takahashi has come to a party as a special guest.
There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i.

Takahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0).
A handshake will be performed as follows:

Takahashi chooses one (ordinary) guest x for his left hand and another guest y for his right hand (x and y can be the same).

Then, he shakes the left hand of Guest x and the right hand of Guest y simultaneously to increase the happiness by A_x+A_y.

However, Takahashi should not perform the same handshake more than once. Formally, the following condition must hold:

Assume that, in the k-th handshake, Takahashi shakes the left hand of Guest x_k and the right hand of Guest y_k. Then, there is no pair p, q (1 \leq p < q \leq M) such that (x_p,y_p)=(x_q,y_q).

What is the maximum possible happiness after M handshakes?

Constraints

1 \leq N \leq 10^5

1 \leq M \leq N^2

1 \leq A_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the maximum possible happiness after M handshakes.

Sample Input 1

5 3
10 14 19 34 33

Sample Output 1

202

Let us say that Takahashi performs the following handshakes:

In the first handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 4.

In the second handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 5.

In the third handshake, Takahashi shakes the left hand of Guest 5 and the right hand of Guest 4.

Then, we will have the happiness of (34+34)+(34+33)+(33+34)=202.

We cannot achieve the happiness of 203 or greater, so the answer is 202.

Sample Input 2

9 14
1 3 5 110 24 21 34 5 3

Sample Output 2

1837

Sample Input 3

9 73
67597 52981 5828 66249 75177 64141 40773 79105 16076

Sample Output 3

8128170


object Main {

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

    val N = sc.nextInt()
    val M = sc.nextLong()
    val A = Array.fill(N)(sc.nextLong()).sorted(Ordering.Long.reverse)
    // 左手と右手で握手できる.
    // その時, 左手で握手した人のパワー + 右手で握手した人のパワーが上昇する
    // しかし, 全く同じ握手を二回以上行えない,
    // 右手と左手を入れ替えて握手することは可能, また, 両手で握手することも可能
    // パワーが大きい順に貪欲に握手していけば良さそうな気がする
    // まず、パワーが大きい順にソート.
    // 左から, 両手で握手して, 左手で握手,
    // ただ, Mが10^5なので, このままでは間に合わない
    // 握手を行う人と, 握手を行わない人を分別する必要がある
    // 二分探索でその境界を探す
    // 握手を行う人の, 握手の組み合わせの数, 「握手する人から2つを選ぶ数」がM以上になる境界
    // 「握手する人から2つを選ぶ数」は, 「握手をする人 * 握手をする人」通りある
    // そしてその仮定の素では、選んだ全ての人と1 + 2 * (L - 1)回握手することになる, 両手は一回, 他の人と左手, 右手
    // そして探したM以上になるやつで, Mになるまで小さい順から握手を減らしていけばいい
    // うーーん、違うか
//    def solve(N: Int, M: Long, A: Array[Long]): Long = {
//      // 組み合わせの数が M 以上になる握手人数
//      def lowerBounds(M: Long): Int = {
//        def loop(left: Int, right: Int): Int =
//          if (right - left > 1) {
//            val mid = left + (right - left) / 2
//            if (mid * mid >= M) loop(left, mid)
//            else loop(mid, right)
//          } else right
//        loop(-1, N)
//      }
//      val L = lowerBounds(M)
//      val MAXP = (0 until L).map(i => A(i)).sum * (2 * (L - 1) + 1)// 最大数
//      val AA = A.take(L).sorted // 対象にしているやつのみ選び昇順にソートする
//
//      println(MAXP, L)
//      def loop(i: Int, rest: Long, acm: Long): Long =
//        if (rest > M) {
//          if (M - rest >= 3) {
//            loop(i + 1, rest - 3, acm - 4 * AA(i) - 2 * AA(i+1))
//          } else if (M - rest >= 2) {
//            loop(i + 1, rest - 2, acm - 3 * AA(i) - 1 * AA(i+1))
//          } else {
//            loop(i + 1, rest - 1, acm - 2 * AA(i))
//          }
//        } else acm
//      loop(0, L, MAXP)
//    }

    // 単に全ての組み合わせの中から幸福度が高い順番にM個取り出せば良いが、間に合わない
    // 組み合わせの中から高い順にM個取り出せばいい、ということは,
    // 幸福度が上がる量が X 以上の 組み合わせが M通り以上ある場合の最小のXについて求める
    // 左手で握手する人を決めた場合、右手で握手できる人が何人いるか？
    // 累積和のくだりよくわからんので, 左手で握手する人を決め,
    // 右手で握手できる人数を二分探索で求めることにする
    // 先に大きい順に並び変えておく. O(NlogNlogN)で求まるはず.
    // そのXが求まった場合, それを満たす場合の計算をする
    def solve(N: Int, M: Long, A: Array[Long]): Long = {
      val AMAX = Math.pow(10, 5).toInt * 2
      def lowerBounds(M: Long): Long = {
        def loop(left: Long, right: Long): Long =
          if (right - left > 1) {
            val mid = left + (right - left) / 2
            if (check(mid)) loop(mid, right)
            else loop(left, mid)
          } else left
        loop(-1, AMAX)
      }
      def check(X: Long): Boolean =
        (0 until N).foldLeft(0L)((acm, l) => {
          val r = lowerBounds2(X, l)
          acm + (r + 1)
        }) >= M
      // lを決めた時に,X以上にできる数のindex, = lの時見つからなかかった
      def lowerBounds2(X: Long, l: Int): Int = {
        def loop(left: Int, right: Int): Int =
          if (right - left > 1) {
            val mid = left + (right - left) / 2
            if (A(l) + A(mid) >= X) loop(mid, right)
            else loop(left, mid)
          } else left
        loop(-1, N)
      }

      val R = new Array[Long](N)
      R(0) = A(0)
      (1 until N).foreach(i => {
        R(i) += A(i) + R(i-1)
      })
      val X = lowerBounds(M)
      // M回を超える場合があるので, 超えた分を X * 超えた分引く必要がある
      val over = (0 until N).foldLeft(0L)((acm, l) => {
        val r = lowerBounds2(X, l)
        acm + (r + 1)
      }) - M
      (0 until N).foldLeft(0L)((acm, l) => {
        val r = lowerBounds2(X, l)
        if (r >= 0) {
          acm + R(r) + A(l) * (r + 1)
        } else acm
      }) - over * X
    }

    println(solve(N, M, A))
  }

}


object Main {

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

    val N, A, B = sc.nextLong()

    // 負けが右, 勝ちが左へ
    // 一番左で勝っても動かず、一番右で負けても動かない
    // 同時に動く場合, 一度に2ずつ近づける
    // * L = 2N + 1 台間にある場合には N ラウンドでOK
    // * L = 2N 台間にある場合には そのまま近づいていってもダメなので
    //   (A max B) min ((N - A) max (N - B)) で良い？
    def solve(N: Long, A: Long, B: Long): Long = {
      val L = B - A
      if ((L - 1L) % 2L == 1L) L / 2L
      else ((A - 1) min (N - B) + 1 + (B - A - 1) / 2)
    }

    println(solve(N, A, B))
  }

}

Score : 300 points

Problem Statement

2N players are running a competitive table tennis training on N tables numbered from 1 to N.

The training consists of rounds.
In each round, the players form N pairs, one pair per table.
In each pair, competitors play a match against each other.
As a result, one of them wins and the other one loses.

The winner of the match on table X plays on table X-1 in the next round,
except for the winner of the match on table 1 who stays at table 1.

Similarly, the loser of the match on table X plays on table X+1 in the next round,
except for the loser of the match on table N who stays at table N.

Two friends are playing their first round matches on distinct tables A and B.
Let's assume that the friends are strong enough to win or lose any match at will.
What is the smallest number of rounds after which the friends can get to play a match against each other?

Constraints

2 \leq N \leq 10^{18}

1 \leq A < B \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the smallest number of rounds after which the friends can get to play a match against each other.

Sample Input 1

5 2 4

Sample Output 1

1

If the first friend loses their match and the second friend wins their match, they will both move to table 3 and play each other in the next round.

Sample Input 2

5 2 3

Sample Output 2

2

If both friends win two matches in a row, they will both move to table 1.


object Main {
  def main(args: Array[String]): Unit = {
    val str_len = io.StdIn.readInt
    val Array(str1, str2) = io.StdIn.readLine.split(" ")
    var ans_str = ""

    (0 until str_len).foreach{ i =>
      ans_str += str1(i).toString + str2(i)
    }
    println(ans_str)
  }
}

Score : 200 points

Problem Statement

Given are strings s and t of length N each, both consisting of lowercase English letters.

Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of S, the N-th character of T. Print this new string.

Constraints

1 \leq N \leq 100

|S| = |T| = N

S and T are strings consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S T

Output

Print the string formed.

Sample Input 1

2
ip cc

Sample Output 1

icpc

Sample Input 2

8
hmhmnknk uuuuuuuu

Sample Output 2

humuhumunukunuku

Sample Input 3

5
aaaaa aaaaa

Sample Output 3

aaaaaaaaaa