Boboniu gives you  $$$r$$$ red balls,  $$$g$$$ green balls,  $$$b$$$ blue balls,  $$$w$$$ white balls. He allows you to do the following operation as many times as you want:   Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations.

The first line contains one integer $$$T$$$ ($$$1\le T\le 100$$$) denoting the number of test cases. For each of the next $$$T$$$ cases, the first line contains four integers $$$r$$$, $$$g$$$, $$$b$$$ and $$$w$$$ ($$$0\le r,g,b,w\le 10^9$$$).

For each test case, print "Yes" if it's possible to arrange all the balls into a palindrome after doing several (possibly zero) number of described operations. Otherwise, print "No".

NoteIn the first test case, you're not able to do any operation and you can never arrange three balls of distinct colors into a palindrome.In the second test case, after doing one operation, changing $$$(8,1,9,3)$$$ to $$$(7,0,8,6)$$$, one of those possible palindromes may be "rrrwwwbbbbrbbbbwwwrrr".A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. For example, "rggbwbggr", "b", "gg" are palindromes while "rgbb", "gbbgr" are not. Notice that an empty word, phrase, or sequence is palindrome.

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  private def check(r: Long, g: Long, b: Long, w: Long): Boolean =
    r >= 0 && g >= 0 && b >= 0 && List(r, g, b, w).foldLeft(0L)(_ + _ % 2) <= 1

  (0 until t).foreach { _ =>
    val Array(r, g, b, w) = readLine().split(" ").map(_.toLong)

    val ans = check(r, g, b, w) || check(r - 1, g - 1, b - 1, w + 3)

    if (ans) println("Yes") else println("No")
  }
}

import scala.io.StdIn._

object taskA extends App {

  def singleCheck(input: Array[Int]): Boolean = {
    input.foreach { x =>
      if (x < 0)
        return false
    }
    if (input(3) % 2 == 0) {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 <= 1)
        true
      else
        false
    } else {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 0)
        true
      else
        false
    }
  }
4

  def check(input: Array[Int]): String = {
    var res: Boolean = false
    if (singleCheck(input)) res = true
    else {
      val newInput = input.map(x => x - 1)
      newInput(3) += 4
      res = singleCheck(newInput)
    }
    if (res) "Yes" else "No"
  }

  //READING THE STANDARD INPUT
  val sets = readInt

  var lst: List[String] = List()
  (1 to sets).foreach { _ =>
    val input: Array[Int] = readLine.split(" ").map(_.toInt)
    //println(check(input))
    lst = lst ::: List(check(input))
  }

  lst.foreach { x =>
    println(x)
  }

}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val r = in.nextInt()
      val g = in.nextInt()
      val b = in.nextInt()
      val w = in.nextInt()

      val count = (r % 2) + (g % 2) + (b % 2) + (w % 2)
      if (count == 0 || count == 1) {
        println("Yes")
      } else {
        val c2 = (r % 2) + (g % 2) + (b % 2)
        if (r != 0 && g != 0 && b != 0) {
          if (w % 2 == 1) {
            if (c2 >= 2) println("Yes") else println("No")
          } else {
            if (c2 == 1 || c2 == 3) println("Yes") else println("No")
          }
        } else {
          println("No")
        }
      }
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[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(Files.newBufferedReader(path, codec.charSet))

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

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

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    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 next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

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

import scala.io.StdIn._

object taskA extends App {

  def singleCheck(input: Array[Int]): Boolean = {
    input.foreach { x =>
      if (x < 0)
        return false
    }
    if (input(3) % 2 == 0) {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 <= 1)
        true
      else
        false
    } else {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 0)
        true
      else
        false
    }
  }
4

  def check(input: Array[Int]): String = {
    var res: Boolean = false
    if (singleCheck(input)) res = true
    else res = singleCheck(input.map(x => x - 1))
    if (res) "Yes" else "No"
  }

  //READING THE STANDARD INPUT
  val sets = readInt

  var lst: List[String] = List()
  (1 to sets).foreach { _ =>
    val input: Array[Int] = readLine.split(" ").map(_.toInt)
    //println(check(input))
    lst = lst ::: List(check(input))
  }

  lst.foreach { x =>
    println(x)
  }

}

import scala.io.StdIn._

object taskA extends App {

  def singleCheck(input: Array[Int]): Boolean = {
    input.foreach { x =>
      if (x < 0)
        return false
    }
    if (input(3) % 2 == 0) {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 1)
        true
      else
        false
    } else {
      if (input(0) % 2 + input(1) % 2 + input(2) % 2 == 0)
        true
      else
        false
    }
  }

  def check(input: Array[Int]): String = {
    var res: Boolean = false
    if (singleCheck(input)) res = true
    else res = singleCheck(input.map(x => x - 1))
    if (res) "Yes" else "No"
  }

  //READING THE STANDARD INPUT
  val sets = readInt

  var lst: List[String] = List()
  (1 to sets).foreach { _ =>
    val input: Array[Int] = readLine.split(" ").map(_.toInt)
    //println(check(input))
    lst = lst ::: List(check(input))
  }

  lst.foreach { x =>
    println(x)
  }

}


Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.

The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input.

Print a single integer — the maximum possible total length of words in Andrew's article.

NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}.

//package round329.a

import java.util.Scanner

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

  val n = sc.nextInt
  sc.nextLine
  val words = (1 to n).map(_ => sc.nextLine())

//  println(words)

  val goodWords = words.filter { word =>
    val grouped = word.toList.groupBy(c => c)
    grouped.keys.size <= 2
  }

  var best = 0

  def containsOnly(s: String, allowed: List[Char]): Boolean = {
    s.forall(c => allowed.contains(c))
  }

//  println(goodWords)

  ('a' to 'z').foreach { char1 =>
    ('a' to 'z').foreach { char2 =>
      val wrds = goodWords.filter(w => containsOnly(w, List(char1, char2)))
      val payment = wrds.map(_.length).sum
//      println(s"trying $char1, $char2: $payment")
      best = Math.max(best, payment)
    }
  }

  println(best)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var map = ('a' to 'z').flatMap { i =>
    (i to 'z').map(j => "" + i + j -> 0)
  }.toMap
  (1 to n).foreach {_ =>
      val str = in.next()
      val distinct = str.distinct
      if (distinct.length == 2) {
        val key = distinct.sorted
        map +=  (key -> (map(key) + str.length))
      } else if (distinct.length == 1) {
        ('a' to 'z').foreach { j =>
          val key = (distinct + j).sorted
          map += (key -> (map(key) + str.length))
        }
      }
  }
  println(map.values.max)
}

