import java.util.Scanner

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

  val s = sc.next
  val n = s.length

  def loop(str: String): String ={
    val l = str.length
    if(l < n && str.substring(0,l/2) == str.substring(l/2)) str
    else loop(str.substring(0,l - 2))
  }

  val res = loop(s).length

  println(res)
}

Score : 200 points

Problem Statement

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

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

Constraints

2 \leq |S| \leq 200

S is an even string consisting of lowercase English letters.

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

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

abaababaab

Sample Output 1

6

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

abaababaa is not even.

abaababa is not even.

abaabab is not even.

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

Sample Input 2

xxxx

Sample Output 2

2

xxx is not even.

xx is even.

Sample Input 3

abcabcabcabc

Sample Output 3

6

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

Sample Input 4

akasakaakasakasakaakas

Sample Output 4

14

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


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

  def loop(num: Int, count: Int): Int = {
    if (num == 2) count
    else if (count > n) -1
    else loop(list(num - 1), count + 1)
  }

  println(loop(1, 0))
}

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

Score : 200 points

Problem Statement

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

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

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

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

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

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

Sample Input 1

3
3
1
2

Sample Output 1

2

Press Button 1, then Button 3.

Sample Input 2

4
3
4
1
2

Sample Output 2

-1

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

Sample Input 3

5
3
3
4
2
4

Sample Output 3

3

Submitted source-code file size, in bytes.

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

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


object Main {
  def solve(i:Int, n: Int, maxNum: Int, arr: IndexedSeq[Int]):Int = {
    if (n == maxNum){
      -1
    }else{
      if(arr(i)==1){
        n + 1
      }else{
        solve(arr(i), n+1, maxNum, arr)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readLine().toInt
    val arr = for(i <- 0 until n) yield io.StdIn.readLine().toInt-1
    println(solve(0,0,n,arr))
  }
}


import io.StdIn.readInt
import annotation.tailrec
import collection.mutable.{Seq => MutableSeq}

object Main extends App {
  val n = readInt
  val as = Seq.fill(n)(readInt)
  val vs = MutableSeq.fill(n)(false)

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

  @tailrec def solve(pos: Int, res: Int, as: Seq[Int], vs: MutableSeq[Boolean]): Int = {
    if (pos == 1) res
    else if (vs(pos)) -1
    else {
      solve(as(pos) - 1, res + 1, as, vs.updated(pos, true))
    }
  }
}


import java.util.Scanner

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

  val s = sc.next
  val distinct = s.distinct

  val res = distinct.map(loop(_, s).max).min
  println(res)

  def loop(ch: Char, str: String, vec: Vector[Int] = Vector.empty): Vector[Int] = {
    str.foldLeft(vec){ case (acc, c) =>
      val (tr, fa) = str.span(_ != ch)
      if(fa.isEmpty) vec :+ tr.length
      else loop(ch, fa.tail, vec :+ tr.length)
    }
  }
}

Score : 300 points

Problem Statement

Snuke can change a string t of length N into a string t' of length N - 1 under the following rule:

For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t.

There is a string s consisting of lowercase English letters.
Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same.
Find the minimum necessary number of operations.

Constraints

1 ≤ |s| ≤ 100

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum necessary number of operations to achieve the objective.

Sample Input 1

serval

Sample Output 1

3

One solution is: serval → srvvl → svvv → vvv.

Sample Input 2

jackal

Sample Output 2

2

One solution is: jackal → aacaa → aaaa.

Sample Input 3

zzz

Sample Output 3

0

All the characters in s are the same from the beginning.

Sample Input 4

whbrjpjyhsrywlqjxdbrbaomnw

Sample Output 4

8

In 8 operations, he can change s to rrrrrrrrrrrrrrrrrr.


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

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

    val colors = scala.collection.mutable.Set[String]()
    var over3200 = 0
    for (i <- 0 until n) {
      if (a(i) <= 399) colors.add("grey")
      else if (a(i) <= 799) colors.add("brown")
      else if (a(i) <= 1199) colors.add("green")
      else if (a(i) <= 1599) colors.add("light_blue")
      else if (a(i) <= 1999) colors.add("blue")
      else if (a(i) <= 2399) colors.add("yellow")
      else if (a(i) <= 2799) colors.add("orange")
      else if (a(i) <= 3199) colors.add("red")
      else over3200 += 1
    }

    val min = colors.size
    val max = math.min(colors.size + over3200, 8)
    println(min + " " + max)

  }
}

Score : 300 points

Problem Statement

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

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

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

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

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

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

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

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

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

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

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

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

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

Sample Input 3

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

Sample Output 3

1 1

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


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

	val a: Array[Int] = new Array(N)
	val b: Array[Int] = new Array(9)

	for(i <- 0 until N){
		a(i) = x.split(" ")(i).toInt
	}

	def find(x: Int):Int = {
		if(1<=x && x<=399){
			return 0;
		}else if(400<=x && x<=799){
			return 1;
		}else if(800<=x && x<=1199){
			return 2;
		}else if(1200<=x && x<=1599){
			return 3;
		}else if(1600<=x && x<=1999){
			return 4;
		}else if(2000<=x && x<=2399){
			return 5;
		}else if(2400<=x && x<=2799){
			return 6;
		}else if(2800<=x && x<=3199){
			return 7;
		}else{
			return 8;
		}
	}

	for(i<- 0 until N){
		val t = find(a(i))

		b(t) = b(t) + 1;
	}

	var count = 0

	for(i<- 0 to 7){
		if(b(i) != 0) count = count + 1
	}

	if(b(8) == 0){
		println(count + " " + count)
	}else{
		val u = count + b(8)
		if(u <= 8){
			println(count + " "+ u)
		}else{
			println(count + " 8")
		}
	}

}


object Main {
  def main(args: Array[String]): Unit = {
    import collection._
    val n = io.StdIn.readLine()
    val str = io.StdIn.readLine()

    val (l, r) = str.foldLeft((0,0)){
      case ((lacc, acc), c) => {
        c match {
          case '(' => (lacc, acc + 1)
          case ')' if acc == 0 => (lacc + 1, 0)
          case _ => (lacc, acc - 1)
        }
      }
    }

    val left = Seq.fill(l)('(')
    val right = Seq.fill(r)(')')
    println(left.mkString + str + right.mkString)
  }
}

