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 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, h) = get[Int, Int]
    val (as, bs) = {
      val as = Array.ofDim[Int](n)
      val bs = Array.ofDim[Int](n)
      n.times { i =>
        val (a, b) = get[Int, Int]
        as(i) = a
        bs(i) = b
      }
      (as, bs)
    }

    val maxA = as.max

    def useOnlyB(bs: Array[Int]): (Long, Int) = {
      @tailrec
      def inner(i: Int, sum: Long): (Long, Int) = {
        if (sum >= h || i == bs.length) {
          (sum, i)
        } else {
          inner(i + 1, sum + bs(i))
        }
      }
      inner(0, 0L)
    }

    val (sumOfB, countUseOnlyB) = useOnlyB(bs.filter(_ >= maxA).sorted(Ordering[Int].reverse))
    if (sumOfB >= h) {
      out.println(countUseOnlyB)
    } else {
      out.println((h - sumOfB + maxA - 1) / maxA + countUseOnlyB)
    }

    out.flush()
  }
}

Score : 400 points

Problem Statement

You are going out for a walk, when you suddenly encounter a monster. Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and can perform the following two kinds of attacks in any order:

Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.

Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.

The monster will vanish when the total damage it has received is H points or more. At least how many attacks do you need in order to vanish it in total?

Constraints

1 ≤ N ≤ 10^5

1 ≤ H ≤ 10^9

1 ≤ a_i ≤ b_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N H
a_1 b_1
:
a_N b_N

Output

Print the minimum total number of attacks required to vanish the monster.

Sample Input 1

1 10
3 5

Sample Output 1

3

You have one katana. Wielding it deals 3 points of damage, and throwing it deals 5 points of damage. By wielding it twice and then throwing it, you will deal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing the monster.

Sample Input 2

2 10
3 5
2 6

Sample Output 2

2

In addition to the katana above, you also have another katana. Wielding it deals 2 points of damage, and throwing it deals 6 points of damage. By throwing both katana, you will deal 5 + 6 = 11 points of damage in two attacks, vanishing the monster.

Sample Input 3

4 1000000000
1 1
1 10000000
1 30000000
1 99999999

Sample Output 3

860000004

Sample Input 4

5 500
35 44
28 83
46 62
31 79
40 43

Sample Output 4

9


import scala.io.{StdIn => in}

object Main extends App {
  val Array(n, h) = in.readLine.split(" ").map(_.toInt)
  val k = Iterator.continually(in.readLine)
    .take(n)
    .map(_.split(" ").map(_.toInt))
    .toArray
    .transpose

  val ans = {
    val a = k(0).max
    val b = k(1).filter(_ > a).sorted(Ordering[Int].reverse)

    def rec(hp:Int, cnt:Int):(Int,Int) = {
      if(hp <= 0 || cnt >= b.size) (hp,cnt)
      else rec(hp-b(cnt),cnt+1)
    }

    val (hp,cnt) = rec(h,0)
    if(hp <= 0) cnt else cnt + (hp + (a-1)) / a
  }

  println(ans)
}

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

Submitted source-code file size, in bytes.

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

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


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

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

  val N, H = in.next().toInt
  val _a = new Array[Int](N)
  val _b = new Array[Int](N)

  for(i <- 0 until N) {
    val a, b = in.next().toInt
    _a(i) = a
    _b(i) = b
  }

  val a = _a.sorted.reverse
  val b = _b.filter(_ > a(0)).sorted.reverse

  var ans = 0
  var hp = H
  breakable {

    for (e <- b) {
      hp -= e
      ans += 1
      if(hp <= 0)
        break
    }
  }

  if(hp <= 0)
    println(ans)
  else {
    ans += hp / a(0)
    if (hp % a(0) != 0) {
      ans += 1
    }
    println(ans)
  }

}

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


object Main extends App {
	val nh = scala.io.StdIn.readLine.split(" ").map(_.toLong)
	var a = new Array[Long](nh(0).toInt)
	var b = new Array[Long](nh(0).toInt)

	for(i<-0 until nh(0).toInt){
		val temp = scala.io.StdIn.readLine.split(" ").map(_.toLong)
		a(i) = temp(0)
		b(i) = temp(1)
	}

	b = b.sorted.reverse

	val max = a.max
	var ans = 0
	var temp = nh(1)

	for(i<-0 until nh(0).toInt){
		if(temp <=0){

		}else if(b(i) >= max){
			temp -= b(i)
			ans += 1
		}
	}

	if(temp <=0) println(ans)
	else println(ans + (temp + max - 1)/max)

}


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val n, a, b = sc.nextInt()
  var  ans = 0
  for (i <- 1 to n) {
    val sum = i.toString.toList.foldLeft(0)((x, y) => x + y.asDigit)
    if (a <= sum && sum <= b) {
      ans += i
    }
  }
  println(ans)
}

Score : 200 points

Problem Statement

Find the sum of the integers between 1 and N (inclusive), whose sum of digits written in base 10 is between A and B (inclusive).

Constraints

1 \leq N \leq 10^4

1 \leq A \leq B \leq 36

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the sum of the integers between 1 and N (inclusive), whose sum of digits written in base 10 is between A and B (inclusive).

Sample Input 1

20 2 5

Sample Output 1

84

Among the integers not greater than 20, the ones whose sums of digits are between 2 and 5, are: 2,3,4,5,11,12,13,14 and 20. We should print the sum of these, 84.

Sample Input 2

10 1 2

Sample Output 2

13

Sample Input 3

100 4 16

Sample Output 3

4554


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n, a, b = sc.nextInt()
  val ans = (1 to n).filter{ x =>
    val sum = x.toString.map(_.toString.toInt).sum
    a <= sum && sum <= b
  }.sum
  println(ans)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, A, B = sc.nextInt()
  val result = 1.to(N).map { i =>
    val sum = i.toString.split("").map(_.toInt).sum
    if (A <= sum && sum <= B) i else 0
  }.sum
  println(result)
}


import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val a = sc.nextInt()
  val b = sc.nextInt()

  private val res = (1 to n)
    .map(i => (i, i.toString.split("").filter(_.length!=0).map(_.toInt).sum))
    .filter { case (_, isum) => isum >= a && isum <= b }.map(_._1).sum

  println(res)

}


import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val a = sc.nextInt()
  val b = sc.nextInt()

  private val res = (1 to n)
    .map(i => (i, i.toString.split("").map(_.toInt).sum))
    .filter { case (_, isum) => isum >= a && isum <= b }.map(_._1).sum

  println(res)

}


object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in);
    val n = sc.nextInt();
    val min = sc.nextInt();
    val max = sc.nextInt();
    println((1 to n).filter(k => isBetween(k.toString.split("")
      .map(_.toInt).sum, min, max)).sum.toString);

    def isBetween(num: Int, min: Int, max: Int): Boolean = {
      min <= num && num <= max
    }
  }
}


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

  val elements = for {
    e <- (0 to n).toList
    str = e.toString.split("").filter(_.nonEmpty)
    sum = str.map(_.toInt).sum
    if a <= sum
    if sum <= b
  } yield e

  println(elements.sum)
}


object Main extends App {
  val arr = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val (n, a, b) = (arr(0), arr(1), arr(2))

  var ls = scala.collection.mutable.ArrayBuffer.empty[Int]
  for (e <- 0 to n) e match {
    case x if x < 10 && (a to b).contains(x) => ls += x
    case x if x >= 10 && (a to b).contains(x.toString.map(_.asDigit).sum) => ls += x
    case _ => None
  }

  val ans = ls.sum

  println(ans)
}


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

var cnt = 0
for (i<-1 to n){
  val hoge = i.toString.toList.map(_.toString.toInt).sum
//   println(i,hoge)
  if (hoge >= a && hoge <= b) cnt += i
}
println(cnt)
}


object Main extends App {
  def recursive_sum(i: Int): Int = {
    def accumlator(acc: Int, i: Int): Int = if (i == 0) {
      acc
    } else {
      accumlator(acc + (i % 10), i / 10)
    }

    accumlator(0, i)
  }

  val sc = new java.util.Scanner(System.in)
  val n, a, b = sc.nextInt()
  val xs = for {
    i <- Iterator.range(1, n + 1)
    t = (i, recursive_sum(i))
    if a <= t._2 && t._2 <= b
  } yield {
    t._1
  }
  val ret = xs.sum
  println(ret)
}


object Main extends App {

  def rec(m:Int, t:Int):Int = {
    if(m > 0) rec(m/10, t + (m%10))
    else t
  }

  val Array(n, a, b) = io.StdIn.readLine.split(" ").map(_.toInt)

  val ans = (1 to n).foldLeft(0)( (acc,i) => {
    val sum = rec(i, 0)
    if(a <= sum && sum <= b ) acc + i else acc
  })

  println(ans)
}


object Main extends App {

  val Array(n, a, b) = io.StdIn.readLine.split(" ").map(_.toInt)

  val ans = (1 to n).foldLeft(0)( (acc,i) => {
    val sum = (1 to 5).foldLeft((i,0))( (acc,_) => {
      (acc._1 / 10, acc._2 + (acc._1 % 10))
    })._2
    if(a <= sum && sum <= b ) acc + i else acc
  })

  println(ans)
}


object Main extends App {

  val Array(n, a, b) = io.StdIn.readLine.split(" ").map(_.toInt)