import scala.collection._

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)
  val ss = Array.fill(n){ readLine.toCharArray }

  var max = 0

  for (a <- 'a' to 'z') {
    for (b <- 'a' to 'z') if (b != a) {
      var sum = 0
      for (i <- 0 until n) {
        var ok = true
        for (c <- ss(i)) {
          if (c != a && c != b) ok = false
        }
        if (ok) {
          sum += ss(i).length
        }
      }
      if (sum > max) {
        max = sum
      }
    }
  }

  println(max)
}

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

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  def solve: Int = {
    val n = nextInt
    val words = new Array[String](n)
    for (i <- 0 until n)
      words(i) = next
    var max = 0
    for (c1 <- 'a' to 'z') {
      for (c2 <- 'a' to 'z') {
        if (c1 != c2) {
          var len = 0
          for (i <- 0 until n) {
            var flag = true
            for (j <- 0 until words(i).toCharArray.length) {
              if (words(i).toCharArray().apply(j) != c1 && words(i).toCharArray().apply(j) != c2)
                flag = false
            }
            if (flag) {
              len += words(i).toCharArray.length
            }
          }
          max = Math.max(max, len)
        }
      }
    }
    out.println(max)
    return 0
  }
}

import scala.annotation.tailrec
import scala.collection.immutable.IndexedSeq
import scala.collection.mutable
import scala.util._
import scala.math.Ordering.Implicits._

object _593A extends CodeForcesApp {
  import CodeForcesApp._
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val words = Seq.fill(n)(next())

    val all: IndexedSeq[((Char, Char), String)] = for {
      i <- 'a' to 'z'
      j <- 'a' to 'z'
      w <- words
      t = w.replace(i.toString, "").replaceAll(j.toString, "")
      if t.isEmpty
    } yield (i, j) -> w

    val map = all.groupBy(_._1).mapValues(_.map(_._2.length).sum)
    if (map.isEmpty) 0 else map.values.max
  }

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[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(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  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 next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}


You are given a set $$$S$$$, which contains the first $$$n$$$ positive integers: $$$1, 2, \ldots, n$$$.You can perform the following operation on $$$S$$$ any number of times (possibly zero):   Choose a positive integer $$$k$$$ where $$$1 \le k \le n$$$, such that there exists a multiple of $$$k$$$ in $$$S$$$. Then, delete the smallest multiple of $$$k$$$ from $$$S$$$. This operation requires a cost of $$$k$$$. You are given a set $$$T$$$, which is a subset of $$$S$$$. Find the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$. We can show that such a transformation is always possible.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The description of the test cases follows. The first line contains a single positive integer $$$n$$$ ($$$1 \le n \le 10^6$$$). The second line of each test case contains a binary string of length $$$n$$$, describing the set $$$T$$$. The $$$i$$$-th character of the string is '1' if and only if $$$i$$$ is an element of $$$T$$$, and '0' otherwise. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.

For each test case, output one non-negative integer — the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$.

NoteIn the first test case, we shall not perform any operations as $$$S$$$ is already equal to $$$T$$$, which is the set $$$\{1, 2, 3, 4, 5, 6\}$$$.In the second test case, initially, $$$S = \{1, 2, 3, 4, 5, 6, 7\}$$$, and $$$T = \{1, 2, 4, 7\}$$$. We shall perform the following operations:   Choose $$$k=3$$$, then delete $$$3$$$ from $$$S$$$.  Choose $$$k=3$$$, then delete $$$6$$$ from $$$S$$$.  Choose $$$k=5$$$, then delete $$$5$$$ from $$$S$$$. The total cost is $$$3+3+5 = 11$$$. It can be shown that this is the smallest cost possible.In the third test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{\}$$$ (empty set). We shall perform $$$4$$$ operations of $$$k=1$$$ to delete $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$.In the fourth test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{3\}$$$. We shall perform two operations with $$$k=1$$$ to delete $$$1$$$ and $$$2$$$, then perform one operation with $$$k=2$$$ to delete $$$4$$$.

import scala.io.StdIn

/**
 * @author zhuxi
 * @since 2022/9/28 11:11
 * @note
 * 1734C. Removing Smallest Multiples | 难度：1200
 */
object Solution1734C {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 0 until t) {
      val n = StdIn.readInt()
      val visit = new Array[Boolean](n + 1)
      val str = StdIn.readLine()
      var res = 0L
      for (i <- 1 to n) {
        var break = false
        for (j <- i to n by i if !break) {
          if (str(j - 1) == '1') break = true
          else if (!visit(j)) {
            visit(j) = true
            res += i
          }
        }
      }
      println(res)
    }
  }
}

import scala.io.StdIn

/**
 * @author zhuxi
 * @since 2022/9/28 11:11
 * @note
 * 1734C. Removing Smallest Multiples | 难度：1200
 */
object Solution1734C {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 0 until t) {
      val n = StdIn.readInt()
      val visit = new Array[Boolean](n + 1)
      val str = StdIn.readLine()
      var res = 0
      for (i <- 1 to n) {
        var break = false
        for (j <- i to n by i if !break) {
          if (str(j - 1) == '1') break = true
          else if (!visit(j)) {
            visit(j) = true
            res += i
          }
        }
      }
      println(res)
    }
  }
}


Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that:  the cashier needs 5 seconds to scan one item;  after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.

The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 ≤ ki ≤ 100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 ≤ mi, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.

Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.

NoteIn the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val k = in.next().split(" ").map(_.toInt)
  val p = (1 to n).map(_ => in.next().split(" ").map(_.toInt))
  val res = p.map(t => t.sum * 5 + t.length * 15)
  println(res.min)
}

object A408 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val k = readInts(n)
    val m = k.map(readInts)
    println(m.map(a => a.sum*5 + a.length*15).min)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._
import scala.collection.mutable.ArrayBuffer
import java.util.Arrays.binarySearch

object P408A extends App {

  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val K = Array.fill(N)(sc.nextInt)
  val slurpQueue: Int => List[Int] = i => List.fill(K(i))(sc.nextInt)
  val Q = List.tabulate(N)(slurpQueue)
  val stopTime: List[Int] => Int = { lst => lst.sum * 5 + lst.size * 15 }
  val res = Q.map(stopTime).min

  out.println(res)
  out.close
}

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object A408 extends App {

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val k: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var min: Int = Int.MaxValue
    for (i <- 0 until n) {
      val m: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val latency = m.map(bucket => bucket * 5 + 15).sum
      min = Math.min(min, latency)
    }
    println(min)
  }

  solve()

}