Score : 400 points

Problem Statement

You are given a string S of length N consisting of ( and ). Your task is to insert some number of ( and ) into S to obtain a correct bracket sequence.

Here, a correct bracket sequence is defined as follows:

() is a correct bracket sequence.

If X is a correct bracket sequence, the concatenation of (, X and ) in this order is also a correct bracket sequence.

If X and Y are correct bracket sequences, the concatenation of X and Y in this order is also a correct bracket sequence.

Every correct bracket sequence can be derived from the rules above.

Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.

Constraints

The length of S is N.

1 ≤ N ≤ 100

S consists of ( and ).

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into S.

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

(((())))(((())))


import java.io.{PrintWriter, _}
import java.util
import java.util._

object Main {
  def main(args: Array[String]): Unit = {
    val inputStream = System.in
    val outputStream = System.out
    val in = new InputReader(inputStream)
    val out = new PrintWriter(outputStream)
    val solver = new Task
    solver.solve(1, in, out)
    out.close()
  }

  class Task {
    def solve(testNumber: Int, in: InputReader, out: PrintWriter): Unit = {
      val a = in.nextInt
      val b = in.nextInt
      if (a + b < 10) {
        println(a + b)
      } else {
        println("error")
      }
    }
  }

  class InputReader(val stream: InputStream) extends AutoCloseable {
    //reader = new BufferedReader(new FileReader(stream), 32768);
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer = new StringTokenizer("")

    def next: String = {
      while ( {
        tokenizer == null || !tokenizer.hasMoreTokens
      }) try
        tokenizer = new StringTokenizer(reader.readLine)
      catch {
        case e: IOException =>
          throw new RuntimeException(e)
      }
      tokenizer.nextToken
    }

    def nextLine: String = {
      try
        return reader.readLine
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      ""
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    override def close(): Unit = {
    }
  }

}

Score : 100 points

Problem Statement

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

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

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


object Main extends App {
    val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val x = a(0)
    val y = a(1)
    val ret = if (x+y<10) x+y else "error"
    println(ret)
}


import java.util.Scanner

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

  val s = sc.next

  val res = if(s.distinct.length == s.length) "yes" else "no"

  println(res)
}

Score : 200 points

Problem Statement

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

Constraints

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

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

uncopyrightable

Sample Output 1

yes

Sample Input 2

different

Sample Output 2

no

Sample Input 3

no

Sample Output 3

yes


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val s = List.fill(sc.nextInt())(sc.nextInt()).sorted
  val max = s.sum match {
    case sum if sum % 10 != 0 => sum
    case sum => s.find(_ % 10 != 0).map(sum - _).getOrElse(0)
  }
  println(max)
}

Score : 300 points

Problem Statement

You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

1 ≤ N ≤ 100

1 ≤ s_i ≤ 100

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 0.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be 35 if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of 10 and displayed as 0.


object Main extends App {
	val Array(x, y) = scala.io.StdIn.readLine.split(" ").map(_.toInt)

	val a1 = Set(1,3,5,7,8,10,12)
	val a2 = Set(4,6,9,11)
	val a3 = Set(2)

	if(a1.contains(x) && a1.contains(y)){
		println("Yes")
	}else if(a2.contains(x) && a2.contains(y)){
		println("Yes")
	}else if(a3.contains(x) && a3.contains(y)){
		println("Yes")
	}else{
		println("No")
	}

}

Score : 100 points

Problem Statement

Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below.
Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

