object Main {

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

    val N = sc.nextInt()
    val A = Array.fill(N)(sc.nextInt()).sorted
    val B = Array.fill(N)(sc.nextInt())
    val C = Array.fill(N)(sc.nextInt()).sorted(Ordering.Int.reverse)

    // 3カテゴリーのパーツがそれぞれN個ずつあります
    // パーツのサイズ
    // 中部のパーツのサイズは、上部のパーツのサイズより真に大きく
    // 下部のパーツのサイズは、中部のパーツのサイズより真に大きくなければなりません
    // 作れる祭壇は何種類あるでしょうか/
    // ただし 2つの祭壇が異なるとは, 上部, 中部, 下部に使われるピースのうち少なくとも1つが異なる
    // 1つ決めた時の, そのパーツより大きいパーツはO(log N)で出すことができる
    // 普通にやると, O(N^2logN)とかになる, 間に合わない
    // なので, 中部を先に決めておく
    // 中部を決めた時, その時上部のパーツに使えるのは, 中部より小さいもの
    // 下部のパーツに使えるのは, 中部より大きいもの,
    // これらは それぞれ O(log N)で求めることができ, O(NlogN)で求めることができる

    def upperBounds(A: Array[Int], b: Int): Int = {
      def recursive(l: Int, r: Int): Int =
        if (r - l > 1) {
          val mid = l + (r - l) / 2
          if (A(mid) >= b) recursive(l, mid)
          else recursive(mid, r)
        } else l
      recursive(-1, N)
    }

    def lowerBounds(C: Array[Int], b: Int): Int = {
      def recursive(l: Int, r: Int): Int =
        if (r - l > 1) {
          val mid = l + (r - l) / 2
          if (C(mid) <= b) recursive(l, mid)
          else recursive(mid, r)
        } else l
      recursive(-1, N)
    }

    val r = (0 until N).foldLeft(0L) { case (sum, i) =>
      sum + (upperBounds(A, B(i)) + 1L) * (lowerBounds(C, B(i)) + 1L)
    }

    println(r)
  }

}

Score : 300 points

Problem Statement

The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.

He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.

To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.

How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9(1\leq i\leq N)

1 \leq B_i \leq 10^9(1\leq i\leq N)

1 \leq C_i \leq 10^9(1\leq i\leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N
B_1 ... B_N
C_1 ... C_N

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

Upper: 1-st part, Middle: 1-st part, Lower: 1-st part

Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part

Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output 3

87


object Main extends App {
  val s = io.StdIn.readLine()
  val check = s.filterNot(_=='x')

  if(check!=check.reverse){
    println(-1)
    sys.exit()
  }

  var ans = 0
  var first = 0
  var latter = 0
  var i = 0
  while( i < (s.length + first + latter)/2){
    if( s(i - first) != s(-1+(-1)*i+latter+s.length) ){
      ans += 1
      if( s(i-first)=='x' ){
        latter += 1
      }else{
        first += 1
      }
    }
    i += 1
  }

  println(ans)

}

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

Score : 400 points

Problem Statement

We have a string s consisting of lowercase English letters.
Snuke can perform the following operation repeatedly:

Insert a letter x to any position in s of his choice, including the beginning and end of s.

Snuke's objective is to turn s into a palindrome.
Determine whether the objective is achievable. If it is achievable, find the minimum number of operations required.

Notes

A palindrome is a string that reads the same forward and backward.
For example, a, aa, abba and abcba are palindromes, while ab, abab and abcda are not.

Constraints

1 \leq |s| \leq 10^5

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

If the objective is achievable, print the number of operations required.
If it is not, print -1 instead.

Sample Input 1

xabxa

Sample Output 1

2

One solution is as follows (newly inserted x are shown in bold):

xabxa → xaxbxa → xaxbxax

Sample Input 2

ab

Sample Output 2

-1

No sequence of operations can turn s into a palindrome.

Sample Input 3

a

Sample Output 3

0

s is a palindrome already at the beginning.

Sample Input 4

oxxx

Sample Output 4

3

One solution is as follows:

oxxx → xoxxx → xxoxxx → xxxoxxx

Submitted source-code file size, in bytes.

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

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


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

object Main extends App{
  val sc = new java.util.Scanner(System.in)
  val a = sc.nextInt
  val b = sc.nextInt
  val c = sc.nextInt
    if(a==b){
    println(c)
  }
  else if(a==c){
    println(b)
  }
  else{
    println(a)
  }
}

Score : 100 points

Problem Statement

You are given three integers, A, B and C.

Among them, two are the same, but the remaining one is different from the rest.

For example, when A=5,B=7,C=5, A and C are the same, but B is different.

Find the one that is different from the rest among the given three integers.

Constraints

-100 \leq A,B,C \leq 100

A, B and C are integers.

The input satisfies the condition in the statement.

Input

Input is given from Standard Input in the following format:

A B C

Output

Among A, B and C, print the integer that is different from the rest.

Sample Input 1

5 7 5

Sample Output 1

7

This is the same case as the one in the statement.

Sample Input 2

1 1 7

Sample Output 2

7

In this case, C is the one we seek.

Sample Input 3

-100 100 100

Sample Output 3

-100


object Main {

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

    val N = sc.nextInt()
    // 制約から, h, n, w <= 3500を探索することになる
    val (h, n, w) = (for {
      h <- 1L to 3500L
      n <- 1L to 3500L
      top = N * h * n
      bottom = 4L * h * n - N * n - N * h
      if bottom > 0
      if top % bottom == 0
      w = top / bottom
    } yield (h, n, w)).head

    println(s"$h $n $w")
  }

}

Score : 300 points

Problem Statement

You are given an integer N.

Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.

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

Constraints

It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.

Inputs

Input is given from Standard Input in the following format:

N

Outputs

Print a triple of positive integers h, n and w that satisfies the condition, in the following format:

h n w

Sample Input 1

2

Sample Output 1

1 2 2

4/2 = 1/1 + 1/2 + 1/2.

Sample Input 2

3485

Sample Output 2

872 1012974 1539173474040

It is allowed to use an integer exceeding 3500 in a solution.

Sample Input 3

4664

Sample Output 3

3498 3498 3498


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

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val (a, b) = na2(N)
    val del = Array.ofDim[Boolean](N)
    var ans = 0L
    REP_r(30) { k =>
      if ((K>>k&1) == 1) {
        // 0の場合
        var sum = 0L
        REP(N) { i =>
          if (!del(i) && (a(i)>>k&1) == 0) {
            sum += b(i)
          }
        }
        ans = max(ans, sum)
        // delは変わらない
      } else {
        // 0の場合
        REP(N) { i =>
          if (!del(i) && (a(i)>>k&1) == 1) {
            del(i) = true
          }
        }
      }
//      debug(del)
    }

    var sum = 0L
    REP(N) { i =>
      if (!del(i)) {
        sum += b(i)
      }
    }
    ans = max(ans, sum)

    out.println(ans)
  }
}

Score : 500 points

Problem Statement

Seisu-ya, a store specializing in non-negative integers, sells N non-negative integers. The i-th integer is A_i and has a utility of B_i.
There may be multiple equal integers with different utilities.

Takahashi will buy some integers in this store. He can buy a combination of integers whose bitwise OR is less than or equal to K. He wants the sum of utilities of purchased integers to be as large as possible.

Find the maximum possible sum of utilities of purchased integers.

Constraints

1 \leq N \leq 10^5

0 \leq K < 2^{30}

0 \leq A_i < 2^{30}(1\leq i\leq N)

1 \leq B_i \leq 10^9(1\leq i\leq N)

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N K
A_1 B_1
:
A_N B_N

Outputs

Print the maximum possible sum of utilities of purchased integers.

Sample Input 1

3 5
3 3
4 4
2 5

Sample Output 1

8

Buy 2 and 3 to achieve the maximum possible total utility, 8.

Sample Input 2

3 6
3 3
4 4
2 5

Sample Output 2

9

Buy 2 and 4 to achieve the maximum possible total utility, 9.

Sample Input 3

7 14
10 5
7 4
11 4
9 8
3 6
6 2
8 9

Sample Output 3

32


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

	N match {
		case 'Y'::'A'::'K'::'I'::rest => println("Yes")
		case _ => println("No")
	}

}

Score : 100 points

Problem Statement

Ringo is giving a present to Snuke.

Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with YAKI in Japanese, and does not like other things.

You are given a string S representing the Japanese name of Ringo's present to Snuke. Determine whether S starts with YAKI.

Constraints

1 \leq |S| \leq 10

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S starts with YAKI, print Yes; otherwise, print No.

