//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

  def nextDouble(): Double = next().toDouble

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) =>
      nodes(t).parent = Some(root(p))
      nodes(t).parent.get
  }
}

object Main {
  def solve(sc: => Scanner): Unit = {
    val X, Y, A, B, C = sc.nextInt()
    println(recursive(
      (Array.fill(A)((sc.nextLong(), 'P')) ++ Array.fill(B)((sc.nextLong(), 'Q')) ++ Array.fill(C)((sc.nextLong(), 'R'))).sorted.toList,
      A + B + C - X - Y,
      B + C - X,
      A + C - Y
    ))
  }

  def flip(A: Array[Boolean], B: Array[(Int, Long)]): Array[(Int, Long)] = {
    B.map { case (index, _) =>
      (index, (if (0 < index && A(index - 1)) B(index - 1)._2 else 0L) + (if (index + 1 < B.length && !A(index + 1)) B(index + 1)._2 else 0L))
    }
  }

  val mod: Long = (1e9 + 7).toLong

  @scala.annotation.tailrec
  def recursive(Arr: List[(Long, Char)], remaining: Int, remainingA: Int, remainingB: Int, sum: Long = 0): Long = {
    if (remaining == 0) Arr.map(_._1).sum + sum
    else {
      if (Arr.head._2 == 'P')
        if (remainingA > 0) recursive(Arr.tail, remaining - 1, remainingA - 1, remainingB, sum)
        else recursive(Arr.tail, remaining, remainingA, remainingB, sum + Arr.head._1)
      else if (Arr.head._2 == 'Q')
        if (remainingB > 0) recursive(Arr.tail, remaining - 1, remainingA, remainingB - 1, sum)
        else recursive(Arr.tail, remaining, remainingA, remainingB, sum + Arr.head._1)
      else recursive(Arr.tail, remaining - 1, remainingA - 1, remainingB - 1, sum)
    }
  }

  @scala.annotation.tailrec
  def factorial(now: Long, ans: Long = 1): Long = {
    if (now == 0) 0 else if (now == 1) ans else factorial(now - 1, now * ans)
  }

  implicit class implicitInt(val N: Int) {
    def times[B](function: Int => B): IndexedSeq[B] = (0 until N).map(function)
  }

  def calc(input: (Long, Long, Long, Long, Long, Long)): Long = {
    input match {
      case (a, b, c, x, y, z) => {
        var ans: Long = Long.MaxValue
        if (b >= 3 && (a >= 2 || c >= 2)) {
          ans = Math.min(ans, Math.max(a - (b - 1), 0) * x + Math.max(c - Math.min(a - 1, b - 2), 0) * z)
          ans = Math.min(ans, Math.max(a - Math.min(c - 1, b - 2), 0) * x + Math.max(c - (b - 1), 0) * z)
        }
        //        println(ans)
        if (b >= 2 && (a >= b && c >= b + 1)) {
          ans = Math.min(ans, y + Math.max(0, a - (c - 1)) * x)
        }
        //        println(ans)
        if (b >= 2 && (a >= b + 1 && c >= b)) {
          ans = Math.min(ans, y + Math.max(0, c - (a - 1)) * z)
        }
        //        println(ans)
        if (a >= 2 && c >= 2)
          if (a != c)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 1)) * y)
          else if (a >= 3 && c >= 3)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 2)) * y + Math.min(x, z))
        //        println(ans)
        if (ans == Long.MaxValue) ans = -1
        ans
      }
    }
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getFibonacci(prevprev: Long = 0, prev: Long = 1): Stream[Long] =
    Stream.cons(prevprev, getFibonacci(prev, prevprev + prev))

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

object Util {
  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getPrimeList: Stream[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: Stream[Long]): Stream[Long] =
    Stream.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): Stream[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  private val codeTable: List[(Int, String)] = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      @scala.annotation.tailrec
      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      @scala.annotation.tailrec
      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}

object PowMod {
  def naivePowMod(a: Long, k: Long, m: Long): Long = {
    var t: Long = 1
    val aMod: Long = a % m

    for (_ <- 1L to k) {
      t = ((t % m) * aMod) % m
    }
    t.toInt
  }

  def powMod(a: Long, k: Long, m: Long): Long = {
    if (k == 0) 1
    else {
      val t = powMod(a, k / 2, m)
      if ((k % 2) == 0) (t * t) % m else (((t * t) % m) * a) % m
    }
  }
}


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

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 Array(x, y, a, b, c) = in.readLine().split("\\s+").map(_.toInt)
    val ps = in.readLine().split("\\s+").map(_.toLong).sorted(Ordering[Long].reverse)
    val qs = in.readLine().split("\\s+").map(_.toLong).sorted(Ordering[Long].reverse)
    val rs = in.readLine().split("\\s+").map(_.toLong).sorted(Ordering[Long].reverse)

//    out.println((ps.take(x) ++ qs.take(y) ++ rs).sorted(Ordering[Long].reverse).take(x + y).sum)

    var result = 0L
    for (i <- 0 until x) {
      result += ps(i)
    }
    for (i <- 0 until y) {
      result += qs(i)
    }

    var pi = x - 1
    var qi = y - 1
    var ri = 0
    var break = false

    while (!break) {
      if ((pi < 0 || ps(pi) > rs(ri)) && (qi < 0 || qs(qi) > rs(ri))) {
        break = true
      } else if (pi >= 0 && (qi < 0 || ps(pi) < qs(qi))) {
        result = result - ps(pi) + rs(ri)
        pi -= 1
        ri += 1
      } else if (qi >= 0 && (pi < 0 || ps(pi) >= qs(qi))) {
        result = result - qs(qi) + rs(ri)
        qi -= 1
        ri += 1
      } else {
        break = true
      }
      if (ri == rs.length) {
        break = true
      }
    }

    out.println(result)
    out.flush()
  }
}

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

Score : 500 points

Problem Statement

You are going to eat X red apples and Y green apples.

You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C.

Before eating a colorless apple, you can paint it red or green, and it will count as a red or green apple, respectively.

From the apples above, you will choose the apples to eat while making the sum of the deliciousness of the eaten apples as large as possible.

Find the maximum possible sum of the deliciousness of the eaten apples that can be achieved when optimally coloring zero or more colorless apples.

Constraints

1 \leq X \leq A \leq 10^5

1 \leq Y \leq B \leq 10^5

1 \leq C \leq 10^5

1 \leq p_i \leq 10^9

1 \leq q_i \leq 10^9

1 \leq r_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y A B C
p_1 p_2 ... p_A
q_1 q_2 ... q_B
r_1 r_2 ... r_C

Output

Print the maximum possible sum of the deliciousness of the eaten apples.

Sample Input 1

1 2 2 2 1
2 4
5 1
3

Sample Output 1

12

The maximum possible sum of the deliciousness of the eaten apples can be achieved as follows:

Eat the 2-nd red apple.

Eat the 1-st green apple.

Paint the 1-st colorless apple green and eat it.

Sample Input 2

2 2 2 2 2
8 6
9 1
2 1

Sample Output 2

25

Sample Input 3

2 2 4 4 4
11 12 13 14
21 22 23 24
1 2 3 4

Sample Output 3