If x and y belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No


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

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

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

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

        (Math.max(h/3,0) to Math.min(h,h/3+1)).foreach(x => {
            val hx = h-x
            val w0 = w/2
            val w1 = w-w/2
            val can = Seq(x*h,hx*w0,hx*w1)
            res = Math.min(res,can.max-can.min)
        })
        /*
        h=Math.max(H,W)
        w=Math.min(H,W)

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

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

        res
    }

    println(res)
}

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

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

Score : 400 points

Problem Statement

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

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

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

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

Sample Input 1

3 5

Sample Output 1

0

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

Sample Input 2

4 5

Sample Output 2

2

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

Sample Input 3

5 5

Sample Output 3

4

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

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


import java.util.Scanner
import scala.collection.mutable.PriorityQueue

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

  val n = sc.nextInt()
  val a = new Array[Int](3*n + 1)

  for(i <- 1 to 3*n)
    a(i) = sc.nextInt()

  val left = new Array[Long](n+1)
  val right = new Array[Long](n+1)

  // left
  left(0) = a.slice(1, n+1).sum
  val pqd = new PriorityQueue[Int]()(Ordering.Int.reverse)
  for(i <- 1 to n)
    pqd.enqueue(a(i))
  for(i <- n+1 to 2*n){
    pqd.enqueue(a(i))
    left(i-n) = left(i-n-1) + a(i) - pqd.dequeue
  }

  // right
  right(n) = a.slice(2*n+1, 3*n+1).sum
  val pqa = new PriorityQueue[Int]
  for(i <- (2*n+1 to 3*n).reverse)
    pqa.enqueue(a(i))
  for(i <- (n to 2*n-1).reverse){
    pqa.enqueue(a(i+1))
    right(i-n) = right(i-n+1) + a(i+1) - pqa.dequeue
  }

  var ans = -1e18.toLong
  for(i <- 0 to n){
    ans = Math.max(ans, left(i) - right(i))
  }

  println(ans)
}

Score : 500 points

Problem Statement

Let N be a positive integer.

There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}).
Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').

Find the maximum possible score of a'.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Partial Score

In the test set worth 300 points, N ≤ 1000.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the maximum possible score of a'.

Sample Input 1

2
3 1 4 1 5 9

Sample Output 1

1

When a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3 + 4) - (1 + 5) = 1.

Sample Input 2

1
1 2 3

Sample Output 2

-1

For example, when a_1 are removed, a' will be (2, 3), which has a score of 2 - 3 = -1.

Sample Input 3

3
8 2 2 7 4 6 5 3 8

Sample Output 3

5

For example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3), which has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5.


import java.util.Scanner

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

  val a = sc.nextInt
  val b = sc.nextInt
  val c = sc.nextInt

  val res = if(a <= c && c <= b) "Yes" else "No"

  println(res)
}

Score : 100 points

Problem Statement

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

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

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

Sample Input 1

1 3 2

Sample Output 1

Yes

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

Sample Input 2

6 5 4

Sample Output 2

No

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

Sample Input 3

2 2 2

Sample Output 3

Yes


object Main extends App{
    val ary = io.StdIn.readLine().split(" ")
    val ret = if (ary(0)<=ary(2)&&ary(2)<=ary(1)) "Yes" else "No"
    println(ret)
}


import java.util.Scanner

import scala.collection.mutable.PriorityQueue

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

  val n = sc.nextInt()
  val k = sc.nextLong()

  var q = PriorityQueue()(Ordering.by((_: (Int, Long))._1).reverse)

  for (i <- 1 to n) {
    val a, b = sc.nextInt()
    q.enqueue((a, b))
  }

  val (_, ans) = q.foldLeft((0L, -1)) {

    case ((cnt, ans), (a, b)) =>
      if (ans > 0) (cnt, ans)
      else if (cnt + b >= k) (cnt, a)
      else (cnt + b, ans)
  }

  println(ans)
}

Score : 300 points

Problem Statement

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

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

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

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

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

Sample Input 2

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

Sample Output 2

1


import scala.collection.mutable.Stack

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

  def shortestPath(s: Int, n: Int, edges: Seq[(Int, Int, Int)]): Array[Long] = {
    val adj = Array.fill(n)(List[Int]())
    for ((u, v, _) <- edges) {
      adj(u) ::= v
    }

    val sp = Array.fill(n)(Long.MaxValue)
    sp(s) = 0

    for {
      _ <- 1 until n
      (u, v, l) <- edges if sp(u) != Long.MaxValue
    } {
      sp(v) = sp(v).min(sp(u) + l)
    }

    var visited = Set[Int]()
    val stack = Stack[Int]()
    for ((u, v, l) <- edges if sp(u) != Long.MaxValue) {
      if (sp(v) > sp(u) + l) {
        visited += v
        stack.push(v)
      }
    }

    while (stack.nonEmpty) {
      val u = stack.pop()
      for (v <- adj(u) if !visited(v)) {
        visited += v
        stack.push(v)
      }
    }

    for (u <- visited) {
      sp(u) = Long.MinValue
    }

    sp
  }

  val sp = shortestPath(0, n, e)
  println(if (sp(n-1) == Long.MinValue) "inf" else -sp(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


import scala.collection.mutable.ArrayBuffer

object Main {

  val INF = Long.MaxValue
  case class Edge(to: Int, weight: Int)
  def main(args: Array[String]): Unit = {
    // 仮定, スコアが無限に増えるケースでは閉路が存在するから, inf
    // つまり, 正常な場合は閉路がないことから有効非巡回グラフになっているので
    // トポロジカルソート版ベルマンフォードが有効
    // 閉路検出は, トポロジカルソート順に再度緩和した時, 緩和できるかどうか?
    // なお, 1からVまで必ず到達できることを保証しているが, それ以外が連結かどうかを示していない
    val sc = new java.util.Scanner(System.in)

    val V, E = sc.nextInt()
    val G = Array.fill(V+1)(new ArrayBuffer[Edge]())
    for (_ <- 0 until E) {
      val u, v, w = sc.nextInt()
      G(u).append(Edge(v, -w))
    }

    bellmanFord(V, G, 1) match {
      case Some(v) => println(v)
      case _ => println("inf")
    }
  }

  def bellmanFord(V: Int, G: Array[ArrayBuffer[Edge]], s: Int): Option[Long] = {
    val dist = Array.fill(V+1)(INF)
    dist(s) = 0

    def relax(u: Int, v: Int, w: Int): Boolean =
      if (dist(u) != INF && dist(v) > dist(u) + w) {
        dist(v) = dist(u) + w
        true
      } else false

    val sorted = topologicalSort(V, G, 1)
    for {
      u <- sorted
      e <- G(u)
    } relax(u, e.to, e.weight)

    if (!sorted.exists(u => G(u).exists(e => relax(u, e.to, e.weight))))
      Some(-dist(V))
    else None
  }

  private def topologicalSort(V: Int, G: Array[ArrayBuffer[Edge]], s: Int): List[Int] = {
    val visited = new Array[Boolean](V+1)
    def dfs(stack: List[Int], sorted: List[Int]): List[Int] =
      if (stack.nonEmpty) {
        val u = stack.head
        if (u < 0) dfs(stack.tail, (-u)-1 :: sorted)
        else if (!visited(u)) {
          visited(u) = true
          dfs(
            G(u).foldLeft(-(u+1) :: stack.tail)(
              (stack, e) => e.to :: stack), sorted)
        } else dfs(stack.tail, sorted)
      } else sorted
    dfs(s :: Nil, Nil)
  }

}


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] = {
        import num._
        val dist = Array.fill[T](V)(INF)
        dist(s) = zero
        for (i <- 1 to V) {
            for (Edge(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 = Edges[Long]()
        for (_ <- 1 to M) {
            val s, t = sc.nextInt
            val c = sc.nextLong
            edges += Edge(s-1, t-1, -c)
        }
        // println(edges.toList)
        val res = bellmanFord[Long](edges, N, 0, Long.MaxValue)
        // println(res.toList)
        if (res.isEmpty) println("inf")
        else {
            println(-res(N-1))
        }
    }
}


import java.util.Scanner

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

  val n = sc.nextInt(); val m = sc.nextLong()
  val graph = new Array[List[(Int, Int)]](n + 1)
  for(i <- 0 to n)
    graph(i) = List()

  for(i <- 1 to n){
    val a = sc.nextInt(); val b = sc.nextInt(); val c = sc.nextInt()
    graph(a) = (b, c) :: graph(a)
  }

  // main process
  var tmp = 0L
  var flag = false
  val dp: Array[Long] = Array.fill(n+1)(-1e18.toLong)
  dp(1) = 0

  for(i <- 1 to 2 * (n-1)) {
    for(a <- 1 to n) {
      for((b, c) <- graph(a)){
        dp(b) = Math.max(dp(b), dp(a) + c)
      }
    }

    if(i == n-1)
      tmp = dp(n)
    else if(i == 2 * (n-1) && tmp < dp(n))
      flag = true
  }

  if(flag)
    println("inf")
  else
    println(dp(n))
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val A = sc.next()
  val B = sc.next()
  val C = sc.next()

  println(if (A.last == B.head && B.last == C.head) "YES" else "NO")
}

Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datA, datB, datC) = readLine.split(" ").map(_.toInt)
    val ans = (datA to (datA * datB) by datA).exists(a => (a % datB) == datC)
    println(if(ans) "YES" else "NO")
  }
}

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


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datA, datB, datC) = readLine.split(" ").map(_.toInt)
    val ans = (datA to (datA * datB) by datA).exists(a => (a % datB) == datC)
    println(if(ans) "Yes" else "No")
  }
}


import scala.io.StdIn._

object Main{
    def main(args:Array[String]){
        val s  = readLine.split(" ").map(_.toInt)
        var f = false
        for (i <- 1 to s(1)) {
            if (s(0) * i % s(1) == s(2)) {
                f = true
            }
        }
        if (f) {
            printf("YES\n")
        } else {
            printf("NO\n")
        }
    }
}


import scala.io.StdIn._
object Main extends App {
  val Array(_, t) = readLine.split(" ").map(_.toInt)
  val (_, sum) = readLine.split(" ").map(_.toInt).foldLeft((0, 0)){case ((until, cur), x) =>
    (x + t, cur + t - (if (x < until) until - x else 0))
  }
  println(sum)
}

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.readLine

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

  var nextT = 0
  var sum = 0
  for(i <- 0 until n) {
    val ti = t(i)
    if(nextT <= ti) {
      sum += time
    } else {
      sum += ti + time - nextT
    }
    nextT = ti + time
  }

  println(sum)

}


import java.util.Scanner

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

  println(Array.fill(3)(sc.next()).foldLeft("")((z, x) => z + x(0).toUpper.toString))
}

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.io.{PrintWriter, _}
import java.util._

object Main {
  def main(args: Array[String]): Unit = {
    val inputStream = System.in
    val outputStream = System.out
    val in = new InputReader(inputStream)
    val out = new PrintWriter(outputStream)
    val solver = new Task
    solver.solve(1, in, out)
    out.close()
  }

  class Task {
    def solve(testNumber: Int, in: InputReader, out: PrintWriter): Unit = {
      val a = in.next
      val b = in.next
      val c = in.next
      out.println(a(0).toUpper + "" + b(0).toUpper + "" + c(0).toUpper)
    }
  }

  class InputReader(val stream: InputStream) extends AutoCloseable {
    //reader = new BufferedReader(new FileReader(stream), 32768);
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer = new StringTokenizer("")

    def next: String = {
      while ( {
        tokenizer == null || !tokenizer.hasMoreTokens
      }) try
        tokenizer = new StringTokenizer(reader.readLine)
      catch {
        case e: IOException =>
          throw new RuntimeException(e)
      }
      tokenizer.nextToken
    }

    def nextLine: String = {
      try
        return reader.readLine
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      ""
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    override def close(): Unit = {
    }
  }

}


import java.util.Scanner

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

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

  val res =
    if (a.length != b.length){
      if (a.length > b.length ) "GREATER"
      else                      "LESS"
    }
    else {
      val diff = (a zip b).find(t => t._1 != t._2)

      diff.map{case (aa, bb) =>
        if (aa > bb) "GREATER"
        else         "LESS"
      }.getOrElse("EQUAL")
      }

  println(res)
}

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 {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val _ = readLine
    val datA = readLine.split(" ").map(_.toLong).dropWhile(_ == 0)

    def judgement(acc: (Long, Long), cur: (Long, Long)): (Long, Long) = {
      val sum = acc._1
      val count = acc._2
      val a = cur._1
      if (sum > 0) {
        if (sum + a >= 0) (-1, count + math.abs(sum + a) + 1)
        else (sum + a, count)
      }
      else if (sum < 0) {
        if (sum + a <= 0) (1, count + math.abs(sum + a) + 1)
        else (sum + a, count)
      } else {
        (a, count)
      }
    }
    val posA = datA.map(a => (a, 0L)).foldLeft((0L, 0L)){ judgement(_, _) }
    val negA = datA.tail.map(a => (a, 0L)).foldLeft(
      if(datA.head > 0) -1L else 1L, math.abs(datA.head)
    ){ judgement(_, _) }

    val ans = math.min(posA._2, negA._2)
    println(ans)
  }
}

Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each a_i is an integer.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print the minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


import scala.io.StdIn
import scala.annotation.tailrec

object Main extends App {
  val n = StdIn.readInt
  val a = StdIn.readLine.split(" ").map(_.toLong)

  val init1 = if(a.head < 0) 1 - a.head else 0
  val ans1 = a.tail./:(a.head + init1, init1.abs)((acc,i) => {
    val (bsum, bcnt) = acc
    val sum = bsum + i
    val cnt = if(bsum < 0 && sum < 0) 1 - sum
    else if(bsum > 0 && sum > 0) -1 - sum
    else if(sum == 0) if(bsum < 0) 1 else -1
    else 0
    // println(sum + " " + cnt)
    (sum+cnt, bcnt+cnt.abs)
  })._2

  val init2 = if(a.head < 0) 0 else -1 - a.head
  val ans2 = a.tail./:(a.head + init2, init2.abs)((acc,i) => {
    val (bsum, bcnt) = acc
    val sum = bsum + i
    val cnt = if(bsum < 0 && sum < 0) 1 - sum
    else if(bsum > 0 && sum > 0) -1 - sum
    else if(sum == 0) if(bsum < 0) 1 else -1
    else 0
    // println(sum + " " + cnt)
    (sum+cnt, bcnt+cnt.abs)
  })._2

  println(math.min(ans1,ans2))
}


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

  val mod = 1000000007

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

  val c = x.sliding(2).map{
    case List(x1, x2) => x2 - x1
  }.zipWithIndex.map{
    case (e, idx) => times(times(e, idx+1), n-idx-1)
  }.reduceLeft(plus)

  val d = y.sliding(2).map{
    case List(y1, y2) => y2 - y1
  }.zipWithIndex.map{
    case (e, idx) => times(times(e, idx+1), m-idx-1)
  }.reduceLeft(plus)

  println(times(c, d))
}

Score : 500 points

Problem Statement

On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis.
Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i.
Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i.

For every rectangle that is formed by these lines, find its area, and print the total area modulo 10^9+7.

That is, for every quadruple (i,j,k,l) satisfying 1\leq i < j\leq n and 1\leq k < l\leq m, find the area of the rectangle formed by the lines x=x_i, x=x_j, y=y_k and y=y_l, and print the sum of these areas modulo 10^9+7.

Constraints

2 \leq n,m \leq 10^5

-10^9 \leq x_1 < ... < x_n \leq 10^9

-10^9 \leq y_1 < ... < y_m \leq 10^9

x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

n m
x_1 x_2 ... x_n
y_1 y_2 ... y_m

Output

Print the total area of the rectangles, modulo 10^9+7.

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

The total area of the nine rectangles A, B, ..., I shown in the following figure, is 60.

Sample Input 2

6 5
-790013317 -192321079 95834122 418379342 586260100 802780784
-253230108 193944314 363756450 712662868 735867677

Sample Output 2

835067060


import io.StdIn.{readInt, readLine}
object Main extends App {
  val n = readInt
  val as = readLine.split(" ").map(_.toLong)

  val sorted = as.sorted.reverse
  val result = (0 until n)
                .map(_*2)
                .map(_+1)
                .map(sorted(_))
                .sum

  println(result)
}

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.


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


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

Score : 100 points

Problem Statement

Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.

In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".

The current time is A o'clock, and a contest will begin in exactly B hours.
When will the contest begin? Answer in 24-hour time.

Constraints

0 \leq A,B \leq 23

A and B are integers.

Input

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

A B

Output

Print the hour of the starting time of the contest in 24-hour time.

Sample Input 1

9 12

Sample Output 1

21

In this input, the current time is 9 o'clock, and 12 hours later it will be 21 o'clock in 24-hour time.

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

The contest will begin at 1 o'clock the next day.


object Main extends App {
	var a = readLine
	var sum = a.split(" ")(0).toInt + a.split(" ")(1).toInt

	println(sum % 24)
}


object Main extends App{
    // Here your code !
    val sc = new java.util.Scanner(System.in)
    println((sc.nextInt+sc.nextInt)%24)
}


import io.StdIn.readLong
object Main extends App {
  def digitOf(n: Long) = math.log10(n).floor.toInt + 1

  val n = readLong
  println(digitOf((for (a <- 1 to math.sqrt(n).toInt; if n % a == 0; b = n / a) yield b).min))
}

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 {

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

    def combinationTable(n: Int): Array[Array[Long]] = {
      val C = Array.fill(n+1, n+1)(1L)
      (2 to n) foreach { i =>
        (1 until i) foreach { j =>
          C(i)(j) = C(i-1)(j-1) + C(i-1)(j)
        }
      }
      C
    }

    // 品物の中で, 大きい順にA個選べば良い？
    // 同じ平均になる選び方が何通りあるか?
    // 最後に取った数と同じものが何個あるか？で決まる？

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

    val C = combinationTable(N)
    val V = Array.fill(N)(sc.nextLong()).sorted(Ordering.Long.reverse)
    val ave = V.take(A).sum / A.toDouble

    println(ave)
    if (V.takeWhile(_ == V(0)).length >= A) {
      val length = V.takeWhile(_ == V(0)).length
      println((A to B).foldLeft(0L)((b, n) =>
        b + C(length)(n)
      ))
    } else {
      val b = V.take(A)
      val r = b.count(_ == V(A-1))
      val n = V.count(_ == V(A-1))
      println(C(n)(r))
    }
  }

}

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


object Main {

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

    def combinationTable(n: Int): Array[Array[Long]] = {
      val C = Array.fill(n+1, n+1)(1L)
      (2 to n) foreach { i =>
        (1 until i) foreach { j =>
          C(i)(j) = C(i-1)(j-1) + C(i-1)(j)
        }
      }
      C
    }

    // 品物の中で, 大きい順にA個選べば良い？
    // 同じ平均になる選び方が何通りあるか?
    // 最後に取った数と同じものが何個あるか？で決まる？

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

    val C = combinationTable(N)
    val V = Array.fill(N)(sc.nextLong()).sorted(Ordering.Long.reverse)
    val ave = V.take(A).sum / A.toDouble

    println(ave)
    if (V.takeWhile(_ == V(0)).length >= A) {
      val length = V.takeWhile(_ == V(0)).length
      println((A to length).foldLeft(0L)((b, n) =>
        b + C(length)(n)
      ))
    } else {
      val b = V.take(A)
      val r = b.count(_ == V(A-1))
      val n = V.dropWhile(_ != V(A-1)).takeWhile(_ == V(A-1)).length
      println(C(n)(r))
    }
  }

}


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

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

object Main {
  val MOD = 1000000007
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, A, B = sc.nextInt()
    val V = Array.fill[Long](N)(sc.nextLong())

    val dp = Array.ofDim[Long](N + 1, N + 1)
    val cnt = Array.ofDim[Long](N + 1, N + 1)
    (0 until N) foreach (i => cnt(i)(0) = 1)

    for {
      j <- 1 to N
      i <- 1 to N
    } {
      val v = dp(i - 1)(j - 1) + V(i - 1)
      val v0 = dp(i - 1)(j)
      if (v > v0) {
        dp(i)(j) = v
        cnt(i)(j) = cnt(i - 1)(j - 1)
      } else if (v == v0) {
        dp(i)(j) = v0
        cnt(i)(j) = cnt(i - 1)(j) + cnt(i - 1)(j - 1)
      } else {
        dp(i)(j) = v0
        cnt(i)(j) = cnt(i - 1)(j)
      }
    }

    val averages = dp(N).zipWithIndex.slice(A, B + 1) map {
      case (v, j) => (v.toDouble / j, cnt(N)(j))
    }
    val (m, count) = averages.groupBy(_._1) mapValues (_.map(_._2).sum) maxBy (_._1)

    println(f"$m%.6f")
    println(count)
  }

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

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

}


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

  var ans = 0
  var i = 0
  var count = 0
  var time = 0

  while (i < n) {
    val now = t(i)
    ans += 1

    while (i < n && count < c && t(i)-now <= k) {
      count += 1
      i += 1
    }

    count = 0
  }

  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


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

  println(800 * n - (n / 15) * 200)
}

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.


import java.io.{PrintWriter, _}
import java.util._

object Main {
  def main(args: Array[String]): Unit = {
    val inputStream = System.in
    val outputStream = System.out
    val in = new InputReader(inputStream)
    val out = new PrintWriter(outputStream)
    val solver = new Task
    solver.solve(1, in, out)
    out.close()
  }

  class Task {
    def solve(testNumber: Int, in: InputReader, out: PrintWriter): Unit = {
      val s = in.nextInt
      println(s * 600 - s / 15 * 200)
    }
  }

  class InputReader(val stream: InputStream) extends AutoCloseable {
    //reader = new BufferedReader(new FileReader(stream), 32768);
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer = new StringTokenizer("")

    def next: String = {
      while ( {
        tokenizer == null || !tokenizer.hasMoreTokens
      }) try
        tokenizer = new StringTokenizer(reader.readLine)
      catch {
        case e: IOException =>
          throw new RuntimeException(e)
      }
      tokenizer.nextToken
    }

    def nextLine: String = {
      try
        return reader.readLine
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      ""
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    override def close(): Unit = {
    }
  }

}


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

  val mod: Long = 1000000007L
  val result = (1 to n).foldLeft(1L)((z, v) => z * v % mod)
  println(result)
}

Score : 200 points

Problem Statement

Snuke loves working out. He is now exercising N times.

Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.

Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.

Constraints

1 ≤ N ≤ 10^{5}

Input

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

N

Output

Print the answer modulo 10^{9}+7.

Sample Input 1

3

Sample Output 1

6

After Snuke exercises for the first time, his power gets multiplied by 1 and becomes 1.

After Snuke exercises for the second time, his power gets multiplied by 2 and becomes 2.

After Snuke exercises for the third time, his power gets multiplied by 3 and becomes 6.

Sample Input 2

10

Sample Output 2

3628800

Sample Input 3

100000

Sample Output 3

457992974

Print the answer modulo 10^{9}+7.


import io.StdIn.readLong
object Main extends App {
  val n = readLong
  println(((1L to n) :\ 1L) {
    case (i, ans) => i * ans % 1000000007
  })
}


import java.util.Scanner

/**
 * Created by sonetsuyoshi on 2015/12/16.
 */

