import collection.mutable.ArrayBuffer
import scala.reflect.ClassTag
import scala.language.implicitConversions

trait Graph {
    case class Edge[T:Numeric](from : Int, to : Int, cost : T)

    class Edges[T:Numeric](val data : ArrayBuffer[Edge[T]]) {
        def size = data.size
    }
    object Edges {
        def apply[T:Numeric](xs : Edge[T]*) = new Edges(ArrayBuffer(xs:_*))
        implicit def toUnderLying[T](x:Edges[T]) = x.data
    }

    class WeightedGraph[T:Numeric](val size : Int, val data : Array[Edges[T]]) {
        def this(size : Int) = this(size, Array.fill(size)(Edges()))
    }
    object WeightedGraph {
        // def apply[T:Numeric](size : Int) = new WeightedGraph[T](size)
        implicit def toUnderLying[T](x:WeightedGraph[T]) = x.data
    }

    class UnWeightedGraph[T:Numeric](val size : Int, val data: Array[ArrayBuffer[T]]) {
        def this(size : Int) = this(size, Array.fill(size)(ArrayBuffer[T]()))
    }
    object UnWeightedGraph {
        // def apply[T:Numeric](size : Int) = new UnWeightedGraph[T](size)
        implicit def toUnderLying[T](x:UnWeightedGraph[T]) = x.data
    }

    class Matrix[T:Numeric:ClassTag](val row : Int, val col : Int, val data : Array[Array[T]]) {
        def this(row : Int, col : Int) = this(row, col, Array.fill(row, col)(implicitly[Numeric[T]].zero))
        def this(size : Int) = this(size, size)
    }
    object Matrix {
        implicit def toUnderLying[T](x:Matrix[T]) = x.data
    }
}

// object BellmanFord extends Graph {
//     import Edges._

//     // return ArrayBuffer() when find a negative cycle
//     def bellmanFord[T:ClassTag](edges : Edges[T], V : Int, s : Int, INF : T)(implicit num : Numeric[T]) : Array[T] = {
//         val dist = Array.fill[T](V)(INF)
//         dist(s) = num.zero
//         for (i <- 1 to V) {
//             for (e <- edges) {
//                 if(dist(e.from) != INF
//                     && num.lt(num.plus(dist(e.from), e.cost), dist(e.to))) {
//                         dist(e.to) = num.plus(dist(e.from), e.cost)
//                         if (i == V && e.to == V-1) return Array.empty
//                     }
//             }
//         }
//         dist
//     }
// }

object BellmanFord extends Graph {
    import Edges._

    // return ArrayBuffer() when find a negative cycle
    def bellmanFord(edges : ArrayBuffer[(Int, Int, Long)], V : Int, s : Int, INF : Long) : Array[Long] = {
        val dist = Array.fill(V)(INF)
        dist(s) = 0L
        for (i <- 1 to V) {
            for ((from, to, cost) <- edges) {
                if(dist(from) != INF
                    && (dist(from) + cost) < dist(to)) {
                        dist(to) = (dist(from) + cost)
                        if (i == V && to == V-1) return Array.empty
                    }
            }
        }
        dist
    }
}

import BellmanFord._

object Main {
    def main(args: Array[String]) = {
        val sc = new java.util.Scanner(System.in)
        val N, M = sc.nextInt
        val edges = ArrayBuffer[(Int, Int, Long)]()
        for (_ <- 1 to M) {
            val s, t = sc.nextInt
            val c : Long = sc.nextLong
            edges += ((s-1, t-1, -c))
        }
        // println(edges.toList)
        val res = bellmanFord(edges, N, 0, Long.MaxValue)
        // println(res.toList)
        if (res.isEmpty) println("inf")
        else {
            println(-res(N-1))
        }
    }
}

Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges.
The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i.
We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0.
The player can move the piece as follows:

When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i.

The player can end the game only when the piece is placed at vertex N.
The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be?
If it is possible to increase the score indefinitely, print inf.

Constraints

2≤N≤1000

1≤M≤min(N(N-1),2000)

1≤a_i,b_i≤N (1≤i≤M)

a_i≠b_i (1≤i≤M)

a_i≠a_j or b_i≠b_j (1≤i<j≤M)

-10^9≤c_i≤10^9 (1≤i≤M)

c_i is an integer.

In the given graph, there exists a path from vertex 1 to vertex N.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

There are two ways to move the piece to vertex N=3:

vertex 1 → vertex 2 → vertex 3 : score 4+3=7

vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

-5000000000


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

  def exchange(x:Int,y:Int,z:Int):Int={
  if((x % 2 == 0) && (y % 2 == 0) && (z % 2 == 0)){1+exchange((x+y)/2,(y+z)/2,(z+x)/2)}
    else return 0
  }

  	val cookies =readLine.split(" ").map(_.toInt);
  val a = cookies(0)
  val b = cookies(1)
  val c = cookies(2)
  if(a == b && b == c){if(a % 2 == 0){println("-1")}else println("0")}
  else {
  println(exchange(a,b,c))
  }
}

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

Score : 300 points

Problem Statement

Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.

This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action?
Note that the answer may not be finite.

Constraints

1 ≤ A,B,C ≤ 10^9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times the action will be performed by the three people, if this number is finite.
If it is infinite, print -1 instead.

Sample Input 1

4 12 20

Sample Output 1

3

Initially, Takahashi, Aoki and Snuke have 4, 12 and 20 cookies. Then,

After the first action, they have 16, 12 and 8.

After the second action, they have 10, 12 and 14.

After the third action, they have 13, 12 and 11.

Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is 3.

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1

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

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

  def solve(input: String): String = {
    val s: Scanner = new Scanner(input)
    val a,b,c = s.nextInt
    if (c == 0) "YES"
    else {
      def modByB(n: Int): Stream[Int] = ((a * n) % b) #:: modByB(n + 1)
      if (modByB(1).take(b-1).contains(c)) "YES"
      else "NO"
    }
  }

  val tests = List(
    """7 5 1""" -> """YES""",
    """2 2 1""" -> """NO""",
    """1 100 97""" -> """YES""",
    """40 98 58""" -> """YES""",
    """77 42 36""" -> """NO"""
  )

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

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


import scala.io.StdIn
import java.io.{BufferedReader,InputStreamReader}

object Main extends App {
  val in = new BufferedReader(new InputStreamReader(System.in))
  val Array(n, t) = in.readLine.split(" ").map(_.toInt)
  val a = in.readLine.split(" ")

  val ans = a.tail./:(t.toLong,0)((acc,e) => {
    val ti = e.toInt
    val dur = ti - acc._2
    if(dur < t) (ti + t, ti)
    else (acc._1 + t, ti)
  })._1

  println(ans)
}

Score : 300 points

Problem Statement

In a public bath, there is a shower which emits water for T seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds.
Note that it does not mean that the shower emits water for T additional seconds.

N people will push the switch while passing by the shower.
The i-th person will push the switch t_i seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

Assume that the shower will emit water for a total of X seconds. Print X.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67


import scala.io.StdIn
import java.io.{BufferedReader,InputStreamReader}

object Main extends App {
  val in = new BufferedReader(new InputStreamReader(System.in))
  val Array(n, t) = in.readLine.split(" ").map(_.toInt)
  val a = in.readLine.split(" ")

  val ans = a.tail./:(t,0)((acc,e) => {
    val ti = e.toInt
    val dur = ti - acc._2
    if(dur < t) (ti + t, ti)
    else (acc._1 + t, ti)
  })._1

  println(ans)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val s1, s2, s3 = sc.next().toUpperCase
  println(s"${s1.head}${s2.head}${s3.head}")
}

Score : 100 points

Problem Statement

You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between.
Print the acronym formed from the uppercased initial letters of the words.

Constraints

s_1, s_2 and s_3 are composed of lowercase English letters.

1 ≤ |s_i| ≤ 10 (1≤i≤3)

Input

Input is given from Standard Input in the following format:

s_1 s_2 s_3

Output

Print the answer.

Sample Input 1

atcoder beginner contest

Sample Output 1

ABC