74

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 {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
  import java.util.Arrays.sort

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

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

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

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

  def solve(): Unit = {
    val X, Y, A, B, C = ni()
    val P = nal(A).sorted.reverse
    val Q = nal(B).sorted.reverse
    val R = nal(C).sorted.reverse
    var ans = 0L
    val cumR = cumSum(R)
    var sumP, sumQ = 0L
    var i, j = 0
    REP_r(min(C, X + Y) + 1) { c =>
      while(i + j + c < X + Y) {
        if ((i < min(A, X) && j < min(B, Y) && P(i) > Q(j)) || j == min(B, Y)) {
          sumP += P(i)
          i += 1
        } else {
          sumQ += Q(j)
          j += 1
        }
      }
      debug(s"i:$i j:$j")
      ans = max(ans, cumR(c) + sumP + sumQ)
    }
    out.println(ans)
  }
}


import scala.math.sqrt
object Main extends App {
  val in = new java.util.Scanner(System.in)
  val A, B, C = in.nextInt
  println(if (sqrt(A) + sqrt(B) < sqrt(C)) "Yes" else "No")
}

Score : 300 points

Problem Statement

Does \sqrt{a} + \sqrt{b} < \sqrt{c} hold?

Constraints

1 \leq a, b, c \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a \ b \ c

Output

If \sqrt{a} + \sqrt{b} < \sqrt{c}, print Yes; otherwise, print No.

Sample Input 1

2 3 9

Sample Output 1

No

\sqrt{2} + \sqrt{3} < \sqrt{9} does not hold.

Sample Input 2

2 3 10

Sample Output 2

Yes

\sqrt{2} + \sqrt{3} < \sqrt{10} holds.


//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

  def nextDouble(): Double = next().toDouble

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) =>
      nodes(t).parent = Some(root(p))
      nodes(t).parent.get
  }
}

object Main {
  def solve(sc: => Scanner): Unit = {
    val A, B, C = sc.nextLong()
    println(if (4 * A * B < (C - A - B) * (C - A - B)) "Yes" else "No")
  }

  def flip(A: Array[Boolean], B: Array[(Int, Long)]): Array[(Int, Long)] = {
    B.map { case (index, _) =>
      (index, (if (0 < index && A(index - 1)) B(index - 1)._2 else 0L) + (if (index + 1 < B.length && !A(index + 1)) B(index + 1)._2 else 0L))
    }
  }

  val mod: Long = (1e9 + 7).toLong

  @scala.annotation.tailrec
  def recursive(Arr: List[(Long, Char)], remaining: Int, remainingA: Int, remainingB: Int, sum: Long = 0): Long = {
    if (remaining == 0) Arr.map(_._1).sum + sum
    else {
      if (Arr.head._2 == 'P')
        if (remainingA > 0) recursive(Arr.tail, remaining - 1, remainingA - 1, remainingB, sum)
        else recursive(Arr.tail, remaining, remainingA, remainingB, sum + Arr.head._1)
      else if (Arr.head._2 == 'Q')
        if (remainingB > 0) recursive(Arr.tail, remaining - 1, remainingA, remainingB - 1, sum)
        else recursive(Arr.tail, remaining, remainingA, remainingB, sum + Arr.head._1)
      else recursive(Arr.tail, remaining - 1, remainingA - 1, remainingB - 1, sum)
    }
  }

  @scala.annotation.tailrec
  def factorial(now: Long, ans: Long = 1): Long = {
    if (now == 0) 0 else if (now == 1) ans else factorial(now - 1, now * ans)
  }

  implicit class implicitInt(val N: Int) {
    def times[B](function: Int => B): IndexedSeq[B] = (0 until N).map(function)
  }

  def calc(input: (Long, Long, Long, Long, Long, Long)): Long = {
    input match {
      case (a, b, c, x, y, z) => {
        var ans: Long = Long.MaxValue
        if (b >= 3 && (a >= 2 || c >= 2)) {
          ans = Math.min(ans, Math.max(a - (b - 1), 0) * x + Math.max(c - Math.min(a - 1, b - 2), 0) * z)
          ans = Math.min(ans, Math.max(a - Math.min(c - 1, b - 2), 0) * x + Math.max(c - (b - 1), 0) * z)
        }
        //        println(ans)
        if (b >= 2 && (a >= b && c >= b + 1)) {
          ans = Math.min(ans, y + Math.max(0, a - (c - 1)) * x)
        }
        //        println(ans)
        if (b >= 2 && (a >= b + 1 && c >= b)) {
          ans = Math.min(ans, y + Math.max(0, c - (a - 1)) * z)
        }
        //        println(ans)
        if (a >= 2 && c >= 2)
          if (a != c)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 1)) * y)
          else if (a >= 3 && c >= 3)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 2)) * y + Math.min(x, z))
        //        println(ans)
        if (ans == Long.MaxValue) ans = -1
        ans
      }
    }
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getFibonacci(prevprev: Long = 0, prev: Long = 1): Stream[Long] =
    Stream.cons(prevprev, getFibonacci(prev, prevprev + prev))

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

object Util {
  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getPrimeList: Stream[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: Stream[Long]): Stream[Long] =
    Stream.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): Stream[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  private val codeTable: List[(Int, String)] = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      @scala.annotation.tailrec
      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      @scala.annotation.tailrec
      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}

object PowMod {
  def naivePowMod(a: Long, k: Long, m: Long): Long = {
    var t: Long = 1
    val aMod: Long = a % m

    for (_ <- 1L to k) {
      t = ((t % m) * aMod) % m
    }
    t.toInt
  }

  def powMod(a: Long, k: Long, m: Long): Long = {
    if (k == 0) 1
    else {
      val t = powMod(a, k / 2, m)
      if ((k % 2) == 0) (t * t) % m else (((t * t) % m) * a) % m
    }
  }
}


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.map(_.split(' ').map(_.toLong))
  val A = BigInt(ls(0)(0))
  val B = BigInt(ls(0)(1))
  val C = BigInt(ls(0)(2))

  //A + B + 2sqrt(AB) < C
  //val left = Math.sqrt(A.toLong * B) * 2
  //val right = C.toLong - A - B
  val left = A*B - C*C + A*B
  val right = A*(A - C*2) + B*(B - C*2)
  //println(left)
  //println(right)
  val ret = left < right
  println(if(ret) "Yes" else "No")
}


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.map(_.split(' ').map(_.toLong))
  val A = ls(0)(0).toLong
  val B = ls(0)(1).toLong
  val C = ls(0)(2).toLong

  //A + B + 2sqrt(AB) < C
  //val left = Math.sqrt(A.toLong * B) * 2
  //val right = C.toLong - A - B
  val left = A*B - C*C + A*B
  val right = A*(A - C*2) + B*(B - C*2)
  //println(left)
  //println(right)
  val ret = left < right
  println(if(ret) "Yes" else "No")
}


object Main extends App {
	val Array(a, b, c) = scala.io.StdIn.readLine.split(" ").map(_.toLong)
	val tp1 = scala.math.sqrt(a) + scala.math.sqrt(b)
	val tp2 = scala.math.sqrt(c)

	if(tp1 < tp2 ) println("Yes")
	else println("No")
}


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.map(_.split(' ').map(_.toLong))
  val A = ls(0)(0)
  val B = ls(0)(1)
  val C = ls(0)(2)

  //A + B + 2sqrt(AB) < C
  val left = Math.sqrt(A.toLong * B) * 2
  val right = C.toLong - A - B
  //println(left)
  //println(right)
  val ret = left < right
  println(if(ret) "Yes" else "No")
}


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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
  import java.util.Arrays.sort

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

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

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

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

  def solve(): Unit = {
    val a, b, c = nl()
    val cab = c - a - b
    val ans = if (cab > 0 && 4 * a * b < cab * cab) "Yes" else "No"
    out.println(ans)
  }
}