  val ans = (1 to n).par.foldLeft(0)( (acc,i) => {
    val sum = (1 to 4).foldLeft((i,0))( (acc,_) => {
      (acc._1 / 10, acc._2 + (acc._1 % 10))
    })._2
    if(a <= sum && sum <= b ) acc + i else acc
  })

  println(ans)
}


object Main extends App {

  val Array(n, a, b) = io.StdIn.readLine.split(" ").map(_.toInt)

  val ans = (1 to n).map( i => {
      val sum = String.valueOf(i).map(_.asDigit).sum
      if(a <= sum && sum <= b ) i else 0
    }).sum

  println(ans)
}


object Main{
  def main(args: Array[String]){
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString("\n");
      println(solve(input).trim());
    }
  }

  def solve(input:String):String={
    val List(n,a,b)=input.trim.split(" ").map(_.toInt).toList;
    (1 to n).filter(x=>bitween(x.toString().split("").map(_.toInt).sum,a,b)).sum.toString()
  }

  def bitween(x:Int,min:Int,max:Int)=min<=x&&x<=max;

  val tests=List("""20 2 5""" -> """84""",
    """10 1 2""" -> """13""",
"""100 4 16"""->"""4554""");

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


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

	def f(x: Int): Int = {
		var temp = x/10
		var z = x%10

		while(temp != 0){
			z = z + temp%10
			temp = temp / 10
		}
		z
	}

	for(i<-1 to temp(0)){
		val t = f(i)
		if(temp(1) <= t && t <= temp(2)) result = result + i
	}

	println(result)
}


object Main {
  def main(args: Array[String]): Unit = {
    val in = readLine.split(" ").map(_.toInt)
    val N = in(0)
    val A = in(1)
    val B = in(2)

    var count = 0
    for(i <- 1 to N){
      val deg = i.toString.length - 1
      val array = (0 to deg).map{idx => i.toString.charAt(idx).toString.toInt}.toArray
      if (A <= array.sum & array.sum <= B) count += i
    }

    print(count)

  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val in = readLine.split(" ").map(_.toInt)
    val N = in(0)
    val A = in(1)
    val B = in(2)

    val smallDeg = A.toString.length

    var count = 0
    for(i <- 1 until N){
      val deg = i.toString.length
      val Array = (0 until deg).map{idx => i.toString.charAt(idx).toInt}.toArray
      if (A <= Array.sum && Array.sum <= B) count += Array.sum
    }

    print(count)

  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  println(sc.next().count(_ == '1'))
}

Score : 100 points

Problem Statement

Snuke has a grid consisting of three squares numbered 1, 2 and 3.
In each square, either 0 or 1 is written. The number written in Square i is s_i.

Snuke will place a marble on each square that says 1.
Find the number of squares on which Snuke will place a marble.

Constraints

Each of s_1, s_2 and s_3 is either 1 or 0.

Input

Input is given from Standard Input in the following format:

s_{1}s_{2}s_{3}

Output

Print the answer.

Sample Input 1

101

Sample Output 1

2

A marble will be placed on Square 1 and 3.

Sample Input 2

000

Sample Output 2

0

No marble will be placed on any square.


import java.util.Scanner
import scala.math._

object Main extends App {

  val sc = new Scanner(System.in)
  val S = sc.next()

  println(S.count{_ == '1'})

}


object Main {

  import java.util.Scanner
  import java.lang.String

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    val str :String = scanner.next()

    var count : Int = 0
    if(str.charAt(0) == '1')
      count += 1;
    if(str.charAt(1) == '1')
      count += 1;
    if(str.charAt(2) == '1')
      count += 1;
    println(count)
  }
}


object Main {
	def main(args: Array[String]) {
		val input = io.Source.stdin.getLines().mkString("\n")
		println(solve(input).trim)
	}

	def solve(input: String): String = {
		input.split("").filter(_.length!=0).filter(_=="1").length.toString()
	}
}


object Main extends App {
  val s = readLine()
  val n = s.foldLeft(0){ (r, e) => r + e.toString.toInt}
  println(n)
}


import scala.io.StdIn.readLine

object Main extends App {
  val n = readLine.toCharArray.map(_.asDigit).count(_ == 1)
  println(n)
}


import scala.io.StdIn.readLine

object Main extends App {
  val n = readLine.split("").map(_.toInt).count(_ == 1)
  println(n)
}


import scala.io.StdIn
object Main extends App {
  val input = StdIn.readLine()
  val answer = input.map(_.asDigit).foldLeft(0)((z, n) => z + n)
  println(answer)
}


import scala.io.StdIn
object Main{
  def main(args: Array[String]): Unit ={
    //val one_or_zero: String = readLine("please write down:")
    var counter = 0
    val judge1: Unit = if (args(0) == '1') counter = counter+1
    val judge2: Unit = if (args(1) == '1') counter = counter+1
    val judge3: Unit = if (args(2) == '1') counter = counter+1
    println(counter)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.stdin.getLines().toList
    println(solve(lines))
  }

  def solve(lines: List[String]): Int = {
    val list = lines(0).split("").map(_.toInt).toList
    list.filter(_ == 1).length
  }
}


object Main {
  def main(args: Array[String]) {
    val input = io.Source.stdin.getLines().mkString("\n")
    println(solve(input).trim())

  }

  def solve(input: String): String = {
    input.split("").filter(_ == "1").size.toString
  }
}


object Main {
  def main(args: Array[String]) {
    val input = io.Source.stdin.getLines().mkString("\n")
    println(solve(input).trim())

  }

  def solve(input: String): String = {
    input.split("").map(_.toInt).filter(_ == 1).size.toString
  }
}


object Main extends App {
    val sc = new java.util.Scanner(System.in)
    val line = sc.nextLine()
    val ret = (for {
      x <- line.toCharArray() if x == '1'
    } yield {
      x
    }).length
    println(ret)
}


object Main{
  def main(args: Array[String]){
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString("\n");
      println(solve(input).trim());
    }
  }

  def solve(input:String):String={
    input.split("").filter(_=="1").size.toString()
  }

  val tests=List("""101""" -> """2""",
    """000""" -> """0""");

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


object Main {
  def main(args: Array[String]): Unit = {
//    val sc = new java.util.Scanner(System.in)
//    val in = sc.next()
    val in = args(0)
    print(in.count(_ == '1'))
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val in = sc.next
    print(in.count(_ == "1"))
  }
}


object Main extends App {
	val a = scala.io.StdIn.readLine.toArray

	var sum = 0

	for(i<-a){
		if(i == '1') sum = sum + 1
	}

	println(sum)

}


import java.io.{BufferedReader, InputStreamReader}

object Main extends App {

  def isMatch(arr:Array[Char], t:String, k:Int):Boolean = {
    for(i <- 0 until t.length) {
      if(t.charAt(i) != arr(i+k) && arr(i+k) != '?')
        return false
    }
    true
  }
  def construct(arr:Array[Char], t:String, k:Int):Unit = {
      for(i <- 0 until t.length) {
        arr(i+k) = t.charAt(i)
      }
  }

  val in = new BufferedReader(new InputStreamReader(System.in))
  val s, t = in.readLine

  val ans = {
    val arr = s.toCharArray
    var isMatched = false

    for(i <- s.length - t.length to 0 by -1) {
      if(!isMatched) {
        if(isMatch(arr, t, i)) {
          construct(arr, t, i)
          isMatched = true
        }
      }
    }

    if(isMatched) {
      for(i <- 0 until s.length) {
        if(arr(i) == '?') {
          arr(i) = 'a'
        }
      }
      arr.mkString
    }
    else "UNRESTORABLE"
  }

  println(ans)
}

Score : 300 points

Problem Statement

E869120 found a chest which is likely to contain treasure.

However, the chest is locked. In order to open it, he needs to enter a string S consisting of lowercase English letters.

He also found a string S', which turns out to be the string S with some of its letters (possibly all or none) replaced with ?.

One more thing he found is a sheet of paper with the following facts written on it:

Condition 1: The string S contains a string T as a contiguous substring.

Condition 2: S is the lexicographically smallest string among the ones that satisfy Condition 1.

Print the string S.

If such a string does not exist, print UNRESTORABLE.

Constraints

1 \leq |S'|, |T| \leq 50

S' consists of lowercase English letters and ?.

T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T'

Output

Print the string S.

If such a string does not exist, print UNRESTORABLE instead.

Sample Input 1

?tc????
coder

Sample Output 1

atcoder

There are 26 strings that satisfy Condition 1: atcoder, btcoder, ctcoder,..., ztcoder.
Among them, the lexicographically smallest is atcoder, so we can say S = atcoder.

Sample Input 2

??p??d??
abc

Sample Output 2

UNRESTORABLE

There is no string that satisfies Condition 1, so the string S does not exist.


import java.io.{BufferedReader, InputStreamReader}

object Main extends App {

  def isMatch(arr:Array[Char], t:String, k:Int):Boolean = {
    for(i <- 0 until t.length) {
      if(t.charAt(i) != arr(i+k) && arr(i+k) != '?')
        return false
    }
    true
  }
  def construct(arr:Array[Char], t:String, k:Int):Unit = {
      for(i <- 0 until t.length) {
        arr(i+k) = t.charAt(i)
      }
  }

  val in = new BufferedReader(new InputStreamReader(System.in))
  val s, t = in.readLine