The initial letters of atcoder, beginner and contest are a, b and c. Uppercase and concatenate them to obtain ABC.

Sample Input 2

resident register number

Sample Output 2

RRN

Sample Input 3

k nearest neighbor

Sample Output 3

KNN

Sample Input 4

async layered coding

Sample Output 4

ALC


import java.util.Scanner

import scala.collection.immutable.Range.BigInt

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

    val ans = if (a.compareTo(b)==1) "GRATER" else if (a.equals(b)) "EQUAL" else "LESS"

    println(ans)
  }

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

Score : 200 points

Problem Statement

You are given two positive integers A and B. Compare the magnitudes of these numbers.

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print GREATER if A>B, LESS if A<B and EQUAL if A=B.

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


object Main extends App {
	var odd = io.StdIn.readLine.toList
//	println(odd)
	var even = io.StdIn.readLine.toList
//	println(even)

	val z = math.max(odd.size, even.size)

	var list: List[Char] = List()

	for(i <- 0 until z){
		list = list :+ odd.head
		list = list :+ even.head
		odd = odd.drop(1)
		even = even.drop(1)
	}

	println(list.mkString)

}

Score : 200 points

Problem Statement

Snuke signed up for a new website which holds programming competitions.
He worried that he might forget his password, and he took notes of it.
Since directly recording his password would cause him trouble if stolen,
he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions.

You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order.
Restore the original password.

Constraints

O and E consists of lowercase English letters (a - z).

1 \leq |O|,|E| \leq 50

|O| - |E| is either 0 or 1.

Input

Input is given from Standard Input in the following format:

O
E

Output

Print the original password.

Sample Input 1

xyz
abc

Sample Output 1

xaybzc

The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc.

Sample Input 2

atcoderbeginnercontest
atcoderregularcontest

Sample Output 2

aattccooddeerrbreeggiunlnaerrccoonntteesstt


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val datN = readLine.split(" ").map(_.toInt).head
    val datA = readLine.split(" ").map(_.toLong).toList

    val ans = datA.sorted.reverse.slice(0, datN * 2).zipWithIndex.filter(_._2 % 2 == 1).map(_._1).sum

    println(ans)
  }
}

Score : 300 points

Problem Statement

There are 3N participants in AtCoder Group Contest.
The strength of the i-th participant is represented by an integer a_i.
They will form N teams, each consisting of three participants.
No participant may belong to multiple teams.

The strength of a team is defined as the second largest strength among its members.
For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.

Find the maximum possible sum of the strengths of N teams.

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

The following is one formation of teams that maximizes the sum of the strengths of teams:

Team 1: consists of the first, fourth and fifth participants.

Team 2: consists of the second, third and sixth participants.

Sample Input 2

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 2

10000000000

The sum of the strengths can be quite large.


import io.StdIn._
object Main extends App {
    val Array(n, m) = readLine.split(" ").map(_.toInt)
    val abs = for(count <- 1 to n) yield readLine.split(" ").map(_.toLong)
    val cds = for(count <- 1 to m) yield readLine.split(" ").map(_.toLong)

    for(ab <- abs) {
        val manhattans = cds.map(cd => (ab.head - cd.head).abs + (ab.last - cd.last).abs)
        val min = manhattans.min
        val index = manhattans.indexOf(min)
        println(index+1)
    }
}

Score : 200 points

Problem Statement

There are N students and M checkpoints on the xy-plane.

The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|.

Here, |x| denotes the absolute value of x.

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

1 \leq N,M \leq 50

-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8

All input values are integers.

Input

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

N M
a_1 b_1
:
a_N b_N
c_1 d_1
:
c_M d_M

Output

Print N lines.

The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint 1: |2-(-1)|+|0-0|=3

For checkpoint 2: |2-1|+|0-0|=1

The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint 1: |0-(-1)|+|0-0|=1

For checkpoint 2: |0-1|+|0-0|=1

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1.

Sample Input 2

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

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1


object Main extends App {
  val n = scala.io.StdIn.readLong()
  var a = 0L
  for (i <- 1 to Math.sqrt(n).toInt) {
    if (n % i == 0) {
      a = i
    }
  }

  println((n / a).toString.length)
}

Score : 300 points

Problem Statement

You are given an integer N.

For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B.

For example, F(3,11) = 2 since 3 has one digit and 11 has two digits.

Find the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Constraints

1 \leq N \leq 10^{10}

N is an integer.

Input

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

N

Output

Print the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Sample Input 1

10000

Sample Output 1

3

F(A,B) has a minimum value of 3 at (A,B)=(100,100).

Sample Input 2

1000003

Sample Output 2

7

There are two pairs (A,B) that satisfy the condition: (1,1000003) and (1000003,1). For these pairs, F(1,1000003)=F(1000003,1)=7.

Sample Input 3

9876543210

Sample Output 3

6


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n, a, b = sc.nextInt()
  val v = Array.fill(n)(sc.nextLong()).sorted
  val max = v.takeRight(a).sum.toDouble / a
  val x = v(n-a)
  val m = v.count(_ == x)
  val k = v.takeRight(a).count(_ == x)

  def initCombTable(n: Int): Array[Array[Long]] = {
    val comb = Array.tabulate(n+1)(i => Array.fill(i+1)(1L))
    for {
      i <- 1 to n
      j <- 1 until i
    } {
      comb(i)(j) = comb(i-1)(j-1) + comb(i-1)(j)
    }
    comb
  }

  val comb = initCombTable(m)

  val ans = if (v.takeRight(a).distinct.length == 1) {
    (k to k + (b - a).min(m - k)).map(comb(m)(_)).sum
  } else {
    comb(m)(k)
  }

  println(f"$max%f")
  println(ans)
}

Score : 400 points

Problem Statement

You are given N items.

The value of the i-th item (1 \leq i \leq N) is v_i.

Your have to select at least A and at most B of these items.

Under this condition, find the maximum possible arithmetic mean of the values of selected items.

Additionally, find the number of ways to select items so that the mean of the values of selected items is maximized.

Constraints

1 \leq N \leq 50

1 \leq A,B \leq N

1 \leq v_i \leq 10^{15}

Each v_i is an integer.

Input

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

N A B
v_1
v_2
...
v_N

Output

Print two lines.

The first line should contain the maximum possible arithmetic mean of the values of selected items. The output should be considered correct if the absolute or relative error is at most 10^{-6}.

The second line should contain the number of ways to select items so that the mean of the values of selected items is maximized.

Sample Input 1

5 2 2
1 2 3 4 5

Sample Output 1

4.500000
1

The mean of the values of selected items will be maximized when selecting the fourth and fifth items. Hence, the first line of the output should contain 4.5.

There is no other way to select items so that the mean of the values will be 4.5, and thus the second line of the output should contain 1.

Sample Input 2

4 2 3
10 20 10 10

Sample Output 2

15.000000
3

There can be multiple ways to select items so that the mean of the values will be maximized.

Sample Input 3

5 1 5
1000000000000000 999999999999999 999999999999998 999999999999997 999999999999996

Sample Output 3

1000000000000000.000000
1


import java.util.Scanner

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

  val a = sc.next
  val b = sc.next

  val res = (a,b) match{
    case ("H","H") => "H"
    case ("H","D") => "D"
    case ("D","H") => "D"
    case ("D","D") => "H"
  }

  println(res)
}

Score : 100 points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters a and b as the input. Each of them is either H or D, and carries the following information:

If a=H, AtCoDeer is honest; if a=D, AtCoDeer is dishonest.
If b=H, AtCoDeer is saying that TopCoDeer is honest; if b=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

a=H or a=D.

b=H or b=D.

Input

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

a b

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H


import scala.io.StdIn._
object Main extends App {
  val x = readLong
  println(binSearch(500000000, 1, 1000000000))

  @scala.annotation.tailrec
  def binSearch(n: Long, l: Long, r: Long): Long = {
    val (min, max) = range(n)
    if (min < x && x <= max) n
    else if (x <= min) binSearch((l + n) / 2, l, n)
    else binSearch((r + n) / 2, n, r)
  }