object Main extends App {
  val in = scala.io.Source.stdin.getLines.toSeq
  val ls = in.map(_.split(' ').map(_.toLong))
  val A = ls(0)(0)
  val B = ls(0)(1)
  val C = ls(0)(2)

  //A + B + 2sqrt(AB) < C
  val left = Math.sqrt(A.toDouble * B) * 2
  val right = C - A - B
  //println(left)
  //println(right)
  val ret = left < right
  println(if(ret) "Yes" else "No")
}


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

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 Array(a, b, c) = in.readLine().split("\\s+").map(i => BigInt(i.toInt))

    out.println(
      if (4 * a * b < (c - a - b) * (c - a - b)) {
        "Yes"
      } else {
        "No"
      }
    )
    out.flush()
  }
}


import scala.collection.immutable.HashSet

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, M = sc.nextInt()
  val pairs = HashSet.fill(M)(sc.nextInt() - 1 -> sc.next().toCharArray.head)
  val isMatched = (i: String) => pairs.forall { case (s, c) => i(s) == c }
  val range = if (N == 1) 0.to(9) else math.pow(10, N - 1).toInt.to(("9" * N).toInt)
  println(range.find(i => isMatched(i.toString)).getOrElse(-1))
}

Score : 300 points

Problem Statement

If there is an integer not less than 0 satisfying the following conditions, print the smallest such integer; otherwise, print -1.

The integer has exactly N digits in base ten. (We assume 0 to be a 1-digit integer. For other integers, leading zeros are not allowed.)

The s_i-th digit from the left is c_i. \left(i = 1, 2, \cdots, M\right)

Constraints

All values in input are integers.

1 \leq N \leq 3

0 \leq M \leq 5

1 \leq s_i \leq N

0 \leq c_i \leq 9

Input

Input is given from Standard Input in the following format:

N M
s_1 c_1
\vdots
s_M c_M

Output

Print the answer.

Sample Input 1

3 3
1 7
3 2
1 7

Sample Output 1

702

702 satisfies the conditions - its 1-st and 3-rd digits are 7 and 2, respectively - while no non-negative integer less than 702 satisfies them.

Sample Input 2

3 2
2 1
2 3

Sample Output 2

-1

Sample Input 3

3 1
1 0

Sample Output 3

-1


import scala.collection.immutable.HashSet

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, M = sc.nextInt()
  val pairs = HashSet.fill(M)(sc.nextInt() - 1 -> sc.next().toCharArray.head)
  val isMatched = (i: String) => pairs.forall { case (s, c) => i(s) == c }
  println {
    math.pow(10, N - 1).toInt.to(("9" * N).toInt).collectFirst {
      case i if isMatched(i.toString) => i
    }.getOrElse(-1)
  }
}


import scala.collection.immutable.HashSet

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, M = sc.nextInt()
  val pairs = HashSet.fill(M)(sc.nextInt() -> sc.nextInt())
  val map = pairs.toMap
  println {
    if (pairs.size == map.size && !(N != 1 && map.get(1).contains(0))) {
      1.to(N).foldLeft("")((acc, i) => acc + map.getOrElse(i, 0))
    } else {
      "-1"
    }
  }
}


import scala.io.StdIn._

object Main extends App {

  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val hintArr = Array.fill(m)(readLine().split(" ").map(_.toInt))

  def solve(): Int = {
    val default = Map.empty[Int, Int]
    val digitAndNumMap = hintArr.foldLeft(default) { (acc, hint) =>
      acc.get(hint(0)) match {
        case Some(v) =>
          if(v == hint(1)) acc else return -1
        case None =>
          if(n != 1 && hint(0) == 1 && hint(1) == 0) return -1
          else acc.updated(hint(0), hint(1))
      }
    }
    val ansStr = (1 to n).map { i =>
      digitAndNumMap.getOrElse(i, 0)
    }.mkString("")
    if(n != 1 && ansStr.startsWith("0")) ansStr.updated(0, '1').mkString("").toInt
    else ansStr.toInt
  }

  println(solve())

}


import scala.io.StdIn._

object Main extends App {

  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val hintArr = Array.fill(m)(readLine().split(" ").map(_.toInt))

  def solve(): Int = {
    val default = Map.empty[Int, Int]
    val digitAndNumMap = hintArr.foldLeft(default) { (acc, hint) =>
      acc.get(hint(0)) match {
        case Some(v) =>
          if(v == hint(1)) acc else return -1
        case None =>
          if(n != 1 && hint(0) == 1 && hint(1) == 0) return -1
          else acc.updated(hint(0), hint(1))
      }
    }
    (1 to n).map { i =>
      if(i == 1) digitAndNumMap.getOrElse(i, 1)
      else digitAndNumMap.getOrElse(i, 0)
    }.mkString("").toInt
  }

  println(solve())

}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n: Int = sc.nextInt
  val m: Int = sc.nextInt()
  val list: List[(Int, Int)] = List.fill(m)(sc.nextInt, sc.nextInt())

  val checkedMap = list.groupBy(_._1).values.foldLeft(Map[Int, Int]())((acc ,c) => {
    if (c.count(_ != c.head) != 0) {
      // 一つの桁について、複数の値が指定されていた場合は -1 を追加。
      acc.updated(c.head._1, -1)
    } else if (c.head._1 == 1 && c.head._2 == 0 && n != 1) {
      acc.updated(c.head._1, -1)
    } else {
      // 一つの桁について、指定されていた値が一つだけであれば、その桁と値のペアを Map に追加。
      acc.updated(c.head._1, c.head._2)
    }
  })

  val validatedMap = Range(1, n + 1).toList.foldLeft(Map[Int, Int]())((acc, c) => {
    acc.updated(c, checkedMap.getOrElse(c, 0))
  })

  if(validatedMap.values.toSeq.contains(-1)) {
    println(-1)
  } else {
    println(validatedMap.map(x => {
      if (x._1 == 1 && x._2 == 0 && n != 1) "1" else x._2.toString
    }).mkString(""))
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n: Int = sc.nextInt
  val m: Int = sc.nextInt()
  val list: List[(Int, Int)] = List.fill(m)(sc.nextInt, sc.nextInt())

  val checkedMap = list.groupBy(_._1).values.foldLeft(Map[Int, Int]())((acc ,c) => {
    if (c.count(_ != c.head) != 0) {
      // 一つの桁について、複数の値が指定されていた場合は -1 を追加。
      acc.updated(-1, -1)
    } else {
      // 一つの桁について、指定されていた値が一つだけであれば、その桁と値のペアを Map に追加。
      acc.updated(c.head._1, c.head._2)
    }
  })
  if ((checkedMap.getOrElse(checkedMap.keys.max, 0) == 0 && n != 1) || checkedMap.contains(-1)) {
    println(-1)
  } else {
    println(x.toList.map(_.toString).mkString(""))
  }
  val x = for {
    x <- 1 to n
    hoge = checkedMap.getOrElse(x, 0)
  } yield hoge
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n: Int = sc.nextInt
  val m: Int = sc.nextInt()
  val list: List[(Int, Int)] = List.fill(m)(sc.nextInt, sc.nextInt())

  val checkedMap = list.groupBy(_._1).values.foldLeft(Map[Int, Int]())((acc ,c) => {
    if (c.count(_ != c.head) != 0) {
      // 一つの桁について、複数の値が指定されていた場合は -1 を追加。
      acc.updated(-1, -1)
    } else {
      // 一つの桁について、指定されていた値が一つだけであれば、その桁と値のペアを Map に追加。
      acc.updated(c.head._1, c.head._2)
    }
  })
  if ((checkedMap.getOrElse(checkedMap.keys.max, 0) == 0 && n != 1) || checkedMap.contains(-1)) {
    println(-1)
  }
  val x = for {
    x <- 1 to n
    hoge = checkedMap.getOrElse(x, 0)
  } yield hoge
  println(x.toList.map(_.toString).mkString(""))
}