  val ans = {
    val arr = s.toCharArray
    var isMatched = false

    for(i <- s.length - t.length to 0 by -1) {
      if(isMatch(arr, t, i)) {
        if(!isMatched) {
          construct(arr, t, i)
          isMatched = true
        }
      }
    }

    if(isMatched) {
      for(i <- 0 until s.length) {
        if(arr(i) == '?') {
          arr(i) = 'a'
        }
      }
      arr.mkString
    }
    else "UNRESTORABLE"
  }

  println(ans)
}


import java.io.{BufferedReader, InputStreamReader}

object Main extends App {

  def isMatch(arr:Array[Char], t:String, k:Int):Boolean = {
    for(i <- 0 until t.length) {
      if(t.charAt(i) != arr(i+k) && arr(i+k) != '?')
        return false
    }
    true
  }
  def construct(arr:Array[Char], t:String, k:Int):Unit = {
      for(i <- 0 until t.length) {
        arr(i+k) = t.charAt(i)
      }
  }

  val in = new BufferedReader(new InputStreamReader(System.in))
  val s, t = in.readLine

  val ans = {
    val arr = s.toCharArray
    var isMatched = false

    for(i <- 0 to s.length - t.length) {
      if(isMatch(arr, t, i)) {
        isMatched = true
        construct(arr, t, i)
      }
    }

    if(isMatched) {
      for(i <- 0 until s.length) {
        if(arr(i) == '?') {
          arr(i) = 'a'
        }
      }
      arr.mkString
    }
    else "UNRESTORABLE"
  }

  println(ans)
}


import scala.io.StdIn

object Main extends App {

  var ss = StdIn.readLine()
  val t = StdIn.readLine()
  var replaced = false

  def solve(i: Int): String = {
    if (i == 0) {
      ss
    } else {
      var k = 0
      while (k < t.length && 0 <= i - k && (ss(i - k) == t(t.length - k - 1) || ss(i - k) == '?')) {
        k += 1
      }
      if (k == t.length) {
        replaced = true
        val idx = i + 1 - k
        ss.take(idx) + t + ss.drop(idx + k)
      } else {
        solve(i - 1)
      }
    }
  }

  val r = solve(ss.length - 1)
  println(if (!replaced) "UNRESTORABLE" else r.replace("?", "a"))

}


import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Main extends App {

  var ss = StdIn.readLine().reverse
  val t = StdIn.readLine().reverse
  //val buff = ArrayBuffer.empty[Char]
  val ret = ArrayBuffer.empty[String]

  val len = ss.length
  val lent = t.length
  var i = 0
  while (i < len) {
    var j = 0
    var k = i
    var unmatch = false
    //buff.clear()
    while (j < lent && !unmatch && k < len) {
      //if(t(j) == ss(k) || ss(k) == '?'){
      if(t(j) != ss(k) && ss(k) != '?'){
        unmatch = true
      } else {
        //buff.append(t(j))
        j += 1
        k += 1
      }
    }
    if(j == lent && !unmatch){
      ret.append(t)
      ret.append(ss.drop(k))
      i += len
    } else {
      ret.append(ss(i).toString)
      i += 1
    }
  }

  val result = ret.mkString("")
  println(if(len < lent || result == ss) "UNRESTORABLE" else result.replace("?", "a").reverse)

}


import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Main extends App {

  var ss = StdIn.readLine().reverse
  val t = StdIn.readLine().reverse
  val buff = ArrayBuffer.empty[Char]
  val ret = ArrayBuffer.empty[String]

  val len = ss.length
  val lent = t.length
  var i = 0
  while (i < len) {
    var j = 0
    var k = i
    var unmatch = false
    buff.clear()
    while (j < lent && !unmatch && k < len) {
      if(t(j) == ss(k) || ss(k) == '?'){
        buff.append(t(j))
        j += 1
        k += 1
      } else {
        unmatch = true
      }
    }
    if(j == lent && !unmatch){
      ret.append(buff.mkString(""))
      ret.append(ss.drop(k))
      i += len
    } else {
      ret.append(ss(i).toString)
      i += 1
    }
  }

  val result = ret.mkString("")
  println(if(len < lent || result == ss) "UNRESTORABLE" else result.replace("?", "a").reverse)

}


import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Main extends App {

  var ss = StdIn.readLine()
  val t = StdIn.readLine()
  val buff = ArrayBuffer.empty[Char]
  val ret = ArrayBuffer.empty[String]

  val len = ss.length
  val lent = t.length
  var i = 0
  while (i < len) {
    var j = 0
    var k = i
    var unmatch = false
    buff.clear()
    while (j < lent && !unmatch && k < len) {
      if(t(j) == ss(k) || ss(k) == '?'){
        buff.append(t(j))
        j += 1
        k += 1
      } else {
        unmatch = true
      }
    }
    if(j == lent && !unmatch){
      ret.append(buff.mkString(""))
      i += j
    } else {
      ret.append(ss(i).toString)
      i += 1
    }
  }

  val result = ret.mkString("")
  println(if(len < lent || result == ss) "UNRESTORABLE" else result.replace("?", "a"))

}


import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Main extends App {

  var ss = StdIn.readLine()
  val t = StdIn.readLine()
  val buff = ArrayBuffer.empty[Char]
  val ret = ArrayBuffer.empty[String]

  val len = ss.length
  val lent = t.length
  var i = 0
  while (i < len) {
    var j = 0
    var k = i
    var unmatch = false
    buff.clear()
    while (j < lent && !unmatch && k < len) {
      if(t(j) == ss(k) || ss(k) == '?'){
        buff.append(t(j))
        j += 1
        k += 1
      } else {
        unmatch = true
      }
    }
    if(j == lent && !unmatch){
      ret.append(buff.mkString(""))
      i += j
    } else {
      ret.append(ss(i).toString)
      i += 1
    }
  }

  val result = ret.mkString("")
  println(if( result == ss) "UNRESTORABLE" else result.replace("?", "a"))

}


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

	val KK = Array.ofDim[Char](K.size,K.size)
	for(i<-0 until K.size){
		for(j<-0 until K.size){
			KK(i)(j) = '?'
		}
		KK(i)(i) = K(i)
	}

	var flag = false
	var t = 0

	while(!flag && t < K.size){
		flag = N.mkString.contains(KK(t).mkString) || flag
		t = t + 1;
	}

	if(flag){
		val A = N.mkString.replace(KK(t-1).mkString,K.mkString)
		println(A.replaceAllLiterally("?","a"))
	}else{
		println("UNRESTORABLE")
	}
}


object Main{
  def ok(s:String,t:String) : Boolean = {
    if(s.length != t.length){
      return false
    }else{
      for(i <- 0 to s.length-1){
        if(s(i)!=t(i) && s(i)!='?') return false
      }
      true
    }
  }
  def gen(s:String,t:String,idx:Int) : String = {
    var sc = s.toCharArray
    for(i <- 0 to t.length-1) sc(idx+i) = t(i)
    for(i <- 0 to sc.length-1) if(sc(i) == '?') sc(i) = 'a'
    sc.mkString
  }

  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val s,t = sc.nextLine
    val n = s.length
    val m = t.length
    val end = "z" * 100

    val ar = for(i <- 0 to n-1) yield {
      val sub = s.slice(i,i+m)
      val isok = ok(sub,t)
      if(isok) gen(s,t,i)
      else end
    }
    val ans = ar.filter(x=>x.length>0).min
    if(ans.length <= 50) println(ans)
    else println("UNRESTORABLE")
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val H, W = sc.nextInt()
  val squares =
    Array.fill(W + 2)('X') +:
      Array.fill(H)('X' +: sc.next().toCharArray :+ 'X') :+
      Array.fill(W + 2)('X')

  val rounds = for (x <- -1 to 1; y <- -1 to 1 if !(x == 0 && y == 0)) yield x -> y
  for (i <- 1 to H; j <- 1 to W if squares(i)(j) != '#') {
    squares(i)(j) = (rounds.count { case (x, y) => squares(i + x)(j + y) == '#' } + '0').toChar
  }

  squares.collect {
    case line if !line.forall(_ == 'X') =>
      line.filterNot(_ == 'X').mkString
  }.foreach(println)
}

Score : 200 points

Problem Statement

You are given an H × W grid.

The squares in the grid are described by H strings, S_1,...,S_H.

The j-th character in the string S_i corresponds to the square at the i-th row from the top and j-th column from the left (1 \leq i \leq H,1 \leq j \leq W).

. stands for an empty square, and # stands for a square containing a bomb.

Dolphin is interested in how many bomb squares are horizontally, vertically or diagonally adjacent to each empty square.

(Below, we will simply say "adjacent" for this meaning. For each square, there are at most eight adjacent squares.)

He decides to replace each . in our H strings with a digit that represents the number of bomb squares adjacent to the corresponding empty square.

Print the strings after the process.

Constraints

1 \leq H,W \leq 50

S_i is a string of length W consisting of # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the H strings after the process.

The i-th line should contain a string T_i of length W, where the j-th character in T_i corresponds to the square at the i-th row from the top and j-th row from the left in the grid (1 \leq i \leq H, 1 \leq j \leq W).

Sample Input 1

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

Sample Output 1

11211
1#2#1
11211

For example, let us observe the empty square at the first row from the top and first column from the left.

There is one bomb square adjacent to this empty square: the square at the second row and second column.

Thus, the . corresponding to this empty square is replaced with 1.

Sample Input 2

3 5
#####
#####
#####

Sample Output 2

#####
#####
#####

It is possible that there is no empty square.

Sample Input 3

6 6
#####.
#.#.##
####.#
.#..#.
#.##..
#.#...

