import java.util.Scanner

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

		val result = a.zipWithIndex.count( t => a(t._1 - 1) == (t._2 + 1)) / 2

		println(result)
	}
}

Score : 200 points

Problem Statement

There are N rabbits, numbered 1 through N.

The i-th (1≤i≤N) rabbit likes rabbit a_i.
Note that no rabbit can like itself, that is, a_i≠i.

For a pair of rabbits i and j (i＜j), we call the pair (i，j) a friendly pair if the following condition is met.

Rabbit i likes rabbit j and rabbit j likes rabbit i.

Calculate the number of the friendly pairs.

Constraints

2≤N≤10^5

1≤a_i≤N

a_i≠i

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 friendly pairs.

Sample Input 1

4
2 1 4 3

Sample Output 1

2

There are two friendly pairs: (1，2) and (3，4).

Sample Input 2

3
2 3 1

Sample Output 2

0

There are no friendly pairs.

Sample Input 3

5
5 5 5 5 1

Sample Output 3

1

There is one friendly pair: (1，5).


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

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

object Main {
  val DEBUG = false

  lazy val debugOut: PrintWriter = {
    new PrintWriter(new BufferedOutputStream(new FileOutputStream("log.txt", true)))
  }

  def log(message: => String): Unit = {
    if (DEBUG) {
      Console.err.println(message)
    }
  }

  def debug(closure: => Unit): Unit = {
    if (DEBUG) {
      closure
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    inner(n, width - 1)
  }

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

    inner(n % m, p, 1)
  }

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

    log("=== start")

    val alphaNum = 'z' - 'a' + 1

    val s = get[String]
    var k = get[Int]

    def step1(s: String): Array[Char] = {
      val cs = s.toCharArray

      for (index <- cs.indices) {
        val remain = ('a' + alphaNum - cs(index)) % alphaNum
        if (remain <= k) {
          cs(index) = 'a'
          k -= remain
        }
      }

      cs
    }

    def step2(cs: Array[Char]): Array[Char] = {
      cs(cs.length - 1) = ((cs.last - 'a' + k % alphaNum) % alphaNum + 'a').toChar
      cs
    }

    out.println(step2(step1(s)))

    out.flush()
    log("=== end")
    debug {
      debugOut.flush()
    }
  }
}

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

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

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

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap

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 main(args: Array[String]): Unit = {
    val str = io.StdIn.readLine()
    var k = io.StdIn.readLine().toLong

    val newStr = for (i <- 0 to (str.length - 2)) yield {
      val d = 'z' + 1 - str(i)
      if (d <= k) { k = k - d; 'a' }
      else str(i)
    }

    val lastChar = {
      val c = str.last + (k % 26)
      if (c > 'z') c - 25
      else         c
    }

    val ans = newStr.mkString + lastChar.toChar
    println(ans)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val str = io.StdIn.readLine()
    var k = io.StdIn.readLine().toLong

    val newStr = for (i <- 0 to (str.length - 2)) yield {
      val d = 'z' + 1 - str(i)
      if (d <= k) { k = k - d; 'a' }
      else str(i)
    }

    val lastChar = {
      val c = str.last + k % 26
      if (c > 'z') c - 26
      else         c
    }

    val ans = newStr.mkString + lastChar.toChar
    println(ans)
  }
}


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

  def solve(a: String, b: String, c: String, turn: Char): String = {
    turn match {
      case 'a' =>
        if (a.isEmpty) {
          "A"
        } else {
          solve(a.tail, b, c, a.head)
        }
      case 'b' =>
        if (b.isEmpty) {
          "B"
        } else {
          solve(a, b.tail, c, b.head)
        }
      case 'c' =>
        if (c.isEmpty) {
          "C"
        } else {
          solve(a, b, c.tail, c.head)
        }
    }
  }

  println(solve(a, b, c, 'a'))
}

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

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

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


import scala.io.StdIn

object Main extends App {
  val s =  StdIn.readLine()

  def solve(s: String): Long = {
    var ret :Long = s.toLong

    (1 to s.length - 1).foreach {i =>

      (1 to s.length - 1).combinations(i).foreach {j =>

        if (j.isEmpty)
          ret += s.toInt

        (0 to j.length).foreach { k =>
          if (k == 0) {
            ret = ret + s.substring(0, j(k)).toInt
          } else if (k == j.length) {
            ret = ret + s.substring(j(k - 1)).toInt
          } else {
            ret = ret +  s.substring(j(k - 1), j(k)).toInt
          }
        }
      }
    }
    ret
  }