object A extends App {

  def calc(in:Array[Int]): Int = {
    in.sum * 5 + in.length*15
  }

  var ans = (1<<30)
  val n = readInt()
  val t = readLine()
  for (i <- 0 until n) {
    val line = readLine()
    val in:Array[Int]  = line.split(" ") map (_.toInt)
    ans = ans min calc(in)
  }
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val k = in.next().split(" ").map(_.toInt)
  val p = (1 to n).map(_ => in.next().split(" ").map(_.toInt))
  val res = p.map(t => t.sum * 5 + t.length * 15)
  println(res.zipWithIndex.min._2 + 1)
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P405A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt

  type Cards = List[Int]
  val CS: Cards = List.fill(N)(sc.nextInt)

  def solve(): Unit = {

    @tailrec
    def loop(spt: Int, dpt: Int, turn: Int, cs: Cards, rcs: Cards): Unit = {
      if (turn == N) out.println(List(spt, dpt).mkString(" "))
      else (cs, rcs) match {
        case (x :: xs, y :: ys) if x > y => if (turn % 2 == 0) loop(spt + x, dpt, turn + 1, xs, rcs)
                                            else loop(spt, dpt + x, turn + 1, xs, rcs)
        case (_, y :: ys) => if (turn % 2 == 0) loop(spt + y, dpt, turn + 1, cs, ys)
                             else loop(spt, dpt + y, turn + 1, cs, ys)
      }
    }

    loop(0, 0, 0, CS, CS.reverse)
  }

  solve
  out.close
}

object A extends App {

  def calc(in:Array[Int]): Int = {
    in.sum * 5 + in.length*15
  }

  var ans = (1<<30)
  val n = readInt()
  for (i <- 0 until n) {
    val line = readLine()
    val in:Array[Int]  = line.split(" ") map (_.toInt)
    ans = ans min calc(in)
  }
  println(ans)
}


There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.

The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000,  - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.

Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers.

NoteExplanation to the first and second samples from the statement, respectively:

object CF291B extends App {
  val Array(n, x, y) = readLine().split(" ").map(_.toInt)

  val ax = new Array[Int](n)
  val ay = new Array[Int](n)

  val shot = new Array[Boolean](n)

  (0 until n) foreach { i =>
    shot(i) = false
    val Array(tx, ty) = readLine().split(" ").map(_.toInt)
    ax(i) = tx
    ay(i) = ty
  }

  var res = 0
  (0 until n) foreach { i =>
    if (!shot(i)) {
      res += 1
      (0 until n) foreach { j =>
        if ((y - ay(i)) * (x - ax(j)) == (y - ay(j)) * (x - ax(i))) shot(j) = true
      }
    }
  }

  print(res)
}

object B514 {

  import IO._
  import collection.{mutable => cu}

  def sameLine(x: Int, y: Int, x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {
    (x-x1)*(y-y2) == (x-x2)*(y-y1)
  }

  def main(args: Array[String]): Unit = {
    val Array(n, x0, y0) = readInts(3)
    val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1)))
    val vis = Array.fill(n)(false)
    def dfs(a: Int): Unit = {
      vis(a) = true
      for(i <- 0 until n if !vis(i)) {
        if(sameLine(x0, y0, in(a)._1, in(a)._2, in(i)._1, in(i)._2))
          vis(i) = true
      }
    }
    var res = 0
    for(i <- 0 until n) {
      if(!vis(i)) {
        dfs(i)
        res += 1
      }
    }
    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine;
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Double, Int]
    var undef = 0

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      if (p1-x != 0 ) {
        val slope = (p2 - y) / (p1 - x).toDouble
        if (!map.contains(slope)) {
          map.put(slope, 1)
        }
      } else {
        undef = 1
      }
    }

    println(map.size + undef)
  }

}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Int, Int]

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      val slope = if ((p1-x) == 0) 0 else math.abs((p2-y)/(p1-x))
      if (!map.contains(slope))
        map.put(slope, 1)
    }

    println(map.size)
  }

}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Int, Int]
    var undef = 0

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      if (p1-x != 0 ) {
        val slope = (p2 - y) / (p1 - x)
        if (!map.contains(slope)) {
          map.put(slope, 1)
        }
      } else {
        undef = 1
      }
    }

    println(map.size + undef)
  }

}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Int, Int]
    var undef = 0

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      if (p1-x != 0 ) {
        val slope = math.abs ((p2 - y) / (p1 - x))
        if (!map.contains(slope)) {
          map.put(slope, 1)
        }
      } else {
        undef = 1
      }
    }

    println(map.size + undef)
  }

}

import java.util.Scanner

import scala.collection.mutable

/**
 * Created by dimitar on 2/14/15.
 * slope y2-y1/x2-x1
 */
object Points {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val p = sc.nextInt()
    val x = sc.nextInt()
    val y = sc.nextInt()

    val map = new mutable.HashMap[Int, Int]

    (0 until p) foreach { _ =>

      val p1 = sc.nextInt()
      val p2 = sc.nextInt()
      val slope = if ((p1-x) == 0) 0 else (p2-y)/(p1-x)
      if (!map.contains(slope))
        map.put(slope, 1)
    }

    println(map.size)
  }

}


Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of actions Valentin did. The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types:    Valentin pronounced some word and didn't get an electric shock. This action is described by the string ". w" (without quotes), in which "." is a dot (ASCII-code 46), and w is the word that Valentin said.  Valentin pronounced some word and got an electric shock. This action is described by the string "! w" (without quotes), in which "!" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said.  Valentin made a guess about the selected letter. This action is described by the string "? s" (without quotes), in which "?" is a question mark (ASCII-code 63), and s is the guess — a lowercase English letter.  All words consist only of lowercase English letters. The total length of all words does not exceed 105. It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after pronouncing some word, then it contains the selected letter; and also if Valentin didn't get an electric shock after pronouncing some word, then it does not contain the selected letter.

Output a single integer — the number of electric shocks that Valentin could have avoided if he had told the selected letter just after it became uniquely determined.

8
! hello
! codeforces
? c
. o
? d
? h
. l
? e

7
! ababahalamaha
? a
? b
? a
? b
? a
? h

NoteIn the first test case after the first action it becomes clear that the selected letter is one of the following: a, b, c. After the second action we can note that the selected letter is not a. Valentin tells word "b" and doesn't get a shock. After that it is clear that the selected letter is c, but Valentin pronounces the word cd and gets an excessive electric shock. In the second test case after the first two electric shocks we understand that the selected letter is e or o. Valentin tries some words consisting of these letters and after the second word it's clear that the selected letter is e, but Valentin makes 3 more actions before he makes a correct hypothesis.In the third example the selected letter can be uniquely determined only when Valentin guesses it, so he didn't get excessive electric shocks.