object Main extends App{
  import scala.io.StdIn._
  val Array(n,m)=readLine().split(" ").map(_.toInt)
  var a:Int=_
  var s=new Array[Int](n);var o=new Array[Boolean](n);var flag=true;var f:Array[Int]=_
  for{i <- (0 until(m))}{
    f=readLine().split(" ").map(_.toInt)
    if(s(f(0)-1)!=f(1)&&o(f(0)-1)){
      flag=false
    }
    o(f(0)-1)=true
    s(f(0)-1)=f(1)
  }
  if(s(0)!=0||n!=1) {
    for {i <- (0 until (n))} {
      a *= 10
      a += s(i)
    }
  }else if(n==1){
    a=0
  } else{
    flag=false
  }
  println(if(flag)a else -1)
}


object Main extends App{
  import scala.io.StdIn._
  val Array(n,m)=readLine().split(" ").map(_.toInt)
  var ans=new Array[Int](n);var a:Int=_
  var s=new Array[Int](n);var o=new Array[Boolean](n);var flag=true;var f:Array[Int]=_
  for{i <- (0 until(m))}{
    f=readLine().split(" ").map(_.toInt)
    if(s(f(0)-1)!=f(1)&&o(f(0)-1)){
      flag=false
    }
    o(f(0)-1)=true
    s(f(0)-1)=f(1)
  }
  if(s(0)!=0) {
    for {i <- (0 until (n))} {
      a *= 10
      ans(i) = s(i)
      a += ans(i)
    }
  }else{
    flag=false
  }
  println(if(flag)a else -1)
}


object Main extends App{
  import scala.io.StdIn._
  val Array(n,m)=readLine().split(" ").map(_.toInt)
  var ans=new Array[Int](n);var a:Int=_
  var s=new Array[Int](n);var flag=true;var f:Array[Int]=_
  for{i <- (0 until(m))}{
    f=readLine().split(" ").map(_.toInt)
    if(s(f(0)-1)!=f(1)&&f(1)==0){
      flag=false
    }
    s(f(0)-1)=f(1)
  }
  if(s(0)!=0) {
    for {i <- (0 until (n))} {
      a *= 10
      ans(i) = s(i)
      a += ans(i)
    }
  }else{
    flag=false
  }
  println(if(flag)a else -1)
}


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N, M = in.nextInt
  val sc = (1 to M).map(_ => (in.nextInt, in.nextInt)).distinct.groupBy(_._1).mapValues(_.map(_._2))

  def proc(pos: Int, num: Int): Int = {
    if (pos > N) num
    else {
      sc.get(pos) match {
        case None => proc(pos + 1, num * 10 + (if (pos == 1) 1 else 0))
        case Some(l) =>
          if (l.size > 1 || (N > 1 && l.head == 0 && pos == 1)) -1
          else proc(pos + 1, num * 10 + l.head)
      }
    }
  }

  println(proc(1, 0))
}


//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

  def nextDouble(): Double = next().toDouble

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) =>
      nodes(t).parent = Some(root(p))
      nodes(t).parent.get
  }
}

object Main {
  def solve(sc: => Scanner): Unit = {
    val N = sc.nextInt()
    val A = Array.fill(sc.nextInt())((sc.nextInt(), sc.nextInt()))
    println(
      (0 until 1000)
        .filter(x => {
          val now = x / math.pow(10, N - 1).toLong
          1 <= now && now <= 9 || x == 0 && N == 1
        }).find(x => A.forall(y => {
        x / math.pow(10, N - y._1).toLong % 10 == y._2
      }))
        .getOrElse(-1)
    )
  }

  def flip(A: Array[Boolean], B: Array[(Int, Long)]): Array[(Int, Long)] = {
    B.map { case (index, _) =>
      (index, (if (0 < index && A(index - 1)) B(index - 1)._2 else 0L) + (if (index + 1 < B.length && !A(index + 1)) B(index + 1)._2 else 0L))
    }
  }

  val mod: Long = (1e9 + 7).toLong

  @scala.annotation.tailrec
  def recursive(sc: => Scanner, S: Long, Flip: Boolean, ans: String): String = {
    if (S == 0) if (Flip) ans else ans.reverse
    else {
      val Q = sc.nextInt()
      if (Q == 1) recursive(sc, S - 1, !Flip, ans)
      else {
        val F = sc.nextInt()
        if (Flip == (F == 1)) recursive(sc, S - 1, Flip, sc.next() + ans)
        else recursive(sc, S - 1, Flip, ans + sc.next())
      }
    }
  }

  @scala.annotation.tailrec
  def factorial(now: Long, ans: Long = 1): Long = {
    if (now == 0) 0 else if (now == 1) ans else factorial(now - 1, now * ans)
  }

  implicit class implicitInt(val N: Int) {
    def times[B](function: Int => B): IndexedSeq[B] = (0 until N).map(function)
  }

  def calc(input: (Long, Long, Long, Long, Long, Long)): Long = {
    input match {
      case (a, b, c, x, y, z) => {
        var ans: Long = Long.MaxValue
        if (b >= 3 && (a >= 2 || c >= 2)) {
          ans = Math.min(ans, Math.max(a - (b - 1), 0) * x + Math.max(c - Math.min(a - 1, b - 2), 0) * z)
          ans = Math.min(ans, Math.max(a - Math.min(c - 1, b - 2), 0) * x + Math.max(c - (b - 1), 0) * z)
        }
        //        println(ans)
        if (b >= 2 && (a >= b && c >= b + 1)) {
          ans = Math.min(ans, y + Math.max(0, a - (c - 1)) * x)
        }
        //        println(ans)
        if (b >= 2 && (a >= b + 1 && c >= b)) {
          ans = Math.min(ans, y + Math.max(0, c - (a - 1)) * z)
        }
        //        println(ans)
        if (a >= 2 && c >= 2)
          if (a != c)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 1)) * y)
          else if (a >= 3 && c >= 3)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 2)) * y + Math.min(x, z))
        //        println(ans)
        if (ans == Long.MaxValue) ans = -1
        ans
      }
    }
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getFibonacci(prevprev: Long = 0, prev: Long = 1): Stream[Long] =
    Stream.cons(prevprev, getFibonacci(prev, prevprev + prev))

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

object Util {
  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getPrimeList: Stream[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: Stream[Long]): Stream[Long] =
    Stream.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): Stream[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  private val codeTable: List[(Int, String)] = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      @scala.annotation.tailrec
      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      @scala.annotation.tailrec
      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}

object PowMod {
  def naivePowMod(a: Long, k: Long, m: Long): Long = {
    var t: Long = 1
    val aMod: Long = a % m

    for (_ <- 1L to k) {
      t = ((t % m) * aMod) % m
    }
    t.toInt
  }

  def powMod(a: Long, k: Long, m: Long): Long = {
    if (k == 0) 1
    else {
      val t = powMod(a, k / 2, m)
      if ((k % 2) == 0) (t * t) % m else (((t * t) % m) * a) % m
    }
  }
}