  println(solve(s))
}

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

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

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


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

    if(n <= k) {
      println(n * x);
    }
    else {
      println(k * x + (n - k) * y);
    }
  }
}

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

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

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


import java.util.Scanner

object Main extends App  {
  val sc = new Scanner(System.in)
  val w = sc.next.split("(?<=.)")

  val ac = new Array[Int](26)
  val alphabets = "abcdefghijklmnopqrstuvwxyz"

  val tArr =
    w.foldLeft(ac){case (arr, c) =>
      val i = alphabets.indexOf(c)
      val x = arr(i)
      arr.update(i, x + 1)
      arr
    }

  val res = if(tArr.forall(_ % 2 == 0)) "Yes" else "No"

  println(res)
}

Score : 200 points

Problem Statement

Let w be a string consisting of lowercase letters.
We will call w beautiful if the following condition is satisfied:

Each lowercase letter of the English alphabet occurs even number of times in w.

You are given the string w. Determine if w is beautiful.

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

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

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times.

Sample Input 2

hthth

Sample Output 2

No


import scala.io.Source

object Main extends App {
    val xs = Source.stdin.getLines()
    val Array(n, a) = xs.next().split(' ').map(_.toInt)
    val ds = xs.next().split(' ').map(_.toInt)

    println(solve(n, a, ds))

    def solve(n: Int, a: Int, ds: Seq[Int]): String = {
        var c = 0

        powerset(ds).foreach { dss =>
            val avg = if (dss.length > 0) {
                if (dss.sum % dss.length == 0) {
                    dss.sum / dss.length
                } else {
                    -1
                }
            } else {
                -1
            }
            c = c + (if (avg == a) 1 else 0)
        }

        c.toString
    }

    def powerset[T](xss: Seq[T]): Seq[Seq[T]] = {
        xss match {
            case Nil =>
                Seq(Seq.empty[T])
            case x +: xs =>
                val qs = powerset(xs)
                val rs = for (ps <- qs) yield x +: ps
                rs ++: qs
        }
    }
}

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

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

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.


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

    val nx = (a :: x).max * n

    val dp = collection.mutable.ArrayBuffer.fill(n + 1, n + 1, nx + 1)(-1L)
    def dpFunc(j: Int, k: Int, s: Int): Long = {
    	if (dp(j)(k)(s) >= 0) return dp(j)(k)(s)

    	val ret = if (j == 0 && k == 0 && s == 0) 1L
    		else if (j > 0 && s < x(j - 1)) dpFunc(j - 1, k, s)
    		else if (j > 0 && k > 0 && s >= x(j - 1)) dpFunc(j - 1, k, s) + dpFunc(j - 1, k - 1, s - x(j - 1))
    		else 0L
    	dp(j)(k)(s) = ret
    	ret
    }

    val ans = (1 to n).map(k => dpFunc(n, k, k * a)).sum

    println(ans)

  }
}


import java.util.Scanner

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

  val a = sc.nextInt
  val xs = Vector.fill(n)(sc.nextDouble)

  val ints = for (i <- 1 to n) yield (0 until n).combinations(i)

  val dA = a.toDouble
  var ans = 0L
  for {
    p <- ints.flatten
  } yield {
    val ave = p.map(xs(_)).sum / p.length
    if (ave == dA) {
      ans = ans + 1L
    }
  }

  println(ans)
}


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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, S = sc.nextLong()

    def test(b: Long, n: Long, s: Long): Boolean = {
      if (n == 0) {
        s == 0
      } else {
        val c = n % b
        test(b, n / b, s - c)
      }
    }

    def toRt: Option[Int] = {
      (2 to math.sqrt(N).toInt) find { b =>
        test(b, N, S)
      }
    }

    def afterRt: Option[Long] = {
      val rt = math.sqrt(N).toLong
      (rt to 1) find { c =>
        if ((N - S) % c != 0) false
        else {
          val b = (N - S) / c + 1
          val c0 = S - c
          0 < c0 && c0 * c0 < N && rt < b
        }
      }
    }

    val ans = if (S == 1) N else toRt orElse afterRt getOrElse -1
    out.println(ans)
  }

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

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def rep(n: Int)(f: Int => Unit): Unit = {
    var i = 0
    while(i < n) { f(i); i += 1 }
  }
  def rep_r(n: Int)(f: Int => Unit): Unit = {
    var i = n - 1
    while(i >= 0) { f(i); i -= 1 }
  }

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

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

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

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

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

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

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

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

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

Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

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

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1


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

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