object Main extends App {
  val sc = new Scanner(System.in)
  val a = (sc.nextInt + 13) % 15
  val b = (sc.nextInt + 13) % 15

  val d = a - b

  val ans = if(d == 0) "Draw"
  else if(d > 0) "Alice"
  else "Bob"

  println(ans)
}

Score : 100 points

Problem Statement

Alice and Bob are playing One Card Poker.

One Card Poker is a two-player game using playing cards.

Each card in this game shows an integer between 1 and 13, inclusive.

The strength of a card is determined by the number written on it, as follows:

Weak 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < 11 < 12 < 13 < 1 Strong

One Card Poker is played as follows:

Each player picks one card from the deck. The chosen card becomes the player's hand.

The players reveal their hands to each other. The player with the stronger card wins the game.

If their cards are equally strong, the game is drawn.

You are watching Alice and Bob playing the game, and can see their hands.

The number written on Alice's card is A, and the number written on Bob's card is B.

Write a program to determine the outcome of the game.

Constraints

1≦A≦13

1≦B≦13

A and B are integers.

Input

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

A B

Output

Print Alice if Alice will win. Print Bob if Bob will win. Print Draw if the game will be drawn.

Sample Input 1

8 6

Sample Output 1

Alice

8 is written on Alice's card, and 6 is written on Bob's card.
Alice has the stronger card, and thus the output should be Alice.