import java.util

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

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    var excessiveCount = 0
    var poss = new mutable.HashSet[Char]()
    (0 until 26).map('a' + _).map(_.asInstanceOf[Char]).foreach(c => poss.add(c))
    var step = 0
    while (step < n) {
      val Array(cmd, wd) = StdIn.readLine().split(" ")
      cmd match {
        case "!" =>
          if (poss.size <= 1) {
            excessiveCount += 1
          }
          poss = poss.intersect(wd.toSet)
        case "." => poss = poss.diff(wd.toSet)
        case "?" =>
          if (poss.size <= 1 && step != n - 1) {
            excessiveCount += 1
          }
          poss.remove(wd(0))
      }
      step += 1
    }
    println(excessiveCount)
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

}

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)

  val checked = Array.fill('z' - 'a' + 1)(false)
  var res = 0

  for (_ <- 0 until n) {
    //println(checked.count(_ == false))
    val solved = checked.count(_ == false) == 1
    readLine.split(" ") match {

      case Array(".", w) =>
        for (c <- w) checked(c - 'a') = true

      case Array("!", w) =>
        if (solved) res += 1
        val bad = w.toSet
        for (c <- 'a' to 'z') if (!bad(c)) checked(c - 'a') = true

      case Array("?", s) =>
        if (solved) res += 1
        checked(s.head - 'a') = true
    }
  }

  println(Math.max(0, res - 1))
}


В самолёте есть n рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа.Известно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, которые часто летают) и обычные. Перед вами стоит задача рассадить ещё k обычных пассажиров так, чтобы суммарное число соседей у статусных пассажиров было минимально возможным. Два пассажира считаются соседями, если они сидят в одном ряду и между ними нет других мест и прохода между рядами. Если пассажир является соседним пассажиром для двух статусных пассажиров, то его следует учитывать в сумме соседей дважды.

В первой строке следуют два целых числа n и k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10·n) — количество рядов мест в самолёте и количество пассажиров, которых нужно рассадить. Далее следует описание рядов мест самолёта по одному ряду в строке. Если очередной символ равен '-', то это проход между рядами. Если очередной символ равен '.', то это свободное место. Если очередной символ равен 'S', то на текущем месте будет сидеть статусный пассажир. Если очередной символ равен 'P', то на текущем месте будет сидеть обычный пассажир.  Гарантируется, что количество свободных мест не меньше k. Гарантируется, что все ряды удовлетворяют описанному в условии формату.

В первую строку выведите минимальное суммарное число соседей у статусных пассажиров. Далее выведите план рассадки пассажиров, который минимизирует суммарное количество соседей у статусных пассажиров, в том же формате, что и во входных данных. Если в свободное место нужно посадить одного из k пассажиров, выведите строчную букву 'x' вместо символа '.'.

4 9
PP.-PPPS-S.S
PSP-PPSP-.S.
.S.-S..P-SS.
P.S-P.PP-PSP

15
PPx-PPPS-S.S
PSP-PPSP-xSx
xSx-SxxP-SSx
P.S-PxPP-PSP

ПримечаниеВ первом примере нужно посадить ещё двух обычных пассажиров. Для минимизации соседей у статусных пассажиров, нужно посадить первого из них на третье слева место, а второго на любое из оставшихся двух мест, так как независимо от выбора места он станет соседом двух статусных пассажиров. Изначально, у статусного пассажира, который сидит на самом левом месте уже есть сосед. Также на четвёртом и пятом местах слева сидят статусные пассажиры, являющиеся соседями друг для друга (что добавляет к сумме 2).Таким образом, после посадки ещё двух обычных пассажиров, итоговое суммарное количество соседей у статусных пассажиров станет равно пяти.

object CF928A extends App {
val sc = new java.util.Scanner(System.in)
val n: Int = sc.nextInt()
val k: Int = sc.nextInt()
sc.nextLine()
val planOfAirplan: List[String] = (1 to n).toList.foldLeft(List.empty[String]){case (list, _) => list :+ sc.nextLine()}
def findCountOfPlacesAtTheLineFirstStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {
  def isFree(previos: Char, current: Char, next: Char): Int = if(current == '.' && next != 'S' && previos != 'S') 1 else 0
  def countInLine(currentString: String, count: Int = 0, completedString: String = ""): (Int, String) = {
    val tail = currentString.tail
    val tailTail = tail.tail
    if (tailTail.nonEmpty && count + countAtAll < k) {
      val head = currentString.head
      val tailHead = tail.head
      val isFreeResult = isFree(head, tailHead, tailTail.head)
      countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)
    } else (count, completedString + currentString)
  }
  val first = if ((line.startsWith(".P") || line.startsWith(".."))  && countAtAll < k) 1 else 0
  val second = if ((line.endsWith("P.") || line.endsWith("..")) && countAtAll + first < k) 1 else 0
  countInLine(line match {
    case _ if first == 1 && second == 1 => line.replaceFirst("^\\.P", "xP").replaceFirst("P\\.$", "Px").replaceFirst("^\\.\\.", "x.").replaceFirst("\\.\\.$", ".x")
    case _ if first == 1 => line.replaceFirst("^\\.P", "xP").replaceFirst("^\\.\\.", "x.")
    case _ if second == 1 => line.replaceFirst("P\\.$", "Px").replaceFirst("\\.\\.$", ".x")
    case _ => line
  }, count = first + second)
} else (0, line)
def findCountOfPlacesAtTheLineSecondStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {
  def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next != previos && (next == 'S' || previos == 'S')) 1 else 0
  def countInLine(currentString: String, count: Int = 0, completedString: String = ""): (Int, String) = {
    val tail = currentString.tail
    val tailTail = tail.tail
    if (tailTail.nonEmpty  && count + countAtAll < k) {
      val head = currentString.head
      val tailHead = tail.head
      val isFreeResult = isFree(head, tailHead, tailTail.head)
      countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)
    } else (count, completedString  + currentString)
  }
  val first = if (line.startsWith(".S") && countAtAll < k) 1 else 0
  val second = if (line.endsWith("S.") && countAtAll + first < k) 1 else 0
  countInLine(line match {
    case _ if first == 1 && second == 1 => line.replaceFirst("^\\.S", "xS").replaceFirst("S\\.$", "Sx")
    case _ if first == 1 => line.replaceFirst("^\\.S", "xS")
    case _ if second == 1 => line.replaceFirst("S\\.$", "Sx")
    case _ => line
  }, count = first + second)
} else (0, line)
def findCountOfPlacesAtTheLineThirdStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {
  def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next == 'S' && previos == 'S') 1 else 0
  def countInLine(currentString: String, count: Int = 0, completedString: String = ""): (Int, String) = {
    val tail = currentString.tail
    val tailTail = tail.tail
    if (tailTail.nonEmpty  && count + countAtAll < k) {
      val head = currentString.head
      val tailHead = tail.head
      val isFreeResult = isFree(head, tailHead, tailTail.head)
      countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)
    } else (count, completedString  + currentString)
  }
  countInLine(line)
} else (0, line)
def findCountOfPlacesAtTheLinFinalStage(line: String): Int = if (line.contains('P') || line.contains('x') || line.contains('S')) {
  def isNeeded(previos: Char, current: Char, next: Char): Int = if ((current != '.' && current != '-')  && (previos == 'S' || next == 'S')) if (previos == next) 2 else 1 else 0
  def countInLine(currentString: String, count: Int = 0): Int = {
    val tail = currentString.tail
    val tailTail = tail.tail
    if (tailTail.nonEmpty) {
      countInLine(tail, count + isNeeded(currentString.head, tail.head, tailTail.head))
    } else count
  }
  val head = line.head
  val last = line.last
  countInLine(line) + (if (head != '.' && head != '-' &&  line.tail.head == 'S') 1 else 0) + (if (last != '.' && last != '-' && line.init.last == 'S') 1 else 0)
} else 0
val firstResult = planOfAirplan.foldLeft((0, List.empty[String])){(tupNew, line) =>
  val tupOld = findCountOfPlacesAtTheLineFirstStage(line, tupNew._1)
  (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)
}
val fullResult = if (firstResult._1 < k) {
  val secondResult = firstResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>
    val tupOld = findCountOfPlacesAtTheLineSecondStage(line, firstResult._1 + tupNew._1)
    (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)
  }
  if (secondResult._1 < k)
    secondResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>
      val tupOld = findCountOfPlacesAtTheLineThirdStage(line, firstResult._1 + secondResult._1 + tupNew._1)
      (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)
    }
  else
    secondResult
} else {
  firstResult
}
val result = fullResult._2.map(findCountOfPlacesAtTheLinFinalStage).sum
println(result)
fullResult._2.map(println)
}