object Main {
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val S = sc.next

    def two = (S zip S.drop(1)).zipWithIndex find { case ((c1, c2), _) => c1 == c2 }
    def three = (S zip S.drop(1) zip S.drop(2)).zipWithIndex find { case (((c1, c2), c3), _) => c1 == c2 || c1 == c3 || c2 == c3}

    val ans = (two map { case (_, i) =>
      s"${i + 1} ${i + 2}"
    }) orElse (three map { case (_, i) =>
      s"${i + 1} ${i + 3}"
    }) getOrElse "-1 -1"

    println(ans)
  }

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

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

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

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

}

Score : 400 points

Problem Statement

Given a string t, we will call it unbalanced if and only if the length of t is at least 2, and more than half of the letters in t are the same. For example, both voodoo and melee are unbalanced, while neither noon nor a is.

You are given a string s consisting of lowercase letters. Determine if there exists a (contiguous) substring of s that is unbalanced. If the answer is positive, show a position where such a substring occurs in s.

Constraints

2 ≦ |s| ≦ 10^5

s consists of lowercase letters.

Partial Score

200 points will be awarded for passing the test set satisfying 2 ≦ N ≦ 100.

Input

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

s

Output

If there exists no unbalanced substring of s, print -1 -1.

If there exists an unbalanced substring of s, let one such substring be s_a s_{a+1} ... s_{b} (1 ≦ a < b ≦ |s|), and print a b. If there exists more than one such substring, any of them will be accepted.

Sample Input 1

needed

Sample Output 1

2 5

The string s_2 s_3 s_4 s_5 = eede is unbalanced. There are also other unbalanced substrings. For example, the output 2 6 will also be accepted.

Sample Input 2

atcoder

Sample Output 2

-1 -1

The string atcoder contains no unbalanced substring.


object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val s = sc.next
    val unb = findUnbalance(s)
    println(unb(0) + " " + unb(1))
  }
  def findUnbalance(s: String) =  {
    if (s.length < 2) {
      Array(-1, -1)
    } else if (s.length == 2) {
      if (s(0) == s(1)) Array(0, 1) else Array(-1, -1)
    } else {

    val N = s.length
    var unb = Array(-1, -1)
    for (i <- 0 until N-2) {
      val s1 = s(i)
      val s2 = s(i+1)
      val s3 = s(i+2)
      if (s1 == s2) unb = Array(i+1, i+2)
      if (s2 == s3) unb = Array(i+2, i+3)
      if (s1 == s3) unb = Array(i+1, i+3)
    }
    val u = unb
    u
    }
  }

}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  println(1.to(N).sum)
}

Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

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

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val s = sc.next
  val cs: Seq[Char] = s.toCharArray.toList

  def solve(cs: Seq[Char], acc: String): String = cs match {
    case x +: xs =>
      x match {
        case 'B' => if (acc.isEmpty) solve(xs, "") else solve(xs, acc.substring(0, acc.length - 1))
        case z => solve(xs, acc + z)
      }
    case _ => acc
  }

  val ans = solve(cs, "")

  println(ans)
}

Score : 200 points

Problem Statement

Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.

To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:

The 0 key: a letter 0 will be inserted to the right of the string.

The 1 key: a letter 1 will be inserted to the right of the string.

The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.

Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?

Constraints

1 ≦ |s| ≦ 10 (|s| denotes the length of s)

s consists of the letters 0, 1 and B.

The correct answer is not an empty string.

Input

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

s

Output

Print the string displayed in the editor in the end.

Sample Input 1

01B0

Sample Output 1

00

Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.

Sample Input 2

0BB1

Sample Output 2

1

Each time the key is pressed, the string in the editor will change as follows: 0, (empty), (empty), 1.


import java.util.Scanner