import io.StdIn._

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

  val constraints = Range(0, M).map { _ =>
    val SC = readLine.split(" ").map(_.toInt)
    (SC(0) - 1, SC(1))
  }

  val ans = Range.inclusive(0, 999).find { n =>
    val ketaToDigit = n.toString.map(_.toInt - 48)
    println(ketaToDigit)

    ketaToDigit.length == N &&
      constraints.forall { case (s, c) => ketaToDigit(s) == c }
  }

  println(ans.getOrElse(-1))
}


import io.StdIn._

object Main extends App {

  val NM = readLine.split(" ").map(_.toInt)
  val N = NM(0)
  val M = NM(1)

  val constraints = Range(0, M).map { _ =>
    val SC = readLine.split(" ").map(_.toInt)
    (SC(0), SC(1))
  }

  val ans = Range.inclusive(0, 999).find { n =>
    var keta = N
    val ketaToDigit = Array.fill[Int](N)(0)
    var nx = n

    do {
      ketaToDigit(keta) = nx % 10
      nx /= 10
      keta -= 1
    } while (nx >= 10)

    keta == 1 && constraints.forall { case (s, c) => ketaToDigit(s) == c }
  }

  println(ans.getOrElse(-1))
}


object Main extends App {
	val sc = new java.util.Scanner(System.in)
	val pw = new java.io.PrintWriter(System.out)

	val n, m = sc.nextInt

	val a = Array.fill(n)(-1)
	var flag = true

	Seq.fill(m)((sc.nextInt-1, sc.nextInt)) foreach { case (s, c) =>
		if (a(s) != -1 && a(s) != c) flag = false
		a(s) = c
	}

	if (n >= 2 && a(0) == -1) a(0) == 1
	val r = a.map(e => if (e == -1) "0" else s"$e").mkString.toInt.toString

	pw.println( if (flag && r.size == n) r.toInt else -1 )
	pw.flush()
}


object Main extends App {
  val nmInput  = scala.io.StdIn.readLine()
  val nmArray = nmInput.split(" ").map(_.toInt).toSeq
  val n = nmArray(0)
  val m = nmArray(1)

  var scArray = Vector.empty[(Int, Int)]
  (1 to m).foreach { _=>
    val scInput  = scala.io.StdIn.readLine()
    val scInputArray = scInput.split(" ").map(_.toInt)
    val scTuple = (scInputArray(0), scInputArray(1))
    if (scArray.find(sc => sc == scTuple).isEmpty) {
      scArray :+= scTuple
    }
  }
  scArray = scArray.sortBy(sc => sc._1)
  if(n == 1 && scArray.length == 1 && scArray.head._1 == 1 && scArray.head._2 == 0) {
    println(0)
  } else if (
    (scArray.length > 0 && scArray.head._1 == 1 && scArray.head._2 == 0) ||
    scArray.groupBy(sc => sc._1).map(sc => sc._2.size).find(sc => sc >= 2).isDefined
  ) {
    println(-1)
  } else if(scArray.length == 0) {
    if(n == 1) {
      println(0)
    } else {
      var result = ""
      (1 to n).foreach { i =>
        if(i == 1) {
          result = "1"
        } else {
          result = result + "0"
        }
      }
      println(result)
    }
  } else {
    var result = ""
    (1 to n).foreach { i =>
      val sc = scArray.find(sc => sc._1 == i)
      if (sc.isEmpty) {
        if(i == 1) {
          result = "1"
        } else {
          result = result + "0"
        }
      } else {
        result = result + sc.get._2.toString
      }
    }
    println(result)
  }

}


object Main extends App {
  val nmInput  = scala.io.StdIn.readLine()
  val nmArray = nmInput.split(" ").map(_.toInt).toSeq
  val n = nmArray(0)
  val m = nmArray(1)

  var scArray = Vector.empty[(Int, Int)]
  (1 to m).foreach { _=>
    val scInput  = scala.io.StdIn.readLine()
    val scInputArray = scInput.split(" ").map(_.toInt)
    val scTuple = (scInputArray(0), scInputArray(1))
    if (scArray.find(sc => sc == scTuple).isEmpty) {
      scArray :+= scTuple
    }
  }
  scArray = scArray.sortBy(sc => sc._1)
  if (
    (scArray.length != 0 && scArray.head._1 == 1 && scArray.head._2 == 0) ||
    scArray.groupBy(sc => sc._1).map(sc => sc._2.size).find(sc => sc >= 2).isDefined
  ) {
    println(-1)
  } else if(scArray.length == 0) {
    if(n == 1) {
      println(0)
    } else {
      println(-1)
    }
  } else {
    var result = ""
    (1 to n).foreach { i =>
      val sc = scArray.find(sc => sc._1 == i)
      if (sc.isEmpty) {
        if(i == 1) {
          result = "1"
        } else {
          result = result + "0"
        }
      } else {
        result = result + sc.get._2.toString
      }
    }
    println(result)
  }

}


object Main {
  def main(args:Array[String]) {
    val read = readLine().split(' ').map(_.toInt)
    var N = read(0)
    var M = read(1)
    var ans = 0
    var anslist = Array.fill(N)(-1)
    for(i <- 0 until M) {
      var sc = readLine().split(' ').map(_.toInt)
      if(sc(0) == 1 && sc(1) == 0) ans = -1
      else if(anslist(sc(0) - 1) == -1 || anslist(sc(0) - 1) == sc(1)) anslist(sc(0) - 1) = sc(1)
      else ans = -1
    }
    if(ans != -1) {
      var ind = 0
      for(i <- anslist.size - 1 to 0 by -1) {
        if(i == 0) anslist(i) = 1
        else if(anslist(i) == -1) anslist(i) = 0
        ans += anslist(ind) * math.pow(10, i).toInt
        ind += 1
      }
    }
    println(ans)
  }
}


object Main extends App {
  val nmInput  = scala.io.StdIn.readLine()
  val nmArray = nmInput.split(" ").map(_.toInt).toSeq
  val n = nmArray(0)
  val m = nmArray(1)

  var scArray = Vector.empty[(Int, Int)]
  (1 to m).foreach { _=>
    val scInput  = scala.io.StdIn.readLine()
    val scInputArray = scInput.split(" ").map(_.toInt)
    val scTuple = (scInputArray(0), scInputArray(1))
    if (scArray.find(sc => sc == scTuple).isEmpty) {
      scArray :+= scTuple
    }
  }
  scArray = scArray.sortBy(sc => sc._1)
  if (
    (scArray.length != 0 && scArray.head._1 == 1 && scArray.head._2 == 0) ||
    scArray.groupBy(sc => sc._1).map(sc => sc._2.size).find(sc => sc >= 2).isDefined
  ) {
    println(-1)
  } else if(scArray.length == 0) {
    println(0)
  } else {
    var result = ""
    (1 to n).foreach { i =>
      val sc = scArray.find(sc => sc._1 == i)
      if (sc.isEmpty) {
        if(n == 1 && i == 1) {
          result = "0"
        } else if (i == 1) {
          result = "1"
        } else {
          result = result + "0"
        }
      } else {
        result = result + sc.get._2.toString
      }
    }
    println(result)
  }

}


object Main extends App {
  val nmInput  = scala.io.StdIn.readLine()
  val nmArray = nmInput.split(" ").map(_.toInt).toSeq
  val n = nmArray(0)
  val m = nmArray(1)