  def range(n: Long): (Long, Long) = {
    val sum = n * (n + 1) / 2
    (sum - n, sum)
  }
}

Score : 200 points

Problem Statement

There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0.
During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right.
That is, if his coordinate at time i-1 is x, he can be at coordinate x-i, x or x+i at time i.
The kangaroo's nest is at coordinate X, and he wants to travel to coordinate X as fast as possible.
Find the earliest possible time to reach coordinate X.

Constraints

X is an integer.

1≤X≤10^9

Input

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

X

Output

Print the earliest possible time for the kangaroo to reach coordinate X.

Sample Input 1

6

Sample Output 1

3

The kangaroo can reach his nest at time 3 by jumping to the right three times, which is the earliest possible time.

Sample Input 2

2

Sample Output 2

2

He can reach his nest at time 2 by staying at his position during the first second, and jumping to the right at the next second.

Sample Input 3

11

Sample Output 3

5


object Main extends App {
  val Array(n,c,k) = readLine.split(" ").map{_.toInt}
  val t = (1 to n).map{_ => readInt}.toArray.sorted
  val t_list = t.toList

  var ans = 0
  var i = 0

  while (i < n) {
    ans += 1
    val c_th_id = t(Array(n-1,i+c-1).min)
    val num_within_k = t_list.drop(i).takeWhile{_ <= t(i)+k}.length

    if(c <= num_within_k) i += c else i += num_within_k
  }

  println(ans)
}

Score : 300 points

Problem Statement

Every day, N passengers arrive at Takahashi Airport.
The i-th passenger arrives at time T_i.

Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers.
Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport.
Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane.
For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).

When setting the departure times for buses under this condition, find the minimum required number of buses.
Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.

Constraints

2 \leq N \leq 100000

1 \leq C \leq 10^9

1 \leq K \leq 10^9

1 \leq T_i \leq 10^9

C, K and T_i are integers.

Input

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

N C K
T_1
T_2
:
T_N

Output

Print the minimum required number of buses.

Sample Input 1

5 3 5
1
2
3
6
12

Sample Output 1

3

For example, the following three buses are enough:

A bus departing at time 4.5, that carries the passengers arriving at time 2 and 3.

A bus departing at time 6, that carries the passengers arriving at time 1 and 6.

A bus departing at time 12, that carries the passenger arriving at time 12.

Sample Input 2

6 3 3
7
6
2
8
10
6

Sample Output 2

3


import scala.math._

// longでrangeの作り方

object Main extends App {

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

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

  val paid = n * 800
  val received = n / 15 * 200
  val ans = paid - received

  println(ans)

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

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

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

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

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

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

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

Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

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

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


object Main {

  import scala.math._

  def main(args: Array[String]) {

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

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

    if (check(arr)) println("YES")
    else println("NO")

  }
  def check(arr: Array[Int]): Boolean = {
    val n = arr.length
    def f(arr: Array[Int]): Boolean = {
      def calc(idx: Int, max_idx: Int): Int = {
        if (idx-max_idx > 0 ) arr(idx) - (idx - max_idx)
        else arr(idx)-(n + idx - max_idx)
      }
      def is_all_0(arr: Array[Int]): Boolean = {
        if (arr.filter(_ != 0).isEmpty) true
        else false
      }
      def exist_not_positive(arr: Array[Int]): Boolean = {
        if (arr.filter(_ < 1).length > 0) true
        else false
      }
      val max_idx = (0 until n).toList.maxBy(arr(_))
      val new_arr = (0 until n).toArray.map(calc(_, max_idx))

      if (is_all_0(new_arr)) true
      else if (exist_not_positive(new_arr)) false
      else f(new_arr)
    }
    f(arr)
  }
}

Score : 500 points

Problem Statement

There are N boxes arranged in a circle. The i-th box contains A_i stones.

Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:

Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-th box. Here, the (N+k)-th box is identified with the k-th box.

Note that the operation cannot be performed if there is a box that does not contain enough number of stones to be removed.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

Input

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

N
A_1 A_2 … A_N

Output

If it is possible to remove all the stones from the boxes, print YES. Otherwise, print NO.

Sample Input 1

5
4 5 1 2 3

Sample Output 1

YES

All the stones can be removed in one operation by selecting the second box.

Sample Input 2

5
6 9 12 10 8

Sample Output 2

YES

Sample Input 3

4
1 2 3 1

Sample Output 3

NO


object Main {

  val scanner = new java.util.Scanner(System.in)

  def main(args: Array[String]): Unit = {
    val target = scanner.nextInt()
    if (target < 1200) {
      println("ARC")
    } else {
      println("ABC")
    }
  }

}

Score : 100 points

Problem Statement

Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.

You are given Smeke's current rating, x. Print ABC if Smeke will participate in ABC, and print ARC otherwise.

Constraints

1 ≦ x ≦ 3{,}000

x is an integer.

Input

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

x

Output

Print the answer.

Sample Input 1

1000

Sample Output 1

ABC

Smeke's current rating is less than 1200, thus the output should be ABC.

Sample Input 2

2000

Sample Output 2

ARC

Smeke's current rating is not less than 1200, thus the output should be ARC.


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 private final 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[Long]]): 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 private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

class 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にしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val n, m = ni()
    val (l, r) = na2(n)

    val ans = Array.ofDim[Int](m + 2)
    val rt = math.sqrt(m).toInt
    debug(s"rt:$rt")
    REP(rt, 1) { d =>
      REP(n) { i =>
        val j = (l(i)-1) / d * d
        if (j + d <= r(i)) {
          ans(d) += 1
          ans(d + 1) -= 1
        }
      }
    }

    REP(n) { i =>
      REP(rt + 1, 1) { x =>
      var r0 = 0
        val l1 = (l(i) + x - 1) / x
        val r1 = r(i) / x
        val l2 = max(rt + 1, max(r0, l1)) // rtまで計算ずみ
        debug(s"i:$i x:$x l1:$l1 r1:$r1 l2:$l2")
        if (l2 <= r1) {
          ans(l2) += 1
          ans(r1 + 1) -= 1
        }
        r0 = r1 + 1
      }
    }

    REP(m) { i =>
      ans(i + 1) += ans(i)
    }

    debug(ans)

    REP(m, 1) { d =>
      out.println(ans(d))
    }
  }
}

Score : 700 points

Problem Statement

Snuke has decided to play a game, where the player runs a railway company.
There are M+1 stations on Snuke Line, numbered 0 through M.
A train on Snuke Line stops at station 0 and every d-th station thereafter, where d is a predetermined constant for each train.
For example, if d = 3, the train stops at station 0, 3, 6, 9, and so forth.

There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind of souvenirs can be purchased when the train stops at one of the following stations: stations l_i, l_i+1, l_i+2, ..., r_i.

There are M values of d, the interval between two stops, for trains on Snuke Line: 1, 2, 3, ..., M.
For each of these M values, find the number of the kinds of souvenirs that can be purchased if one takes a train with that value of d at station 0.
Here, assume that it is not allowed to change trains.

Constraints

1 ≦ N ≦ 3 × 10^{5}

1 ≦ M ≦ 10^{5}

1 ≦ l_i ≦ r_i ≦ M

Input

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

N M
l_1 r_1
:
l_{N} r_{N}

Output

Print the answer in M lines. The i-th line should contain the maximum number of the kinds of souvenirs that can be purchased if one takes a train stopping every i-th station.

Sample Input 1

3 3
1 2
2 3
3 3

Sample Output 1

3
2
2

If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3.

If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2.

If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3.

Sample Input 2

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

Sample Output 2

7
6
6
5
4
5
5
3
2


class FenwickTree(val n:Int, init:Int) {
  val dat = new Array[Int](n+1)
  for (i <- 1 to n) add(i, init)

  def this(n:Int) {
    this(n, 0)
  }

  def add(_idx:Int, value:Int) {
    var idx = _idx+1
    while(idx <= n) {
      dat(idx) += value
      idx += idx & -idx
    }
  }