Sample Input 2

1 1

Sample Output 2

Draw

Since their cards have the same number, the game will be drawn.

Sample Input 3

13 1

Sample Output 3

Bob


object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val nums = inputs.head.split(" ").map(_.toInt)
  val n = nums(0)
  val m = nums(1)
  val images = inputs.tail

  println(solve(n, m, images))

  private def solve(n: Int, m: Int, images: Seq[String]): String = {
    val loopEnd = n - m
    val imagesTup = images.splitAt(n)
    val nImage  = imagesTup._1
    val mImage  = imagesTup._2
    val checkStart = mImage(0)(0)

    (0 to loopEnd).foreach { i =>
      val line = nImage(i)

      (0 to loopEnd).foreach { j =>
        if(line(j) == checkStart) {
          var ok = true
          (0 until m).foreach { k =>
            val checkLine = images(i + k).splitAt(j)._2.splitAt(m)._1
            if( checkLine != mImage(k)) {
              ok = false
            }
          }

          if(ok) {
            return "Yes"
          }
        }
      }

    }
    return "No"
  }
}

Score : 200 points

Problem Statement

You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels.

A pixel is the smallest element of an image, and in this problem it is a square of size 1×1.

Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: . corresponds to a white pixel, and # corresponds to a black pixel.

The image A is given as N strings A_1,...,A_N.

