object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val R = sc.nextInt()
  println(2 * R * math.Pi)
}

Score : 100 points

Problem Statement

Print the circumference of a circle of radius R.

Constraints

1 \leq R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R

Output

Print the circumference of the circle.
Your output is considered correct if and only if its absolute or relative error from our answer is at most 10^{-2}.

Sample Input 1

1

Sample Output 1

6.28318530717958623200

Since we accept an absolute or relative error of at most 10^{-2}, 6.28 is also an acceptable output, but 6 is not.

Sample Input 2

73

Sample Output 2

458.67252742410977361942


import java.security.KeyStore.TrustedCertificateEntry
import java.util
import java.util.regex.Pattern
import java.util.{ArrayList, Collections, Comparator, List => JList}

import scala.collection.immutable.TreeMap
import scala.math._
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.util.{Failure, Success, Try}

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

  def init (nRows: Int, nCols: Int, default: Int) = Array.tabulate(nRows,nCols)( (x,y) =>  default)

  def sortIgnoreCase1(list: JList[String]): JList[String] = {
    val r = new ArrayList[String](list)
    Collections.sort(r, new Comparator[String] {
      override def compare(o1: String, o2: String): Int = o1.compareToIgnoreCase(o2)
    })
    r
  }

  def solve(input: String): String = {
    val r = input.toInt
    (2 * r * Pi).toString
  }

  def factorize(x: Long): List[Long] = {
    def foo(x: Long, a: Long = 2, list: List[Long] = Nil): List[Long] = a*a > x match {
      case false if x % a == 0 => foo(x / a, a    , a :: list)
      case false               => foo(x    , a + 1, list)
      case true                => x :: list
    }
    foo(x)
  }

  def divisors(n: Long): Vector[Long] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(_ % n == 0).map(_.toLong)
    val reversedList = if (sqrt(n).floor == sqrt(n)) halfList.reverse.tail.map(n/_) else halfList.reverse.map(n/_)
    halfList ++ reversedList
  }

  def gcd(m: Long, n: Long): Long = n match {
    case 0 => m
    case _ => gcd(n, m % n)
  }
  def lcm(a: Long, b: Long): Long = a * b / gcd(a, b)

  val tests=List(
    """33""".stripMargin -> """2 -1
                              |
                                   |
                                 |
                                   |""".stripMargin,
    """1""".stripMargin -> """0 -1""".stripMargin
  )

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

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

Submitted source-code file size, in bytes.

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

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


object Main extends App {
	val R = scala.io.StdIn.readDouble
	println(math.Pi * R * 2.0)
}


object Main extends App{
  val s = io.StdIn.readLine().toInt
  println(s*6.28)
}


//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 = {
    println(2 * sc.nextDouble * Math.PI)
  }

  @scala.annotation.tailrec
  def recursive(AB: List[(Long, Long)], ansX: String, now: Long, usedA: Int, usedB: Int, MaxValues: List[Long]): Option[String] = {
    if (AB.isEmpty) Some(ansX)
    else if (MaxValues.head < now) None
    else {
      val h = AB.head
      if (usedA > 0 && now <= h._1) recursive(AB.tail, ansX ++ "A", h._1, usedA - 1, usedB, MaxValues.tail)
      else if (usedB > 0 && now <= h._2) recursive(AB.tail, ansX ++ "B", h._2, usedA, usedB - 1, MaxValues.tail)
      else None
    }
  }

  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 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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: LazyList[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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

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

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): LazyList[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 scala.io.StdIn.readLine
import scala.io.StdIn.readInt
object Main extends App {
    var a = readInt
    println(a * 2 * 3.141592653);
}


object Main extends App {
  val r = io.StdIn.readDouble
  val t = 2.0 * scala.math.Pi * r
  println(t)

}


object Main extends App {
  val R = scala.io.StdIn.readLine().toInt

  println(math.Pi * R * 2.0)

}


import scala.math

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

	def solve(input: String): String = {
		 val a = input.toInt
		 val ans = a * 2 * math.Pi
		 ans.toString
	}

}