  def query(_l:Int, _r:Int):Int = {
    var ans = 0
    var r = _r+1
    var l = _l+1
    while(r > 0) {
      ans += dat(r)
      r -= r & -r
    }
    while(l > 0) {
      ans -= dat(l)
      l -= l & -l
    }
    return ans
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n,m) = scala.io.StdIn.readLine().split(' ').map(_.toInt)
    val intervals = for(i <- Range(0,n).toArray) yield {
      val Array(l,r) = scala.io.StdIn.readLine().split(' ').map(_.toInt)
      Array((r-l+1), l, r)
    }
    var sortedInt = intervals.sortBy(_.apply(0))
    val ft = new FenwickTree(m+1)

    for(d <- 1 to m) {
      var count = 0
      val (before, after) = sortedInt.span(_.apply(0) < d)
      for (int <- before) {
        ft.add(int(1), 1)
        ft.add(int(2)+1, -1)
      }
      for(i <- Range(0, m+1, d)) count += ft.query(-1, i)
      count += after.length
      sortedInt = after
      println(count)
    }
  }
}


import scala.io.StdIn.readLine

/**
 * Created by sonetsuyoshi on 2015/12/16.
 */
object Main extends App {
  val arg = readLine.split(" ").map(_.toInt)
  val N = arg.apply(0)
  val A = arg.apply(1)
  val B = arg.apply(2)

  val x = readLine.split(" ").map(_.toLong)

  val ans: Long = 1.until(N).foldLeft(0.toLong)((s, i) => s + math.min((x(i) - x (i - 1)) * A, B)
  )

  println(ans)
}

Score : 500 points

Problem Statement

There are N towns on a line running east-west.
The towns are numbered 1 through N, in order from west to east.
Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value.
The coordinate of town i is X_i.

You are now at town 1, and you want to visit all the other towns.
You have two ways to travel:

Walk on the line.
Your fatigue level increases by A each time you travel a distance of 1, regardless of direction.

Teleport to any location of your choice.
Your fatigue level increases by B, regardless of the distance covered.

Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways.

Constraints

All input values are integers.

2≤N≤10^5

1≤X_i≤10^9

For all i(1≤i≤N-1), X_i<X_{i+1}.

1≤A≤10^9

1≤B≤10^9

Input

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

N A B
X_1 X_2 ... X_N

Output

Print the minimum possible total increase of your fatigue level when you visit all the towns.

Sample Input 1

4 2 5
1 2 5 7

Sample Output 1

11

From town 1, walk a distance of 1 to town 2, then teleport to town 3, then walk a distance of 2 to town 4.
The total increase of your fatigue level in this case is 2×1+5+2×2=11, which is the minimum possible value.

Sample Input 2

7 1 100
40 43 45 105 108 115 124

Sample Output 2

84

From town 1, walk all the way to town 7.
The total increase of your fatigue level in this case is 84, which is the minimum possible value.

Sample Input 3

7 1 2
24 35 40 68 72 99 103

Sample Output 3

12

Visit all the towns in any order by teleporting six times.
The total increase of your fatigue level in this case is 12, which is the minimum possible value.


import scala.io.{ StdIn => in}

object Main extends App {
  println(in.readLine.replace(","," "))
}

Score : 100 points

Problem Statement

As a New Year's gift, Dolphin received a string s of length 19.

The string s has the following format: [five lowercase English letters],[seven lowercase English letters],[five lowercase English letters].

Dolphin wants to convert the comma-separated string s into a space-separated string.

Write a program to perform the conversion for him.

Constraints

The length of s is 19.

The sixth and fourteenth characters in s are ,.

The other characters in s are lowercase English letters.

Input

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

s

Output

Print the string after the conversion.

Sample Input 1

happy,newyear,enjoy

Sample Output 1

happy newyear enjoy

Replace all the commas in happy,newyear,enjoy with spaces to obtain happy newyear enjoy.

Sample Input 2

haiku,atcoder,tasks

Sample Output 2

haiku atcoder tasks

Sample Input 3

abcde,fghihgf,edcba

Sample Output 3

abcde fghihgf edcba


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val sx, sy, tx, ty = sc.nextInt()
  val dx = tx - sx
  val dy = ty - sy
  val ans = s"${"R" * dx}${"U" * dy}${"L" * dx}${"D" * (dy+1)}${"R" * (dx+1)}${"U" * (dy+1)}LU${"L" * (dx + 1)}${"D" * (dy+1)}R"
  println(ans)
}

Score : 300 points

Problem Statement

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.

Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.

Here, both the x- and y-coordinates before and after each movement must be integers.

He will first visit the point (tx,ty) where sx < tx and sy < ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).

Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).

Under this condition, find a shortest path for him.

Constraints

-1000 ≤ sx < tx ≤ 1000

-1000 ≤ sy < ty ≤ 1000

sx,sy,tx and ty are integers.

Input

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

sx sy tx ty

Output

Print a string S that represents a shortest path for Dolphin.

The i-th character in S should correspond to his i-th movement.

The directions of the movements should be indicated by the following characters:

U: Up

D: Down

L: Left

R: Right

If there exist multiple shortest paths under the condition, print any of them.

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

Going from (sx,sy) to (tx,ty) for the first time: (0,0) → (0,1) → (0,2) → (1,2)

Going from (tx,ty) to (sx,sy) for the first time: (1,2) → (1,1) → (1,0) → (0,0)

Going from (sx,sy) to (tx,ty) for the second time: (0,0) → (-1,0) → (-1,1) → (-1,2) → (-1,3) → (0,3) → (1,3) → (1,2)

Going from (tx,ty) to (sx,sy) for the second time: (1,2) → (2,2) → (2,1) → (2,0) → (2,-1) → (1,-1) → (0,-1) → (0,0)

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL


object Main extends App {
  val Array(sx, sy, tx, ty) = scala.io.StdIn.readLine.split(' ').map(_.toInt)

  val path1 = "U" * (ty - sy) + "R" * (tx - sx)
  val path2 = "R" * (tx - sx) + "U" * (ty - sy)
  val path3 = "D" + "R" * (tx - sx + 1) + "U" * (ty - sy + 1) + "L"
  val path4 = "L" + "U" * (ty - sy + 1) + "R" * (tx - sx + 1) + "D"

  println(Array(path1, path2, path3, path4).mkString)
}


import java.util.Scanner

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

  val sx = sc.nextInt()
  val sy = sc.nextInt()
  val tx = sc.nextInt()
  val ty = sc.nextInt()

  var ans = ""
  for(i <- sx to tx-1)
    ans += "R"
  for(i <- sy to ty-1)
    ans += "U"
  for(i <- sx to tx-1)
    ans += "L"
  for(i <- sy to ty-1)
    ans += "D"

  ans += "D"
  for(i <- sx to tx)
    ans += "R"
  for(i <- sy to ty)
    ans += "U"
  ans += "L"

  ans += "U"
  for(i <- sx to tx)
    ans += "L"
  for(i <- sy to ty)
    ans += "U"
  ans += "R"

  println(ans)
}


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

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

object Main {
  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val x, y = sc.nextInt()

    def sign(a: Int) = a >= 0

    val ans = if (x < y && sign(x) == sign(y)) y - x
    else if (x < 0 && y == 0) -x
    else if (x > 0 && y == 0) x + 1
    else if (sign(x) != sign(y)) abs(abs(y) - abs(x)) + 1
    else abs(abs(y) - abs(x)) + 2