Sample Input 1

YAKINIKU

Sample Output 1

Yes

YAKINIKU starts with YAKI.

Sample Input 2

TAKOYAKI

Sample Output 2

No

TAKOYAKI (a Japanese snack. tako: octopus) does not start with YAKI.

Sample Input 3

YAK

Sample Output 3

No


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}

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

  val N, M, R = in.next().toInt
  val r = new Array[Int](R)
  for (i <- 0 until R) {
    r(i) = in.next().toInt
  }

  val d = Array.ofDim[Long](N+1, N+1)  // d[a][b] は辺 e = (a, b) のコスト(存在しない場合はINF, ただし d[i][i] = 0 とする)
  val MAX = Integer.MAX_VALUE

  // 初期化
  for(i <- 0 to N; j <- 0 to N){
    if(i == j)
      d(i)(j) = 0
    else
      d(i)(j) = MAX
  }

  // input d
  for(_ <- 0 until M) {
    val a, b, c = in.next().toInt
    d(a)(b) = c
    d(b)(a) = c
  }

  // function
  def warshall_floyd() =
    for(k <- 1 to N; i <- 1 to N; j <- 1 to N){
      d(i)(j) = Math.min(d(i)(j), d(i)(k) + d(k)(j))
    }

  // main process
  warshall_floyd()

  var ans: Long = Integer.MAX_VALUE
  for(pl <- r.toList.permutations) {
    var tmp = 0L
    for(i <- 0 until pl.length - 1) {
      tmp += d(pl(i))(pl(i+1))
    }
    ans = Math.min(ans, tmp)
  }

  println(ans)
}

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

Score : 400 points

Problem Statement

There are N towns in the State of Atcoder, connected by M bidirectional roads.

The i-th road connects Town A_i and B_i and has a length of C_i.

Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order).

She will fly to the first town she visits, and fly back from the last town she visits, but for the rest of the trip she will have to travel by road.

If she visits the towns in the order that minimizes the distance traveled by road, what will that distance be?

Constraints

2≤N≤200

1≤M≤N×(N-1)/2

2≤R≤min(8,N) (min(8,N) is the smaller of 8 and N.)

r_i≠r_j (i≠j)

1≤A_i,B_i≤N, A_i≠B_i

(A_i,B_i)≠(A_j,B_j),(A_i,B_i)≠(B_j,A_j) (i≠j)

1≤C_i≤100000

Every town can be reached from every town by road.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M

Output

Print the distance traveled by road if Joisino visits the towns in the order that minimizes it.

Sample Input 1

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

Sample Output 1

2

For example, if she visits the towns in the order of 1, 2, 3, the distance traveled will be 2, which is the minimum possible.

Sample Input 2

3 3 2
1 3
2 3 2
1 3 6
1 2 2

Sample Output 2

4

The shortest distance between Towns 1 and 3 is 4. Thus, whether she visits Town 1 or 3 first, the distance traveled will be 4.

Sample Input 3

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

Sample Output 3

3


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}

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

  val N, M, R = in.next().toInt
  val r = new Array[Int](R)
  for (i <- 0 until R) {
    r(i) = in.next().toInt
  }

  val d = Array.ofDim[Long](N+1, N+1)  // d[a][b] は辺 e = (a, b) のコスト(存在しない場合はINF, ただし d[i][i] = 0 とする)
  val MAX = 100002L

  // 初期化
  for(i <- 0 to N; j <- 0 to N){
    if(i == j)
      d(i)(j) = 0
    else
      d(i)(j) = MAX
  }

  // input d
  for(i <- 0 until M) {
    val a, b, c = in.next().toInt
    d(a)(b) = c
    d(b)(a) = c
  }

  // function
  def warshall_floyd() =
    for(k <- 1 to N; i <- 1 to N; j <- 1 to N){
      d(i)(j) = Math.min(d(i)(j), d(i)(k) + d(k)(j))
    }

  // main process
  warshall_floyd()

  var ans: Long = Integer.MAX_VALUE
  for(pl <- r.toList.permutations) {
    var tmp = 0L
    for(i <- 0 until pl.length - 1) {
      tmp += d(pl(i))(pl(i+1))
    }
    ans = Math.min(ans, tmp)
  }

  println(ans)
}

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


import scala.io.{StdIn => in}

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

  val s = in.readLine.toCharArray()
  for(i <- 0 until s.size by 2) {
    out.print(s(i))
  }

  out.println
  out.flush
}

Score : 200 points

Problem Statement

You are given a string s consisting of lowercase English letters. Extract all the characters in the odd-indexed positions and print the string obtained by concatenating them. Here, the leftmost character is assigned the index 1.

Constraints

Each character in s is a lowercase English letter.

1≤|s|≤10^5

Input

The input is given from Standard Input in the following format:

s

Output

Print the string obtained by concatenating all the characters in the odd-numbered positions.

Sample Input 1

atcoder

Sample Output 1

acdr

Extract the first character a, the third character c, the fifth character d and the seventh character r to obtain acdr.

Sample Input 2

aaaa

Sample Output 2

aa

Sample Input 3

z

Sample Output 3

z

Sample Input 4

fukuokayamaguchi

Sample Output 4

fkoaaauh


object Main extends App {
  val s = readLine.toList
  println((0 to s.length-1).toList.filter{_ % 2 == 0}.map{i => s(i)}.mkString(""))
}


object Main extends App {
  val s = readLine.toList
  println(s.zipWithIndex.map{case (x,i) => if (i%2==0) x else ""}.mkString(""))
}


import java.util.Scanner

object Main {

  def solve() = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    var ans = 0
    var prev = false
    (1 to N) foreach { i =>
      val p = sc.nextInt()
      if (prev) {
        ans += 1
        prev = false
      } else {
        prev = p == i
      }
    }
    if (prev) ans += 1
    println(ans)
  }

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

Score : 400 points

Problem Statement

You are given a permutation p_1,p_2,...,p_N consisting of 1,2,..,N.
You can perform the following operation any number of times (possibly zero):

Operation: Swap two adjacent elements in the permutation.

You want to have p_i ≠ i for all 1≤i≤N.
Find the minimum required number of operations to achieve this.

Constraints

2≤N≤10^5

p_1,p_2,..,p_N is a permutation of 1,2,..,N.

Input

The input is given from Standard Input in the following format:

N
p_1 p_2 .. p_N

Output

Print the minimum required number of operations

Sample Input 1

5
1 4 3 5 2

Sample Output 1

2

Swap 1 and 4, then swap 1 and 3. p is now 4,3,1,5,2 and satisfies the condition.
This is the minimum possible number, so the answer is 2.

Sample Input 2

2
1 2

Sample Output 2

1

Swapping 1 and 2 satisfies the condition.

Sample Input 3

2
2 1

Sample Output 3

0

The condition is already satisfied initially.

Sample Input 4

9
1 2 4 9 5 8 7 3 6

Sample Output 4

3


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    inner(n, width - 1)
  }

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

    inner(n % m, p, 1)
  }

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

    val map = as.map(_ - 'a').foldLeft(Array.ofDim[Long]('z' - 'a' + 1)) {
      case (acc, c) =>
        acc(c) += 1
        acc
    }

    def nc2(n: Long): Long = {
      n * (n - 1) / 2L
    }

    out.println(
      map.foldLeft(nc2(as.length) + 1) {
        case (acc, count) => acc - nc2(count)
      }
    )

    out.flush()
  }
}

Score : 500 points

Problem Statement

You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.

You can choose any two indices i and j such that 1 \leq i \leq j \leq n and reverse substring A_i A_{i+1} ... A_j.

You can perform this operation at most once.

How many different strings can you obtain?

Constraints

1 \leq |A| \leq 200,000

A consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

A

Output

Print the number of different strings you can obtain by reversing any substring in A at most once.

Sample Input 1

aatt

Sample Output 1

5