import java.util.Scanner

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

    println(2*n*math.Pi)

  }
}


object Main extends App {
  val r =  scala.io.StdIn.readInt()
  println(r.toDouble * 3.1415926535 * 2d)
}


object Main extends App {
  val r = io.StdIn.readInt()
  println(Math.PI * 2 * r)
}


import scala.io.StdIn._
import scala.math._

object Main extends App with StdInHelper {
  val n = readLine()

  println(if (n.contains("7")) "Yes" else "No")
}

trait StdInHelper {
  def readInts = readLine.split(" ").map(_.toInt)
  def readLongs = readLine.split(" ").map(_.toLong)
}

Score : 100 points

Problem Statement

Given is a three-digit integer N. Does N contain the digit 7?

If so, print Yes; otherwise, print No.

Constraints

100 \leq N \leq 999

Input

Input is given from Standard Input in the following format:

N

Output

If N contains the digit 7, print Yes; otherwise, print No.

Sample Input 1

117

Sample Output 1

Yes

117 contains 7 as its last digit.

Sample Input 2

123

Sample Output 2

No

123 does not contain the digit 7.

Sample Input 3

777

Sample Output 3

Yes


import scala.io.StdIn._

object Main extends App {
  if (readLine().contains('7'))
    println("Yes")
  else
    println("No")
}


object Main extends App {

  val n = scala.io.StdIn.readLine().split("")

  def solve(): String = {
    if(n.contains("7")) "Yes" else "No"
  }
  println(solve)
}


object Main {

  val n = scala.io.StdIn.readLine().split("")

  def solve(): String = {
    if(n.contains("7")) "Yes" else "No"
  }
  println(solve)
}


import java.util.Scanner

object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val a = sc.nextInt //最初の整数が読み込まれる
    a.toString.contains("7") match{
    case true => println("Yes")
    case false => println("No")
    }
  }
}


object Main extends App {
  val n =  scala.io.StdIn.readLine()
  if (n.contains('7')) println("Yes") else println("No")
}


object Main extends App {
  val n = io.StdIn.readLine()
  println(if (n.contains('7')) "Yes" else "No")
}


import scala.io.StdIn._
object Main extends App{
  // 入力
  val strN = readLine()

  if(strN.contains('7')) println("YES")
  else println("NO")
}


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

  if (n.contains("7")) {
    println("Yes")
  } else {
    println("No")
  }
}


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

object Main extends App {

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

  val all = 1 to readInt()

  println(Seq(all.sum,
    all.combinations(2).map(combi => gcd(combi(0), combi(1))).sum*6,
    all.combinations(3).map(combi => gcd(gcd(combi(0), combi(1)), combi(2))).sum*6).foldLeft(0)(_+_))
}

Score : 300 points

Problem Statement

Find \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.

Here \gcd(a,b,c) denotes the greatest common divisor of a, b, and c.

Constraints

1 \leq K \leq 200

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the value of \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.

Sample Input 1

2

Sample Output 1

9

\gcd(1,1,1)+\gcd(1,1,2)+\gcd(1,2,1)+\gcd(1,2,2)
+\gcd(2,1,1)+\gcd(2,1,2)+\gcd(2,2,1)+\gcd(2,2,2)
=1+1+1+1+1+1+1+2=9

Thus, the answer is 9.

Sample Input 2

200

Sample Output 2

10813692


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val K = in.nextInt
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  val gcds = for {
    a <- 1 to K
    b <- 1 to K
    c <- 1 to K
  } yield gcd(gcd(a, b), c)

  println(gcds.sum)
}


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val K = in.nextInt
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
  def gcd(a: Int, b: Int, c: Int): Int = gcd(gcd(a, b), c)

  val gcds = for {
    a <- 1 to K
    b <- 1 to K
    c <- 1 to K
  } yield gcd(a, b, c)

  println(gcds.sum)
}