    out.println(ans)
  }

  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 = _

    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)
  }
  def rep(n: Int)(f: Int => Unit): Unit = {
    var i = 0
    while(i < n) { f(i); i += 1 }
  }
  def rep_r(n: Int)(f: Int => Unit): Unit = {
    var i = n - 1
    while(i >= 0) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

Score : 300 points

Problem Statement

Snuke has a calculator. It has a display and two buttons.

Initially, the display shows an integer x.
Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:

Button A: When pressed, the value on the display is incremented by 1.

Button B: When pressed, the sign of the value on the display is reversed.

Find the minimum number of times Snuke needs to press the buttons to achieve his objective.
It can be shown that the objective is always achievable regardless of the values of the integers x and y.

Constraints

x and y are integers.

|x|, |y| ≤ 10^9

x and y are different.

Input

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

x y

Output

Print the minimum number of times Snuke needs to press the buttons to achieve his objective.

Sample Input 1

10 20

Sample Output 1

10

Press button A ten times.

Sample Input 2

10 -10

Sample Output 2

1

Press button B once.

Sample Input 3

-10 -20

Sample Output 3

12

Press the buttons as follows:

Press button B once.

Press button A ten times.

Press button B once.


import io.StdIn.readLine

object Main {
  def main(args: Array[String]): Unit = {
    val Array(x, y) = readLine().split(' ' ).map(_.toInt)
    val xa = Math.abs(x)
    val ya = Math.abs(y)

    if (xa == ya) {
      if (x == y) println(0)
      else println(1)
    } else if (xa > ya) {
           if (x > 0 && y  > 0) println(2 + xa - ya)
      else if (x > 0 && y <= 0) println(1 + xa - ya)
      else if (x < 0 && y  > 0) println(1 + xa - ya)
      else println(xa - ya)
    } else {
           if (x == 0 && y > 0) println(y)
      else if (x == 0 && y < 0) println(y + 1)
      else if (x  > 0 && y > 0) println(ya - xa)
      else if (x  > 0 && y < 0) println(1 + ya - xa)
      else if (x  < 0 && y > 0) println(1 + ya - xa)
      else println(2 + ya - xa)
    }
  }
}


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

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

object Main {
  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val A0, A1, A2, A3, A4, A5, A6 = sc.nextInt()

    val ans = A0 / 2 * 2 + A1 + min(A3, A4) * 2

    out.println(ans)
  }

  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 = _

    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)
  }
  def rep(n: Int)(f: Int => Unit): Unit = {
    var i = 0
    while(i < n) { f(i); i += 1 }
  }
  def rep_r(n: Int)(f: Int => Unit): Unit = {
    var i = n - 1
    while(i >= 0) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

Score : 600 points

Problem Statement

A tetromino is a figure formed by joining four squares edge to edge.
We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively:

Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession are a_I, a_O, a_T, a_J, a_L, a_S and a_Z, respectively.
Snuke will join K of his tetrominos to form a rectangle that is two squares tall and 2K squares wide.
Here, the following rules must be followed:

When placing each tetromino, rotation is allowed, but reflection is not.

Each square in the rectangle must be covered by exactly one tetromino.

No part of each tetromino may be outside the rectangle.

Snuke wants to form as large a rectangle as possible.
Find the maximum possible value of K.

Constraints

0≤a_I,a_O,a_T,a_J,a_L,a_S,a_Z≤10^9

a_I+a_O+a_T+a_J+a_L+a_S+a_Z≥1

Input

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

a_I a_O a_T a_J a_L a_S a_Z

Output

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

Sample Input 1

2 1 1 0 0 0 0

Sample Output 1

3

One possible way to form the largest rectangle is shown in the following figure:

Sample Input 2

0 0 10 0 0 0 0

Sample Output 2

0

No rectangle can be formed.


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

    def solve(N: Int, A: Array[Int]): Long = {
      val MAX = N - 1
      val C = new Array[Int](N)
      (0 to MAX) foreach { n =>
        C(((MAX - n) - n).abs) += 1
      }

      val INF = Math.pow(10, 9).toLong + 7.toLong
      def ans(n: Int, acm: Long): Long =
        if (n < N / 2) ans(n + 1, acm << 1 % INF)
        else acm

      def find(i: Int): Long =
        if (i < N) {
          C(A(i)) -= 1
          find(i + 1)
        } else {
          if (C.forall(_ == 0)) ans(0, 1)
          else 0
        }

      find(0)
    }

    println(solve(N, A))
  }

}

Score : 300 points

Problem Statement

There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.

Constraints

1≦N≦10^5

0≦A_i≦N-1

Input

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

N
A_1 A_2 ... A_N

Output

Print the number of the possible orders in which they were standing, modulo 10^9+7.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

2,1,4,5,3

2,5,4,1,3

3,1,4,5,2

3,5,4,1,2

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is 0.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


import java.util.Scanner

object Main {
  def main(args:Array[String]): Unit = {
    val vowels = Array("a", "i", "u", "e", "o")
    val sc = new Scanner(System.in)

    if (vowels.contains(sc.nextLine())) {
      println("vowel")
    } else {
      println("consonant")
    }
  }
}

Score : 100 points

Problem Statement

Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

c is a lowercase English letter.

Input

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

c

Output

If c is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val Array(h, w) = sc.nextLine.split(" ").map(_.toInt)
    val rectangle = List.fill(h)(sc.nextLine)
    (1 to 2 * h).map{
      ind => rectangle((ind - 1)/2)
    }.foreach(println)
  }
}


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

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

object Main {
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val K = sc.nextInt()
    val L = sc.nextInt()

    var i = 0
    val uf_road = new UnionFind(N + 1)
    i = 0
    while (i < K) {
//    (0 until K) foreach { _ =>
      uf_road.unite(sc.nextInt(), sc.nextInt())
      i += 1
    }

    val uf_rail = new UnionFind(N + 1)
    i = 0
    while (i < L) {
//    (0 until L) foreach { _ =>
      uf_rail.unite(sc.nextInt(), sc.nextInt())
      i += 1
    }

    val group = new java.util.HashMap[(Int, Int), Int](N) // key => group
    i = 1
    while (i <= N) {
//    (1 to N) foreach { i =>
      val k = (uf_road.find(i), uf_rail.find(i))
      group.put(k, i)
      i += 1
    }
    val i2g = Array.ofDim[Int](N + 1) // i => group
    i = 1
    while (i <= N) {
//    (1 to N) foreach { i =>
      val k = (uf_road.find(i), uf_rail.find(i))
      i2g(i) = group.get(k)
      i += 1
    }
    val count = Array.ofDim[Int](N + 1) // group => count
    i = 1
    while (i <= N) {
//    (1 to N) foreach { i =>
      count(i2g(i)) += 1
      i += 1
    }
    i = 1
    while (i <= N) {
//    (1 to N) foreach { i =>
      if (i > 1) print(" ")
      print(count(i2g(i)))
      i += 1
    }

//    val count = mutable.Map[(Int, Int), Int]()
//    var i = 1
//    while(i <= N) {
//      val k = key(i)
//      if (!(count contains k)) count(k) = 0
//      count(k) = count(k) + 1
//      i += 1
//    }
//
//    i = 1
//    while(i <= N) {
//      if (i > 1) print(" ")
//      print(count(key(i)))
//      i += 1
//    }
//    println()
//    val count = ((1 to N) map key).groupBy(identity).mapValues(_.size)
//    val ans = ((1 to N) map (key _).andThen (count(_))).mkString(" ")
//    println(ans)
  }

  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 nextLong(): Long = next.toLong
    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
        }
      }
    }
  }
}

Score : 400 points

Problem Statement

There are N cities. There are also K roads and L railways, extending between the cities.
The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities.
No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.

We will say city A and B are connected by roads if city B is reachable from city A by traversing some number of roads. Here, any city is considered to be connected to itself by roads.
We will also define connectivity by railways similarly.

For each city, find the number of the cities connected to that city by both roads and railways.

Constraints

2 ≦ N ≦ 2*10^5

1 ≦ K, L≦ 10^5

1 ≦ p_i, q_i, r_i, s_i ≦ N

p_i < q_i

r_i < s_i

When i ≠ j, (p_i, q_i) ≠ (p_j, q_j)

When i ≠ j, (r_i, s_i) ≠ (r_j, s_j)

Input

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

N K L
p_1 q_1
:
p_K q_K
r_1 s_1
:
r_L s_L

Output

Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.

Sample Input 1

4 3 1
1 2
2 3
3 4
2 3

Sample Output 1

1 2 2 1

All the four cities are connected to each other by roads.

By railways, only the second and third cities are connected. Thus, the answers for the cities are 1, 2, 2 and 1, respectively.

Sample Input 2

4 2 2
1 2
2 3
1 4
2 3

Sample Output 2

1 2 2 1

Sample Input 3

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

Sample Output 3

1 1 2 1 2 2 2


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

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