import scala.annotation.tailrec

object Util {
  @tailrec
  def loop(start: Int, end: Int)(f: Int => Unit) {
    if (start < end) {
      f(start)
      loop(start + 1, end)(f)
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    //nextLineとnextを同時に使ったら死ぬ
    val sc = new Scanner(System.in)
    val a, b = sc.nextLong()
    if (a * b <= 0) {
      println("Zero")
    } else if (a + b > 0) {
      println("Positive")
    } else {
      if ((b - a) % 2 == 0) {
        println("Negative")
      } else {
        println("Positive")
      }
    }

  }
}

Problem Statement

You are given two integers a and b (a≤b). Determine if the product of the integers a, a+1, …, b is positive, negative or zero.

Constraints

a and b are integers.

-10^9≤a≤b≤10^9

Partial Score

In test cases worth 100 points, -10≤a≤b≤10.

Input

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

a b

Output

If the product is positive, print Positive. If it is negative, print Negative. If it is zero, print Zero.

Sample Input 1

1 3

Sample Output 1

Positive

1×2×3=6 is positive.

Sample Input 2

-3 -1

Sample Output 2

Negative

(-3)×(-2)×(-1)=-6 is negative.

Sample Input 3

-1 1

Sample Output 3

Zero

(-1)×0×1=0.


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

	if(a > 0L){
		println("Positive")
	}else if(a<=0L && b>=0L){
		println("Zero")
	}else{

		if(b-a+1L % 2L == 0L){
			println("Positive")
		}else{
			println("Negative")
		}
	}

}


object Main extends App {

  import scala.io.StdIn.readLine
  val Array(n, m) = readLine().trim.split(" ").map(_.toInt)
  val arr = Array.fill(n)((1, 0))
  arr(0) = (0, 1)
  (0 until m).foreach { i =>
    val Array(a, b) = readLine().trim.split(" ").map(_.toInt)
    val x = a - 1
    val y = b - 1
    if (0  < arr(x)._2) {
      arr(y) = (0, arr(y)._1 + arr(y)._2 + 1)
      arr(x) = (arr(x)._1, arr(x)._2 - 1)
    } else {
      if (0 < arr(y)._2) {
        arr(y) = (0, arr(y)._1 + arr(y)._2 + 1)
        arr(x) = (arr(x)._1 - 1, arr(x)._2)
      } else {
        arr(y) = (arr(y)._1 + 1, arr(y)._2)
        arr(x) = (arr(x)._1 - 1, arr(x)._2)
      }
    }
  }

  println(arr.count(t => t._2 > 0))

}

Problem Statement

We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

2≤N≤10^5

1≤M≤10^5

1≤x_i,y_i≤N

x_i≠y_i

Just before the i-th operation is performed, box x_i contains at least 1 ball.

Input

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

N M
x_1 y_1
:
x_M y_M

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box 1 is empty, box 2 contains one red ball and one white ball, and box 3 contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box 2, the red ball will go into box 3. If he picks the white ball instead, the red ball will stay in box 2.
Thus, the number of boxes that may contain the red ball after all operations, is 2.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box 3.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


object Main extends App {
   val n = readLine.split(' ').map(_.toInt).sorted.toList
   n match {
     case List(5,5,7) => println("YES")
     case _ => println("NO")
   }
}

Score : 100 points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

1≦A,B,C≦10

Input

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

A B C

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  var fee, cols = sc.nextInt
  val xss = List.fill(cols)(sc.nextInt)
  var ten: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  var cash = 0
  var count = 0
  var n = 1000
  var flag = false

  for (i <- 0 to 9) {
    if (xss.contains(i)) {
      ten = ten.filter {
        _ != i
      }
    }
  }

  if(ten.contains(fee / 1000)){
    for(i <- 0 to 9){
      if(flag == false) {
        if (ten.contains((fee % 1000) / 100 + i)) {
          for (j <- 0 to 9) {
            if (ten.contains((fee % 100) / 10 + j)) {
              for (k <- 0 to 9) {
                if (ten.contains((fee % 10) + k)) {
                  flag = true
                  cash = (fee / 1000) * 1000 + (fee % 1000 / 100 + i) * 100 + (fee % 100 / 10 + j) * 10 + (fee % 10 + k)
                }
              }
            }
          }
        }
      }
    }
  }else {
    cash = (fee / 1000 + 1) * 1000 + ten.head * 111
  }

  print(cash)

}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    if (sc.nextLine.split(" ").map(_.toInt).sorted sameElements Array(5, 5, 7)) println("YES")
    else println("NO")
  }
}