You can obtain aatt (don't do anything), atat (reverse A[2..3]), atta (reverse A[2..4]), ttaa (reverse A[1..4]) and taat (reverse A[1..3]).

Sample Input 2

xxxxxxxxxx

Sample Output 2

1

Whatever substring you reverse, you'll always get xxxxxxxxxx.

Sample Input 3

abracadabra

Sample Output 3

44


import java.util.Scanner

object Main {
  def solve(sc: => Scanner): Unit = {
    val Arr = Array.fill[Int](sc.nextInt)(sc.nextInt).groupBy(a => a).filter(A => A._2.length >= 2).foldLeft[(Int, Int)]((0, 0))((A, B) => (
      if (B._2.length >= 4) ((math.max(A._1, B._1), math.max(A._2, B._1))) else (if (A._1 < A._2) ((math.max(A._1, B._1), A._2)) else ((A._1, math.max(A._2, B._1))))
      ))
    println(Arr._1 * Arr._2)
  }

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

Score : 300 points

Problem Statement

We have N sticks with negligible thickness.
The length of the i-th stick is A_i.

Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides.
Find the maximum possible area of the rectangle.

Constraints

4 \leq N \leq 10^5

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible area of the rectangle.
If no rectangle can be formed, print 0.

Sample Input 1

6
3 1 2 4 2 1

Sample Output 1

2

1 \times 2 rectangle can be formed.

Sample Input 2

4
1 2 3 4

Sample Output 2

0

No rectangle can be formed.

Sample Input 3

10
3 3 3 3 4 4 4 5 5 5

Sample Output 3

20


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val ls = List.fill(n)(sc.nextInt).sorted(Ordering[Int].reverse)

  def recur(ls: List[Int], a: Int, b: Int): Int = ls match {
    case x :: y :: rest if x == y =>
      if (a == -1) recur(rest, x, b)
      else a * x
    case _ :: rest =>
      recur(rest, a, b)
    case _ => 0
  }
  println(recur(ls, -1, -1))
}


import java.util.Scanner

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

  val n  = sc.nextInt
  val al = Vector.fill(n)(sc.nextInt)

  val cnt   = al.zipWithIndex.groupBy(_._1)
  val cnt2  = cnt.filter(_._2.size >= 2)
  val cnt4  = cnt2.filter(_._2.size >= 4)
  val over2 = cnt2.keySet
  val over4 = cnt4.keySet

  val bl = (over2 ++ over4).toSeq.sortWith(_ > _)

  val res =
    if(bl.length <= 1) 0L
    else bl.head.toLong * bl.tail.head.toLong

  println(res)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val a, b, c, d = sc.nextInt

  val res = (0 to 100).foldLeft(0) { (acc, n) =>
    if (a <= n && n < b && c <= n && n < d) acc+1 else acc
  }
  println(res)
}

Score : 200 points

Problem Statement

Alice and Bob are controlling a robot. They each have one switch that controls the robot.

Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up.

Bob started holding down his button C second after the start-up, and released his button D second after the start-up.

For how many seconds both Alice and Bob were holding down their buttons?

Constraints

0≤A<B≤100

0≤C<D≤100

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.

Sample Input 1

0 75 25 100

Sample Output 1

50

Alice started holding down her button 0 second after the start-up of the robot, and released her button 75 second after the start-up.

Bob started holding down his button 25 second after the start-up, and released his button 100 second after the start-up.

Therefore, the time when both of them were holding down their buttons, is the 50 seconds from 25 seconds after the start-up to 75 seconds after the start-up.

Sample Input 2

0 33 66 99

Sample Output 2

0

Alice and Bob were not holding their buttons at the same time, so the answer is zero seconds.

Sample Input 3

10 90 20 80

Sample Output 3

60


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

	val A = temp(0)
	val B = temp(1)
	val C = temp(2)
	val D = temp(3)

	def max(x: Int, y: Int): Int = {
		if(x < y) return y
		else x
	}

	def min(x: Int, y: Int): Int = {
		if(x < y) return x
		else y
	}

	val re = min(B,D) - max(A,C)

	if(re<0) println(0)
	else println(re)
}


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

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

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

  println(t.reduceLeft(lcm))
}

Score : 300 points

Problem Statement

We have N clocks. The hand of the i-th clock (1≤i≤N) rotates through 360° in exactly T_i seconds.

Initially, the hand of every clock stands still, pointing directly upward.

Now, Dolphin starts all the clocks simultaneously.

In how many seconds will the hand of every clock point directly upward again?

Constraints

1≤N≤100

1≤T_i≤10^{18}

All input values are integers.

The correct answer is at most 10^{18} seconds.

Input

Input is given from Standard Input in the following format:

N
T_1
:
T_N

Output

Print the number of seconds after which the hand of every clock point directly upward again.

Sample Input 1

2
2
3

Sample Output 1

6

We have two clocks. The time when the hand of each clock points upward is as follows:

Clock 1: 2, 4, 6, ... seconds after the beginning

Clock 2: 3, 6, 9, ... seconds after the beginning

Therefore, it takes 6 seconds until the hands of both clocks point directly upward.

Sample Input 2

5
2
5
10
1000000000000000000
1000000000000000000

Sample Output 2

1000000000000000000


import java.util.Scanner

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

  val n = sc.nextInt
  val tl = List.fill(n)(sc.nextLong)

  val res = tl.tail.foldLeft(tl.head)(lcm)

  println(res)

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

  def gcd(a: Long, b: Long): Long ={
    (a,b) match{
      case (x,y) if y == 0 => x
      case (x,y) if x < y  => gcd(y, x)
      case (x,y)           => gcd(y, x % y)
    }
  }

}


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

    val multipleOf4 = a.filter( _ % 4 == 0)
    val ans = if (multipleOf4.length < a.length / 2) "No" else "Yes"

    println(ans)
  }
}

Score : 400 points

Problem Statement

We have a sequence of length N, a = (a_1, a_2, ..., a_N).
Each a_i is a positive integer.

Snuke's objective is to permute the element in a so that the following condition is satisfied:

For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.

Determine whether Snuke can achieve his objective.

Constraints

2 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If Snuke can achieve his objective, print Yes; otherwise, print No.

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is (1, 100, 10).

Sample Input 2

4
1 2 3 4

Sample Output 2

No

It is impossible to permute a so that the condition is satisfied.

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes


import scala.io.StdIn

object Main extends App {
  val n = StdIn.readInt
  val ans = "ABC" + n

  println(ans)
}

Score : 100 points

Problem Statement

This contest, AtCoder Beginner Contest, is abbreviated as ABC.

When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC.

What is the abbreviation for the N-th round of ABC? Write a program to output the answer.

Constraints

100 ≤ N ≤ 999

Input

Input is given from Standard Input in the following format:

N

Output

Print the abbreviation for the N-th round of ABC.

Sample Input 1

100

Sample Output 1

ABC100

The 100th round of ABC is ABC100.

Sample Input 2

425

Sample Output 2

ABC425

Sample Input 3

999

Sample Output 3

ABC999


import scala.io.StdIn
object Main extends App {
  def breakNumber(number: Int): Int = {
    var count = 0
    var n = number
    while (n > 1) {
      n /= 2
      count += 1
    }
    count
  }
  val N = StdIn.readLine().toInt
  var maxCount = Int.MinValue
  var answer = 0
  for (i <- 1 to N) {
    val count = breakNumber(i)
    if (count > maxCount) {
      maxCount = count
      answer = i
    }
  }
  println(answer)
}

Score : 200 points

Problem Statement

Takahashi loves numbers divisible by 2.

You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique.

Here, the number of times an integer can be divisible by 2, is how many times the integer can be divided by 2 without remainder.

For example,

6 can be divided by 2 once: 6 -> 3.

8 can be divided by 2 three times: 8 -> 4 -> 2 -> 1.

3 can be divided by 2 zero times.

Constraints

1 ≤ N ≤ 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

7

Sample Output 1

4

4 can be divided by 2 twice, which is the most number of times among 1, 2, ..., 7.

Sample Input 2

32

Sample Output 2

32

Sample Input 3

1

Sample Output 3

1

Sample Input 4

100

Sample Output 4

64


object Main extends App {
  var a = readInt
  def b(c:Int,d:Int):Int ={
	if(c*2<=d) {
      b(c*2,d)
    } else {
      return c
    }
  }
  print(b(1,a))
}


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

  val ls = (1 to 100).map { i =>
    if (i % 2 != 0) 0 else {
      var j = i
      var c = 0
      while(j % 2 == 0) {
        j /= 2
        c += 1
      }
      c
    }
  }
  val lss = ls.take(n)
  val max = lss.max
  println(lss.indexWhere(_ == max) + 1)
}


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

object Main extends App {

  val Array(n, m) = StdIn.readLine.split(" ").map(_.toInt)
  val a = Iterator.continually(StdIn.readLine)
    .take(m)
    .map(_.split(" ").map(_.toInt))
    .toArray

  val graph = Array.fill(n+1)(ListBuffer.empty[Int])
  a.foreach(e => {
    graph(e(0)) += e(1)
  })

  val visit = Array.ofDim[Boolean](n+1)
  def dfs(pos:Int, cnt:Int):Unit = {
    if(cnt < 0) return
    visit(pos) = true
    // print(pos + " ")
    for(i <- graph(pos)) {
      dfs(i, cnt-1)
    }
  }