  var scArray = Vector.empty[(Int, Int)]
  (1 to m).foreach { _=>
    val scInput  = scala.io.StdIn.readLine()
    val scInputArray = scInput.split(" ").map(_.toInt)
    val scTuple = (scInputArray(0), scInputArray(1))
    if (scArray.find(sc => sc == scTuple).isEmpty) {
      scArray :+= scTuple
    }
  }
  scArray = scArray.sortBy(sc => sc._1)
  if (
    (scArray.length != 0 && scArray.head._1 == 1 && scArray.head._2 == 0) ||
    scArray.groupBy(sc => sc._1).map(sc => sc._2.size).find(sc => sc >= 2).isDefined
  ) {
    println(-1)
  } else if(scArray.length == 0) {
    println(0)
  } else {
    var result = ""
    (1 to n).foreach { i =>
      val sc = scArray.find(sc => sc._1 == i)
      if (sc.isEmpty) {
        if(i == 1) {
          result = "1"
        } else {
          result = result + "0"
        }
      } else {
        result = result + sc.get._2.toString
      }
    }
    println(result)
  }

}


import io.StdIn._

object Main extends App {

  var range = Range.inclusive(0, 999).toArray

  val NM = readLine.split(" ").map(_.toInt)
  val N = NM(0)
  val M = NM(1)
  range = range.filter { n =>
    N match {
      case 1 => n < 10
      case 2 => n >= 10 && n < 100
      case 3 => n >= 100
    }
  }

  for (_ <- 0 until M) {
    val SC = readLine.split(" ").map(_.toInt)
    val S = SC(0)
    val C = SC(1)

    range = range.filter { n =>

      (N, S) match {
        case (3, 1) => n / 100 == C
        case (3, 2) => (n / 10) % 10 == C
        case (3, 3) => n % 10 == C

        case (2, 1) => n / 10 == C
        case (2, 2) => n % 10 == C

        case (1, 1) => n == C
        case _ => false
      }
    }
  }

  println(if(range.isEmpty) -1 else range(0))
}


import io.StdIn._

object Main extends App {

  var range = Range.inclusive(0, 999).toArray

  val NM = readLine.split(" ").map(_.toInt)
  val N = NM(0)
  val M = NM(1)
  range = range.filter { n =>
    N match {
      case 1 => n < 10
      case 2 => n >= 10 && n < 100
      case 3 => n >= 100
    }
  }

  for (_ <- 0 until M) {
    val SC = readLine.split(" ").map(_.toInt)
    val S = SC(0)
    val C = SC(1)

    range = range.filter { n =>

      (N, S) match {
        case (3, 3) => n % 100 == C
        case (3, 2) => (n / 10) % 10 == C
        case (3, 1) => n / 100 == C

        case (2, 2) => n % 10 == C
        case (2, 1) => n / 10 == C

        case (1, 1) => n == C
        case _ => false
      }
    }
  }

  println( if(range.isEmpty) -1 else range(0))
}


object Main extends App {
	val sc = new java.util.Scanner(System.in)
	val pw = new java.io.PrintWriter(System.out)

	val n, m = sc.nextInt

	val a = Array.fill(n)(-1)
	var flag = true

	Seq.fill(m)((sc.nextInt-1, sc.nextInt)) foreach { case (s, c) =>
		if (a(s) != -1 && a(s) != c) flag = false
		a(s) = c
	}

	if (n != 1 && a(0) == 0) flag = false
	if (a(0) == -1) a(0) == 1

	pw.println( if (flag) a.map(e => if (e == -1) "0" else s"$e").mkString.toInt else -1 )
	pw.flush()
}


object Main extends App {
	val sc = new java.util.Scanner(System.in)
	val pw = new java.io.PrintWriter(System.out)

	val n, m = sc.nextInt

	val a = Array.fill(n)(-1)
	var flag = true

	Seq.fill(m)((sc.nextInt-1, sc.nextInt)) foreach { case (s, c) =>
		if (a(s) != -1 && a(s) != c) flag = false
		a(s) = c
	}

	if (a(0) == 0) flag = false
	if (a(0) == -1) a(0) == 1

	pw.println( if (flag) a.map(e => if (e == -1) "0" else s"$e").mkString.toInt else -1 )
	pw.flush()
}


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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, m = sc.nextInt()
    val ss = new Array[Int](m)
    val cs = new Array[Int](m)
    val num = Array.fill[Int](n)(-1)
    var flg = true
    for (i <- 0 until m) {
      ss(i) = sc.nextInt()
      cs(i) = sc.nextInt()

    }

    for (i <- 0 until m) {
      if (num(ss(i) - 1) == -1) {
        num(ss(i) - 1) = cs(i)
      } else if (num(ss(i) - 1) != cs(i)) {
        flg = false
      }
    }

    if (!flg) {
      println(-1)
      return
    } else if (n > 1 && num(0) == 0) {
      println(-1)
      return
    }

    // これはひどい。。
    if (n == 1 && m == 0) {
      num(0) = 0
    }

    if (num(0) == -1) {
      num(0) = 1
    }
    for (i <- 1 until n) {
      if (num(i) == -1) {
        num(i) = 0
      }
    }

    println(num.mkString(""))
  }
}


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

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, m = sc.nextInt()
    val ss = new Array[Int](m)
    val cs = new Array[Int](m)
    val num = Array.fill[Int](n)(-1)
    var flg = true
    for (i <- 0 until m) {
      ss(i) = sc.nextInt()
      cs(i) = sc.nextInt()

    }

    for (i <- 0 until m) {
      if (num(ss(i) - 1) == -1) {
        num(ss(i) - 1) = cs(i)
      } else if (num(ss(i) - 1) != cs(i)) {
        flg = false
      }
    }

    if (!flg) {
      println(-1)
      return
    } else if (n > 1 && num(0) == 0) {
      println(-1)
      return
    }

    if (num(0) == -1) {
      num(0) = 1
    }
    for (i <- 1 until n) {
      if (num(i) == -1) {
        num(i) = 0
      }
    }

    println(num.mkString(""))

  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

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

  val N = in.next().toInt
  var K = in.next().toLong
  val A = new Array[Long](N)
  var zero = 0L
  var _posi = List[Long]()
  var _nega = List[Long]()
  for (i <- 0 until N) {
    val now = in.next().toLong
    A(i) = now

    if (now == 0)
      zero += 1
    else if (now < 0)
      _nega = now :: _nega
    else
      _posi = now :: _posi
  }

  val posi = _posi.toArray.sorted
  val nega = _nega.toArray.sorted.reverse

  //
  // 条件を満たす最小の値を返す
  def binarySearch(_min: Long, _max: Long, k: Long): Long = {
    def check(i: Long): Boolean = {
      var cnt = 0

      var pos = 0
      var neg = 0
      while (neg < negaNum) {
        if (nega(neg) * posi(pos) <= i) {
          if (pos == posiNum - 1) {
            cnt += pos+1
            neg += 1
          }
          else
            pos += 1
        }
        else {
          cnt += pos
          neg += 1
        }
      }

      cnt >= k
    }

    def func(min: Long, max: Long): Long = {
      val mid: Long = (max + min) / 2
        (max - min) match{
        case 0 | 1 =>
          check(min) match{
            case true  => min
            case false => max
          }
        case _ =>
          (check(mid)) match{
            case true  => func(min, mid)
            case false => func(mid, max)
          }
      }
    }

    func(_min, _max)
  }

  // 条件を満たす最小の値を返す
  def binarySearch2(_min: Long, _max: Long, k: Long): Long = {
    def check(i: Long): Boolean = {
      var cnt = 0

      var l = 0; var r = posiNum - 1
      while (r >= 0) {
        if (posi(l) * posi(r) <= i) {
          if (l == posiNum - 1) {
            cnt += l
            r -= 1
          }
          else {
            l += 1
          }
        }
        else {
          cnt += l
          r -= 1
        }
      }

      cnt -= posi.count(n => n * n <= i)

      var res = cnt / 2
      cnt = 0

      // nega
      l = 0; r = negaNum - 1
      while (r >= 0) {
        if (nega(l) * nega(r) <= i) {
          if (l == negaNum - 1) {
            cnt += l
            r -= 1
          }
          else {
            l += 1
          }
        }
        else {
          cnt += l
          r -= 1
        }
      }

      cnt -= nega.count(n => n * n <= i)
      res += cnt / 2

      res >= k
    }

    def func(min: Long, max: Long): Long = {
      val mid: Long = (max + min) / 2
        (max - min) match{
        case 0 | 1 =>
          check(min) match{
            case true  => min
            case false => max
          }
        case _ =>
          (check(mid)) match{
            case true  => func(min, mid)
            case false => func(mid, max)
          }
      }
    }

    func(_min, _max)
  }

  val posiNum = posi.length
  val negaNum = nega.length

  var ans = 0L
  breakable {
    val minus = posiNum * negaNum
    if (K <= minus) {
      ans = binarySearch(-1e18.toLong, -1, K)
      break
    }
    K -= minus

    val hoge = zero * (posiNum + negaNum) + (zero * (zero - 1)) / 2
    if (K <= hoge) {
      ans = 0
      break
    }
    K -= hoge

    ans = binarySearch2(1, 1e18.toLong, K)
  }

  println(ans)
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

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