object CF928A extends App {
  val sc = new java.util.Scanner(System.in)
  val n: Int = sc.nextInt()
  val k: Int = sc.nextInt()
  sc.nextLine()
  val planOfAirplan: List[String] = (1 to n).toList.foldLeft(List.empty[String]){case (list, _) => list :+ sc.nextLine()}
  def findCountOfPlacesAtTheLineFirstStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {
    def isFree(previos: Char, current: Char, next: Char): Int = if(current == '.' && next != 'S' && previos != 'S') 1 else 0
    def countInLine(currentString: String, count: Int = 0, completedString: String = ""): (Int, String) = {
      val tail = currentString.tail
      val tailTail = tail.tail
      if (tailTail.nonEmpty && count + countAtAll < k) {
        val head = currentString.head
        val tailHead = tail.head
        val isFreeResult = isFree(head, tailHead, tailTail.head)
        countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)
      } else (count, completedString + currentString)
    }
    val res = countInLine(line.replaceFirst("^\\.P", "xP").replaceFirst("P\\.$", "Px"))
    res.copy(_1 = res._1 + (if (line.startsWith(".P")) 1 else 0) + (if (line.endsWith("P.")) 1 else 0))
  } else (0, line)
  def findCountOfPlacesAtTheLineSecondStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {
    def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next != previos && (next == 'S' || previos == 'S')) 1 else 0
    def countInLine(currentString: String, count: Int = 0, completedString: String = ""): (Int, String) = {
      val tail = currentString.tail
      val tailTail = tail.tail
      if (tailTail.nonEmpty  && count + countAtAll < k) {
        val head = currentString.head
        val tailHead = tail.head
        val isFreeResult = isFree(head, tailHead, tailTail.head)
        countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)
      } else (count, completedString  + currentString)
    }
    val res = countInLine(line.replaceFirst("^\\.S", "xS").replaceFirst("S\\.$", "Sx"))
    res.copy(_1 = res._1 + (if (line.startsWith(".S")) 1 else 0) + (if (line.endsWith("S.")) 1 else 0))
  } else (0, line)
  def findCountOfPlacesAtTheLineThirdStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {
    def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next == 'S' && previos == 'S') 1 else 0
    def countInLine(currentString: String, count: Int = 0, completedString: String = ""): (Int, String) = {
      val tail = currentString.tail
      val tailTail = tail.tail
      if (tailTail.nonEmpty  && count + countAtAll < k) {
        val head = currentString.head
        val tailHead = tail.head
        val isFreeResult = isFree(head, tailHead, tailTail.head)
        countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)
      } else (count, completedString  + currentString)
    }
    countInLine(line)
  } else (0, line)
  def findCountOfPlacesAtTheLinFinalStage(line: String): Int = if (line.contains('P') || line.contains('x') || line.contains('S')) {
    def isNeeded(previos: Char, current: Char, next: Char): Int = if ((current != '.' && current != '-')  && (previos == 'S' || next == 'S')) if (previos == next) 2 else 1 else 0
    def countInLine(currentString: String, count: Int = 0): Int = {
      val tail = currentString.tail
      val tailTail = tail.tail
      if (tailTail.nonEmpty) {
        countInLine(tail, count + isNeeded(currentString.head, tail.head, tailTail.head))
      } else count
    }
    val head = line.head
    val last = line.last
    countInLine(line) + (if (head != '.' && head != '-' && line.tail.head != '.' && line.tail.head == 'S') 1 else 0) + (if (last != '.' && last != '-' && line.init.last != '.'  && line.init.last == 'S') 1 else 0)
  } else 0
  val firstResult = planOfAirplan.foldLeft((0, List.empty[String])){(tupNew, line) =>
    val tupOld = findCountOfPlacesAtTheLineFirstStage(line, tupNew._1)
    (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)
  }
  val fullResult = if (firstResult._1 < k) {
    val secondResult = firstResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>
      val tupOld = findCountOfPlacesAtTheLineSecondStage(line, firstResult._1 + tupNew._1)
      (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)
    }
    if (secondResult._1 < k)
      secondResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>
        val tupOld = findCountOfPlacesAtTheLineThirdStage(line, firstResult._1 + secondResult._1 + tupNew._1)
        (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)
      }
    else
      secondResult
  } else {
    firstResult
  }
  val result = fullResult._2.map(findCountOfPlacesAtTheLinFinalStage).sum
  println(result)
  fullResult._2.map(println)
}