//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 K = sc.nextInt()
    println((
      for {
        i <- 1 to K
        j <- 1 to K
        l = gcd(i, j)
        k <- 1 to K
      } yield gcd(l, k)
      ).sum
    )
  }

  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(N: Long, num: Long, ans: Long): Long = {
    if (N == 0) ans
    else recursive(N - 1, num * 2, ans + num * 3)
  }

  @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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: LazyList[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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

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

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): LazyList[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 scala.io.StdIn._
object Main extends App{
  val k = readLine().toInt

  var sum = 0
  (1 to k).foreach(h =>{
    (1 to k).foreach(i => {
      (1 to k).foreach(j => {
        sum = sum + gcd(h, i ,j)
      })
    })
  })

  println(sum)

  def gcd(a: Int, b:Int, c: Int):Int = {
    val ab = gcd(a, b)
    if(ab > c) gcd(ab, c)
    else if(ab == c) c
    else gcd(c, ab)
  }

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


object Main extends App {
  //最大公約数
  def gcd(x: Long, y: Long): Long = {
    if(y == 0) x
    else gcd(y, (x % y))
  }

  val k =  scala.io.StdIn.readInt()
  var result = 0L

  (1 to k).foreach { a =>
    (1 to k).foreach { b =>
      (1 to k).foreach { c =>
        val gcdResult = gcd(gcd(a.toLong, b.toLong), c.toLong)
        if(a == b && a == c && b ==c) {
          result += gcdResult
        } else {
          result += gcdResult
        }

      }
    }
  }
  println(result)
}


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

import scala.collection.mutable

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 k = in.readLine().toInt

    val memo = mutable.HashMap.empty[(Int, Int), Int]

    def gcd(a: Int, b: Int): Int = {
      if (b == 0) {
        a
      } else if (a < b) {
        gcd(b, a)
      } else {
        memo.getOrElseUpdate((a, b), gcd(b, a % b))
      }
    }

    def gcd3(a: Int, b: Int, c: Int): Int = {
      gcd(a, gcd(b, c))
    }

    var sum = 0L

    for (a <- 1 to k) {
      for (b <- 1 to k) {
        for (c <- 1 to k) {
          sum += gcd3(a, b, c)
        }
      }
    }
    out.println(sum)

    out.flush()
  }

}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val k = sc.nextInt()
    var ans: Long = 0L

    for (i <- 1 to k) {
      for (j <- 1 to k) {
        for (n <- 1 to k) {
          ans += gcds(i, j, n)
        }
      }
    }

    println(ans)
  }

  def gcds(a: Int, b: Int, c: Int): Int = {
    val m = gcd(a, b)
    gcd(m, c)
  }

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

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


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N = in.nextInt
  val S = in.next
  val nR = S.count(_ == 'R')
  val nG = S.count(_ == 'G')
  val nB = N - nR - nG

  @inline
  def c(i: Int) = S.charAt(i)

  val un = (for {
    i <- 0 to N - 3
    j <- i + 1 to N - 2 if 2 * j - i < N
  } yield if (c(i) != c(j) && c(i) != c(2 * j - i) && c(j) != c(2 * j - i)) 1 else 0).sum

  println(nR * nG * nB - un)
}

Score : 400 points

Problem Statement

We have a string S of length N consisting of R, G, and B.

Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:

S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.

j - i \neq k - j.

Constraints

1 \leq N \leq 4000

S is a string of length N consisting of R, G, and B.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of triplets in question.

Sample Input 1

4
RRGB

Sample Output 1

1

Only the triplet (1,~3,~4) satisfies both conditions. The triplet (2,~3,~4) satisfies the first condition but not the second, so it does not count.

Sample Input 2

39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB

Sample Output 2

1800


//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 = {
    sc.nextInt()
    val S = sc.next().zipWithIndex
    val R = S.filter(_._1 == 'R').map(_._2)
    val G = S.filter(_._1 == 'G').map(_._2)
    val B = S.filter(_._1 == 'B').map(_._2).toSet

    println(R.map(i => G.map(j => (B - (2 * j - i) - (2 * i - j) - (if ((i + j) % 2 == 0) (i + j) / 2 else -1)).size).sum).sum)
  }

  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(N: Long, num: Long, ans: Long): Long = {
    if (N == 0) ans
    else recursive(N - 1, num * 2, ans + num * 3)
  }

  @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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: LazyList[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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

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

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): LazyList[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 n = io.StdIn.readInt()
  val s = io.StdIn.readLine()

  var count = 0
  for (i <- 0 until n-2)
    for (j <- i until n-1; if (s(i) != s(j)))
      for (k <- j until n; if (s(i) != s(k) && s(j) != s(k) && j-i != k-j)) {
          count += 1
      }

  println(count)
}