Sample Output 3

#####3
#8#7##
####5#
4#65#2
#5##21
#4#310


import scala.collection.mutable.ArrayBuffer

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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val h, w = sc.nextInt
    sc.nextLine
    val s = new Array[Array[Char]](h)
    for (i <- 0 until h) {
      s(i) = sc.nextLine.toCharArray
    }

    val result = ArrayBuffer.fill[ArrayBuffer[Int]](h)(ArrayBuffer.fill[Int](w)(0))

    val SHP = 1001001001
    val DI = Array(-1, -1, 0, 1, 1, 1, 0, -1)
    val DJ = Array(0, -1, -1, -1, 0, 1, 1, 1)

    for (si <- 0 until h; sj <- 0 until w) {
      // すべてのマスをチェックしていく
      if (s(si)(sj) == '#') {
        result(si)(sj) = SHP
      } else {
        for (i <- 0 until 8) {
          val ni = si + DI(i)
          val nj = sj + DJ(i)
          if (
            ((ni >= 0 && ni < h) && (nj >= 0 && nj < w)) // 枠内に収まる
              && s(ni)(nj) == '#' // 到達不可能マス
          ) {
            result(si)(sj) += 1
          }
        }
      }
    }
    result.foreach(raw => println(raw.map(v => if (v == SHP) "#" else v.toString).mkString))
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val Array(h, w) = sc.nextLine.split(" ").map(_.toInt)
  val seqs = Seq.fill(h)(sc.nextLine.split("").toSeq.filter(_.nonEmpty).zipWithIndex).zipWithIndex

  def findOpt[T](index: Int, seq: Seq[(T, Int)]): Option[T] = {
    import scala.util.Try
    Try(seq.map{case (t, index) => t}.apply(index)).toOption
  }

  val results = seqs.map{ case (seq, seqIndex) =>
    val preSeq = findOpt(seqIndex - 1, seqs)
    val curSeq = findOpt(seqIndex, seqs)
    val nextSeq = findOpt(seqIndex + 1, seqs)

    seq.map { case (e, eIndex) =>
      if (e == "#" ) "#"
      else Seq(preSeq.flatMap(findOpt(eIndex - 1, _)),
              preSeq.flatMap(findOpt(eIndex, _)),
              preSeq.flatMap(findOpt(eIndex + 1, _)),
              curSeq.flatMap(findOpt(eIndex - 1, _)),
              curSeq.flatMap(findOpt(eIndex + 1, _)),
              nextSeq.flatMap(findOpt(eIndex - 1, _)),
              nextSeq.flatMap(findOpt(eIndex, _)),
              nextSeq.flatMap(findOpt(eIndex + 1, _))
             ).count(_.contains("#")).toString
    }
  }

  results.foreach(seq => println(seq.mkString))
}


import java.util.Scanner

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

  def countMine(x:Int, y: Int, g:Vector[Vector[Char]]): Int = {
    val xMax = g.size
    val yMax = g(0).size
    var mineCount: Int = 0
    for (
      cx <- x - 1 to x + 1 if cx >= 0 && cx < xMax;
      cy <- y - 1 to y + 1 if cy >= 0 && cy < yMax && (cx, cy) != (x, y)
    ) {
      if (g(cx)(cy) == '#') mineCount = mineCount + 1
    }
    mineCount
  }

  def solve(input: String): String = {
    val s: Scanner = new Scanner(input)
    val h,w = s.nextInt
    val g:Vector[Vector[Char]] = Vector.fill(h)(s.next.toCharArray.toVector)
    val ans:Vector[Vector[String]] =
      Vector.tabulate(h, w){(y, x) => if (g(y)(x) == '#') "#" else countMine(y,x,g).toString}
    ans.map(_.mkString("")).mkString("\n")
  }

  val tests = List(
    """3 5
      |.....
      |.#.#.
      |.....
    """.stripMargin ->
      """
        |11211
        |1#2#1
        |11211
      """.stripMargin,
    """3 5
      |#####
      |#####
      |#####
    """.stripMargin ->
    """
      |#####
      |#####
      |#####
    """.stripMargin,
    """6 6
      |#####.
      |#.#.##
      |####.#
      |.#..#.
      |#.##..
      |#.#...
    """.stripMargin ->
    """
      |#####3
      |#8#7##
      |####5#
      |4#65#2
      |#5##21
      |#4#310
    """.stripMargin
  )

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


import java.util.Scanner

object Main {
  def solve(sc: => Scanner): Unit = {
    val H, W = sc.nextInt
    val A = Array.fill[Array[Char]](H)(sc.next.toArray)
    for (i <- 0 until H) {
      for (j <- 0 until W) {
        print(if (A(i)(j) == '.') {
          var count = 0
          for (k <- -1 to 1) {
            for (l <- -1 to 1) {
              if (0 <= i + k && i + k < H && 0 <= j + l && j + l < W && A(i + k)(j + l) == '#') {
                count += 1
              }
            }
          }
          count
        } else ('#')
        )
      }
      println
    }
  }

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

    solve(sc)
  }
}


class MineMap(val height: Int, val width: Int) {

  type Mine = (Int, Int)

  private val internalCounts = Array.fill(height)(Array.fill(width)(0))
  private var mines = Seq.empty[Mine]

  private def isInside(coordinate: Mine): Boolean =
    0 <= coordinate._1 && coordinate._1 < height && 0 <= coordinate._2 && coordinate._2 < width

  def setMines(mines: Mine*): Unit = mines.foreach { mine =>
    this.mines = this.mines :+ mine
    for {
      h <- mine._1 - 1 to mine._1 + 1
      w <- mine._2 - 1 to mine._2 + 1
    } yield {
      if (isInside((h, w))) internalCounts(h)(w) += 1
    }
  }

  def opened(mineChar: String = "#"): Array[Array[String]] = {
    val stringMap = internalCounts.map { line =>
      line.map(_.toString)
    }
    this.mines.foreach { mine =>
      stringMap(mine._1)(mine._2) = mineChar
    }
    stringMap
  }
}

import java.util.Scanner

trait Reader {
  val scanner = new Scanner(System.in)
}

object Main extends App with Reader {

  final val H = scanner.nextInt()
  final val W = scanner.nextInt()
  val mineMap = new MineMap(H, W)

  val mines = (0 until H).foldLeft(Seq.empty[(Int, Int)]) { (acc, h) =>
    acc ++  scanner.next().zipWithIndex.collect {
      case ('#', w) => (h, w)
    }
  }
  mineMap.setMines(mines:_*)
  val answer = mineMap.opened().map { line =>
    line.map(_.toString).mkString
  }.mkString("\n")
  println(answer)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val lr = List.fill(n)((sc.nextInt(), sc.nextInt()))
  val ans = lr.map{case (l, r) => r-l+1}.sum
  println(ans)
}

Score : 200 points

Problem Statement

Joisino is working as a receptionist at a theater.

The theater has 100000 seats, numbered from 1 to 100000.

According to her memo, N groups of audiences have come so far, and the i-th group occupies the consecutive seats from Seat l_i to Seat r_i (inclusive).

How many people are sitting at the theater now?

Constraints

1≤N≤1000

1≤l_i≤r_i≤100000

No seat is occupied by more than one person.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
l_1 r_1
:
l_N r_N

Output

Print the number of people sitting at the theater.

Sample Input 1

1
24 30

Sample Output 1

7

There are 7 people, sitting at Seat 24,25,26,27,28,29 and 30.

Sample Input 2

2
6 8
3 3

Sample Output 2

4


import java.util.Scanner

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

  val n = sc.nextInt
  val tl = Seq.fill(n)((sc.nextInt, sc.nextInt))

  val res = tl.foldLeft(0L){case (sum, (left, right)) =>
      sum + (right - left + 1)
  }

  println(res)
}


import scala.io.StdIn

object Main extends App {

  val n = StdIn.readLine().toInt
  val r = (0 until n).foldLeft(0) { (acc, _) =>
    val a = StdIn.readLine().split(' ').map(_.toInt)
    acc + (a(1) - a(0)) + 1
  }
  println(r)

}


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val s = sc.next().toList.distinct.sorted
  val a = ("abcdefghijklmnopqrstuvwxyz").toList
  val ans = a.zip(s).find{case (x, y) => x != y}.map{case (x, y) => x}.getOrElse("None")
  println(ans)
}

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Find the lexicographically (alphabetically) smallest lowercase English letter that does not occur in S.
If every lowercase English letter occurs in S, print None instead.

Constraints

1 \leq |S| \leq 10^5 (|S| is the length of string S.)

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the lexicographically smallest lowercase English letter that does not occur in S.
If every lowercase English letter occurs in S, print None instead.

Sample Input 1

atcoderregularcontest

Sample Output 1

b

The string atcoderregularcontest contains a, but does not contain b.

Sample Input 2

abcdefghijklmnopqrstuvwxyz

Sample Output 2

None

This string contains every lowercase English letter.

Sample Input 3

fajsonlslfepbjtsaayxbymeskptcumtwrmkkinjxnnucagfrg

Sample Output 3

d


object Main extends App {
    val pre_s = io.StdIn.readLine

    val s = pre_s.distinct

    var result = "None"
    var has = false
    for (char <- "abcdefghijklmnopqrstuvwxyz" if !has) {
        if (! s.contains(char)) {
            has = true
            result = char.toString
        }
    }