  dfs(1,2)
  val ans = if(visit(n)) "POSSIBLE" else "IMPOSSIBLE"
  println(ans)
}

Score : 300 points

Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands.
For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands.
Each service connects two islands. The i-th service connects Island a_i and Island b_i.

Cat Snuke is on Island 1 now, and wants to go to Island N.
However, it turned out that there is no boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

Help him.

Constraints

3 ≤ N ≤ 200 000

1 ≤ M ≤ 200 000

1 ≤ a_i < b_i ≤ N

(a_i, b_i) \neq (1, N)

If i \neq j, (a_i, b_i) \neq (a_j, b_j).

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

POSSIBLE

Sample Input 2

4 3
1 2
2 3
3 4

Sample Output 2

IMPOSSIBLE

You have to use three boat services to get to Island 4.

Sample Input 3

100000 1
1 99999

Sample Output 3

IMPOSSIBLE

Sample Input 4

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

Sample Output 4

POSSIBLE

You can get to Island 5 by using two boat services: Island 1 -> Island 4 -> Island 5.


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

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

object Main {
  val MOD = 1000000007
  val out = new PrintWriter(System.out)
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val K = sc.nextLong()

    def a(N: Int, applyCnt: Long): Long = {
      N - 1 + applyCnt * N - K + applyCnt
    }

    val A_MAX = 100000000L * 100000000 + 1000
    def validate(a: Long): Boolean = 0 <= a && a <= A_MAX

    def ok(N: Int): Boolean = {
      val a0 = a(N, K / N)
      val a1 = a(N, K / N + 1)
      if (K % N == 0) validate(a0)
      else validate(a0) && validate(a1)
    }

    val N = ((2 to 50) find ok).get
    val cnt1 = (K % N).toInt
    val cnt0 = N - cnt1
    val a0 = a(N, K / N)
    val a1 = a(N, K / N + 1)

    out.println(N)
    out.println((map(cnt0)(_ => a0) ++ map(cnt1)(_ => a1)).mkString(" "))
  }

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

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

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

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

  private def rep(n: Int)(f: Int => Unit): Unit = {
    (0 until n) foreach f
  }

  private def map[@specialized(Int, Long) A](n: Int)(f: Int => A): Seq[A] = {
    (0 until n) map f
  }
}

Score : 600 points

Problem Statement

We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller.

Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element by N, and increase each of the other elements by 1.

It can be proved that the largest element in the sequence becomes N-1 or smaller after a finite number of operations.

You are given an integer K. Find an integer sequence a_i such that the number of times we will perform the above operation is exactly K. It can be shown that there is always such a sequence under the constraints on input and output in this problem.

Constraints

0 ≤ K ≤ 50 \times 10^{16}

Input

Input is given from Standard Input in the following format:

K

Output

Print a solution in the following format:

N
a_1 a_2 ... a_N

Here, 2 ≤ N ≤ 50 and 0 ≤ a_i ≤ 10^{16} + 1000 must hold.

Sample Input 1

0

Sample Output 1

4
3 3 3 3

Sample Input 2

1

Sample Output 2

3
1 0 3

Sample Input 3

2

Sample Output 3

2
2 2

The operation will be performed twice: [2, 2] -> [0, 3] -> [1, 1].

Sample Input 4

3

Sample Output 4

7
27 0 0 0 0 0 0

Sample Input 5

1234567894848

Sample Output 5

10
1000 193 256 777 0 1 1192 1234567891011 48 425


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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val g = nm(N, M)

    def test(x: Int): Boolean = {
      debug(s"test($x)")
      val ix = Array.ofDim[Int](N)
      val disable = Array.ofDim[Boolean](M + 1)
      val count = Array.ofDim[Int](M + 1)
      REP(N) { i =>
        count(g(i)(0)) += 1
      }
      def step(): Boolean = {
        var mxCnt = 0
        var mxNum = 0
        REP(N) { i =>
          while(disable(g(i)(ix(i)))) {
            ix(i) += 1
            count(g(i)(ix(i))) += 1
          }
//          debug(count)
          if (count(g(i)(ix(i))) > mxCnt) {
            mxCnt = count(g(i)(ix(i)))
            mxNum = g(i)(ix(i))
            debug(s"change mxCnt:$mxCnt mxNum:$mxNum")
          }
        }
        debug(s"step mxCnt:$mxCnt mxNum:$mxNum")
        disable(mxNum) = true // 次のstepに備えて
        mxCnt <= x
      }

      REP(N) { _ =>
        if (step()) return true
      }
      false
    }

    val ans = findMin(test, 1, N)
    out.println(ans)
  }

  def findMin(f: Int => Boolean, min: Int, max: Int): Int = {
    var l = min - 1
    var h = max
    while(h - l > 1) {
      val x = (h + l) / 2
      if (f(x)) h = x
      else l = x
    }
    h
  }
}

Score : 700 points

Problem Statement

Takahashi is hosting an sports meet.
There are N people who will participate. These people are conveniently numbered 1 through N.
Also, there are M options of sports for this event. These sports are numbered 1 through M.
Among these options, Takahashi will select one or more sports (possibly all) to be played in the event.

Takahashi knows that Person i's j-th favorite sport is Sport A_{ij}.
Each person will only participate in his/her most favorite sport among the ones that are actually played in the event, and will not participate in the other sports.

Takahashi is worried that one of the sports will attract too many people.
Therefore, he would like to carefully select sports to be played so that the number of the participants in the sport with the largest number of participants is minimized.
Find the minimum possible number of the participants in the sport with the largest number of participants.

Constraints

1 \leq N \leq 300

1 \leq M \leq 300

A_{i1} , A_{i2} , ... , A_{iM} is a permutation of the integers from 1 to M.

Input

Input is given from Standard Input in the following format:

N M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
:
A_{N1} A_{N2} ... A_{NM}

Output

Print the minimum possible number of the participants in the sport with the largest number of participants.

Sample Input 1

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

Sample Output 1

2

Assume that Sports 1, 3 and 4 are selected to be played. In this case, Person 1 will participate in Sport 1, Person 2 in Sport 3, Person 3 in Sport 3 and Person 4 in Sport 4.
Here, the sport with the largest number of participants is Sport 3, with two participants.
There is no way to reduce the number of participants in the sport with the largest number of participants to 1. Therefore, the answer is 2.

Sample Input 2

3 3
2 1 3
2 1 3
2 1 3

Sample Output 2

3

Since all the people have the same taste in sports, there will be a sport with three participants, no matter what sports are selected.
Therefore, the answer is 3.


object Main {

	def main(arg:Array[String]) = {
		var list = scala.io.StdIn.readLine().split(" ").map(_.toInt);
		if(List(list(0), list(1), list(0) + list(1)).exists(_ % 3 == 0)) println("Possible");
		else println("Impossible");
	}

}

Score : 100 points

Problem Statement

Snuke is giving cookies to his three goats.

He has two cookie tins. One contains A cookies, and the other contains B cookies. He can thus give A cookies, B cookies or A+B cookies to his goats (he cannot open the tins).

Your task is to determine whether Snuke can give cookies to his three goats so that each of them can have the same number of cookies.

Constraints

1 \leq A,B \leq 100

Both A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If it is possible to give cookies so that each of the three goats can have the same number of cookies, print Possible; otherwise, print Impossible.

Sample Input 1

4 5

Sample Output 1

Possible

If Snuke gives nine cookies, each of the three goats can have three cookies.

Sample Input 2

1 1

Sample Output 2

Impossible

Since there are only two cookies, the three goats cannot have the same number of cookies no matter what Snuke gives to them.


import scala.io.StdIn

object Main extends App {
  val n = StdIn.readInt
  val a = StdIn.readLine.split(" ").map(_.toInt)
  val sum = a.sum
  val initial = (math.abs(a.head-(sum-a.head)),a.head)

  val ans = a.tail.init./:(initial)((acc,i) => {
      val xy = math.min(math.abs((acc._2+i)-(sum-(acc._2+i))), acc._1)
      (xy, acc._2 + i)
    })._1

  println(ans)
}

Score : 300 points

Problem Statement

Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.

They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards.
Here, both Snuke and Raccoon have to take at least one card.

Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively.
They would like to minimize |x-y|.
Find the minimum possible value of |x-y|.

Constraints

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

-10^{9} \leq a_i \leq 10^{9}

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Print the answer.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

1

If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, x=10, y=11, and thus |x-y|=1. This is the minimum possible value.

Sample Input 2

2
10 -10

Sample Output 2

20

Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, x=10, y=-10, and thus |x-y|=20.