import scala.io.StdIn._
object Main extends App{
  val N = readLine().toInt
  val S = readLine()

  var sum = 0
  (0 until N-2).foreach(i => {
    (i+1 until N-1).foreach(j => {
      (j+1 until N).foreach(k => {
        val si = S(i)
        if((si != S(j)) && (S(i) != S(k)) && (S(j) != S(k)) && ((j-i) != (k-j))){
          sum = sum + 1
        }
      })
    })
  })

  println(sum)
}


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

import scala.collection.mutable

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 n = in.readLine().toInt
    val s = in.readLine()

    val rc = Array.ofDim[Int](n)
    val gc = Array.ofDim[Int](n)
    val bc = Array.ofDim[Int](n)

    for (i <- n - 1 to 0 by -1) {
      s(i) match {
        case 'R' => rc(i) = 1
        case 'G' => gc(i) = 1
        case 'B' => bc(i) = 1
      }
      if (i != n - 1) {
        rc(i) += rc(i + 1)
        gc(i) += gc(i + 1)
        bc(i) += bc(i + 1)
      }
    }

    var count = 0L

    for (i <- 0 until n - 2) {
      for (j <- i + 1 until n - 1) {
        if (s(i) != s(j)) {
          count += {
            List('R', 'G', 'B').filter(c => c != s(i) && c != s(j)).head match {
              case 'R' => rc(j + 1) - {
                if (j + j - i < n && s(j + j - i) == 'R') {
                  1
                } else {
                  0
                }
              }
              case 'G' => gc(j + 1) - {
                if (j + j - i < n && s(j + j - i) == 'G') {
                  1
                } else {
                  0
                }
              }
              case 'B' => bc(j + 1) - {
                if (j + j - i < n && s(j + j - i) == 'B') {
                  1
                } else {
                  0
                }
              }
            }
          }
        }
      }
    }

    out.println(count)

    out.flush()
  }

}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val s = sc.next().toCharArray

    val rs = new Array[Int](n)
    val gs = new Array[Int](n)
    val bs = new Array[Int](n)

    for (i <- s.indices) {
      if (i > 0) {
        s(i) match {
          case 'R' =>
            rs(i) = rs(i - 1) + 1
            gs(i) = gs(i - 1)
            bs(i) = bs(i - 1)
          case 'G' =>
            rs(i) = rs(i - 1)
            gs(i) = gs(i - 1) + 1
            bs(i) = bs(i - 1)
          case 'B' =>
            rs(i) = rs(i - 1)
            gs(i) = gs(i - 1)
            bs(i) = bs(i - 1) + 1
        }
      } else {
        s(i) match {
          case 'R' =>
            rs(i) = 1
            gs(i) = 0
            bs(i) = 0
          case 'G' =>
            rs(i) = 0
            gs(i) = 1
            bs(i) = 0
          case 'B' =>
            rs(i) = 0
            gs(i) = 0
            bs(i) = 1
        }
      }
    }

    var ans = 0L

    for (i <- n - 1 to 2 by -1) {
      for (j <- i - 1 to 1 by -1) {
        if ((s(i) == 'R' && s(j) == 'G') || (s(i) == 'G' && s(j) == 'R')) {
          ans += bs(j)
          val m = i - j
          val n = j - m
          if (0 <= n && s(n) == 'B') {
            ans -= 1
          }
        } else if ((s(i) == 'R' && s(j) == 'B') || (s(i) == 'B' && s(j) == 'R')) {
          ans += gs(j)
          val m = i - j
          val n = j - m
          if (0 <= n && s(n) == 'G') {
            ans -= 1
          }
        } else if ((s(i) == 'B' && s(j) == 'G') || (s(i) == 'G' && s(j) == 'B')) {
          ans += rs(j)
          val m = i - j
          val n = j - m
          if (0 <= n && s(n) == 'R') {
            ans -= 1
          }
        }
      }

    }
    println(ans)
  }

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


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val s = sc.next().toCharArray

    val rs = new Array[Int](n)
    val gs = new Array[Int](n)
    val bs = new Array[Int](n)

    for (i <- s.indices) {
      if (i > 0) {
        s(i) match {
          case 'R' =>
            rs(i) = rs(i - 1) + 1
            gs(i) = gs(i - 1)
            bs(i) = bs(i - 1)
          case 'G' =>
            rs(i) = rs(i - 1)
            gs(i) = gs(i - 1) + 1
            bs(i) = bs(i - 1)
          case 'B' =>
            rs(i) = rs(i - 1)
            gs(i) = gs(i - 1)
            bs(i) = bs(i - 1) + 1
        }
      } else {
        s(i) match {
          case 'R' =>
            rs(i) = 1
            gs(i) = 0
            bs(i) = 0
          case 'G' =>
            rs(i) = 0
            gs(i) = 1
            bs(i) = 0
          case 'B' =>
            rs(i) = 0
            gs(i) = 0
            bs(i) = 1
        }
      }
    }

    var ans = 0L

    for (i <- n - 1 to 2 by -1) {
      for (j <- i - 1 to 1 by -1) {
        println(i, j, j - (i - j))
        if ((s(i) == 'R' && s(j) == 'G') || (s(i) == 'G' && s(j) == 'R')) {
          ans += bs(j)
          val m = i - j
          val n = j - m
          if (0 <= n && s(n) == 'B') {
            ans -= 1
          }
        } else if ((s(i) == 'R' && s(j) == 'B') || (s(i) == 'B' && s(j) == 'R')) {
          ans += gs(j)
          val m = i - j
          val n = j - m
          if (0 <= n && s(n) == 'G') {
            ans -= 1
          }
        } else if ((s(i) == 'B' && s(j) == 'G') || (s(i) == 'G' && s(j) == 'B')) {
          ans += rs(j)
          val m = i - j
          val n = j - m
          if (0 <= n && s(n) == 'R') {
            ans -= 1
          }
        }
      }

    }

    printArray(gs)
    printArray(rs)
    printArray(bs)
    println(ans)
  }

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


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
  val S = in.next()

  //
  var _R = Vector[Int]()
  var _G = Vector[Int]()
  var _B = Vector[Int]()

  for (i <- 0 until N) {
    S(i) match {
      case 'R' => _R :+= i
      case 'G' => _G :+= i
      case 'B' => _B :+= i
    }
  }

  val R = _R.toArray
  val G = _G.toArray
  val B = _B.toSet

  var ans = R.length.toLong * G.length * _B.length

  for (_ri <- R; _gi <- G) {
    var ri = _ri
    var gi = _gi

    if (ri > gi) {
      val tmp = ri
      ri = gi
      gi = tmp
    }

    val hoge = gi - ri

    if (B(ri - hoge))
      ans -= 1

    if (B(gi + hoge))
      ans -= 1

    if (hoge % 2 == 0)
      if (B(ri + hoge/2))
        ans -= 1
  }

  println(ans)
}

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


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

  var count = 0
  for (i <- 0 until n-2)
    for (j <- i until n-1)
      for (k <- j until n) {
        if (j-i != k-j && s(i) != s(j) && s(i) != s(k) && s(j) != s(k))
          count += 1
      }

  println(count)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val X, Y, Z = sc.nextInt()
  println(s"$Z $X $Y")
}