The j-th character in the string A_i corresponds to the pixel at the i-th row and j-th column of the image A (1≦i,j≦N).

Similarly, the template image B is given as M strings B_1,...,B_M.

The j-th character in the string B_i corresponds to the pixel at the i-th row and j-th column of the template image B (1≦i,j≦M).

Determine whether the template image B is contained in the image A when only parallel shifts can be applied to the images.

Constraints

1≦M≦N≦50

A_i is a string of length N consisting of # and ..

B_i is a string of length M consisting of # and ..

Input

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

N M
A_1
A_2
:
A_N
B_1
B_2
:
B_M

Output

Print Yes if the template image B is contained in the image A. Print No otherwise.

Sample Input 1

3 2
#.#
.#.
#.#
#.
.#

Sample Output 1

Yes

The template image B is identical to the upper-left 2 × 2 subimage and the lower-right 2 × 2 subimage of A. Thus, the output should be Yes.

Sample Input 2

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

Sample Output 2

No

The template image B, composed of a black pixel, is not contained in the image A composed of white pixels.


object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val nums = inputs.head.split(" ").map(_.toInt)
  val n = nums(0)
  val m = nums(1)
  val images = inputs.tail

  println(solve(n, m, images))

  private def solve(n: Int, m: Int, images: Seq[String]): String = {
    val loopEnd = n - m
    val imagesTup = images.splitAt(n)
    val nImage  = imagesTup._1
    val mImage  = imagesTup._2

    (0 until loopEnd).foreach { i =>
      val line = nImage(i)

      (0 until loopEnd).foreach { j =>
        if(line(j) == mImage(0)(0)) {
          var ok = true
          (0 until m).foreach { k =>
            if(images(i + k).splitAt(j)._2.splitAt(m)._1 != mImage(k)) {
              ok = false
            }
          }

          if(ok) {
            return "Yes"
          }
        }
      }

    }
    return "No"
  }
}