object Main {
  def main(args: Array[String]): Unit = {
    val n = readLine()
    val a = readLine().split(" ").toList.map(_.toInt)
    val total = a.sum
    def searchMin(intList: List[Int], min: Int = (a.head - a.drop(1).sum).abs): Int = {
      intList match {
        case int :: tail if tail == Nil => min
        case int :: tail =>
          val diff = (int - tail.sum).abs
          searchMin(tail, if (diff < min) diff else min)
      }
    }
    println(searchMin(a))
  }
}


import java.util.Scanner
import Math.max

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

  val fene = "Fennec"
  val snuke = "Snuke"

  val N = sc.nextInt()
  val edges = Array.fill[List[Int]](N+1)(Nil)
  for (_ <- 1 to N-1) {
    val a, b = sc.nextInt()
    edges(a) = b :: edges(a)
    edges(b) = a :: edges(b)
  }

  // fenec
  val stack = new scala.collection.mutable.Stack[(Int, Int)]
  val dp = new Array[Boolean](N+1)
  dp(1) = true

  var feneMax = 0

  for(e <- edges(1)) {
    stack.push((e, 1))
    dp(e) = true
  }

  while(!stack.isEmpty) {
    val (node, score) = stack.pop

    node match {
      case N =>
        if((score-1) % 2 == 1) feneMax = max(feneMax, score-1)
      case _ =>
        feneMax = max(feneMax, score)
        var flag = true
        for(e <- edges(node)) {
          if(!dp(e)) {
            flag = false
            stack.push((e, score+1))
            dp(e) = true
          }
        }
        if(flag) feneMax = max(feneMax, score)
    }
  }

  // snuke
  for(i <- 1 to N)
    dp(i) = false
  dp(N) = true

  var snukeMax = 0

  for(e <- edges(N)) {
    stack.push((e, 1))
    dp(e) = true
  }

  while(!stack.isEmpty) {
    val (node, score) = stack.pop

    node match {
      case 1 =>
        if((score-1) % 2 == 1) snukeMax = max(snukeMax, score-1)
      case _ =>
        snukeMax = max(snukeMax, score)
        var flag = true
        for(e <- edges(node)) {
          if(!dp(e)) {
            flag = false
            stack.push((e, score+1))
            dp(e) = true
          }
        }
        if(flag) snukeMax = max(snukeMax, score)
    }
  }

  if(feneMax > snukeMax)
    println(fene)
  else
    println(snuke)
}

Score : 400 points

Problem Statement

Fennec and Snuke are playing a board game.

On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree.

Initially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored.
Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell.
More specifically, each player performs the following action in her/his turn:

Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black.

Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white.

A player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally.

Constraints

2 \leq N \leq 10^5

1 \leq a_i, b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

If Fennec wins, print Fennec; if Snuke wins, print Snuke.

Sample Input 1

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

Sample Output 1

Fennec

For example, if Fennec first paints Cell 2 black, she will win regardless of Snuke's moves.

Sample Input 2

4
1 4
4 2
2 3

Sample Output 2

Snuke


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

import scala.collection.mutable
import scala.util.Sorting

object Main {
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val e = Array.ofDim[mutable.Set[Int]](N + 1)
    (0 until N - 1) foreach { _ =>
      val u = sc.nextInt()
      val v = sc.nextInt()
      if (e(u) == null) e(u) = mutable.Set.empty
      if (e(v) == null) e(v) = mutable.Set.empty
      e(u) += v
      e(v) += u
    }

    def findPath(s: Int, t: Int): Seq[Int] = {
      val INF = N + 10
      val d = Array.fill(N + 1)(INF)
      val q = mutable.PriorityQueue.empty[(Int, Int)](Ordering.by((_: (Int, Int))._1)) // (cost, 頂点)
      val prev = Array.fill(N + 1)(-1)

      d(s) = 0
      q.enqueue((0, s))

      while(q.nonEmpty) {
        val (cost, v) = q.dequeue()
        if (cost <= d(v)) {
          e(v).foreach { u =>
            if (d(u) > d(v) + 1) {
              d(u) = d(v) + 1
              prev(u) = v
              q.enqueue((d(u), u))
            }
          }
        }
      }

      def traceback(v: Int, end: Int, path: List[Int]): List[Int] = v match {
        case `end` => v :: path
        case _ => traceback(prev(v), end, v :: path)
      }

      traceback(t, s, Nil)
    }

    def delEdge(u: Int, v: Int): Unit = {
      e(u) -= v
      e(v) -= u
    }

    val oneToN = findPath(1, N)
    oneToN zip oneToN.drop(1) foreach {
      case (u, v) => delEdge(u, v)
    }

    val uf = new UnionFind(N + 1)
    e.indices foreach { v =>
      if (e(v) != null )
        e(v).foreach { u =>
          uf.unite(v, u)
        }
    }

    def countConnected(v: Int): Int = {
      val r = uf.find(v)
      ((1 to N) count (v => uf.find(v) == r)) - 1
    }

    val c1 = countConnected(1)
    val cN = countConnected(N)

    val len = oneToN.length - 2
    val winner = if (c1 + (len & 1) > cN) "Fennec"
    else "Snuke"

    println(winner)
  }

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

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

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

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

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

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

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


import scala.io.StdIn

object Main extends App {

  val q = StdIn.readLine()

  def solve(s: String): Int = {
    val (s1, s2) = s.splitAt(s.length/2)
    if(s1 == s2) s.length
    else solve(s.tail)
  }

  println(solve(q.reverse.tail))

}

Score : 200 points

Problem Statement

We will call a string that can be obtained by concatenating two equal strings an even string.
For example, xyzxyz and aaaaaa are even, while ababab and xyzxy are not.

You are given an even string S consisting of lowercase English letters.
Find the length of the longest even string that can be obtained by deleting one or more characters from the end of S.
It is guaranteed that such a non-empty string exists for a given input.

Constraints

2 \leq |S| \leq 200

S is an even string consisting of lowercase English letters.

There exists a non-empty even string that can be obtained by deleting one or more characters from the end of S.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest even string that can be obtained.

Sample Input 1

abaababaab

Sample Output 1

6

abaababaab itself is even, but we need to delete at least one character.

abaababaa is not even.

abaababa is not even.

abaabab is not even.

abaaba is even. Thus, we should print its length, 6.

Sample Input 2

xxxx

Sample Output 2

2

xxx is not even.

xx is even.

Sample Input 3

abcabcabcabc

Sample Output 3

6

The longest even string that can be obtained is abcabc, whose length is 6.

Sample Input 4

akasakaakasakasakaakas

Sample Output 4

14

The longest even string that can be obtained is akasakaakasaka, whose length is 14.


object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val x, a, b = sc.nextInt

    val text =
      if (a < b) "delicious"
      else if (a + x > b) "safe"
      else "dangerous"

      println(text)
  }
}

Score : 100 points

Problem Statement

Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier.
He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.

Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.

Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.

Write a program that outputs delicious if he found it delicious, safe if he did not found it delicious but did not get a stomachache either, and dangerous if he got a stomachache.

Constraints

1 ≤ X,A,B ≤ 10^9

Input

Input is given from Standard Input in the following format:

X A B

Output

Print delicious if Takahashi found the food delicious; print safe if he neither found it delicious nor got a stomachache; print dangerous if he got a stomachache.

Sample Input 1

4 3 6

Sample Output 1

safe

He ate the food three days after the "best-by" date. It was not delicious or harmful for him.

Sample Input 2

6 5 1

Sample Output 2

delicious

He ate the food by the "best-by" date. It was delicious for him.

Sample Input 3

3 7 12

Sample Output 3

dangerous

He ate the food five days after the "best-by" date. It was harmful for him.


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

  val num = list.scan(1)((a, _) => list(a - 1)).find(_ == 2).fold(-1)(_ + 1)

  println(num)
}

Score : 200 points

Problem Statement

Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.

The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up.
These buttons are numbered 1 through N.
When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It is possible that i=a_i.
When Button i is not lighten up, nothing will happen by pressing it.

Initially, Button 1 is lighten up. Takahashi wants to quit pressing buttons when Button 2 is lighten up.

Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

Print -1 if it is impossible to lighten up Button 2.
Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button 2.

Sample Input 1

3
3
1
2

Sample Output 1

2

Press Button 1, then Button 3.

Sample Input 2

4
3
4
1
2

Sample Output 2

-1

Pressing Button 1 lightens up Button 3, and vice versa, so Button 2 will never be lighten up.

Sample Input 3

5
3
3
4
2
4

Sample Output 3