Score : 100 points

Problem Statement

We have three boxes A, B, and C, each of which contains an integer.

Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively.

We will now do the operations below in order. Find the content of each box afterward.

Swap the contents of the boxes A and B

Swap the contents of the boxes A and C

Constraints

1 \leq X,Y,Z \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z

Output

Print the integers contained in the boxes A, B, and C, in this order, with space in between.

Sample Input 1

1 2 3

Sample Output 1

3 1 2

After the contents of the boxes A and B are swapped, A, B, and C contain 2, 1, and 3, respectively.

Then, after the contents of A and C are swapped, A, B, and C contain 3, 1, and 2, respectively.

Sample Input 2

100 100 100

Sample Output 2

100 100 100

Sample Input 3

41 59 31

Sample Output 3

31 41 59


import java.util.Scanner

import scala.io.StdIn._

object Main extends App {

  val Array(x,y,z) = readLine().split(" ").map(_.toInt)

  def solve() = {
    s"$z $x $y"
  }

  println(solve())

}


object Main{
  import scala.io.StdIn._
  def main(args: Array[String]): Unit = {
    val Array(a,b,c) = readLine().split(' ')
    println(s"$c $a $b")
  }
}


//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, Z = sc.nextLong()
    println(Z + " " + X + " " + 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(N: Long, num: Long, ans: Long): Long = {
    if (N == 0) ans
    else recursive(N - 1, num * 2, ans + num * 3)
  }

  @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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: LazyList[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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

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

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): LazyList[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 {
  import scala.io.StdIn._
  def main(args: Array[String]): Unit = {
    val Array(a, b, c, _*) = readLine().split(' ')
    println(c, a, b)
  }
}


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

  println(Array(z, x, y).mkString(" "))
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  var arr: Array[Int] = Array(-1, -1, -1)

  for(x <- 1 to 3) {
    val inputInt: Int = sc.nextInt
    arr(x - 1) = inputInt
  }

  println(arr(2) + " " + arr(0) + " " + arr(1))
}


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val X, Y, Z = in.next
  println(s"$Z $X $Y")
}


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


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(_.toInt)

    out.println(List(c, a, b).mkString(" "))
    out.flush()
  }
}


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

  println(Array(z, x, y).mkString(" "))
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N, M = sc.nextInt()
  val A = List.fill(N)(sc.nextInt())
  val sum = A.sum
  println(if (M <= A.count(a => sum <= a * 4 * M)) "Yes" else "No")
}