object CF928A extends App {
val sc = new java.util.Scanner(System.in)
val n: Int = sc.nextInt()
val k: Int = sc.nextInt()
sc.nextLine()
val planOfAirplan: List[String] = (1 to n).toList.foldLeft(List.empty[String]){case (list, _) => list :+ sc.nextLine()}
def findCountOfPlacesAtTheLineFirstStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {
  def isFree(previos: Char, current: Char, next: Char): Int = if(current == '.' && next != 'S' && previos != 'S') 1 else 0
  def countInLine(currentString: String, count: Int = 0, completedString: String = ""): (Int, String) = {
    val tail = currentString.tail
    val tailTail = tail.tail
    if (tailTail.nonEmpty && count + countAtAll < k) {
      val head = currentString.head
      val tailHead = tail.head
      val isFreeResult = isFree(head, tailHead, tailTail.head)
      countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)
    } else (count, completedString + currentString)
  }
  val first = if (line.startsWith(".P") && countAtAll < k) 1 else 0
  val second = if (line.endsWith("P.") && countAtAll + first < k) 1 else 0
  countInLine(line match {
    case _ if first == 1 && second == 1 => line.replaceFirst("^\\.P", "xP").replaceFirst("P\\.$", "Px")
    case _ if first == 1 => line.replaceFirst("^\\.P", "xP")
    case _ if second == 1 => line.replaceFirst("P\\.$", "Px")
    case _ => line
  }, count = first + second)
} else (0, line)
def findCountOfPlacesAtTheLineSecondStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {
  def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next != previos && (next == 'S' || previos == 'S')) 1 else 0
  def countInLine(currentString: String, count: Int = 0, completedString: String = ""): (Int, String) = {
    val tail = currentString.tail
    val tailTail = tail.tail
    if (tailTail.nonEmpty  && count + countAtAll < k) {
      val head = currentString.head
      val tailHead = tail.head
      val isFreeResult = isFree(head, tailHead, tailTail.head)
      countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)
    } else (count, completedString  + currentString)
  }
  val first = if (line.startsWith(".S") && countAtAll < k) 1 else 0
  val second = if (line.endsWith("S.") && countAtAll + first < k) 1 else 0
  countInLine(line match {
    case _ if first == 1 && second == 1 => line.replaceFirst("^\\.S", "xS").replaceFirst("S\\.$", "Sx")
    case _ if first == 1 => line.replaceFirst("^\\.S", "xS")
    case _ if second == 1 => line.replaceFirst("S\\.$", "Sx")
    case _ => line
  }, count = first + second)
} else (0, line)
def findCountOfPlacesAtTheLineThirdStage(line: String, countAtAll: Int): (Int, String) = if (line.contains('.')) {
  def isFree(previos: Char, current: Char, next: Char): Int = if (current == '.' && next == 'S' && previos == 'S') 1 else 0
  def countInLine(currentString: String, count: Int = 0, completedString: String = ""): (Int, String) = {
    val tail = currentString.tail
    val tailTail = tail.tail
    if (tailTail.nonEmpty  && count + countAtAll < k) {
      val head = currentString.head
      val tailHead = tail.head
      val isFreeResult = isFree(head, tailHead, tailTail.head)
      countInLine((if (isFreeResult == 1) 'x' else tailHead) + tailTail, count + isFreeResult, completedString + head)
    } else (count, completedString  + currentString)
  }
  countInLine(line)
} else (0, line)
def findCountOfPlacesAtTheLinFinalStage(line: String): Int = if (line.contains('P') || line.contains('x') || line.contains('S')) {
  def isNeeded(previos: Char, current: Char, next: Char): Int = if ((current != '.' && current != '-')  && (previos == 'S' || next == 'S')) if (previos == next) 2 else 1 else 0
  def countInLine(currentString: String, count: Int = 0): Int = {
    val tail = currentString.tail
    val tailTail = tail.tail
    if (tailTail.nonEmpty) {
      countInLine(tail, count + isNeeded(currentString.head, tail.head, tailTail.head))
    } else count
  }
  val head = line.head
  val last = line.last
  countInLine(line) + (if (head != '.' && head != '-' && line.tail.head != '.' && line.tail.head == 'S') 1 else 0) + (if (last != '.' && last != '-' && line.init.last != '.'  && line.init.last == 'S') 1 else 0)
} else 0
val firstResult = planOfAirplan.foldLeft((0, List.empty[String])){(tupNew, line) =>
  val tupOld = findCountOfPlacesAtTheLineFirstStage(line, tupNew._1)
  (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)
}
val fullResult = if (firstResult._1 < k) {
  val secondResult = firstResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>
    val tupOld = findCountOfPlacesAtTheLineSecondStage(line, firstResult._1 + tupNew._1)
    (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)
  }
  if (secondResult._1 < k)
    secondResult._2.foldLeft((0, List.empty[String])) { (tupNew, line) =>
      val tupOld = findCountOfPlacesAtTheLineThirdStage(line, firstResult._1 + secondResult._1 + tupNew._1)
      (tupNew._1 + tupOld._1, tupNew._2 :+ tupOld._2)
    }
  else
    secondResult
} else {
  firstResult
}
val result = fullResult._2.map(findCountOfPlacesAtTheLinFinalStage).sum
println(result)
fullResult._2.map(println)
}


You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The $$$j$$$-th cell of the $$$i$$$-th row contains an integer $$$a_{ij}$$$.First, you have to color each row of the matrix either red or blue in such a way that at least one row is colored red and at least one row is colored blue.Then, you have to choose an integer $$$k$$$ ($$$1 \le k < m$$$) and cut the colored matrix in such a way that the first $$$k$$$ columns become a separate matrix (the left matrix) and the last $$$m-k$$$ columns become a separate matrix (the right matrix).The coloring and the cut are called perfect if two properties hold:   every red cell in the left matrix contains an integer greater than every blue cell in the left matrix;  every blue cell in the right matrix contains an integer greater than every red cell in the right matrix. Find any perfect coloring and cut, or report that there are none.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 5 \cdot 10^5$$$; $$$n \cdot m \le 10^6$$$) — the number of rows and the number of columns in the matrix, respectively. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le 10^6$$$). The sum of $$$n \cdot m$$$ over all testcases doesn't exceed $$$10^6$$$.