3


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.next.toInt
    val bottons = List.fill(n)(sc.nextInt)
    val indexBottonMap = bottons.zipWithIndex.map(item => (item._2, item._1)).toMap

    def go(n: Int, k: Int, acc: Int): Int = {
      if (n == -1) -1
      else if (k == 2) acc
      else {
        go(n - 1, indexBottonMap(k - 1), acc + 1)
      }
    }

    println(go(n, 1, 0))
  }
}


import java.util.Scanner

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

  val n = sc.nextInt
  val al = Vector.fill(n)(sc.nextInt)

  val m = ((1 to n).toVector zip al).toMap

  def loop(list: Vector[Int],num: Int):Vector[Int] ={
    val next = m(num)
    next match{
      case 1 => list
      case 2 => list :+ 2
      case _ => loop(list :+ num, next)
    }
  }

  val temp = loop(Vector.empty[Int], 1)
  val res = if(temp.contains(2)) temp.length else -1

  println(res)
}


import io.StdIn.readInt
import annotation.tailrec
import collection.mutable.ListBuffer
import collection.Searching._

object Main extends App {
  val n = readInt
  val as = Seq.fill(n)(readInt)
  val vs = ListBuffer.empty[Int]

  println(solve(0, 0, as, vs))

  @tailrec def solve(pos: Int, res: Int, as: Seq[Int], vs: ListBuffer[Int]): Int = {
    if (pos == 1) res
    else vs.search(pos) match {
      case Found(_) => -1
      case InsertionPoint(i) => {
        vs.insert(i, pos)
        solve(as(pos) - 1, res + 1, as, vs)
      }
    }
  }
}


import scala.io.StdIn._

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

  def solve(): Unit = {
    val input = readLine().split(" ")
    val n = input(0).toInt
    val m = input(1).toInt
    val mod = 1000000007

    if (math.abs(n - m) > 1) {
      println(0)
    } else {
      if (math.abs(n - m) == 0) {
        println(modfactrial(n, mod) * modfactrial(m, mod) % mod * 2 % mod)
      } else {
        println(modfactrial(n, mod) * modfactrial(m, mod) % mod)
      }
    }
  }

  def modfactrial(n: Int, mod: Long): Long = {
    var result = 1L
    for (i <- 1 to n) {
      result = (result * i.toLong) % mod
    }

    return result;
  }
}

Score : 300 points

Problem Statement

Snuke has N dogs and M monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that).
Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

1 ≤ N,M ≤ 10^5

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of possible arrangements, modulo 10^9+7.

Sample Input 1

2 2

Sample Output 1

8

We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.

Sample Input 2

3 2

Sample Output 2

12

Sample Input 3

1 8

Sample Output 3

0

Sample Input 4

100000 100000

Sample Output 4

530123477


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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)

    val mx = A.max
    val ms = A.min

    // 2以上ずれてるとおかしい
    val ok = mx - ms <= 1 && {
      if (mx == ms) {
        val g = mx
        // 全員違う色
        N - 1 == g || {
          // 全員他の人と同じ色
          N / 2 >= g
        }
      } else {
        val g = mx
        val cntSolo = A.count(_ == ms)
        val cntGrouped = N - cntSolo

        g > cntSolo && cntGrouped / 2 >= g - cntSolo
      }
    }

    if (ok) out.println("Yes")
    else out.println("No")
  }
}

Score : 700 points

Problem Statement

There are N cats.
We number them from 1 through N.

Each of the cats wears a hat.
Cat i says: "there are exactly a_i different colors among the N - 1 hats worn by the cats except me."

Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N-1

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print Yes if there exists a sequence of colors of the hats that is consistent with the remarks of the cats; print No otherwise.

Sample Input 1

3
1 2 2

Sample Output 1

Yes

For example, if cat 1, 2 and 3 wears red, blue and blue hats, respectively, it is consistent with the remarks of the cats.

Sample Input 2

3
1 1 2

Sample Output 2

No

From the remark of cat 1, we can see that cat 2 and 3 wear hats of the same color.
Also, from the remark of cat 2, we can see that cat 1 and 3 wear hats of the same color.
Therefore, cat 1 and 2 wear hats of the same color, which contradicts the remark of cat 3.

Sample Input 3

5
4 3 4 3 4

Sample Output 3

No

Sample Input 4

3
2 2 2

Sample Output 4

Yes

Sample Input 5

4
2 2 2 2

Sample Output 5

Yes

Sample Input 6

5
3 3 3 3 3

Sample Output 6

No


object Main extends App {
  val sc = new java.util.Scanner(System.in)
//  val l = List.fill(3)(sc.nextInt)
  val r, g, b = sc.next

  val ans = if ((r + g + b).toInt % 4 == 0) "YES" else "NO"
  println(ans)
}

Score : 100 points

Problem Statement

AtCoDeer has three cards, one red, one green and one blue.

An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card.

We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer.

Is this integer a multiple of 4?

Constraints

1 ≤ r, g, b ≤ 9

Input

Input is given from Standard Input in the following format:

r g b

Output

If the three-digit integer is a multiple of 4, print YES (case-sensitive); otherwise, print NO.

Sample Input 1

4 3 2

Sample Output 1

YES

432 is a multiple of 4, and thus YES should be printed.

Sample Input 2

2 3 4

Sample Output 2

NO

234 is not a multiple of 4, and thus NO should be printed.


object Main extends App {
    val x = scala.io.StdIn.readLine().split(" ").mkString("").toInt
    val ret = if (x%4==0) "YES" else "NO"
    println(ret)
}


object Main {

  def main(args: Array[String]): Unit = {
    import scala.io.StdIn._
    var over3200 = 0

    val GRAY = 0
    val BROWN = 1
    val GREEN = 2
    val WATER = 3
    val BLUE = 4
    val YELLOW = 5
    val ORANGE = 6
    val RED = 7
    val OVERED = 8
    val visited = new Array[Boolean](8)

    def rateToColor(rate: Int): Int =
      if (rate <= 399) GRAY
      else if (rate <= 799) BROWN
      else if (rate <= 1199) GREEN
      else if (rate <= 1599) WATER
      else if (rate <= 1999) BLUE
      else if (rate <= 2399) YELLOW
      else if (rate <= 2799) ORANGE
      else if (rate <= 3199) RED
      else OVERED

    val N = readLine().toInt
    val a = readLine().split(" ").map(_.toInt)
    (0 until N).foreach { i =>
      val color = rateToColor(a(i))
      if (color == OVERED)
        over3200 += 1
      else {
        visited(color) = true
      }
    }

    var colors = (0 until 8) count visited
    val max = colors + Math.min(8 - colors, over3200)
    val min = if (colors == 0) 1 else colors
    println(s"$min $max")
  }

}

Score : 300 points

Problem Statement

In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.

Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.

Find the minimum and maximum possible numbers of different colors of the users.

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

The user with rating 2100 is "yellow", and the others are "orange". There are two different colors.

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

The user with rating 1100 is "green", the user with rating 1900 is blue and the user with rating 2800 is "red".

If the fourth user picks "red", and the fifth user picks "blue", there are three different colors. This is one possible scenario for the minimum number of colors.

If the fourth user picks "purple", and the fifth user picks "black", there are five different colors. This is one possible scenario for the maximum number of colors.

Sample Input 3

20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990

Sample Output 3

1 1

All the users are "green", and thus there is one color.


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

    val colors = Array.fill(9)(0)
    val indexes = an.map( a => getIndex(a))
    indexes.foreach( index =>
      colors(index) = colors(index) + 1
    )

    val coders = colors.splitAt(8)
    val topCoders: Int = coders._2(0)
    val lowCoders = coders._1.filter(_ > 0).length

    printf("%d %d\n",
      lowCoders,
      if(lowCoders + topCoders <= 8) lowCoders + topCoders
      else 8
    )
  }

  /*
  レート 1-399：灰色
  レート 400-799：茶色
  レート 800-1199：緑色
  レート 1200-1599：水色
  レート 1600-1999：青色
  レート 2000-2399：黄色
  レート 2400-2799：橙色
  レート 2800-3199：赤色
   */
  def getIndex(rate: Int): Int = {
    val i = if (rate < 400) 0
    else if (rate < 800) 1
    else if (rate < 1200) 2
    else if (rate < 1600) 3
    else if (rate < 2000) 4
    else if (rate < 2400) 5
    else if (rate < 2800) 6
    else if (rate < 3200) 7
    else 8

    return i;
  }
}