Score : 200 points

Problem Statement

We have held a popularity poll for N items on sale. Item i received A_i votes.

From these N items, we will select M as popular items. However, we cannot select an item with less than \dfrac{1}{4M} of the total number of votes.

If M popular items can be selected, print Yes; otherwise, print No.

Constraints

1 \leq M \leq N \leq 100

1 \leq A_i \leq 1000

A_i are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 ... A_N

Output

If M popular items can be selected, print Yes; otherwise, print No.

Sample Input 1

4 1
5 4 2 1

Sample Output 1

Yes

There were 12 votes in total. The most popular item received 5 votes, and we can select it.

Sample Input 2

3 2
380 19 1

Sample Output 2

No

There were 400 votes in total. The second and third most popular items received less than \dfrac{1}{4\times 2} of the total number of votes, so we cannot select them. Thus, we cannot select two popular items.

Sample Input 3

12 3
4 56 78 901 2 345 67 890 123 45 6 789

Sample Output 3

Yes


object Main extends App{
  import scala.io.StdIn._
  val Array(n,m)=readLine().split(" ").map(_.toInt)
  val a=readLine().split(" ").map(_.toInt)
  val ans=a.count(s=>s>=a.sum/(4*m))
  println(if(ans >=m ) "Yes" else "No")
}


object Main extends App{
  import scala.io.StdIn._
  val Array(n,m)=readLine().split(" ").map(_.toInt)
  val a=readLine().split(" ").map(_.toInt)
  val ans=a.filter(_>=a.sum/(4*m))
  println(if(ans.length >=m ) "Yes" else "No")
}


object Main extends App{
  import scala.io.StdIn._
  val Array(n,m)=readLine().split(" ").map(_.toInt)
  val a=readLine().split(" ").map(_.toInt)
  println(if(a.filter(_>=a.sum/(4*m)).sum >=m ) "Yes" else "No")
}