import scala.util.control.Breaks._

object Main extends App {
  val Array(n, m) = scala.io.StdIn.readLine().split(' ').map(_.toInt)
  val as = Array.fill(n)(scala.io.StdIn.readLine().split(""))
  val bs = Array.fill(m)(scala.io.StdIn.readLine).mkString

  breakable {
    for (w <- 0 until (n * n - m * m)) {
      val tmp = (for (h <- 0 until m) yield {
        as(h).slice(w, w + m).mkString
      }).mkString

      if (tmp == bs) {
        println("Yes")
        break()
      }
    }

    println("No")
  }
}


import scala.io.StdIn.readLine

object Main extends App {
  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val a = Picture(List.fill(n)(readLine.toList))
  val b = Picture(List.fill(m)(readLine.toList))
  println(if (a contains b) "Yes" else "No")

  case class Picture(dots: List[List[Char]]) {
    def contains(pic: Picture): Boolean = {
      dots.sliding(m) exists {
        slides => (slides zip pic.dots) forall {
          case (slide, picsRow) => slide.sliding(m) exists (_ == picsRow)
        }
      }
    }
  }
}


import scala.io.StdIn.{readInt, readLine}
object Main extends App {
  val n = readInt
  val as = readLine.split(' ').map(_.toInt).toSet
  println(as.size - 1 | 1)
}

Score : 400 points

Problem Statement

Snuke has decided to play a game using cards.
He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written.

He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of remaining cards. Here, N is odd, which guarantees that at least one card can be kept.

Operation: Take out three arbitrary cards from the deck. Among those three cards, eat two: one with the largest value, and another with the smallest value. Then, return the remaining one card to the deck.

Constraints

3 ≦ N ≦ 10^{5}

N is odd.

1 ≦ A_i ≦ 10^{5}

A_i is an integer.

Input

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

N
A_1 A_2 A_3 ... A_{N}

Output

Print the answer.

Sample Input 1

5
1 2 1 3 7

Sample Output 1

3

One optimal solution is to perform the operation once, taking out two cards with 1 and one card with 2. One card with 1 and another with 2 will be eaten, and the remaining card with 1 will be returned to deck. Then, the values written on the remaining cards in the deck will be pairwise distinct: 1, 3 and 7.

Sample Input 2

15
1 3 5 2 1 3 2 8 8 6 2 6 11 1 1

Sample Output 2

7


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val x = sc.nextLong - 1
  val ans = if (x == 0) 0 else {
    val (d, m) = (x / 11L, x % 11L)
    d * 2L + (if (m > 6) 2 else 1)
  }
  println(ans)
}

Score : 300 points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.