    println(result)
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    //nextLineとnextを同時に使ったら死ぬ
    val sc = new Scanner(System.in)
    val s = sc.next()
    val ans =
      ("abcdefghijklmnopqrstuvwxyz".toCharArray.filter(m => !s.contains(m)))
    if (ans.length == 0) {
      println("None")
    } else {
      println(ans.head)
    }
  }
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    //nextLineとnextを同時に使ったら死ぬ
    val sc = new Scanner(System.in)
    val s = sc.next()
    println(
      "abcdefghijklmnopqrstuvwxyz".toCharArray.filter(m => !s.contains(m)).head
    )
  }
}


object Main extends App {
  def check(s:Set[Char]) = {
    val s_ = (for(c <- 'a' to 'z' if !s.contains(c)) yield c).toArray
    if (s_.length == 0) None
    else Some(s_(0))
  }
  val s = readLine.toSet
  println(check(s) match {
    case Some(c) => c
    case None => "None"
  })
}


import scala.io.StdIn
object Main extends App {
  val abcSet = ('a' to 'z').toSet
  val unusedChars = ('a' to 'z').toSet.diff(StdIn.readLine().toSet)
  println(if (unusedChars.isEmpty) "None" else unusedChars.min)
}


object Main extends App {
  var a = readLine.toSet
  print(('a' to 'z').find(!a.contains(_)).getOrElse("None"))
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    val alphabets = sc.nextLine.split("").toSet
    val allAlphabets = "abcdefghijklmnopqrstuvwxyz".split("").toSet
    if ((allAlphabets diff alphabets).isEmpty) println("None")
    else println((allAlphabets diff alphabets).toList.min)
  }
}


import scala.io.StdIn

object Main extends App {

  val s = StdIn.readLine()
  val a = Array.ofDim[Int](26) // a to z

  s.foreach(c => a(c - 'a') += 1)
  val r = a.indexWhere(p => p == 0)

  //println(a.mkString(" "))

  println(if(r < 0) "None" else (r+'a').toChar)

}


import java.util.Scanner

object Main {
  def solve(sc: => Scanner): Unit = {
    val S = sc.next
    println("abcdefghijklmnopqrstuvwxyz".filter(c => !S.exists(c == _)).headOption.getOrElse("None"))
  }

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


object Main {
    def main(args: Array[String]) = {
        val sc = new java.util.Scanner(System.in)
        val s = sc.next
        println(calc(s))
    }
    def calc(s: String) : String = {
        val alphabet = "abcdefghijklmnopqrstuvwxyz"
        val ret = alphabet.filter(x => !s.contains(x))
        if (ret.length > 0) ret(0).toString else "None"
    }
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val S = sc.nextLine()
  println(('a' to 'z').find(!S.contains(_)).getOrElse("None"))
}


import scala.collection.mutable

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  val hashMap = mutable.Map[Int, Int]()
  for (_ <- 1 to N) {
    val i = Integer.numberOfTrailingZeros(sc.nextInt()).min(2)
    hashMap.update(i, hashMap.getOrElse(i, 0) + 1)
  }
  val isSortable =
    hashMap.getOrElse(0, 0) + (if (hashMap.contains(1)) 1 else 0) <= hashMap.getOrElse(2, 0) + 1
  println(if (isSortable) "Yes" else "No")
}

Score : 400 points

Problem Statement

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

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

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

Determine whether Snuke can achieve his objective.

Constraints

2 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

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

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is (1, 100, 10).

Sample Input 2

4
1 2 3 4

Sample Output 2

No

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

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes


import java.util.Scanner

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

  val n = sc.nextInt

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

  val div2 = al.filter(_ % 2 == 0)
  val (divOnly2, divOver4) = div2.partition(_ % 4 != 0)

  val oddCon      = n - div2.size
  val divOnly2Con = divOnly2.size
  val divOver4Con = divOver4.size

  val res =
    if(divOnly2Con >= 1) if( divOver4Con >= oddCon ) "Yes" else "No"
    else if(  divOver4Con + 1 >= oddCon ) "Yes" else "No"

  println(res)
}

/*
*
*
*
*
* */


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

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

object Main {
  val MOD = 1000000007
  val out = new PrintWriter(System.out)
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    var two, four = 0
    rep(N) { _ =>
      val a = sc.nextInt()
      if (a % 4 == 0) four += 1
      else if (a % 2 == 0) two += 1
    }
    val one = N - two - four
    val ok = four + 1 >= one + (if (two > 0) 1 else 0)
    val ans = if (ok) "Yes" else "No"

    out.println(ans)
  }

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

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

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

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

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

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

  private implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    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(a => map.getOrElseUpdate(f(a), ArrayBuffer()) += a)
      map
    }

    def rep(f: A => Unit): Unit = {
      as.indices foreach (i => f(as(i)))
    }

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

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

  def pow(x: Int, n: Int): Int = {
    n match {
      case 0 => 1
      case _ =>
        val r = pow(x * x, n / 2)
        if (n % 2 == 1) r * x else r
    }
  }
}


object Main extends App {
  import collection.mutable.PriorityQueue
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt
  val As = Array.fill(3*N)(sc.nextInt)

  def f(xs: Array[Int], ys: Array[Int]): Array[Int] = {
    val pq = new PriorityQueue[Int]()(Ordering.Int.reverse) ++ xs
    ys.scanLeft(pq.sum) { (s, y) =>
      pq += y
      s + y - pq.dequeue}
  }

  val List(as1, as2, as3) = As.grouped(N).toList
  val ans = f(as1, as2).zip(f(as3.map(a => -a), as2.map(a => -a).reverse).reverse).map(t => t._1 + t._2).max
  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.


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val s = sc.next()
  val aPos = s.indexOf("A")
  val zPos = s.lastIndexOf("Z")
  val az = s.slice(aPos, zPos+1)
  println(az.length)
}

Score : 200 points

Problem Statement

Snuke has decided to construct a string that starts with A and ends with Z, by taking out a substring of a string s (that is, a consecutive part of s).

Find the greatest length of the string Snuke can construct. Here, the test set guarantees that there always exists a substring of s that starts with A and ends with Z.

Constraints

1 ≦ |s| ≦ 200{,}000

s consists of uppercase English letters.

There exists a substring of s that starts with A and ends with Z.

Input

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

s

Output

Print the answer.

Sample Input 1

QWERTYASDFZXCV

Sample Output 1

5

By taking out the seventh through eleventh characters, it is possible to construct ASDFZ, which starts with A and ends with Z.

Sample Input 2

ZABCZ

Sample Output 2

4

Sample Input 3

HASFJGHOGAKZZFEGA

Sample Output 3

12


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val s = sc.next()
  println(s.lastIndexOf('Z') - s.indexOf('A') + 1)
}


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

  val s = inputs.head

  println(solve(s))

  private def solve(s: String): Int = {
    var aIndex = -1
    var zIndex = -1
    val end = s.size - 1
    (0 until end).foreach { i =>
      s(i) match {
        case 'A' if aIndex == -1 => aIndex = i
        case _ => ()
      }

      s(end - i) match {
        case 'Z' if zIndex == -1 => zIndex = end - i
        case _ => ()
      }

      if(aIndex != -1 && zIndex != -1) {
        return zIndex - aIndex + 1
      }
    }
    return -1
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val iobuf = readLine.split(" ").head.dropWhile(_ != 'A').reverse.dropWhile(_ != 'Z').length
    println(iobuf)
  }
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val letter = sc.nextLine
    println(letter.dropWhile(_ != 'A').reverse.dropWhile(_ != 'Z').length)
  }
}


import java.util.Scanner

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

  val s = sc.next

  val res = s.lastIndexOf("Z") -  s.indexOf("A") + 1

  println(res)
}


import scala.io.StdIn

object Main extends App {

  val s = StdIn.readLine()
  val start = s.indexOf("A")
  val end = s.lastIndexOf("Z")
  println(end - start + 1)

}


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

  val nums = inputs.head.split(" ").map(_.toInt)

  println(solve(nums(0), nums(1)))

  private def solve(k: Int, s: Int): Int = {
    val max = 3 * k
    if (s == 0 || s == max) {
      return 1
    }

    var ans = 0
    (0 to k).foreach { i =>
      (0 to k).foreach { j =>
        val sum = i + j
        val dis = s - sum
        if (dis <= k && 0 <= dis) {
          ans = ans + 1
        }
      }
    }

    ans
  }
}

Score : 200 points

Problem Statement

You are given two integers K and S.

Three variable X, Y and Z takes integer values satisfying 0≤X,Y,Z≤K.

How many different assignments of values to X, Y and Z are there such that X + Y + Z = S?

Constraints

2≤K≤2500

0≤S≤3K

K and S are integers.

Input

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

K S

Output

Print the number of the triples of X, Y and Z that satisfy the condition.

Sample Input 1

2 2

Sample Output 1

6

There are six triples of X, Y and Z that satisfy the condition:

X = 0, Y = 0, Z = 2

X = 0, Y = 2, Z = 0

X = 2, Y = 0, Z = 0

X = 0, Y = 1, Z = 1

X = 1, Y = 0, Z = 1

X = 1, Y = 1, Z = 0

Sample Input 2

5 15

Sample Output 2

1