Score: 400 points

Problem Statement

We have N integers A_1, A_2, ..., A_N.

There are \frac{N(N-1)}{2} ways to choose two of them and form a pair. If we compute the product of each of those pairs and sort the results in ascending order, what will be the K-th number in that list?

Constraints

All values in input are integers.

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

1 \leq K \leq \frac{N(N-1)}{2}

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

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the answer.

Sample Input 1

4 3
3 3 -4 -2

Sample Output 1

-6

There are six ways to form a pair. The products of those pairs are 9, -12, -6, -12, -6, 8.

Sorting those numbers in ascending order, we have -12, -12, -6, -6, 8, 9. The third number in this list is -6.

Sample Input 2

10 40
5 4 3 2 -1 0 0 0 0 0

Sample Output 2

6

Sample Input 3

30 413
-170202098 -268409015 537203564 983211703 21608710 -443999067 -937727165 -97596546 -372334013 398994917 -972141167 798607104 -949068442 -959948616 37909651 0 886627544 -20098238 0 -948955241 0 -214720580 277222296 -18897162 834475626 0 -425610555 110117526 663621752 0

Sample Output 3

448283280358331064


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

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

  val N = in.next().toInt
  var K = in.next().toLong
  val A = new Array[Long](N)
  var zero = 0L
  var _posi = List[Long]()
  var _nega = List[Long]()
  for (i <- 0 until N) {
    val now = in.next().toLong
    A(i) = now

    if (now == 0)
      zero += 1
    else if (now < 0)
      _nega = now :: _nega
    else
      _posi = now :: _posi
  }

  val posi = _posi.toArray.sorted
  val nega = _nega.toArray.sorted.reverse
  // println(posi.toList)
  // println(nega.toList)

  //
  // 条件を満たす最小の値を返す
  def binarySearch(_min: Long, _max: Long, k: Long): Long = {
    def check(i: Long): Boolean = {
      var cnt = 0

      var pos = 0
      var neg = 0
      while (neg < negaNum) {
        if (nega(neg) * posi(pos) <= i) {
          if (pos == posiNum - 1) {
            cnt += pos+1
            neg += 1
          }
          else
            pos += 1
        }
        else {
          cnt += pos
          neg += 1
        }
      }

      cnt >= k
    }

    def func(min: Long, max: Long): Long = {
      val mid: Long = (max + min) / 2
        (max - min) match{
        case 0 | 1 =>
          check(min) match{
            case true  => min
            case false => max
          }
        case _ =>
          (check(mid)) match{
            case true  => func(min, mid)
            case false => func(mid, max)
          }
      }
    }

    func(_min, _max)
  }

  val posiNum = posi.length
  val negaNum = nega.length

  var ans = 0L
  breakable {
    val minus = posiNum * negaNum
    if (K <= minus) {
      ans = binarySearch(-1e18.toLong, -1, K)
      break
    }
    K -= minus

    val hoge = zero * (posiNum + negaNum) + (zero * (zero - 1)) / 2
    if (K <= hoge) {
      ans = 0
      break
    }
    K -= hoge

    // TODO: プラスのにぶたん
  }

  println(ans)
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

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


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

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

  val N = in.next().toInt
  var K = in.next().toInt
  val A = new Array[Long](N)
  var zero = 0
  var _posi = List[Long]()
  var _nega = List[Long]()
  for (i <- 0 until N) {
    val now = in.next().toLong
    A(i) = now

    if (now == 0)
      zero += 1
    else if (now < 0)
      _nega = now :: _nega
    else
      _posi = now :: _posi
  }

  val posi = _posi.toArray.sorted
  val nega = _nega.toArray.sorted.reverse
  // println(posi.toList)
  // println(nega.toList)

  //
  // 条件を満たす最小の値を返す
  def binarySearch(_min: Long, _max: Long, k: Long): Long = {
    def check(i: Long): Boolean = {
      var cnt = 0

      var pos = 0
      var neg = 0
      while (neg < negaNum) {
        if (nega(neg) * posi(pos) <= i) {
          if (pos == posiNum - 1) {
            cnt += pos+1
            neg += 1
          }
          else
            pos += 1
        }
        else {
          cnt += pos
          neg += 1
        }
      }

      cnt >= k
    }

    def func(min: Long, max: Long): Long = {
      val mid: Long = (max + min) / 2
        (max - min) match{
        case 0 | 1 =>
          check(min) match{
            case true  => min
            case false => max
          }
        case _ =>
          (check(mid)) match{
            case true  => func(min, mid)
            case false => func(mid, max)
          }
      }
    }

    func(_min, _max)
  }

  val posiNum = posi.length
  val negaNum = nega.length

  var ans = 0L
  breakable {
    val minus = posiNum * negaNum
    if (K <= minus) {
      ans = binarySearch(-1e18.toLong, -1, K)
      break
    }
    K -= minus

    if (K <= zero) {
      ans = 0
      break
    }
    K -= zero

    // TODO: プラスのにぶたん
  }

  println(ans)
}