For each testcase print an answer. If there are no perfect colorings and cuts in the matrix, then print "NO". Otherwise, first, print "YES". Then a string, consisting of $$$n$$$ characters: the $$$i$$$-th character should be 'R' if the $$$i$$$-th row is colored red and 'B' if it's colored blue. The string should contain at least one 'R' and at least one 'B'. Finally, print an integer $$$k$$$ ($$$1 \le k < m$$$) — the number of columns from the left that are cut.

NoteThe coloring and the cut for the first testcase:

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class pair(var minl: Int, var maxl:  Int, var minr: Int, var maxr:  Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return minl.compareTo(that.minl)
        }
    }
    val rem = 998244353
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        val arr = Array.ofDim[Int](n+1, m+1)
        val lmin = Array.ofDim[Int](n+1, m+2)
        val lmax = Array.ofDim[Int](n+1, m+2)
        val rmin = Array.ofDim[Int](n+1, m+2)
        val rmax = Array.ofDim[Int](n+1, m+2)
        for (i <- 1 to n){
            lmin(i)(0) = 1000000
            lmax(i)(0) = 1
            for (j <- 1 to m) {
                arr(i)(j) = readInt()
                lmin(i)(j) = min(lmin(i)(j-1), arr(i)(j))
                lmax(i)(j) = max(lmax(i)(j-1), arr(i)(j))
            }
        }
        for (i <- 1 to n) {
            rmin(i)(m+1) = 1000000
            rmax(i)(m+1) = 1
            for (j <- (1 to m).reverse) {
                rmin(i)(j) = min(rmin(i)(j+1), arr(i)(j))
                rmax(i)(j) = max(rmax(i)(j+1), arr(i)(j))
            }
        }
        var ans = -1
        var col = new Array[Char](n+1)
        var j = 1
        while (j < m && ans == -1) {
            val rows = new Array[pair](n)
            for (i <- 1 to n) {
                rows(i-1) = pair(lmin(i)(j), lmax(i)(j), rmin(i)(j+1), rmax(i)(j+1), i)
            }
            quickSort(rows)
            val minr = new Array[Int](n+1)
            val maxr = new Array[Int](n+1)
            maxr(n) = 0
            for (i <- (0 to n-1).reverse)
                maxr(i) = max(maxr(i+1), rows(i).maxr)
            var close = 0
            var i = 0
            while (i < n-1 && ans == -1) {
                if (i == 0)
                    minr(i) = rows(i).minr
                else
                    minr(i) = min(minr(i-1), rows(i).minr)
                close = max(close, rows(i).maxl)
                if (close < rows(i+1).minl) {
                    if (maxr(i+1) < minr(i)) {
                        ans = j
                        for (k <- 0 to i)
                            col(rows(k).ind) = 'B'
                        for (k <- i+1 to n-1)
                            col(rows(k).ind) = 'R'
                    }
                }
                i += 1
            }
            j += 1
        }
        if (ans == -1) {
            writer.println("NO")
        } else {
            writer.println("YES")
            for (i <- 1 to n)
                writer.print(col(i))
            writer.println(" " + ans)
        }
    }
    writer.flush()
}


A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.

You are given four integers V1, V2, V3, Vm(1 ≤ Vi ≤ 100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1 > V2 > V3.

Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively. If there are multiple possible solutions, print any. If there is no solution, print "-1" (without quotes).

NoteIn first test case all conditions for cars' sizes are satisfied.In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20.

import java.util

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

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  def doCase() : Unit = {
    val Array(f, mo, son, ma) = readIntLine()

    var l = f
    while (l <= f * 2) {
      var m = mo
      while (m < Math.min(mo * 2 + 1, l)) {
        var s = son
        while (s < Math.min(m, son * 2 + 1)) {

          if (ma * 2 >= s && ma <= s && ma * 2 < m) {
            println(l)
            println(m)
            println(s)
            return
          }

          s += 1
        }
        m += 1
      }
      l += 1
    }
    println(-1)

  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(v3, v2, v1, vm) = readInts(4)

  for {
    c1 <- vm to 200
    c2 <- c1 + 1 to 200
    c3 <- c2 + 1 to 200
  } {
    if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&
      /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&
      /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&
      2 * vm >= c1 && 2 * vm < c2 && 2 * vm < c3) {
      println(c3)
      println(c2)
      println(c1)
      System.exit(0)
    }
  }

  println(-1)
}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(v3, v2, v1, vm) = readInts(4)

  for {
    c1 <- vm to 200
    c2 <- c1 + 1 to 200
    c3 <- c2 + 1 to 200
  } {
    if (v1 <= c1 && 2 * v1 >= c1 &&
      v2 <= c2 && 2 * v2 >= c2 &&
      v3 <= c3 && 2 * v3 >= c3 &&
      2 * vm >= c1 && 2 * vm < c2 && 2 * vm < c3) {
      println(c3)
      println(c2)
      println(c1)
      System.exit(0)
    }
  }

  println(-1)
}

object AA extends App {
  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val s3 = v3 max vm
  val s2 = (2 * vm + 1) max (2 * v2)
  val s1 = (2 * vm + 1) max (2 * v1)

  def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s

  if (
    vm <= s1 && vm <= s2 && vm <= s3 &&
    like(v1, s1) && like(v2, s2) && like(v3, s3) &&
    !like(vm, s1) && !like(vm, s2) && like(vm, s3)
  ) {
    println(s1)
    println(s2)
    println(s3)
  } else {
    println("-1")
  }
}

/**
  * @see http://codeforces.com/contest/907/problem/A
  */

object AMashaAndBears extends App {
  def like(a: Int, b: Int): Boolean = a <= b && 2 * a >= b

  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val s3 = v3 max vm
  val s2 = (2 * vm + 1) max v2
  val s1 = (2 * vm + 1) max (s2 + 1) max v1

  if (like(v1, s1) && like(v2, s2) && like(v3, s3) && like(vm, s3)) {
    println(s1)
    println(s2)
    println(s3)
  } else println(-1)
}

import java.util

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

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  def doCase() : Unit = {
    val Array(f, mo, s, ma) = readIntLine()

    var lc = f * 2
    var mc = Math.min(lc - 1, mo * 2)
    var sc = Math.max(s, ma)
    if (s * 2 < sc || ma * 2 < sc || s < sc  || ma < sc || sc >= mc) {
      println(-1)
    } else {
      println(lc)
      println(mc)
      println(sc)
    }

  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

}