//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, M = sc.nextInt()
    val A = Array.fill(N)(sc.nextLong())
    val Asum = A.sum
    println(if (A.count(x => x * 4 * M >= Asum) >= M) "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(N: Long, num: Long, ans: Long): Long = {
    if (N == 0) ans
    else recursive(N - 1, num * 2, ans + num * 3)
  }

  @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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: LazyList[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): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

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

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

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): LazyList[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.util.Scanner
object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n,m = sc.nextInt
    val list = List.fill(n)(sc.nextInt) // nextIntがn回呼ばれる

    val allPoint = list.sum
    val kijun = (allPoint.toDouble/(4D*m.toDouble)).toInt

    def kijunOver(x: Int, m:Int, kijun: Long): Long = {
      x match{
        case x if (x*4.0*m).toLong < kijun => 0
        case x if (x*4.0*m).toLong >= kijun => 1
      }
    }

    val list2 = list.map(kijunOver(_, m, kijun.toLong))

    list2.sum >= m match{
        case true => println("Yes")
        case false => println("No")
    }
  }
}


import java.util.Scanner
object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n,m = sc.nextInt
    val list = List.fill(n)(sc.nextInt) // nextIntがn回呼ばれる

    val allPoint = list.sum
    val kijun = (allPoint/(4.0*m)).toInt

    def kijunOver(x: Int, kijun: Long): Long = {
      x match{
        case x if x.toLong < kijun => 0
        case x if x.toLong >= kijun => 1
      }
    }

    val list2 = list.map(kijunOver(_, kijun.toLong))

    list2.sum >= m match{
        case true => println("Yes")
        case false => println("No")
    }
  }
}


import java.util.Scanner
object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n,m = sc.nextInt //最初の整数が読み込まれる
    val list = List.fill(n)(sc.nextInt) // nextIntがn回呼ばれる

    val allPoint = list.sum
    val kijun = (allPoint.toDouble/(4D*m.toDouble)).toInt

    def kijunOver(x: Int, kijun: Long): Long = {
      x match{
        case x if x.toLong < kijun => 0
        case x if x.toLong >= kijun => 1
      }
    }

    val list2 = list.map(kijunOver(_, kijun.toLong))

    list2.sum >= m match{
        case true => println("Yes")
        case false => println("No")
    }
  }
}


import java.util.Scanner

object Main {
  def main(args: Array[String]) = {
    val s = new Scanner(System.in)
    val n = s.nextInt
    val m = s.nextInt
    val nums = (0 until n).map(i => s.nextInt).toArray
    val sum = nums.sum
    val lowerLimit = (sum.asInstanceOf[Float] / (4 * m)).ceil
    val canPick = nums.filter(_ >= lowerLimit).size >= m
    print(if (canPick) "Yes\n" else "No\n")
  }
}


object Main {
  def main(args : Array[String]) {
    val NM = readLine().split(' ').map(_.toInt)
    var A = readLine().split(' ').map(_.toInt)
    A = A.sorted.reverse

	if((A.sum / (4 * NM(1))) <= A(NM(1) - 1)) println("Yes")
    else println("No")
  }
}


object Main {
  import scala.io.StdIn._
  def main(args: Array[String]): Unit = {
    def readInts() = readLine().split(' ').map(_.toInt)
    val Array(n, m, _*) = readInts()
    val votesOfItems = readInts()
    val total = votesOfItems.sum
    def isOk(votes: Int): Boolean = votes * 4 * m >= total
    println(if(votesOfItems.count(isOk) >= m) "Yes" else "No")
  }
}


object Main {
  import scala.io.StdIn._
  def main(args: Array[String]): Unit = {
    def readInts() = readLine().split(' ').map(_.toInt)
    val Array(n, m, _*) = readInts()
    val votesOfItems = readInts()
    val threahold = 4 * m
    def isOk(votes: Int): Boolean = votes < threahold
    println(if(votesOfItems.count(isOk) >= m) "Yes" else "No")
  }
}


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N, M = in.nextInt
  val As = Array.fill(N)(in.nextInt).sorted.reverse
  println(if (As.take(M).last * 4 * M > As.sum) "Yes" else "No")
}


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

	val Asum = a.sum/(4*m)

	if(a.count(_ >= Asum) >= m) println("Yes")
	else println("No")
}


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

	val Asum = a.sum/4/m

	if(a.count(_ >= Asum) >= m) println("Yes")
	else println("No")
}


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

  var array: Array[Int] = Array.empty

  val input2 = readLine
  for(count1 <- 1 to N){
    var input3 = input2.split(" ")(count1 -1).toInt
    array = array :+ input3
  }

  var sorted = array.sorted.reverse

  if(sorted(M-1) < array.sum / (4.0*M)) println("No")
  else if(sorted(M-1) >= array.sum / (4.0*M)) println("Yes")
}