The maximum value of X + Y + Z is 15, achieved by one triple of X, Y and Z.


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

  val nums = inputs.head.split(" ").map(_.toInt)

  println(solve(nums(0), nums(1)))

  private def solve(k: Int, s: Int): Int = {
    if (3 * k < s) {
      return 0
    }
    var ans = 0

    (0 to k).foreach { i =>
      (0 to k).foreach { j =>
        (0 to k).foreach { n =>
          if((i + j + n) == s) {
            ans = ans + 1
          }
        }
      }
    }

    ans
  }
}


import scala.io.StdIn._
object Main extends App{
  val sc = new java.util.Scanner(System.in)
  var ka,s = sc.nextInt
  var ans=0
  for(i <- 0 to ka){
    if((i+2*ka)>=s){
      for(j <- 0 to ka){
        if((i+j+ka)>=s){
          for(k <- 0 to ka){
            if((i+j+k)==s){
              ans+=1
            }
          }
        }
      }
    }
  }
  print(ans)
}


import scala.io.StdIn._
object Main extends App{
  val sc = new java.util.Scanner(System.in)
  var ka,s = sc.nextInt
  var ans=0
  for(i <- 0 to ka){
    for(j <- 0 to ka){
      for(k <- 0 to ka){
        if((i+j+k)==s){
         ans+=1
        }
      }
    }
  }
  print(ans)
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datK, datS) = readLine.split(" ").map(_.toInt)
    var count = 0
    for (x <- 0 to datK; y <- 0 to datK) {
      if((datS >= x + y) && (datS - (x + y) <= datK)) count += 1
    }
    println(count)
  }
}


object ABC051B {

  import Competitive._

  val K, S = nextInt
  println(Range.inclusive(0, K).flatMap(i => Range.inclusive(0, K).map(j => (i, j, S - (i + j)))).count(t => t._3 >= 0 && K >= t._3))
}
object Main extends App{
  ABC051B
}

object Competitive{
  import scala.io.StdIn.readLine

  implicit class ForInt(val self: Int) {
    @inline def fori(from: Int)(body: Int => Unit): Unit = {
      var i = from
      while (i < self) {
        body(i)
        i += 1
      }
    }

    @inline def fori()(body: Int => Unit): Unit = fori(0)(body)

    @inline def times(body: => Unit): Unit = fori(0){_ => body}
  }

  private var tokenizerBack = readLine().split(" ").iterator
  def tokenizer: Iterator[String] = {
    tokenizerBack = if (tokenizerBack.hasNext) tokenizerBack else readLine().split(" ").iterator
    tokenizerBack
  }

  def next: String = tokenizer.next
  def nextInt: Int = next.toInt
  def nextLong: Long = next.toLong
  def nextIntArray(n: Int): Array[Int] = Array.fill(n)(nextInt)
  def nextLongArray(n: Int): Array[Long] = Array.fill(n)(nextLong)
  def nextArray(n: Int): Array[String] = Array.fill(n)(next)
}


object Main extends App {
  val Array(k,s) = readLine.split(" ").map{_.toInt}
  println((for (x <- 0 to k; y <- 0 to k if (x + y <= s && s - (x + y) <= k)) yield 0).length)
}


import scala.io.StdIn
object Main extends App {
  val List(k, s) = StdIn.readLine().split(" ").map(_.toInt).toList
  var cnt = 0
  for {
    x <- 0 to k
    y <- 0 to k
    z = s - x - y
    if (0 <= z && z <= k)
  } cnt += 1;
  println(cnt)
}


import java.util.Scanner

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

  def solve(input: String): String = {
    val sc: Scanner = new Scanner(input)
    val k, s = sc.nextInt
    val zs = for {
      x <- 0 to k if x <= s
      y <- 0 to k if x + y <= s
    } yield s - (x + y)
    zs.count(_ <= k).toString
  }

  val tests = List(
    """2 2""".stripMargin -> """6""",
    """5 15""".stripMargin -> """1"""
  )

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


import java.util.Scanner

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

  def solve(input: String): String = {
    val sc: Scanner = new Scanner(input)
    val k, s = sc.nextInt
    val zs = for {
      x <- 0 to k
      y <- 0 to k if x + y <= s
    } yield s - (x + y)
    zs.count(_ <= k).toString
  }

  val tests = List(
    """2 2""".stripMargin -> """6""",
    """5 15""".stripMargin -> """1"""
  )

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


import java.util.Scanner

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

  def solve(input: String): String = {
    val sc: Scanner = new Scanner(input)
    val k, s = sc.nextInt
    val xyz = for {
      x <- 0 to k
      y <- 0 to k if x + y <= s
      z <- 0 to k if x + y + z <= s
    } yield x + y + z
    xyz.count(_ == s).toString
  }

  val tests = List(
    """2 2""".stripMargin -> """6""",
    """5 15""".stripMargin -> """1"""
  )

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


object Main extends App {
  var a = readLine.split(" ").map(_.toInt)
  var sum = 0
  for(i<-0 to a(0); j<-0 to a(0)) {
    if(i+j<=a(1)) {
      sum = sum +1
    }
  }
  println(sum)
}


object Main extends App {
  var a = readLine.split(" ").map(_.toInt)
  var sum = 0
  for(i<-0 to a(0); j<-0 to a(0) if(a(1)-i-j>=0)) {
    if(i+j<=a(0)) {
      sum = sum +1
    }
  }
  println(sum)
}


object Main extends App {
  var a = readLine.split(" ").map(_.toInt)
  var sum = 0
  for(i<-0 to a(0); j<-0 to a(0)) {
    if(a(1)-i-j<=a(0)) {
      sum = sum +1
    }
  }
  println(sum)
}


import scala.io.StdIn

object Main extends App {
  val Array(k, s)  = StdIn.readLine.split(" ").map(_.toInt)

  def solve(k: Int, s: Int) : Int  = {
    var cnt = 0
    for(x <- 0 to k; y <- 0 to k; z <- 0 to k) {
      (x + y + z) match {
        case `s` => cnt += 1
        case _ => 0
      }
    }
    cnt
  }
  println(solve(k, s))

}


import scala.io.StdIn

object Main extends App {
  val Array(k, s)  = StdIn.readLine.split(" ").map(_.toInt)

  def solve(k: Int, s: Int) : Int  = {
    var cnt = 0
    for(x <- 0 to k; y <- 0 to k; z <- 0 to k) {
      println(x + y + z)
      (x + y + z) match {
        case `s` => cnt += 1
        case _ => 0
      }
    }
    cnt
  }
  println(solve(k, s))

}


import java.util.Scanner

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

  val k = sc.nextInt
  val s = sc.nextInt

  val res = {
    for {
      x <- (0 to k).toArray
      y <- (0 to k).toArray
      z = s - x - y if 0 <= z && z <= k
    } yield (x,y,z)
  }.length

  println(res)
}


import java.util.Scanner

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

  val k = sc.nextInt
  val s = sc.nextInt

  val res = {
    for {
      x <- 0 to k
      y <- 0 to k
    } yield (x + y to s).size
  }.sum

  println(res)

}


import scala.io.{ StdIn => in}

object Main extends App {
  val Array(k, s) = in.readLine.split(" ").map(_.toInt)

  val ans = {
    var res = 0
    for(z <- 0 to k; sz = s -z; i <- 0 to k) {
      val x = sz - i
      if(0 <= x && x <= k) res += 1
    }
    res
  }

  println(ans)
}


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

    val res = (0 to k).toList.map(x => (0 to k).toList.map(y => (0 to k).toList.map(z => if(x+y+z==s) 1 else 0 ))).flatMap(a=>a).flatMap(a=>a).sum
    println(res)
  }
}


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

    val res = (0 to k).toList.map(x => (0 to k).toList.map(y => (0 to k).toList.map(z => if(x+y+z==s) 1 else 0 ))).flatten.flatten.sum
    println(res)
  }
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val k, s = sc.nextInt
  var res = 0
  for (x <- 0 to k;
       y <- 0 to x;
       z <- 0 to y)
  {
    if (x + y + z == s) {
           if (x == y && y == z) res += 1
      else if (x == y || y == z) res += 3
      else res += 6
    }
  }
  println(res)
}


import java.util.Scanner

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

  s = s.replace("dreameraser","").
    replace("dreamer","").replace("eraser","").
    replace("dream","").replace("erase","")
  if (s.length == 0) {
    println("YES")
  } else {
    println("NO")
  }
}

Score : 300 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Another string T is initially empty.
Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:

Append one of the following at the end of T: dream, dreamer, erase and eraser.

Constraints

1≦|S|≦10^5

S consists of lowercase English letters.

Input

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

S

Output

If it is possible to obtain S = T, print YES. Otherwise, print NO.

Sample Input 1

erasedream

Sample Output 1

YES

Append erase and dream at the end of T in this order, to obtain S = T.

Sample Input 2

dreameraser

Sample Output 2

YES

Append dream and eraser at the end of T in this order, to obtain S = T.

Sample Input 3

dreamerer

Sample Output 3

NO


import java.util.Scanner

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

  s = s.replace("dreamer","").replace("eraser","").
    replace("dream","").replace("erase","")
  if (s.length == 0) {
    println("YES")
  } else {
    println("NO")
  }
}


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

import scala.annotation.tailrec

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

    val candidates = List("dream", "dreamer", "erase", "eraser")

    @tailrec
    def isMatch(ss: List[String]): Boolean = {
      ss match {
        case Nil => false
        case s :: rest =>
          if (s == "") {
            true
          } else {
            isMatch(
              rest ++ candidates.collect {
                case candidate: String if s.startsWith(candidate) =>
                  s.substring(candidate.length)
              }
            )
          }
      }
    }

    out.println(
      if (isMatch(List(s))) {
        "YES"
      } else {
        "NO"
      }
    )
    out.flush()
  }
}


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