object Main {
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val K = sc.nextInt()
    val L = sc.nextInt()

    val uf_road = new UnionFind(N + 1)
    (0 until K) foreach { _ =>
      uf_road.unite(sc.nextInt(), sc.nextInt())
    }

    val uf_rail = new UnionFind(N + 1)
    (0 until L) foreach { _ =>
      uf_rail.unite(sc.nextInt(), sc.nextInt())
    }

    def key(i: Int) = (uf_road.find(i), uf_rail.find(i))

    val count = mutable.Map[(Int, Int), Int]()
    var i = 1
    while(i <= N) {
      val k = key(i)
      if (!(count contains k)) count(k) = 0
      count(k) = count(k) + 1
      i += 1
    }

    i = 1
    while(i <= N) {
      if (i > 1) print(" ")
      print(count(key(i)))
      i += 1
    }
    println()
//    val count = ((1 to N) map key).groupBy(identity).mapValues(_.size)
//    val ans = ((1 to N) map (key _).andThen (count(_))).mkString(" ")
//    println(ans)
  }

  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 nextLong(): Long = next.toLong
    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 java.io.{BufferedReader, IOException, InputStream, InputStreamReader}
import java.util.StringTokenizer
import java.util.concurrent.atomic.AtomicInteger

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

object Main {
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val K = sc.nextInt()
    val L = sc.nextInt()

    val uf_road = new UnionFind(N + 1)
    (0 until K) foreach { _ =>
      uf_road.unite(sc.nextInt(), sc.nextInt())
    }

    val uf_rail = new UnionFind(N + 1)
    (0 until L) foreach { _ =>
      uf_rail.unite(sc.nextInt(), sc.nextInt())
    }

    def key(i: Int) = (uf_road.find(i), uf_rail.find(i))

    val count = mutable.Map[(Int, Int), AtomicInteger]()
    (1 to N) map { i =>
      val k = key(i)
      if (!(count contains k)) count(k) = new AtomicInteger
      count(k).addAndGet(1)
    }

    (1 to N) foreach { i =>
      if (i > 1) print(" ")
      print(count(key(i)).get)
    }
    println()
//    val count = ((1 to N) map key).groupBy(identity).mapValues(_.size)
//    val ans = ((1 to N) map (key _).andThen (count(_))).mkString(" ")
//    println(ans)
  }

  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 nextLong(): Long = next.toLong
    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
        }
      }
    }
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datA, datB, datX) = readLine.split(" ").map(_.toLong)
    val ans = (datB / datX) - ((datA - 1) / datX)
    println(ans)
  }
}

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

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

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


import io.{StdIn => in}

object Main extends App {
  val Array(a, b, x) = in.readLine.split(" ").map(_.toLong)
  val ans = (b / x) - ((a-1) / x)
  println(ans)
}


import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

/**
 * Created by sonetsuyoshi on 2015/12/16.
 */
case class Person(id: Int, langs: Seq[Int])

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

  val langs: Array[mutable.MutableList[Person]] = Array.fill(M)(mutable.MutableList[Person]())
  val ps = 0.until(N).map(x => {
    val p = Person(x, readLine.split(" ").drop(1).map(_.toInt - 1))
    p.langs.foreach(l => langs(l).+=(p))
    p
  })
  val p0 = ps(0)

  val unvisitedPersons = Array.fill(N)(true)
  val unvisitedLangs = Array.fill(M)(true)

  val visitingPersons = mutable.Stack[Person]()
  val visitingLangs = mutable.Stack[Int]()

  visitingPersons.push(p0)

  while(visitingPersons.size > 0) {
    val p = visitingPersons.pop()
    p.langs.filter(l => unvisitedLangs(l)).foreach(l => {
      unvisitedLangs(l) = false
      val pps = langs(l)
      pps.filter(pp => unvisitedPersons(pp.id)).foreach(pp => {
        unvisitedPersons(pp.id) = false
        visitingPersons.push(pp)
      })
    })
  }
  if(unvisitedPersons.forall(_ == false)) {
    println("YES")
  } else {
    println("NO")
  }
}

Score : 400 points

Problem Statement

On a planet far, far away, M languages are spoken. They are conveniently numbered 1 through M.

For CODE FESTIVAL 20XX held on this planet, N participants gathered from all over the planet.

The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1}, L_{i,2}, ..., L_{i,{}K_i}.

Two participants A and B can communicate with each other if and only if one of the following conditions is satisfied:

There exists a language that both A and B can speak.

There exists a participant X that both A and B can communicate with.

Determine whether all N participants can communicate with all other participants.

Constraints

2≦N≦10^5

1≦M≦10^5

1≦K_i≦M

(The sum of all K_i)≦10^5

1≦L_{i,j}≦M

L_{i,1}, L_{i,2}, ..., L_{i,{}K_i} are pairwise distinct.

Partial Score

200 points will be awarded for passing the test set satisfying the following: N≦1000, M≦1000 and (The sum of all K_i)≦1000.

Additional 200 points will be awarded for passing the test set without additional constraints.

Input

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

N M
K_1 L_{1,1} L_{1,2} ... L_{1,{}K_1}
K_2 L_{2,1} L_{2,2} ... L_{2,{}K_2}
:
K_N L_{N,1} L_{N,2} ... L_{N,{}K_N}

Output

If all N participants can communicate with all other participants, print YES. Otherwise, print NO.

Sample Input 1

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

Sample Output 1

YES

Any two participants can communicate with each other, as follows:

Participants 1 and 2: both can speak language 2.

Participants 2 and 3: both can speak language 4.

Participants 1 and 3: both can communicate with participant 2.

Participants 3 and 4: both can speak language 6.

Participants 2 and 4: both can communicate with participant 3.

Participants 1 and 4: both can communicate with participant 2.

Note that there can be languages spoken by no participant.

Sample Input 2

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

Sample Output 2

NO

For example, participants 1 and 3 cannot communicate with each other.


import java.util.Scanner

import scala.collection.mutable

/**
 * Created by sonetsuyoshi on 2015/12/16.
 */
object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val M = sc.nextInt

  val valCountMap = mutable.Map[Int, Int]().withDefaultValue(0)
  val modValMap = Array.fill(M)(mutable.Set[Int]())
  val modCountMap = Array.fill(M)(0)

  for(i <- 0 until N) {
    val n = sc.nextInt
    val m = n % M
    valCountMap.+=((n, valCountMap(n) + 1))
    modValMap(m).+=(n)
    modCountMap(m) += 1
  }

  var count = modCountMap(0) / 2
  for(i <- 1 to ((M - 1) / 2)) {
    val j = M - i
    val (sId, lId) = if(modCountMap(i) < modCountMap(j)) {
      (i, j)
    } else {
      (j, i)
    }

    val countDif = modCountMap(lId) - modCountMap(sId)
    val maxPairNum = countDif / 2

    val pairNum = modValMap(lId).foldLeft(0){case(s, x) => s + valCountMap(x) / 2}

    count += modCountMap(sId) + math.min(maxPairNum, pairNum)
  }

  if(M % 2 == 0) count += modCountMap(M / 2) / 2

  println(count)
}

Score : 700 points

Problem Statement

Takahashi is playing with N cards.

The i-th card has an integer X_i on it.

Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions:

The integers on the two cards are the same.

The sum of the integers on the two cards is a multiple of M.

Find the maximum number of pairs that can be created.

Note that a card cannot be used in more than one pair.

Constraints

2≦N≦10^5

1≦M≦10^5

1≦X_i≦10^5

Input

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

N M
X_1 X_2 ... X_N

Output

Print the maximum number of pairs that can be created.

Sample Input 1

7 5
3 1 4 1 5 9 2

Sample Output 1

3

Three pairs (3,2), (1,4) and (1,9) can be created.

It is possible to create pairs (3,2) and (1,1), but the number of pairs is not maximized with this.

Sample Input 2

15 10
1 5 6 10 11 11 11 20 21 25 25 26 99 99 99

Sample Output 2

6


import java.util.Scanner

import scala.collection.mutable