import java.util.Scanner

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

  val n = sc.nextInt()

  val t = Range(0, n).map(_ => sc.nextInt())
    .sortBy(x => x)
    .map(i => math.min(i/400, 8))
    .groupBy(x => x)
    .toStream
    .sortBy(t => t._1)
    .foldLeft((0, 0)) {
      case ((minV, maxV), (id, seq)) => id match {
        case 8 => (math.max(minV, 1), maxV + seq.size)
        case _ => (minV + 1, maxV + 1)
      }
    }

  println(s"${t._1} ${t._2}")
}


object Main extends App {
    scala.io.StdIn.readLine()
    val ary = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val comp = Array(
        (x:Int) => 1 <= x && x <= 399,
        (x:Int) => 400 <= x && x <= 799,
        (x:Int) => 800 <= x && x <= 1199,
        (x:Int) => 1200 <= x && x <= 1599,
        (x:Int) => 1600 <= x && x <= 1999,
        (x:Int) => 2000 <= x && x <= 2399,
        (x:Int) => 2400 <= x && x <= 2799,
        (x:Int) => 2800 <= x && x <= 3199
        )
    def cnt(ary: Array[Int], f: Array[(Int) => Boolean]): Array[Int] = {
        for (func <- f) yield ary.count(func(_))
    }
    val ret = cnt(ary, comp).count(_>0)
    val min = if (ret==0) 1 else ret
    val max = math.min(ret+ary.count(_>=3200),8)
    println(min+" "+max)
}


object Main extends App {
  val res = io.StdIn.readLine.split(" ").map(_.toInt).sum
  val ans = if(res < 10) res.toString else "error"
  println(ans)
}

Score : 100 points

Problem Statement

You are given two integers A and B as the input. Output the value of A + B.

However, if A + B is 10 or greater, output error instead.

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B.

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


import scala.io.Source

object Main {

  def main(args: Array[String]) {
    val lines = Source.stdin.getLines.toSeq
    val n = lines.head.split(" ")(0).toLong
    val a = lines.head.split(" ")(1).toLong
    val b = lines.head.split(" ")(2).toLong
    val hs = lines.tail.map(_.toLong)
    var min_count = a * n

    def burn(xs: Seq[Long], count: Long) {
      if (min_count < count) {

      } else if (xs.isEmpty) {
        min_count = count
      } else {
        val ys = xs.zipWithIndex
        for ((x, i) <- ys) {
          burn(ys.map {
            case (x2, i2) if i == i2 => x2 - a
            case (x2, i2) => x2 - b
          }.filter(_ > 0), count + 1)
        }
      }
    }

    burn(hs, 0)
    println(min_count)
  }
}


import java.util.Scanner

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

  val str = sc.next()

  if (str.toStream.toSet.size == str.size) {
    println("yes")
  } else {
    println("no")
  }
}

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different.

Constraints

2 ≤ |S| ≤ 26, where |S| denotes the length of S.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If all the characters in S are different, print yes (case-sensitive); otherwise, print no.

Sample Input 1

uncopyrightable

Sample Output 1

yes

Sample Input 2

different

Sample Output 2

no

Sample Input 3

no

Sample Output 3

yes


import java.util.Scanner

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

  val N = sc.nextInt(); val A = sc.nextInt(); val B = sc.nextInt()
  val h = new Array[Int](N)
  for(i <- 0 until N)
    h(i) = sc.nextInt()

  val enes = h.sorted

  def check(n: Int): Boolean = {
    val tmp = enes.foldRight(0)((x, y) =>
      if(x - B*N <= 0) 0 + y else ((x - B*N) / (A-B)) + ((x - B*N) % (A-B)) + y)
    tmp <= n
  }

  // 条件を満たす最小の値を返す
  def binarySearch(min: Int, max: Int): Int = {
    val mid: Int = (max + min) / 2
    (max - min) match{
      case 0 | 1 =>
        check(min) match{
          case true  => min
          case false => max
        }
      case _ =>
        (check(mid)) match{
          case true  => binarySearch(min, mid)
          case false => binarySearch(mid, max)
        }
    }
  }

  val ans = binarySearch(1, 1e9.toInt)
  println(ans)
}

Score : 400 points

Problem Statement

You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below.

Fortunately, you are a skilled magician, capable of causing explosions that damage monsters. In one explosion, you can damage monsters as follows:

Select an alive monster, and cause an explosion centered at that monster. The health of the monster at the center of the explosion will decrease by A, and the health of each of the other monsters will decrease by B. Here, A and B are predetermined parameters, and A > B holds.

At least how many explosions do you need to cause in order to vanish all the monsters?

Constraints

All input values are integers.

1 ≤ N ≤ 10^5

1 ≤ B < A ≤ 10^9

1 ≤ h_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N A B
h_1
h_2
:
h_N

Output

Print the minimum number of explosions that needs to be caused in order to vanish all the monsters.

Sample Input 1

4 5 3
8
7
4
2

Sample Output 1

2

You can vanish all the monsters in two explosion, as follows:

First, cause an explosion centered at the monster with 8 health. The healths of the four monsters become 3, 4, 1 and -1, respectively, and the last monster vanishes.

Second, cause an explosion centered at the monster with 4 health remaining. The healths of the three remaining monsters become 0, -1 and -2, respectively, and all the monsters are now vanished.

Sample Input 2

2 10 4
20
20

Sample Output 2

4

You need to cause two explosions centered at each monster, for a total of four.

Sample Input 3

5 2 1
900000000
900000000
1000000000
1000000000
1000000000

Sample Output 3

800000000


import java.util.Scanner

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

  val n, a, b = sc.nextInt()
  val ar = Range(0, n).map(_ => sc.nextLong()).sorted.toArray

  println(solve)

  def solve(): Long = {
    var l = 1L
    var r = 1000L * 1000L * 1000L
    while (l < r) {
      val c = (l + r) / 2
      if (ok(c)) r = c
      else l = c + 1
    }
    return l
  }

  def ok(cnt: Long): Boolean = {
    ar.foldLeft(0L) {
      case (sum, h) => {
        if (cnt * b > h) {
          sum
        } else {
          sum + ((h - cnt * b - 1) / (a - b)) + 1
        }
      }
    } <= cnt
  }
}


import java.util.Scanner

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

  val n, a, b = sc.nextInt()
  val ar = Range(0, n).map(_ => sc.nextLong()).sorted.toArray

  println(solve)

  def solve(): Long = {
    var l = 0L
    var r = 1000L * 1000L * 1000L
    while (l != r - 1) {
      val c = (l + r) / 2
      if (ok(c)) r = c
      else l = c
    }
    return r
  }

  def ok(cnt: Long): Boolean = {
    ar.foldLeft(0L) {
      case (sum, h) => {
        if (cnt * b > h) {
          sum
        } else {
          sum + ((h - cnt * b - 1) / (a - b)) + 1
        }
      }
    } <= cnt
  }
}


import scala.io.Source

object Main {

  def main(args: Array[String]) {
    val lines = Source.stdin.getLines.toSeq
    val arr = lines.head.split(" ")
    val n = arr(0).toLong
    val a = arr(1).toLong
    val b = arr(2).toLong
    val hs = lines.tail.map(_.toLong)

    def isSat(xs: Seq[Long], count: Long): Boolean =
      if (count < 0) false
      else xs match {
        case Nil => true
        case x +: rest => isSat(rest, count - ((x - 1) / (a - b) + 1))
      }

    def minimize(lower: Long, upper: Long): Long =
      if (lower >= upper) upper
      else {
        val k = (lower + upper) / 2
        val hs2 = hs.map(_ - b * k).filter(_ > 0)
        if (isSat(hs2, k)) minimize(lower, k)
        else minimize(k + 1, upper)
      }

    val lowerBound = hs.max / a
    val upperBound = hs.max / b
    println(minimize(lowerBound, upperBound))
  }

}


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val h, w = sc.nextInt()
  val a = Array.fill(h)(sc.next().toList)

  println("#" * (w+2))
  for (i <- a){
    print("#")
    for (j <- i) {
      print(j)
    }
    println("#")
  }
  println("#" * (w+2))
}

Score : 200 points

Problem Statement

You are given a image with a height of H pixels and a width of W pixels.
Each pixel is represented by a lowercase English letter.
The pixel at the i-th row from the top and j-th column from the left is a_{ij}.

Put a box around this image and output the result. The box should consist of # and have a thickness of 1.

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

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

Output

Print the image surrounded by a box that consists of # and has a thickness of 1.

Sample Input 1

2 3
abc
arc

Sample Output 1

#####
#abc#
#arc#
#####

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###


import scala.io.StdIn
import scala.collection.mutable.ListBuffer

object Main extends App {
  val Array(h, w) = StdIn.readLine.split(" ").map(_.toLong)