object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.toList))
  }
}

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


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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new Abc155(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = false

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class Abc155(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val k = nl()

    val a = na(n).map(_.toLong) ++ Array(Long.MaxValue)

    scala.util.Sorting.quickSort(a)
    var L = -2e18.toLong
    var R = 2e18.toLong

    while (L + 1 != R) {
      val M = L + (R - L) / 2
      var cnt = 0L
      REP(n) { i =>
        if(a(i) < 0) {
          var l = i
          var r = n
          while (l + 1 != r) {
            val m = l + (r - l) / 2
            if(a(i) * a(m) <= M) r = m
            else l = m
          }
          cnt += (n - r)
        } else {
          var l = i
          var r = n
          while (l + 1 != r) {
            val m = l + (r - l) / 2
            if(a(i) * a(m) <= M) l = m
            else r = m
          }
          cnt += (l - i)
        }
      }
      if(cnt < k) L = M
      else R = M
    }
    out.println(R)
  }
}


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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new Abc155(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class Abc155(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val k = ni()

    val a = na(n).map(_.toLong) ++ Array(Long.MaxValue)

    scala.util.Sorting.quickSort(a)
    var L = -1e18.toLong
    var R = 1e18.toLong

    while (L + 1 != R) {
      val M = L + (R - L) / 2
      var cnt = 0
      REP(n) { i =>
        if(a(i) < 0) {
          var l = i
          var r = n
          while (l + 1 != r) {
            val m = l + (r - l) / 2
            if(a(i) * a(m) <= M) r = m
            else l = m
          }
          cnt += (n - r)
        } else {
          var l = i
          var r = n
          while (l + 1 != r) {
            val m = l + (r - l) / 2
            if(a(i) * a(m) <= M) l = m
            else r = m
          }
          cnt += (l - i)
        }
      }
      if(cnt < k) L = M
      else R = M
    }
    out.println(R)
  }
}


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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new Abc155(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class Abc155(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val k = ni()

    val a = na(n)

    scala.util.Sorting.quickSort(a)
    var L = -1e18.toLong
    var R = 1e18.toLong

    while (L + 1 != R) {
      val M = L + (R - L) / 2
      var cnt = 0
      REP(n) { i =>
        if(a(i) < 0) {
          var l = i
          var r = n
          while (l + 1 != r) {
            val m = l + (r - l) / 2
            if(a(i).toLong * a(m) <= M) r = m
            else l = m
          }
          cnt += (n - r)
        } else {
          var l = i
          var r = n
          while (l + 1 != r) {
            val m = l + (r - l) / 2
            if(a(i).toLong * a(m) <= M) l = m
            else r = m
          }
          cnt += (l - i)
        }
      }
      if(cnt < k) L = M
      else R = M
    }
    out.println(R)
  }
}


object Main extends scala.App {
    import java.util
    import scala.collection._
    import scala.collection.mutable.ListBuffer
    import scala.math._

    val sc = new java.util.Scanner(System.in)
    val N, K = sc.nextInt()
    val As = List.fill(N)(sc.nextInt().toLong)

    val gen = for (i <- As.indices; j <- As.indices if i < j) yield (i, j)
    print(gen
            .map(t => As(t._1) * As(t._2))
            .sorted
            .drop(K - 1)
            .head
    )
}


import java.util.Scanner
import java.io.PrintWriter

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

    val a, b = sc.nextInt()
    if (a > 9 || b > 9) {
      pw.println(-1)
    } else {
      pw.println(a * b)
    }

    pw.flush()
  }
}

Score : 100 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation.

Given are two integers A and B.

If Takahashi can calculate A \times B, print the result; if he cannot, print -1 instead.

Constraints

1 \leq A \leq 20

1 \leq B \leq 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If Takahashi can calculate A \times B, print the result; if he cannot, print -1.

Sample Input 1

2 5

Sample Output 1

10

2 \times 5 = 10.

Sample Input 2

5 10

Sample Output 2

-1

5\times 10 = 50, but Takahashi cannot do this calculation, so print -1 instead.

Sample Input 3

9 9

Sample Output 3

81


//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

  def nextDouble(): Double = next().toDouble

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) =>
      nodes(t).parent = Some(root(p))
      nodes(t).parent.get
  }
}

object Main {
  def solve(sc: => Scanner): Unit = {
    val A, B = sc.nextLong()
    println(if (1 <= A && A <= 9 && 1 <= B && B <= 9) A * B else -1)
  }

  def recursive(now: Long, minV: Long): Set[Long] = {
    if (Math.sqrt(now) < minV) Set(now) else {
      if (now % minV == 0) recursive(now / minV, minV + 1) + minV else recursive(now, minV + 1)
    }
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def calc(A: Array[Long]): Array[String] = {
    if (A.length == 0) Array.fill(0)("")
    else {
      val last = A.zipWithIndex.map(x => (x._1 - x._2, x._1)).takeWhile(x => x._1 == A.head).last._2
      if (last == A.head) "%d".format(A.head) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
      else "%d-%d".format(A.head, last) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
    }
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

object Util {
  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getPrimeList: Stream[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: Stream[Long]): Stream[Long] =
    Stream.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): Stream[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  val codeTable = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      @scala.annotation.tailrec
      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      @scala.annotation.tailrec
      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}


import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val re = """([1-9]{1})\s([1-9]{1})""".r
    StdIn.readLine match {
      case re(a, b) => println(a.toInt * b.toInt)
      case _ => println("-1")
    }
  }
}


import scala.math.{abs, max, min}

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

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

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

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    val a, b = ni()
    if (a < 10 && b < 10) out.print(a * b)
    else out.println(-1)
  }
}


object Main extends App {
    var inputs = readLine.split(" ").map(_.toInt)
    var can = true
    for(i <- inputs) {
        if(i > 9) {
            can = false
            println(-1)
        }
    }
    if(can) {
        println(inputs(0) * inputs(1))
    }

}


object Main extends App {
    var inputs = readLine.split(" ").map(_.toInt)
    var can = true
    for(i <- inputs) {
        if(i > 9) {
            can = false
            println(-1)
        }
    }
    if(can) {
        println(inputs.reduce(_ * _))
    }

}


object Main extends App {
    var inputs = readLine.split(" ")
    var can = true
    for(i <- inputs) {
        if(i.length > 1) {
            can = false
            println(-1)
        }
    }
    if(can) {
        println(inputs.map(_.toInt).reduce(_ * _))
    }

}


object Main extends App {
  val ab = scala.io.StdIn.readLine()
  val abArray = ab.split(" ").map(_.toInt).toVector
  val a = abArray(0)
  val b = abArray(1)
  if (a >= 10 || b >= 10) {
    println(-1)
  } else {
    println(a * b)
  }
}


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

    val ss = matcher(s ++ s ++ s ++ s)
    val ans = ss.count(_ == '_') * k / 4
    println(ans)
  }

  import scala.collection.mutable
  def matcher(xs: String): mutable.Buffer[Char] = {
    val buf = xs.toBuffer
    (1 until buf.length).foreach(i => {
      if (buf(i - 1) == buf(i)) {
        buf.update(i, '_')
      }
    })
    buf
  }
}

Score : 300 points

Problem Statement

Given is a string S. Let T be the concatenation of K copies of S.
We can repeatedly perform the following operation: choose a character in T and replace it with a different character.
Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different.

Constraints

1 \leq |S| \leq 100

S consists of lowercase English letters.

1 \leq K \leq 10^9

K is an integer.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the minimum number of operations required.

Sample Input 1

issii
2

Sample Output 1

4

T is issiiissii. For example, we can rewrite it into ispiqisyhi, and now any two adjacent characters are different.

Sample Input 2

qq
81

Sample Output 2

81

Sample Input 3

cooooooooonteeeeeeeeeest
999993333

Sample Output 3

8999939997


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

    val ss = matcher(s ++ s ++ s)
    val wari = if (s.length == 1) 2 else 3
    val ans = ss.count(_ == '_') * k / wari
    println(ans)
  }

  import scala.collection.mutable
  def matcher(xs: String): mutable.Buffer[Char] = {
    val buf = xs.toBuffer
    (1 until buf.length).foreach(i => {
      if (buf(i - 1) == buf(i)) {
        buf.update(i, '_')
      }
    })
    buf
  }
}