/**
 * Created by sonetsuyoshi on 2015/12/16.
 */
object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val M = sc.nextInt

  val valCountMap = mutable.Map[Int, Int]().withDefaultValue(0)
  val modValMap = Array.fill(M)(mutable.Set[Int]())
  val modCountMap = Array.fill(M)(0)

  for(i <- 0 until N) {
    val n = sc.nextInt
    val m = n % M
    valCountMap.+=((n, valCountMap(n) + 1))
    modValMap(m).+=(n)
    modCountMap(m) += 1
  }

  var count = modCountMap(0) / 2
  for(i <- 1 to ((M - 1) / 2)) {
    val j = M - i
    val (sId, lId) = if(modCountMap(i) < modCountMap(j)) {
      (i, j)
    } else {
      (j, i)
    }

    val countDif = modCountMap(lId) - modCountMap(sId)
    val maxPairNum = countDif / 2

    val pairNum = modValMap(lId).foldLeft(0){case(s, x) => s + valCountMap(x) / 2}

    count += modCountMap(sId) + math.min(maxPairNum, pairNum)
  }

  count += modCountMap(M / 2) / 2

  println(count)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val x = Array.fill(3)(sc.nextInt()).sorted
  if (x(0) + x(1) == x(2)) {
    println("Yes")
  } else {
    println("No")
  }
}

Score : 100 points

Problem Statement

Two students of AtCoder Kindergarten are fighting over candy packs.

There are three candy packs, each of which contains a, b, and c candies, respectively.

Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.

Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.

Constraints

1 ≦ a, b, c ≦ 100

Input

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

a b c

Output

If it is possible to distribute the packs so that each student gets the same number of candies, print Yes. Otherwise, print No.

Sample Input 1

10 30 20

Sample Output 1

Yes

Give the pack with 30 candies to one student, and give the two packs with 10 and 20 candies to the other. Then, each gets 30 candies.

Sample Input 2

30 30 100

Sample Output 2

No

In this case, the student who gets the pack with 100 candies always has more candies than the other.

Note that every pack must be given to one of them.

Sample Input 3

56 25 31

Sample Output 3

Yes


import scala.io.StdIn

object Main extends App {

  case class Point(index: Int, x: Int, y: Int, pattern: Int)

  case class Rect(xs: Int, xe: Int, ys: Int, ye: Int)

  val Array(w, h, n) = StdIn.readLine().split(" ").map(_.toInt)
  val points = (0 until n).map { i =>
    val a = StdIn.readLine().split(" ").map(_.toInt)
    Point(i, a(0), a(1), a(2))
  }

  val r = points.foldLeft(Rect(0, w, 0, h)) { (acc, p) =>
    p.pattern match {
      case 1 => Rect(if (acc.xs < p.x) p.x else acc.xs, acc.xe, acc.ys, acc.ye) // < Xi
      case 2 => Rect(acc.xs, if (acc.xe > p.x) p.x else acc.xe, acc.ys, acc.ye) // > Xi
      case 3 => Rect(acc.xs, acc.xe, if (acc.ys < p.y) p.y else acc.ys , acc.ye) // < Yi
      case 4 => Rect(acc.xs, acc.xe, acc.ys, if (acc.ye > p.y) p.y else acc.ye) // > Yi
    }
  }
  // println(r)
  // println(r.xe - r.xs , r.ye - r.ys)
  println(if(r.xe < r.xs || r.ye < r.ys) 0 else (r.xe - r.xs) * (r.ye - r.ys))
}

Score : 200 points

Problem Statement

There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.

Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) point was (x_i, y_i).

Then, he created an integer sequence a of length N, and for each 1 ≦ i ≦ N, he painted some region within the rectangle black, as follows:

If a_i = 1, he painted the region satisfying x < x_i within the rectangle.

If a_i = 2, he painted the region satisfying x > x_i within the rectangle.

If a_i = 3, he painted the region satisfying y < y_i within the rectangle.

If a_i = 4, he painted the region satisfying y > y_i within the rectangle.

Find the area of the white region within the rectangle after he finished painting.

Constraints

1 ≦ W, H ≦ 100

1 ≦ N ≦ 100

0 ≦ x_i ≦ W (1 ≦ i ≦ N)

0 ≦ y_i ≦ H (1 ≦ i ≦ N)

W, H (21:32, added), x_i and y_i are integers.

a_i (1 ≦ i ≦ N) is 1, 2, 3 or 4.

Input

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

W H N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_N y_N a_N

Output

Print the area of the white region within the rectangle after Snuke finished painting.

Sample Input 1

5 4 2
2 1 1
3 3 4

Sample Output 1

9

The figure below shows the rectangle before Snuke starts painting.

First, as (x_1, y_1) = (2, 1) and a_1 = 1, he paints the region satisfying x < 2 within the rectangle:

Then, as (x_2, y_2) = (3, 3) and a_2 = 4, he paints the region satisfying y > 3 within the rectangle:

Now, the area of the white region within the rectangle is 9.

Sample Input 2

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

Sample Output 2

0

It is possible that the whole region within the rectangle is painted black.

Sample Input 3

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

Sample Output 3

64


import scala.io.StdIn._
object Main extends App {
  @scala.annotation.tailrec
  def next(diff: Int, maxValue: Int, num: Int, as: Seq[Int]): Int = {
    as match {
      case Nil => num
      case _ =>
        val targetValue = as.head
        val newDiff = maxValue - targetValue
        if (newDiff > diff) next(newDiff, maxValue, 1, as.tail) // must be (targetValue < maxValue)
        else if (newDiff == diff) next(diff, targetValue, num + 1, as.tail) // must be (targetValue > maxValue)
        else next(diff, targetValue max maxValue, num, as.tail)
    }
  }

  /*
  val n = readLine.split(" ").head map {_.toInt}
  */
  import java.io._
  val br = new BufferedReader(new InputStreamReader(System.in));
  val n = br.readLine.split(" ").head map {_.toInt}
  val as = (readLine.split(" ") map {_.toInt}).toSeq.reverse

  println(next(0, as.head, 0, as.tail))
}

Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

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

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

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

Sample Output 3

2


object Main extends App{
    // Here your code !
    val scanner = new java.util.Scanner(System.in)
    println(cf(scanner.next))

    def cf(ins:String):String = ins match {
            case ins:String if ins.indexOf("C") < ins.lastIndexOf("F") => "Yes"
            case _ => "No"
    }
}

Score : 100 points

Problem Statement

This contest is CODEFESTIVAL, which can be shortened to the string CF by deleting some characters.

Mr. Takahashi, full of curiosity, wondered if he could obtain CF from other strings in the same way.

You are given a string s consisting of uppercase English letters.
Determine whether the string CF can be obtained from the string s by deleting some characters.

Constraints

2 ≤ |s| ≤ 100

All characters in s are uppercase English letters (A-Z).

Input

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

s

Output

Print Yes if the string CF can be obtained from the string s by deleting some characters.
Otherwise print No.

Sample Input 1

CODEFESTIVAL

Sample Output 1

Yes

CF is obtained by deleting characters other than the first character C and the fifth character F.

Sample Input 2

FESTIVALCODE

Sample Output 2

No

FC can be obtained but CF cannot be obtained because you cannot change the order of the characters.

Sample Input 3

CF

Sample Output 3

Yes

It is also possible not to delete any characters.

Sample Input 4

FCF

Sample Output 4

Yes

CF is obtained by deleting the first character.


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

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

object Main {
  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val T, A = map(N)(_ => sc.nextInt())
    sealed trait Fact
    case class Just(a: Int) extends Fact
    case class LE(a: Int) extends Fact

    def judge(fa: Fact, fb: Fact): Int = (fa, fb) match {
      case (Just(a), Just(b)) if a == b => 1
      case (Just(a), LE(b)) if a <= b => 1
      case (LE(a), Just(b)) if a >= b => 1
      case (LE(a), LE(b)) => min(a, b)
      case _ => 0
    }

    val factT, factA = Array.ofDim[Fact](N)
    var max = 0
    rep(N){ i =>
      if (T(i) > max) {
        factT(i) = Just(T(i))
        max = T(i)
      } else {
        factT(i) = LE(max)
      }
    }