import java.util

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

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  def doCase() : Unit = {
    val Array(f, mo, s, ma) = readIntLine()

    var lc = f * 2
    var mc = Math.min(lc - 1, mo * 2)
    var sc = Math.max(s, ma)
    if (s * 2 < sc
      || ma * 2 < sc
      || s < sc
      || ma < sc
      || sc >= mc
      || ma * 2 >= mc) {
      println(-1)
    } else {
      println(lc)
      println(mc)
      println(sc)
    }

  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(v3, v2, v1, vm) = readInts(4)

  for {
    c1 <- vm to 200
    c2 <- c1 to 200
    c3 <- c2 to 200
  } {
    val cMin = Math.min(c1, Math.min(c2, c3))
    if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&
      /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&
      /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&
      2 * vm >= cMin && (2 * vm < c1 || c1 == cMin) &&
        (2 * vm < c2 || c2 == cMin) && (2 * vm < c3 || c3 == cMin)) {
      println(c3)
      println(c2)
      println(c1)
      System.exit(0)
    }
  }

  println(-1)
}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(v3, v2, v1, vm) = readInts(4)

  for {
    c1 <- vm to 200
    c2 <- vm to 200
    c3 <- vm to 200
  } {
    val cMin = Math.min(c1, Math.min(c2, c3))
    if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&
      /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&
      /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&
      2 * vm >= cMin && (2 * vm < c1 || c1 == cMin) &&
        (2 * vm < c2 || c2 == cMin) && (2 * vm < c3 || c3 == cMin)) {
      println(c3)
      println(c2)
      println(c1)
      System.exit(0)
    }
  }

  println(-1)
}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(v3, v2, v1, vm) = readInts(4)

  for {
    c1 <- vm to 200
    c2 <- vm to 200
    c3 <- vm to 200
  } {
    if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&
      /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&
      /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&
      2 * vm >= c1 && 2 * vm < c2 && 2 * vm < c3) {
      println(c3)
      println(c2)
      println(c1)
      System.exit(0)
    }
  }

  println(-1)
}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(v3, v2, v1, vm) = readInts(4)

  for {
    c1 <- vm to 200
    c2 <- vm to 200
    c3 <- vm to 200
  } {
    if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&
      /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&
      /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * c3 >= c3 &&
      2 * vm >= c1 && 2 * vm < c2 && 2 * vm < c3) {
      println(c3)
      println(c2)
      println(c1)
      System.exit(0)
    }
  }

  println(-1)
}

object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(v3, v2, v1, vm) = readInts(4)

  for {
    c1 <- vm to 200
    c2 <- c1 + 1 to 200
    c3 <- c2 + 1 to 200
  } {
    if (v1 <= c1 && 2 * v1 >= c1 && //2 * v1 < c2 && //2 * v1 < c2 */&&
      /*v2 > c1 && */v2 <= c2 && 2 * v2 >= c2 && //2 * v2 < c3 &&
      /*v3 > c1 && v3 > c2 && */v3 <= c3 && 2 * v3 >= c3 &&
      2 * vm >= c1) {
      println(c3)
      println(c2)
      println(c1)
      System.exit(0)
    }
  }

  println(-1)
}

object AA extends App {
  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val s3 = v3 max vm
  val s2 = (2 * vm) max v2
  val s1 = (2 * vm) max v1

  def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s

  if (like(v3, s3) && like(v2, s2) && like(v1, s1) && like(vm, s3) && !like(vm, s2) && !like(vm, s1)) {
    println(v1)
    println(v2)
    println(v3)
  } else {
    println("-1")
  }

}

object AA extends App {
  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val s3 = v3 max vm
  val s2 = (2 * vm + 1) max v2
  val s1 = (2 * vm + 1) max v1

  def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s

  if (
    vm <= s1 && vm <= s2 && vm <= s3 &&
    like(v1, s1) && like(v2, s2) && like(v3, s3) &&
    like(vm, s1) && !like(vm, s2) && !like(vm, s3)
  ) {
    println(v1)
    println(v2)
    println(v3)
  } else {
    println("-1")
  }
}

object AA extends App {
  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val s3 = v3 max vm
  val s2 = (s3 + 1) max v2
  val s1 = (s3 + 1) max v1

  def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s

  if (like(v3, s3) && like(v2, s2) && like(v1, s1) && like(vm, s3) && !like(vm, s2) && !like(vm, s1)) {
    println(v1)
    println(v2)
    println(v3)
  } else {
    println("-1")
  }

}

object AA extends App {
  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val s3 = v3 max vm
  val s2 = (2 * vm + 1) max v2
  val s1 = (2 * vm + 1) max v1

  def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s

  if (
    vm <= s1 && vm <= s2 && vm <= s3 &&
    like(v1, s1) && like(v2, s2) && like(v3, s3) &&
    !like(vm, s1) && !like(vm, s2) && like(vm, s3)
  ) {
    println(v1)
    println(v2)
    println(v3)
  } else {
    println("-1")
  }
}

object AA extends App {
  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  if ((v3 max vm) > ((2 * v3) min (2 * vm))) println("-1")
  else {
    println(v1)
    println(v2)
    println(v3 max vm)
  }
}

object AA extends App {
  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val s3 = v3 max vm
  val s2 = (2 * vm + 1) max v2
  val s1 = (2 * vm + 1) max v1

  def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s

  if (like(v3, s3) && like(v2, s2) && like(v1, s1) && like(vm, s3) && !like(vm, s2) && !like(vm, s1)) {
    println(v1)
    println(v2)
    println(v3)
  } else {
    println("-1")
  }

}

object AA extends App {
  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val s3 = v3 max vm
  val s2 = (2 * vm + 1) max (2 * v2)
  val s1 = (2 * vm + 1) max (2 * v1)

  def like(v: Int, s: Int): Boolean = v <= s && 2 * v >= s

  if (
    vm <= s1 && vm <= s2 && vm <= s3 &&
    like(v1, s1) && like(v2, s2) && like(v3, s3) &&
    !like(vm, s1) && !like(vm, s2) && like(vm, s3)
  ) {
    println(v1)
    println(v2)
    println(v3)
  } else {
    println("-1")
  }
}

/**
  * @see http://codeforces.com/contest/907/problem/A
  */

object AMashaAndBears extends App {
  def like(a: Int, b: Int): Boolean = a <= b && 2 * a >= b

  val Array(v1, v2, v3, vm) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val s3 = v3 max vm
  val s2 = (2 * vm + 1) max v2
  val s1 = (2 * vm + 1) max v1

  if (like(v1, s1) && like(v2, s2) && like(v3, s3) && like(vm, s3)) {
    println(s1)
    println(s2)
    println(s3)
  } else println(-1)
}