import scala.io.StdIn._

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

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

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

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

    def ** (exp: Int): Int = scala.math.pow(i, exp).intValue
  }

  implicit class LongImplicits(val i: Long) {
    def isEven = i % 2 == 0
    def isOdd = !isEven

    def ** (exp: Long): Long = scala.math.pow(i, exp).longValue
  }

  def mycomb[T](n: Int, l: List[T]): List[List[T]] =
    n match {
      case 0 => List(List())
      case _ => for(el <- l;
                sl <- mycomb(n-1, l dropWhile { _ != el } ))
                yield el :: sl
  }

  def comb[T](n: Int, l: List[T]): List[List[T]] = mycomb(n, l.distinct)
}

object Main extends App {
  import Helpers._

  val Array(n, k) = readIntLine
  val ds = readLine.split(" ")

  val u = n to 100000000
  val x = u.dropWhile(_.toString.split("").exists(ds.contains))

  println(x.head)
}

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

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

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  var fee, cols = sc.nextInt
  val xss = List.fill(cols)(sc.nextInt)
  var ten: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  var cash = 0
  var count = 0
  var n = 1000
  var flag = false

  for (i <- 0 to 9) {
    if (xss.contains(i)) {
      ten = ten.filter {
        _ != i
      }
    }
  }

  for(i <- fee to 10000){
    if(!flag) {
      if ((ten.contains(i / 1000) || fee / 1000 == 0) &&
        (ten.contains(i % 1000 / 100) || (fee / 1000 == 0 && fee % 1000 / 100 == 0)) &&
        (ten.contains(i % 100 / 10) || (fee / 1000 == 0 && fee % 1000 / 100 == 0 && fee % 100 / 10 == 0)) &&
        (ten.contains(i % 10))) {
        flag = true
        cash = i
      }
    }
  }

  if(!flag) cash = ten.head * 11111

  print(cash)

}


import java.util.Scanner

object Main {
    def main(args: Array[String]): Unit = {
        val scanner = new Scanner(System.in)
        val n: Int = scanner.nextInt
        val k: Int = scanner.nextInt
        val hates: List[Int] = List.fill(k)(scanner.nextInt)

        println(calc(n, hates))
    }

    def calc( n: Int, hates: List[Int]): Int ={
      (n to (10*n)).find(p => p >= n && !isIncludingHateNum(p, hates)).get
    }

    def isIncludingHateNum(payment: Int, hates: List[Int]): Boolean ={
      val pays:List[Int] = (payment.toString.grouped(1)).toList.map(_.toInt)
      pays.exists(hates.contains(_))
    }
}


import java.util.Scanner

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

  val n, x = sc.nextLong

  println(n * 2 + x)
}

Score : 500 points

Problem Statement

Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light.

Three mirrors of length N are set so that they form an equilateral triangle.
Let the vertices of the triangle be a, b and c.

Inside the triangle, the rifle is placed at the point p on segment ab such that ap = X.
(The size of the rifle is negligible.)
Now, the rifle is about to fire a ray of Mysterious Light in the direction of bc.

The ray of Mysterious Light will travel in a straight line, and will be reflected by mirrors, in the same ways as "ordinary" light.
There is one major difference, though: it will be also reflected by its own trajectory as if it is a mirror!
When the ray comes back to the rifle, the ray will be absorbed.

The following image shows the ray's trajectory where N = 5 and X = 2.

It can be shown that the ray eventually comes back to the rifle and is absorbed, regardless of the values of N and X.
Find the total length of the ray's trajectory.

Constraints

2≦N≦10^{12}

1≦X≦N-1

N and X are integers.

Partial Points

300 points will be awarded for passing the test set satisfying N≦1000.

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

Input

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

N X

Output

Print the total length of the ray's trajectory.

Sample Input 1

5 2

Sample Output 1

12

Refer to the image in the Problem Statement section.
The total length of the trajectory is 2+3+2+2+1+1+1 = 12.