import scala.annotation.tailrec

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

    val candidates = List("dream", "dreamer", "erase", "eraser")

    @tailrec
    def isMatch(ss: List[String]): Boolean = {
      ss match {
        case Nil => false
        case s :: rest =>
          if (s == "") {
            true
          } else {
            isMatch(
              candidates.collect {
                case candidate: String if s.startsWith(candidate) =>
                  s.substring(candidate.length)
              } ++ rest
            )
          }
      }
    }

    out.println(
      if (isMatch(List(s))) {
        "YES"
      } else {
        "NO"
      }
    )
    out.flush()
  }
}


object Main extends App {
  val s = readLine
  val list = Seq("dream", "dreamer", "erase", "eraser")

  def check(str: String): Boolean = {
    val index = list.indexWhere(str.endsWith)

    if (str.isEmpty) true
    else if (index == -1) false
    else check(str.dropRight(list(index).length))
  }

  val result = check(s)
  println(if (result) "YES" else "NO")
}


object Main {

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

    val S = sc.nextLine().reverse.toList

    def loop(S: List[Char]): Boolean =
      S match {
        case Nil => true
        case 'r' :: 'e' :: 'm' :: 'a' :: 'e' :: 'r' :: 'd' :: t => loop(t)
        case 'm' :: 'a' :: 'e' :: 'r' :: 'd' :: t => loop(t)
        case 'r' :: 'e' :: 's' :: 'a' :: 'r' :: 'e' :: t => loop(t)
        case 'e' :: 's' :: 'a' :: 'r' :: 'e' :: t => loop(t)
        case _ => false
      }

    println(if (loop(S)) "YES" else "NO")
  }

}


object Main extends App {
  var s = scala.io.StdIn.readLine()
  val tSeq = Seq("dreamer", "eraser", "dream", "erase")

  def judgeInclude(sInput: String): Boolean = {
    var sTemp = sInput
    while(true) {
      tSeq.find(t => sTemp.endsWith(t)) match {
        case Some(t) =>
          if(t == sTemp) {
            return true
          } else {
            sTemp = sTemp.dropRight(t.length)
          }
        case _ =>
          return false
      }
    }
    return false
  }

  if (judgeInclude(s)) {
    println("YES")
  } else {
    println("NO")
  }
}


import scala.io.StdIn
object Main extends App {
  def f(s: List[Char]): Boolean = {
    s match {
      case List('m','a','e','r','d', x @ _*) => f(x.toList)
      case List('r','e','m','a','e','r','d',x @ _*) => f(x.toList)
      case List('e','s','a','r','e',x @ _*) => f(x.toList)
      case List('r','e','s','a','r','e',x @ _*) => f(x.toList)
      case List() => true
      case _ => false
    }
  }
  val S = StdIn.readLine()
  if (f(S.toList)) println("YES") else println("NO")
}


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

    def rec(s: String): String = {
      if (s.isEmpty) {
        println("YES")
        sys.exit()
      }
      if (s.startsWith("dream")) {
        if (s.startsWith("dreameraser")) {
          rec(s.replaceFirst("dreameraser", ""))
        } else if (s.startsWith("dreamerase")) {
          rec(s.replaceFirst("dreamerase", ""))
        } else if (s.startsWith("dreamer")) {
          rec(s.replaceFirst("dreamer", ""))
        } else {
          rec(s.replaceFirst("dream", ""))
        }
      } else if (s.startsWith("erase")) {
        if (s.startsWith("eraser")) {
          rec(s.replaceFirst("eraser", ""))
        } else {
          rec(s.replaceFirst("erase", ""))
        }
      } else {
        println("NO")
        sys.exit()
      }
    }

    rec(S)
  }
}


import scala.io.{ StdIn => in}

object Main extends App {
  val s = in.readLine
    .replaceAll("eraser","")
    .replaceAll("erase","")
    .replaceAll("dreamer","")
    .replaceAll("dream","")

  val ans = if(s.isEmpty) "YES" else "NO"
  println(ans)
}


import scala.io.StdIn._

trait Solver extends App {
  implicit class Pipe[T](x: T) {
    def |>[U](f: T => U) = f(x)
  }

  class Prefix(prefix: String) {
    def unapply(s: String) = {
      if(s.startsWith(prefix)) Some(s.stripPrefix(prefix))
      else None
    }
  }

  val dream = new Prefix("dream".reverse)
  val dreamer = new Prefix("dreamer".reverse)
  val erase = new Prefix("erase".reverse)
  val eraser = new Prefix("eraser".reverse)

  def solve(s: String): Boolean = s match {
    case "" => true
    case dream(tail)   => solve(tail)
    case dreamer(tail) => solve(tail)
    case erase(tail)   => solve(tail)
    case eraser(tail)  => solve(tail)
    case _ => false
  }
}

object Main extends Solver {
  val s = readLine().reverse
  solve(s) match {
    case true => println("YES")
    case false => println("NO")
  }
}


object Main{
  def main(args: Array[String]){
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString("\n");
      println(solve(input).trim());
    }
  }

  def solve(input:String):String={
    if(f(input.toList.reverse)){
      "YES"
    }else{
      "NO"
    }
  }

  def f(s:List[Char]):Boolean={
    s match{
      case List('m','a','e','r','d',x @ _*)=>f(x.toList)
      case List('r','e','m','a','e','r','d',x @ _*)=>f(x.toList)
      case List('e','s','a','r','e',x @ _*)=>f(x.toList)
      case List('r','e','s','a','r','e',x @ _*)=>f(x.toList)
      case List()=>true
      case _=>false
    }
  }

  val tests=List("""erasedream""" -> """YES""",
    """dreameraser""" -> """YES""",
"""dreamerer"""->"""NO""");

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


import scala.util.control.Breaks

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

    val b = new Breaks
    b.breakable { while (s.size > 0) {
      if (s.size < 5)
        b.break
      val substr = s.take(5)
      if (substr == "erase" || substr == "dream") {
        s = s.drop(5)
        if (s.size >0 && s.head == 'r')
          s = s.drop(1)
      }
    } }
    if (s.size == 0)
      println("YES")
    else
      println("NO")
  }
}


import scala.io.StdIn._
object Main extends App {
  val result = Seq("eraser","erase","dreamer","dream").foldLeft(readLine){(str, word) =>
    str.replaceAll(word, "")
  }
  println(if (result.isEmpty) "YES" else "NO")
}


import scala.io.StdIn._
import java.util.regex.Pattern
object Main extends App {
  val pattern = Pattern.compile("(dream|dreamer|erase|eraser)$")

  @scala.annotation.tailrec
  def removeTail(str: String): String = {
    val newStr = pattern.matcher(str).replaceFirst("")
    if (str == newStr) str else (removeTail(newStr))
  }
  println(if (removeTail(readLine) == "") "YES" else "NO")
}


object Main extends App {
  val s = scala.io.StdIn.readLine
  println(if (s.reverse.matches("""^(maerd|remaerd|esare|resare)+$""")) "YES" else "NO")
}


object Main extends App {

  def partAll(s: String, es: List[String]): Boolean = {
    if (s.length == 0) true
    else {
      es.find(e => {
        if(s.slice(0, e.length) == e)
          partAll(s.drop(e.length), es)
        else
          false
      }) match {
        case None => false
        case Some(_) => true
      }
    }
  }

  val input: String = scala.io.StdIn.readLine // S

  val es: List[String] = List("dream", "dreamer", "erase", "eraser")

  partAll(input, es) match {
    case false => println("NO")
    case true  => println("YES")
  }
}


object Main extends App {
  val s = scala.io.StdIn.readLine
  println(if (s.reverse.matches("""(maerd|remaerd|esare|resare)+""")) "YES" else "NO")
}


object Main extends App {
  import scala.util.parsing.combinator._

  val s = scala.io.StdIn.readLine
  println(if (S(s.reverse)) "YES" else "NO")

  object S extends S {
    def apply(t: String) = parseAll(s, t) match {
      case Success(_, _) => true
      case failure => false
    }
  }
  class S private extends RegexParsers {
    def s = "(maerd|remaerd|esare|resare)+".r
  }
}


object Main extends App {
  import scala.util.parsing.combinator._

  val s = scala.io.StdIn.readLine
  println(if (S(s.reverse)) "YES" else "NO")

  object S extends S {
    def apply(t: String) = parseAll(s, t) match {
      case Success(res, in) => true
      case _ => false
    }
  }
  class S private extends RegexParsers {
    def s = "(maerd|remaerd|esare|resare)+".r
  }
}


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

  def solve(s: String): Boolean = {
    if (s.isEmpty) {
      true
    } else if (s.endsWith("dream")) {
      solve(s.dropRight(5))
    } else if (s.endsWith("dreamer")) {
      solve(s.dropRight(7))
    } else if (s.endsWith("erase")) {
      solve(s.dropRight(5))
    } else if (s.endsWith("eraser")) {
      solve(s.dropRight(6))
    } else {
      false
    }
  }

  if (solve(s)) {
    println("YES")
  } else {
    println("NO")
  }
}


import io.StdIn.readLine

object Main {