For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

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

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


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

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    var i = from
    while(i <= to) { f(i); i += 1 }
  }
  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 + 1)
    val imos = Array.ofDim[Int](m + 2)
    val rt = math.sqrt(m).toInt
    debug(s"rt:$rt")
    REP(n) { i =>
      var d = 1
      while (d <= rt) {
        if (l(i) <= r(i) / d * d) {
          ans(d) += 1
        }
        d += 1
      }

      var l0 = m + 1
      var x = 1
      while (x <= rt + 1) {
        val l1 = (l(i) + x - 1) / x
        val r1 = r(i) / x
        val l2 = max(rt + 1, l1) // rtまでは√Mで計算ずみ
        val r2 = min(r1, l0 - 1) // l0まではx-1で計算ずみ
//        debug(s"i:$i x:$x l1:$l1 l2:$l2 r1:$r1")
        if (l2 <= r2) {
          imos(l2) += 1
          imos(r2 + 1) -= 1
        }
        l0 = l1
        x += 1
      }
    }

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

    debug(ans)

    REP(m, 1) { d =>
      out.println(ans(d) + imos(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


import scala.io.{ StdIn => in}

object Main extends App {
  val ans = in.readLine.split(" ").map(_.toInt)
    .grouped(2)
    .map(e => e(0) * e(1))
    .max
  println(ans)
}

Score : 100 points

Problem Statement

There are two rectangles.
The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B.
The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D.

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Constraints

All input values are integers.

1≤A≤10^4

1≤B≤10^4

1≤C≤10^4

1≤D≤10^4

Input

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

A B C D

Output

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Sample Input 1

3 5 2 7

Sample Output 1

15

The first rectangle has an area of 3×5=15, and the second rectangle has an area of 2×7=14.
Thus, the output should be 15, the larger area.

Sample Input 2

100 600 200 300

Sample Output 2

60000


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val _, s = sc.next()
  val f = (c: Char) => if (c == 'I') 1 else -1
  println(s.scanLeft(0)(_ + f(_)).max)
}

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

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

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.


import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {
  val MOD = 1000000007
  def solve(N: Int): Long = {
    val f = {
      val f: ArrayBuffer[Int] = ArrayBuffer.empty
      for {
        i <- 1 to N
      } f ++= factorize(i)
      f.sorted
    }

    var res: Long = 1
    var i = 0
    while(i < f.length) {
      var j = i
      while (j < f.length && f(i) == f(j)) j += 1
      val len = j - i
      res = res * (len + 1) % MOD
      i = j
    }

    res
  }

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

  def factorize(n: Int): Array[Int] = {
    // 見つからなかったら-1
    def minFactor(n0: Int, i: Int): Int = {
      if (i > n0) -1
      else if (n0 % i == 0) i
      else minFactor(n0, i + 1)
    }

    def step(n0: Int, acc: List[Int]): List[Int] = {
      minFactor(n0, 2) match {
        case -1 => acc
        case f => step(n0 / f, f :: acc)
      }
    }

    step(n, Nil).toArray
  }
}

Score : 300 points

Problem Statement

You are given an integer N.
Find the number of the positive divisors of N!, modulo 10^9+7.

Constraints

1≤N≤10^3

Input

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

N

Output

Print the number of the positive divisors of N!, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

4

There are four divisors of 3! =6: 1, 2, 3 and 6. Thus, the output should be 4.

Sample Input 2

6

Sample Output 2

30

Sample Input 3

1000

Sample Output 3

972926972


import scala.io.StdIn._

/**
 * Created by sonetsuyoshi on 2015/12/16.
 */

object Main extends App {
  val MOD = 1000000007

  val N = readInt

  def primesUnder(n: Int): List[Int] = {
    def rec(i: Int, primes: List[Int]): List[Int] = {
      if (i > n) primes
      else if (prime(i, primes)) rec(i + 1, i :: primes)
      else rec(i + 1, primes)
    }

    rec(2, List()).reverse
  }

  def prime(num: Int, factors: List[Int]): Boolean = factors.forall(num % _ != 0)

  val primes = primesUnder(N)

  val expos = primes.map(x => {
    1.to(N).foldLeft(0.toLong)((s, n) => {
      var m = n
      var count = 0
      while(m % x == 0) {
        m /= x
        count += 1
      }
      (s + count).toLong
    })
  })
  println(expos.foldLeft(1.toLong)((s, n) => s * (n + 1) % MOD))
}


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 s = sc.next
//  val list = List.fill(3)(sc.next)

  val ans = s.replace(',', ' ')

  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

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


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 a, op, b = sc.next
//  val list = List.fill(3)(sc.next)

  val ans = if (op == "+") a.toInt + b.toInt else a.toInt - b.toInt

  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

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

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

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val a, op, b = sc.next()
    val ans = op match {
      case "+" => a.toInt + b.toInt
      case "-" => a.toInt - b.toInt
    }
    println(ans)
  }
}


object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val a = sc.nextLong()
    val op = sc.next()
    val b = sc.nextLong()
    val out = op match {
      case "+" => a + b
      case "-" => a - b
    }
    println(out)
  }
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    inner(n, width - 1)
  }

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

    inner(n % m, p, 1)
  }

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

    val MOD = 1000000007

    def lazyloop(k: Int): LazyList[Int] = k #:: k #:: lazyloop(k + 2)

    out.println(
      if (
        as.zip(n % 2 match {
          case 0 => lazyloop(1)
          case 1 => 0 #:: lazyloop(2)
        }).forall {
          case (a, b) => a == b
        }) {
        modpow(2, n / 2, MOD)
      } else {
        0
      }
    )

    out.flush()
  }
}

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


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]): Int = {
      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).toInt + 7
      def ans(n: Int, acm: Int): Int =
        if (n < N / 2) ans(n + 1, acm << 1 % INF)
        else acm

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

      find(0)
    }

    println(solve(N, A))
  }

}


import java.util.Scanner

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

  val vs = Set("a", "i", "u", "e", "o")

  println(if (vs.contains(c)) "vowel" else "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 scala.annotation.tailrec
import scala.math._

object Main extends App {

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

  val input: Array[Array[Int]] = Array.ofDim(6, 6000000)
  ///////////////////////////////////////////

  val sc = new java.util.Scanner(System.in)
//  val a, b, k = sc.nextInt
  val h, w = sc.nextInt
  println(h, w)
//  val d = List.fill(7)(sc.nextInt)
//  val j = List.fill(7)(sc.nextInt)
  val list = List.fill(h)(sc.next)

  list.foreach(l => {
      l.foreach(print(_))
      println("")
      l.foreach(print(_))
      println("")
    }
  )

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

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

  // https://stackoverflow.com/questions/10199171/matcherror-when-match-receives-an-indexedseq-but-not-a-linearseq/10199441#10199441
  object +: {
    def unapply[T](s: Seq[T]) =
      s.headOption.map(head => (head, s.tail))
  }

  @tailrec
  def foldLeftWithNext[A, B](seq: Seq[A])(z: B)(op: (B, A, A) => B)(tailOp: (B, A) => B): B = {
    seq match {
      case Nil => z
      case a +: Nil => tailOp(z, a)
      case a +: next +: tail => foldLeftWithNext(next +: tail)(op(z, a, next))(op)(tailOp)
    }
  }
}


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

  val line = io.StdIn.readLine
  val c = line.split(' ')(1)(0)
  println(c)
}

Score : 100 points

Problem Statement

Snuke is going to open a contest named "AtCoder s Contest".
Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "AxC".
Here, x is the uppercase English letter at the beginning of s.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of s is between 1 and 100, inclusive.

The first character in s is an uppercase English letter.

The second and subsequent characters in s are lowercase English letters.

Input

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

AtCoder s Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val a, b, x = sc.nextLong()
  if (a == 0) {
    println(b/x + 1)
  } else {
    println(b/x - (a-1)/x)
  }
}

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.


object Main extends App{
    // Here your code !
    val scanner = new java.util.Scanner(System.in)
    val a,b,x   = scanner.nextInt
    println(((b-a)/x).toInt + 1)
}