    max = 0
    rep_r(N){ i =>
      if (A(i) > max) {
        factA(i) = Just(A(i))
        max = A(i)
      } else {
        factA(i) = LE(max)
      }
    }

    var ans = 1L
    rep(N){ i =>
      ans = ans * judge(factT(i), factA(i)) % MOD
    }

    out.println(ans)
  }

  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)
  }
  def rep(n: Int)(f: Int => Unit): Unit = {
    var i = 0
    while(i < n) { f(i); i += 1 }
  }
  def rep_r(n: Int)(f: Int => Unit): Unit = {
    var i = n - 1
    while(i >= 0) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

Score : 400 points

Problem Statement

Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range.
The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N.
Mr. Takahashi traversed the range from the west and Mr. Aoki from the east.

The height of Mt. i is h_i, but they have forgotten the value of each h_i.
Instead, for each i (1 ≤ i ≤ N), they recorded the maximum height of the mountains climbed up to the time they reached the peak of Mt. i (including Mt. i).
Mr. Takahashi's record is T_i and Mr. Aoki's record is A_i.

We know that the height of each mountain h_i is a positive integer.
Compute the number of the possible sequences of the mountains' heights, modulo 10^9 + 7.

Note that the records may be incorrect and thus there may be no possible sequence of the mountains' heights.
In such a case, output 0.

Constraints

1 ≤ N ≤ 10^5

1 ≤ T_i ≤ 10^9

1 ≤ A_i ≤ 10^9

T_i ≤ T_{i+1} (1 ≤ i ≤ N - 1)

A_i ≥ A_{i+1} (1 ≤ i ≤ N - 1)

Input

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

N
T_1 T_2 ... T_N
A_1 A_2 ... A_N

Output

Print the number of possible sequences of the mountains' heights, modulo 10^9 + 7.

Sample Input 1

5
1 3 3 3 3
3 3 2 2 2

Sample Output 1

4

The possible sequences of the mountains' heights are:

1, 3, 2, 2, 2

1, 3, 2, 1, 2

1, 3, 1, 2, 2

1, 3, 1, 1, 2

for a total of four sequences.

Sample Input 2

5
1 1 1 2 2
3 2 1 1 1

Sample Output 2

0

The records are contradictory, since Mr. Takahashi recorded 2 as the highest peak after climbing all the mountains but Mr. Aoki recorded 3.

Sample Input 3

10
1 3776 3776 8848 8848 8848 8848 8848 8848 8848
8848 8848 8848 8848 8848 8848 8848 8848 3776 5

Sample Output 3

884111967

Don't forget to compute the number modulo 10^9 + 7.

Sample Input 4

1
17
17

Sample Output 4

1

Some mountain ranges consist of only one mountain.


object Main {
  def main(args: Array[String]): Unit = {
    var n = io.StdIn.readLine().toInt
    val t = io.StdIn.readLine().split(' ').map(_.toLong)
    val a = io.StdIn.readLine().split(' ').map(_.toLong)

    val h = scala.collection.mutable.ListBuffer.empty[Long]

    if (t(0) > a(0)) {
      println(0)
      return
    } else {
      if (n > 1 && a(0) > a(1) && t(0) != a(0)) {
        println(0)
        return
      } else {
        h += t(0)
      }
    }

    for (i <- 1 to (n - 2)) {
      val ht = if (t(i - 1) < t(i)) t(i) else 0
      val ha = if (a(i) > a(i + 1)) a(i) else 0
      if (ht == 0) {
        h += ha
      } else if (ha == 0) {
        h += ht
      } else if (ht == ha) {
        h += ha
      } else {
        println(0)
        return
      }
    }

    if (t(n - 1) < a(n - 1)) {
      println(0)
      return
    } else {
      if (n > 1 && t(n - 2) < t(n - 1) && t(n - 1) != a(n - 1)) {
        println(0)
        return
      } else {
        h += a(n - 1)
      }
    }

    val candidate = scala.collection.mutable.ListBuffer.empty[(Long, Int)]
    var j = 0
    while (j < n) {
      if (h(j) > 0) {
        j += 1
      } else {
        var k = j
        while (h(k) == 0) {
          k += 1
        }
        candidate += Tuple2(Math.min(h(j - 1), h(k)), k - j)
        j = k
      }
    }

    val p = Math.pow(10, 9).toLong + 7

    val res = candidate.foldLeft(1L) { (acc, pair) =>
      (acc * Math.pow(pair._1 % p, pair._2).toLong % p) % p
    }

    println(res)
  }

}


object Main extends App {
    val c = io.StdIn.readLine.split(" ").distinct
    println(c.length)
}

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

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

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


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

  println(solve(n, k))

  def solve(n: Int, k: Int): Int = {
    (1 until n).foldLeft(k){ (acc, _) => acc * (k - 1) }
  }
}

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

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

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


import scala.math.pow

object Main {
  def main(args: Array[String]): Unit = {
    val List(n, k) = io.StdIn.readLine.split(' ').toList.map(c => c.toInt)
    val answer = k * pow((k - 1), (n - 1)).toLong

    println(answer)
  }
}


import io.StdIn.readLine

object Main {
  def main(args: Array[String]): Unit = {
    val n = readLine().toInt

    var t, a = 1.0

    for (i <- 1 to n) {
      val Array(ti, ai) = readLine().split(' ').map(_.toDouble)
      val times = Math.max(Math.ceil(t / ti).toInt, Math.ceil(a / ai).toInt)
      t = ti * times
      a = ai * times
    }

    println((t + a).toInt)
  }
}

Score : 300 points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

1≦N≦1000

1≦T_i,A_i≦1000 (1≦i≦N)

T_i and A_i (1≦i≦N) are coprime.

It is guaranteed that the correct answer is at most 10^{18}.

Input

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

N
T_1 A_1
T_2 A_2
:
T_N A_N

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930


object Main extends App {
  @scala.annotation.tailrec
  def loop(chars: List[Char], a: Int, b: Int, result: Vector[String]): Vector[String] = chars match {
    case List() => result
    case x::xs => x match {
      case 'a' if 0 < a =>
        loop(xs, a - 1, b, result :+ "Yes")
      case 'a' if 0 < b =>
        loop(xs, 0, b - 1, result :+ "Yes")
      case 'b' if 0 < b =>
        loop(xs, a, b - 1, result :+ "Yes")
      case _ =>
        loop(xs, a, b, result :+ "No")
    }
  }
  val sc = new java.util.Scanner(System.in)
  val _, a, b = sc.nextInt()
  val s = sc.next().toCharArray.toList
  loop(s, a, b, Vector.empty).foreach(println)
}

Score : 200 points

Problem Statement

There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.

Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from the top rank down. Participants who are not students cannot pass the Qualification contests.

A Japanese student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B.

An overseas student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B and the student ranks B-th or above among all overseas students.

A string S is assigned indicating attributes of all participants. If the i-th character of string S is a, this means the participant ranked i-th in the Qualification contests is a Japanese student; b means the participant ranked i-th is an overseas student; and c means the participant ranked i-th is neither of these.

Write a program that outputs for all the participants in descending rank either Yes if they passed the Qualification contests or No if they did not pass.

Constraints

1≦N,A,B≦100000

A+B≦N

S is N characters long.

S consists only of the letters a, b and c.

Input

Inputs are provided from Standard Input in the following form.

N A B
S

Output

Output N lines. On the i-th line, output Yes if the i-th participant passed the Qualification contests or No if that participant did not pass.

Sample Input 1

10 2 3
abccabaabb

Sample Output 1

Yes
Yes
No
No
Yes
Yes
Yes
No
No
No

The first, second, fifth, sixth, and seventh participants pass the Qualification contests.

Sample Input 2

12 5 2
cabbabaacaba

Sample Output 2

No
Yes
Yes
Yes
Yes
No
Yes
Yes
No
Yes
No
No

The sixth participant is third among overseas students and thus does not pass the Qualification contests.

Sample Input 3

5 2 2
ccccc

Sample Output 3

No
No
No
No
No