import scala.util.control.Breaks

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

  val aInput =  scala.io.StdIn.readLine()
  val aArray = aInput.split(" ").map(_.toInt).toVector.sorted.reverse
  val aSum = aArray.sum.toDouble
  var result = true

  val b = new Breaks
  b.breakable {
    (1 to m).foreach { i =>
      val target = aArray(i  - 1).toDouble
      val judge = aSum / (4 * m).toDouble
      if(target < judge) {
        result = false
        b.break()
      }
    }
  }
  println(if (result) "Yes" else "No")
}


object Main extends App {
  val Array(n, m) = io.StdIn.readLine().split(' ').map(_.toInt)
  val an = io.StdIn.readLine().split(' ').map(_.toInt)
  val topM: Array[Int] = an.sortWith{ (x, y) => x > y}.take(m)
  val sum = an.sum
  println(if (topM.forall(_ >= sum.toDouble / (4 * m))) "Yes" else "No")
}


import scala.util.control.Breaks

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

  val aInput =  scala.io.StdIn.readLine()
  val aArray = aInput.split(" ").map(_.toInt).toVector.sorted.reverse
  val aSum = aArray.sum
  var result = true

  val b = new Breaks
  b.breakable {
    (1 to m).foreach { i =>
      val target = aArray(i  - 1)
      val judge = aSum / (4 * 2)
      if(target < judge) {
        result = false
        b.break()
      }
    }
  }
  println(if (result) "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(n, m) = in.readLine().split("\\s+").map(_.toInt)
    val as = in.readLine().split("\\s+").map(_.toInt)

    val sum = as.sum

    out.println(
      if (as.count(a => a * 4 * m >= sum) >= m) {
        "Yes"
      } else {
        "No"
      }
    )
    out.flush()
  }
}


object Main extends App {
  val Array(n, m) = io.StdIn.readLine().split(' ').map(_.toInt)
  val an = io.StdIn.readLine().split(' ').map(_.toInt)
  val topM: Array[Int] = an.sortWith{ (x, y) => x > y}.take(m)
  val sum = an.sum
  println(if (topM.forall(_ >= sum / (4 * m))) "Yes" else "No")
}


object Main extends App {
  val sc = new java.util.Scanner(System.in);
  val x, y, a, b, c = sc.nextInt();
  val ps = Array.fill(a)(-sc.nextInt());
  val qs = Array.fill(b)(-sc.nextInt());
  val rs = Array.fill(c)(-sc.nextInt());

  val answer = -(
    ps.sorted.take(x) ++
    qs.sorted.take(y) ++
    rs.sorted).sorted.take(x + y).map(_.toLong).sum;

  println(answer);
}

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


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 X, Y = in.next().toInt
  val A, B, C = in.next().toInt
  val p = new Array[Long](A+1)
  val q = new Array[Long](B+1)
  val r = new Array[Long](C+1)
  for (i <- 1 to A)
    p(i) = in.next().toLong
  for (i <- 1 to B)
    q(i) = in.next().toLong
  for (i <- 1 to C)
    r(i) = in.next().toLong

  //
  val p1 = p.sorted.reverse.take(X)
  val q1 = q.sorted.reverse.take(Y)

  val ans = (p1 ++ q1 ++ r).sorted.reverse.take(X+Y).sum
  println(ans)
}

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.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,
      A + C - Y,
      B + C - X
    ))
  }

  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.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,
      A + C - X,
      B + 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
    }
  }
}