  val res1 = {
    val list = ListBuffer.empty[Long]
    val m = h / 2L
    val res = (1L until w/2)./:(Long.MaxValue, Long.MaxValue)((min, i) => {
      val a =( h * i )
      list += a
      list += ( m * (w-i) )
      list += ( (h-m) * (w-i) )
      val r1 = list.max - list.min
      list.clear
      val k = (w-i) / 2L
      list += a
      list += ( k * h )
      list += ( (w-i-k) * h )
      val r2 = list.max - list.min
      list.clear
      ( math.min(min._2, r1), math.min(min._2, r2) )
    })
    math.min(res._1, res._2)
  }

  val res2 = {
    val list = ListBuffer.empty[Long]
    val m = w / 2L
    val res = (1L until h/2)./:(Long.MaxValue, Long.MaxValue)((min, i) => {
      val a = w * i
      list += a
      list += ( m * (h-i) )
      list += ( (w-m) * (h-i))
      val r1 = list.max - list.min
      list.clear
      val k = (h-i) / 2L
      list += a
      list += ( k * w )
      list += ( (h-i-k) * w )
      val r2 = list.max - list.min
      list.clear
      ( math.min(min._1, r1), math.min(min._2, r2) )
    })
    math.min(res._1, res._2)
  }

  val ans = math.min(res1, res2)
  println(ans)
}

Score : 400 points

Problem Statement

There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min}.

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

Print the minimum possible value of S_{max} - S_{min}.

Sample Input 1

3 5

Sample Output 1

0

In the division below, S_{max} - S_{min} = 5 - 5 = 0.

Sample Input 2

4 5

Sample Output 2

2

In the division below, S_{max} - S_{min} = 8 - 6 = 2.

Sample Input 3

5 5

Sample Output 3

4

In the division below, S_{max} - S_{min} = 10 - 6 = 4.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


import java.{util => ju}
import scala.collection.{mutable => mu}
import MyPredef._

object Main extends App {
    val H,W = nextLong
    val h=Math.min(H,W)
    val w=Math.max(H,W)

    if(H%3==1&&W%3==1)???

    val res = if(h%3==0||w%3==0){
        0
    }else{
        var res = h

        val X = Math.max(w/3,0)
        val _X = Math.min(w,X+1)
        (X to _X).foreach(x => {
            val wx = w-x
            val h0 = h/2
            val h1 = h-h/2
            val can = Seq(x*h,wx*h0,wx*h1)
            res = Math.min(res,can.max-can.min)
        })

        val Y = Math.max(h/3,0)
        val _Y = Math.min(h,Y+1)
        (Y to _Y).foreach(y => {
            val hy = h-y
            val w0 = w/2
            val w1 = w-w/2
            val can = Seq(y*h,hy*w0,hy*w1)
            res = Math.min(res,can.max-can.min)
        })

        res
    }

    println(res)
}

object MyPredef {
  @inline def rep(n: Int, f: => Unit): Unit = { var c = 0; while (c < n) { f; c += 1 } }
  @inline def rep(n: Int, f: Int => Unit): Unit = { var c = 0; while (c < n) { f(c); c += 1 } }

  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}
object MyArray {
  def fillT[T : scala.reflect.ClassTag](dimX: Int, dimY: Int)(f: => T): Array[Array[T]] = {
    val arrs = Array.ofDim[T](dimX, dimY)
    for {
      y <- (0 until dimY)
      x <- (0 until dimX)
    } {
      arrs(x)(y) = f
    }
    arrs
  }
}


import java.{util => ju}
import scala.collection.{mutable => mu}
import MyPredef._

object Main extends App {
    val H,W = nextLong
    val h=Math.min(H,W)
    val w=Math.max(H,W)

    if(H<10000&&W<10000)???

    val res = if(h%3==0||w%3==0){
        0
    }else{
        var res = h

        val X = Math.max(w/3,0)
        val _X = Math.min(w,X+1)
        (X to _X).foreach(x => {
            val wx = w-x
            val h0 = h/2
            val h1 = h-h/2
            val can = Seq(x*h,wx*h0,wx*h1)
            res = Math.min(res,can.max-can.min)
        })

        val Y = Math.max(h/3,0)
        val _Y = Math.min(h,Y+1)
        (Y to _Y).foreach(y => {
            val hy = h-y
            val w0 = w/2
            val w1 = w-w/2
            val can = Seq(y*h,hy*w0,hy*w1)
            res = Math.min(res,can.max-can.min)
        })

        res
    }

    println(res)
}

object MyPredef {
  @inline def rep(n: Int, f: => Unit): Unit = { var c = 0; while (c < n) { f; c += 1 } }
  @inline def rep(n: Int, f: Int => Unit): Unit = { var c = 0; while (c < n) { f(c); c += 1 } }

  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}
object MyArray {
  def fillT[T : scala.reflect.ClassTag](dimX: Int, dimY: Int)(f: => T): Array[Array[T]] = {
    val arrs = Array.ofDim[T](dimX, dimY)
    for {
      y <- (0 until dimY)
      x <- (0 until dimX)
    } {
      arrs(x)(y) = f
    }
    arrs
  }
}


object Main extends App {
  val scan = new java.util.Scanner(System.in)
  val ns: Array[Long] = Array.fill(1e5.toInt + 100)(0l)
  val n, k = scan.next().toInt
  for (_ <- 1 to n) yield ns(scan.next().toInt) += scan.next().toInt
  val acc = ns.scanLeft(0l)((s, n) => s + n).drop(1)
  println((0 to ns.length).zip(acc).dropWhile(_._2 < k).head._1)
}

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


import io.StdIn.readLine
object Main extends App {
  val Array(a, b, c) = readLine.split(" ").map(_.toInt)
  println(if (a <= c && c <= b) "Yes" else "No")
}


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val n, m = sc.nextInt()
  val r = Array.fill(m*2)(sc.nextInt())
  val ret = r.groupMapReduce(identity)(_ => 1)(_ + _)
  (1 to n).foreach(i => if (ret.contains(i)) println(ret(i)) else println(0))
}

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n, m = sc.nextInt()
  val e = List.fill(2 * m)(sc.nextInt())
  val count = e.groupBy(identity).view.mapValues(_.length)
  for (i <- 1 to n) {
    println(count.getOrElse(i, 0))
  }
}


object Main extends App {
	val Array(n, m) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
	val a = new Array[Int](n)

	for(i<-0 until m){
		val Array(tp1, tp2) = scala.io.StdIn.readLine.split(" ").map(_.toInt  - 1)
		a(tp1) += 1
		a(tp2) += 1
	}

	a.foreach(println)
}


import io.StdIn.readLine
object Main extends App {
  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val (as, bs) = List.fill(m)(readLine.split(" ").map(_.toInt) match {
    case Array(a, b) => (a, b)
  }).unzip
  val rs = (as ++ bs).groupBy(identity)
  for (i <- 1 to n) println(rs(i).size)
}


object Main {

  def main(args: Array[String]): Unit = {
    import scala.io.StdIn._
    val inputs = readLine().split(" ").map(_.toLong)
    val N = inputs(0).toInt
    val K = inputs(1)
    val arr = new Array[Long](100001)

    (0 until N).map(_ => {
      val Array(a, b) = readLine().split(" ").map(_.toInt)
      (a, b)
    }).foreach { case (a, b) =>
      arr(a) += b
    }

    var c = 0L
    (1 to 100000).foreach { i =>
      c += arr(i)
      if (c >= K) {
        println(i)
        return
      }
    }

  }

}

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


object Main extends App {
  val N = Scanner.nextInt
  val K = Scanner.nextLong
  val A = (0 until N).map(i => (Scanner.nextInt, Scanner.nextLong)).sortBy(t => t._1)
  def go(list: Seq[(Int, Long)], acc: Long = 0): Int = list match {
    case head +: tail =>
      if (acc + head._2 >= K) head._1
      else go(tail, acc + head._2)
  }
  println(go(A))
}

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

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

  def next: String = {
    if(!hasNext) ???
    val sb = new StringBuilder
    var b = readByte
    while (isPrintableChar(b)) {
      sb.append(b.toChar)
      b = readByte
    }
    sb.toString
  }
  def nextInt: Int = {
    val n = nextLong
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong: Long = {
    if(!hasNext) ???
    var minus = false
    var b = readByte
    if (b == '-') {
      minus = true
      b = readByte
    }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') go(readByte, n * 10 + b - '0')
      else if (minus) -n
      else n
    go(b)
  }
  def nextDouble: Double = next.toDouble
}