  def main(args: Array[String]): Unit = {
    var s = readLine()
    var state = 0

    while (state == 0) {
      if      (s.endsWith("dream"))   s = s.slice(0, s.length - 5)
      else if (s.endsWith("dreamer")) s = s.slice(0, s.length - 7)
      else if (s.endsWith("erase"))   s = s.slice(0, s.length - 5)
      else if (s.endsWith("eraser"))  s = s.slice(0, s.length - 6)
      else if (s.isEmpty) state = 1
      else              state = 2
    }
    state match {
      case 1 => println("YES")
      case 2 => println("NO")
    }
  }

}


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

  var now = s(0)
  var b_cnt = 0
  var w_cnt = 0

  s.foreach { ch =>
    if (now != ch) {
      if (now == 'B') {
        b_cnt += 1
      } else {
        w_cnt += 1
      }
      now = ch
    }
  }
  if (now == 'B') {
    b_cnt += 1
  } else {
    w_cnt += 1
  }

  def exec(wc: Int, bc: Int, top: (Char, Char)): Int = {
    if (wc == 0 || bc == 0) {
      return 0
    }

    var list = List[Int]()

    if (top._1 == 'W') {
      list = list.::(exec(wc - 1, bc, ('B', top._2)))
    }
    if (top._1 == 'B') {
      list = list.::(exec(wc, bc - 1, ('W', top._2)))
    }
    if (top._2 == 'W') {
      list = list.::(exec(wc - 1, bc, (top._1, 'B')))
    }
    if (top._2 == 'B') {
      list = list.::(exec(wc, bc - 1, (top._1, 'W')))
    }

    list.min + 1
  }

  println(exec(w_cnt, b_cnt, (s.head, s.last)))
}

Score : 300 points

Problem Statement

Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones between the new white stone and another white stone, turn into white stones, and vice versa.

In the middle of a game, something came up and Saburo has to leave the game. The state of the board at this point is described by a string S. There are |S| (the length of S) stones on the board, and each character in S represents the color of the i-th (1 ≦ i ≦ |S|) stone from the left. If the i-th character in S is B, it means that the color of the corresponding stone on the board is black. Similarly, if the i-th character in S is W, it means that the color of the corresponding stone is white.

Jiro wants all stones on the board to be of the same color. For this purpose, he will place new stones on the board according to the rules. Find the minimum number of new stones that he needs to place.

Constraints

1 ≦ |S| ≦ 10^5

Each character in S is B or W.

Input

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

S

Output

Print the minimum number of new stones that Jiro needs to place for his purpose.

Sample Input 1

BBBWW

Sample Output 1

1

By placing a new black stone to the right end of the row of stones, all white stones will become black. Also, by placing a new white stone to the left end of the row of stones, all black stones will become white.

In either way, Jiro's purpose can be achieved by placing one stone.

Sample Input 2

WWWWWW

Sample Output 2

0

If all stones are already of the same color, no new stone is necessary.

Sample Input 3

WBWBWBWBWB

Sample Output 3

9


import io.{StdIn => in}

object Main extends App {
  val s = in.readLine.map(c => if(c == 'W') true else false).toBuffer
  def rec(norm:Boolean,  cnt:Int, size:Int):Unit = {
    if(cnt == size || s(cnt) == norm) return
    else {
      s(cnt) = norm
      rec(norm, cnt+1, size)
    }
  }

  def f(norm:Boolean, cnt:Int):Int = {
    if(s.forall(_ == norm) || s.forall(_ == !norm)) cnt
    else {
      rec(norm, 0, s.size)
      norm +=: s
      f(!norm, cnt + 1)
    }
  }

  val ans = f(!s.head, 0)
  println(ans)
}


object Main {
  def main(args: Array[String]): Unit = {
    val source = readLine().split("").toList

    println(source.reduce {
      (prev, cur) => if (prev.toList.reverse.head.toString != cur) prev + cur else prev
    }.length - 1)

  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val source = readLine().split("").toList

    println(source.reduce {
      (prev, cur) => if (prev(prev.length).toString != cur) prev + cur else prev
    }.length - 1)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val source = readLine().split("").toList
    println(source.reduce {
      (prev, cur) => if (prev.reverse.head.toString != cur) prev + cur else prev
    }.length - 1)
  }
}


import scala.io.StdIn._
object Main extends App {
  println(readLine.split("((?<=B)(?=W)|(?<=W)(?=B))").size - 1)
}


import scala.io.StdIn._
object Main extends App {
  println(readLine.split("((?<=\\B)(?=W)|(?<=W)(?=\\B))").size - 1)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n, l = sc.nextInt()
  val s = List.fill(n)(sc.next())
  println(s.sorted.mkString)
}

Score : 200 points

Problem Statement

Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L.

She will concatenate all of the strings in some order, to produce a long string.

Among all strings that she can produce in this way, find the lexicographically smallest one.

Here, a string s=s_1s_2s_3...s_n is lexicographically smaller than another string t=t_1t_2t_3...t_m if and only if one of the following holds:

There exists an index i(1≦i≦min(n,m)), such that s_j = t_j for all indices j(1≦j<i), and s_i<t_i.

s_i = t_i for all integers i(1≦i≦min(n,m)), and n<m.

Constraints

1 ≦ N, L ≦ 100

For each i, the length of S_i equals L.

For each i, S_i consists of lowercase letters.

Input

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

N L
S_1
S_2
:
S_N

Output

Print the lexicographically smallest string that Iroha can produce.

Sample Input 1

3 3
dxx
axx
cxx

Sample Output 1

axxcxxdxx

The following order should be used: axx, cxx, dxx.


object Main extends App {
  val input = readLine.split(' ').map(_.toInt)
  val n = input(0)
  val l = input(1)

  val a = for(i <- 1 to n) yield readLine
  println(a.sorted.mkString)
}


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, l) = readIntLine
  val ss = readLines(n)

  println(ss.sorted.reduce(_ + _))
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datN, datL) = readLine.split(" ").map(_.toInt)
    val datS = for(i <- 1 to datN) yield (readLine.split(" ").head)

    val ans = datS.sorted.mkString
    println(ans)
  }
}


object Main extends App {
  val input = readLine
  val countOfWords = input.split(" ")(0).toInt
  def getWordsList(i: Int, list: List[String]): List[String] = {
    val word = readLine
    if(countOfWords < i ) list else getWordsList(i + 1, list :+ word)
  }
  val wordsList: List[String] = getWordsList(1, List.empty)
  println(wordsList.sorted.mkString(""))
}


object Main extends App {
  val Array(n,l) = readLine.split(" ").map{_.toInt}
  println((for (i <- 0 to n-1) yield {readLine}).sortWith{_ < _}.foldLeft(""){_ + _})
}


object Main extends App {
  var a = readLine.split(" ").map(_.toInt)
  val c = List.tabulate(a(0))(i => (readLine.toString)).sorted.mkString(",")
  print(c.replace(",",""))
}


object Main {

  def main(args: Array[String]): Unit = {
    import scala.io.StdIn._
    val Array(n, l) = readLine().split(" ").map(_.toInt)
    val S: Array[String] = (0 until n).map(_ => readLine()).toArray
    println(S.sorted.mkString)
  }

}


  // B - 文字列大好きいろはちゃんイージー / Iroha Loves Strings (ABC Edition) https://atcoder.jp/contests/abc042/tasks/abc042_b

  import io.Source

  object Main extends App {
    val xs = Source.stdin.getLines()
    xs.next() // N, Lをスキップ

    println(solve(xs))

    def solve(xs: Iterator[String]): String = {
      xs.toSeq.sorted.foldLeft("")((acc, s) => acc + s)
    }
  }


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn._
    val Array(n, l) = readLine().split(' ').map(_.toInt)
    val str = (0 until n).map(_ => readLine())
    println(str.sorted.fold("")(_ + _))
  }
}


import scala.io.StdIn

object Main extends App {
  val Array(n, l) = StdIn.readLine().split(" ").map(_.toInt)
  println((0 until n).map( _ => StdIn.readLine()).sorted.mkString(""))
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val n, l = sc.nextInt
  val list = List.fill(n)(sc.next).sorted.mkString
  println(list)
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val n, l = sc.nextInt
  val list = List.fill(n)(sc.next).sortBy(_.charAt(0)).mkString
  println(list)
}


object Main {
  var _buf = List[String]()
  def str : String = {
    if (_buf.isEmpty) _buf = io.StdIn.readLine().split(' ').toList
    val res = _buf.head
    _buf = _buf.tail
    return res
  }
  def strs(n:Int) : Array[String] = {
    return new Array[String](n).map(i => str)
  }
  def int : Int = { return str.toInt }
  def long : Long = { return str.toLong }
  def ints(n:Int) : Array[Int] = { return strs(n).map(_.toInt) }
  def longs(n:Int) : Array[Long] = { return strs(n).map(_.toLong) }

  def main(args:Array[String]) = {
    val (n, l) = (int, int)
    val s = strs(n)
    println (s.sorted.mkString(""))
  }
}


object Main extends App{
  val l1 = io.StdIn.readLine()
  val N = l1.split(" ")(0).toInt
  val L = l1.split(" ")(1).toInt

  val words = (0 until N).map((i) => {
    io.StdIn.readLine()
  })

  println(words.sorted.mkString(""))
}


object Main extends App{
  val l1 = io.StdIn.readLine()
  val N = l1.split(" ")(0).toInt
  val L = l1.split(" ")(1).toInt

  val words = (0 until L).map((i) => {
    io.StdIn.readLine()
  })

  println(words.sorted.mkString(""))
}