You are given a string $$$s$$$ consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'. Note that each of the characters '?' is replaced independently from the others.A string $$$t$$$ of length $$$n$$$ is called a palindrome if the equality $$$t[i] = t[n-i+1]$$$ is true for all $$$i$$$ ($$$1 \le i \le n$$$).For example, if $$$s=$$$"01?????0", $$$a=4$$$ and $$$b=4$$$, then you can replace the characters '?' in the following ways:   "01011010";  "01100110". For the given string $$$s$$$ and the numbers $$$a$$$ and $$$b$$$, replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 2 \cdot 10^5$$$, $$$a + b \ge 1$$$). The second line of each test case contains the string $$$s$$$ of length $$$a+b$$$, consisting of the characters '0', '1', and '?'. It is guaranteed that the sum of the string lengths of $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output:    "-1", if you can't replace all the characters '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and that it contains exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1';  the string that is obtained as a result of the replacement, otherwise.  If there are several suitable ways to replace characters, you can output any.

object Main {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.util.control.NonFatal

  def main(_argv: Array[String]): Unit = {
    val input = new BufferedReader(new InputStreamReader(System.in))
    val output = new PrintWriter(System.out)
    val solver = new T1512C(input, output)
    solver.solve()
    //println( solver.oneLine( "0", zeros = 0, ones = 1 ) )
    output.close()
  }

  class T1512C(input: BufferedReader, output: PrintWriter) {

    def solve(): Unit = {
      val num = input.readLine().toInt
      for (_ <- 0 until num) {
        val prms = new StringTokenizer(input.readLine())
        val zeros = prms.nextToken().toInt
        val ones = prms.nextToken().toInt
        val data = input.readLine()
        val result = try {
          oneLine(data, zeros, ones)
        }
        catch {
          case NonFatal(_) => "-1"
        }
        output.println(result)
      }
    }

    def oneLine(str: String, zeros: Int, ones: Int): String = {
      if (zeros + ones != str.length) {
        throw new Exception()
      }
      val buf = new Array[Char](str.length)
      var restZeros = zeros
      var restOnes = ones
      for (idx <- buf.indices) {
        val char = str(idx)
        val oppositIndex = buf.length - idx - 1
        val oppositChar = str(oppositIndex)
        if (idx < buf.length / 2) {
          char match {
            case '0' => oppositChar match {
              case '1' =>
                throw new Exception()
              case '0' | '?' =>
                buf(idx) = char
                buf(oppositIndex) = char
                restZeros -= 2
            }
            case '1' => oppositChar match {
              case '0' =>
                throw new Exception()
              case '1' | '?' =>
                buf(idx) = char
                buf(oppositIndex) = char
                restOnes -= 2
            }
            case '?' => ()
          }
        }
        else {
          char match {
            case '0' => oppositChar match {
              case '?' =>
                buf(idx) = char
                restZeros -= 1
                if (idx != oppositIndex) {
                  buf(oppositIndex) = char
                  restZeros -= 1
                }
              case '0' =>
                if (idx == oppositIndex) {
                  buf(oppositIndex) = char
                  restZeros -= 1
                }
            }
            case '1' => oppositChar match {
              case '?' =>
                buf(idx) = char
                restOnes -= 1
                if (idx != oppositIndex) {
                  buf(oppositIndex) = char
                  restOnes -= 1
                }
              case '1' =>
                if (idx == oppositIndex) {
                  buf(oppositIndex) = char
                  restOnes -= 1
                }
            }
            case '?' => ()
          }
        }
      }

      for (idx <- 0 to str.length / 2) {
        val char = buf(idx)
        if (char == '\0') {
          val oppositIndex = buf.length - idx - 1
          if (idx != oppositIndex) {
            if (restZeros > 1) {
              buf(idx) = '0'
              buf(oppositIndex) = '0'
              restZeros -= 2
            }
            else if (restOnes > 1) {
              buf(idx) = '1'
              buf(oppositIndex) = '1'
              restOnes -= 2
            }
            else {
              throw new Exception()
            }
          }
          else {
            if (restZeros > 0 && restZeros % 2 == 1) {
              buf(idx) = '0'
              restZeros -= 1
            }
            else if (restOnes > 0 && restOnes % 2 == 1) {
              buf(idx) = '1'
              restOnes -= 1
            }
            else {
              throw new Exception()
            }
          }
        }
      }

      if (restZeros == 0 && restOnes == 0) {
        buf.mkString("")
      }
      else {
        throw new Exception()
      }
    }
  }
}

import scala.io.StdIn

object Main {
  def test(): String = {
    val in = StdIn.readLine().split(" ")
    var (a, b) = (in(0).toInt, in(1).toInt)
    val s : String = StdIn.readLine()
    val kek : List[(Char, Int)] = s.toList.zipWithIndex
    val n : Int = s.size
    val f : (Char, Int) => Boolean = (e, i) => (s(n - i - 1) == '?' || e == '?' || s(n - i - 1) == e)
    if (a + b != n)
      return "-1"
    if (!kek.forall { (elem) => f(elem._1, elem._2) } )
      return "-1"
    val s2 : List[Char] = kek.map { elem => if (s(n - elem._2 - 1) != '?') s(n - elem._2 - 1) else elem._1 }
    a = a - (s2.count( _ == '0'))
    b = b - s2.count( _ == '1')
    if (a < 0 || b < 0 || (a % 2 == 1 && b % 2 == 1))
      return "-1"
    if (a % 2 == 1 && s2(n / 2) == '1')
      return "-1"
    if (b % 2 == 1 && s2(n / 2) == '0')
      return "-1"

    val a1 = a % 2
    val a2 = b % 2
    a = a / 2
    b = b / 2
    val res : StringBuilder = new StringBuilder()
    for ((elem, i) <- s2.zipWithIndex) {
        if ( elem == '?' && (a > 0 || i == n / 2 && a1 == 1)) {
          res.append('0')
          a -= 1
        }
        else {
          if ( elem == '?' && (b > 0 || i == n / 2 && a2 == 1)) {
            res.append('1')
            b -= 1
          }
          else {
            if (elem == '?')
              res.append(res(n - i - 1))
            else
              res.append(elem)
          }
        }
    }
    return res.toString()
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().toInt
    (1 to t) foreach {
      _ => println(test())
    }
  }
}

object Main {
import java.io.{BufferedReader, InputStreamReader, PrintWriter}
import java.util.StringTokenizer
import scala.util.control.NonFatal

  def main(_argv: Array[String]): Unit = {
    val input = new BufferedReader(new InputStreamReader(System.in))
    val output = new PrintWriter(System.out)
    val solver = new T1512C(input, output)
    solver.solve()
    //    println( solver.oneLine( "?0??10??", zeros = 4, ones = 4 ) )
    output.close()
  }

  class T1512C(input: BufferedReader, output: PrintWriter) {

    def solve(): Unit = {
      val num = input.readLine().toInt
      for (_ <- 0 until num) {
        val prms = new StringTokenizer(input.readLine())
        val zeros = prms.nextToken().toInt
        val ones = prms.nextToken().toInt
        val data = input.readLine()
        val result = try {
          oneLine(data, zeros, ones)
        }
        catch {
          case NonFatal(_) => "-1"
        }
        output.println(result)
      }
    }

    def oneLine(str: String, zeros: Int, ones: Int): String = {
      if (zeros + ones != str.length) {
        throw new Exception()
      }
      val buf = new Array[Char](str.length)
      var restZeros = zeros
      var restOnes = ones
      for (idx <- buf.indices) {
        val char = str(idx)
        val oppositIndex = buf.length - idx - 1
        val oppositChar = str(oppositIndex)
        if (idx < buf.length / 2) {
          char match {
            case '0' => oppositChar match {
              case '1' =>
                throw new Exception()
              case '0' | '?' =>
                buf(idx) = char
                buf(oppositIndex) = char
                restZeros -= 2
            }
            case '1' => oppositChar match {
              case '0' =>
                throw new Exception()
              case '1' | '?' =>
                buf(idx) = char
                buf(oppositIndex) = char
                restOnes -= 2
            }
            case '?' => ()
          }
        }
        else {
          char match {
            case '0' => oppositChar match {
              case '?' =>
                buf(idx) = char
                restZeros -= 1
                if (idx != oppositIndex) {
                  buf(oppositIndex) = char
                  restZeros -= 1
                }
              case '0' => ()
            }
            case '1' => oppositChar match {
              case '?' =>
                buf(idx) = char
                restOnes -= 1
                if (idx != oppositIndex) {
                  buf(oppositIndex) = char
                  restOnes -= 1
                }
              case '1' => ()
            }
            case '?' => ()
          }
        }
      }

      for (idx <- 0 to str.length / 2) {
        val char = buf(idx)
        if (char == '\0') {
          val oppositIndex = buf.length - idx - 1
          if (idx != oppositIndex) {
            if (restZeros > 1) {
              buf(idx) = '0'
              buf(oppositIndex) = '0'
              restZeros -= 2
            }
            else if (restOnes > 1) {
              buf(idx) = '1'
              buf(oppositIndex) = '1'
              restOnes -= 2
            }
            else {
              throw new Exception()
            }
          }
          else {
            if (restZeros > 0 && restZeros % 2 == 1) {
              buf(idx) = '0'
              restZeros -= 1
            }
            else if (restOnes > 0 && restOnes % 2 == 1) {
              buf(idx) = '1'
              restOnes -= 1
            }
            else {
              throw new Exception()
            }
          }
        }
      }

      if (restZeros == 0 && restOnes == 0) {
        buf.mkString("")
      }
      else {
        throw new Exception()
      }
    }
  }
}

import scala.io.StdIn

object Main {
  def test(): String = {
    val in = StdIn.readLine().split(" ")
    var (a, b) = (in(0).toInt, in(1).toInt)
    val s : String = StdIn.readLine()
    val kek : List[(Char, Int)] = s.toList.zipWithIndex
    val n : Int = s.size
    val f : (Char, Int) => Boolean = (e, i) => (s(n - i - 1) == '?' || e == '?' || s(n - i - 1) == e)
    if (a + b != n)
      return "-1"
    if (!kek.forall { (elem) => f(elem._1, elem._2) } )
      return "-1"
    val s2 : List[Char] = kek.map { elem => if (s(n - elem._2 - 1) != '?') s(n - elem._2 - 1) else elem._1 }
    a = a - (s2.count( _ == '0'))
    b = b - s2.count( _ == '1')
    if (a < 0 || b < 0 || (a % 2 == 1 && b % 2 == 1))
      return "-1"

    a = a / 2 + a % 2
    b = b / 2 + b % 2
    val res : StringBuilder = new StringBuilder()
    for ((elem, i) <- s2.zipWithIndex) {
        if (elem == '?' && a > 0) {
          res.append('0')
          a -= 1
        }
        else {
          if (elem == '?' && b > 0) {
            res.append('1')
            b -= 1
          }
          else {
            if (elem == '?')
              res.append(res(n - i - 1))
            else
              res.append(elem)
          }
        }
    }
    return res.toString()
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().toInt
    (1 to t) foreach {
      _ => println(test())
    }
  }
}


There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:   Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).  When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.  When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.  The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction. You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of employees.  The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.

Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.

NoteConsider one of the voting scenarios for the first sample:   Employee 1 denies employee 5 to vote.  Employee 2 denies employee 3 to vote.  Employee 3 has no right to vote and skips his turn (he was denied by employee 2).  Employee 4 denies employee 2 to vote.  Employee 5 has no right to vote and skips his turn (he was denied by employee 1).  Employee 1 denies employee 4.  Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _749C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val prefs = read[String].toVector

    def init(c: Char) = mutable.Queue(prefs.indicesWhere(_ == c) : _*)

    val remocrats = init('R')
    val depublicans = init('D')

    @tailrec
    def solve(): Char = {
      if (remocrats.isEmpty) {
        'D'
      } else if (depublicans.isEmpty) {
        'R'
      } else {
        val r = remocrats.dequeue()
        val d = depublicans.dequeue()
        if (r < d) remocrats.enqueue(r + n) else depublicans.enqueue(d + n)
        solve()
      }
    }

    write(solve())
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.

The only line contains an integer n (12 ≤ n ≤ 106).

Output two composite integers x and y (1 < x, y < n) such that x + y = n. If there are multiple solutions, you can output any of them.

NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.

import scala.io.StdIn

object Task472A {
	def main(args: Array[String]) {
		val n = StdIn.readInt()
		for (i <- 4 to n)
			if (!isPrime(i) && !isPrime(n-i)) {
				println(i + " " + (n - i))
				return
			}
	}

	def isPrime(n: Int): Boolean = {
		if (n % 2 == 0) return false
		var i = 3
		while (i*i <= n) if (n % i == 0) return false else i += 2
		true
	}
}

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

/**
 * Created by arseny on 28.09.14.
 */
object A extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt

    def sieve(n: Long): Array[Boolean] = {
      val primes = Array.fill(n.toInt + 1)(true)
      primes(0) = false
      primes(1) = false
      for(i <- 2L to n) {
        if(primes(i.toInt)) {
          if(i * i <= n) {
            for(j <- i * i to n by i) {
              primes(j.toInt) = false
            }
          }
        }
      }
      primes
    }

    val primes = sieve(1000000)
    //print(primes.toList)

    var found = false
    for (i <- 2 until n if !found) {
      if ((primes(i) == false) && (primes(n - i) == false)) {
        out.print(s"$i ${n - i}")
        found = true
      }
    }
  }

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

object TaskA {
  def main(args: Array[String]) {
    val n = readInt
    println {
      n match {
        case 12 => "6 6"
        case x if x % 2 == 0 => s"4 ${x - 4}"
        case x => s"9 ${x - 9}"
      }
    }
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._

object HelloWorld {

  def main(args: Array[String]) {

    val n = readInt()

    println(
      if (n % 2 == 0) ("4 " + (n-4))
      else ("9 " + (n-9))
    )

  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._

object HelloWorld {

  def is_compound(value: Int) = {
    var end = false

    for(i <- 2 to sqrt(value).toInt if !end) {
      if (value % i == 0) end = true
    }

    end
  }

  def main(args: Array[String]) {

    val n = readInt()
    var end = false

    for(i <- 4 to (n / 2, 2) if !end) {
      val j = n - i

      if (is_compound(j)) {
        println(i + " " + j)
        end = true
      }
    }

  }
}

object A472 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.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))
  }

  def genPrimes(till: Int): Array[Int] = {
    val isPrime = Array.fill[Boolean](till+1)(true)
    isPrime(0) = false
    isPrime(1) = true // not composite
    for(i <- 4 to till by 2) {
      isPrime(i) = false
    }
    for(i <- 3 to till by 2 if isPrime(i)) {
      for(j <- i+i to till by i) isPrime(j) = false
    }
    isPrime.zipWithIndex.filter(_._1).map(_._2)
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val primes = genPrimes(n).toSet
    for(i <- 1 to n/2) {
      if(!primes.contains(i) && !primes.contains(n - i)) {
        println(s"$i ${n-i}")
        return
      }
    }
  }
}

import scala.math._

object Main extends App{
  val n = readInt
  val iList = List(4, 6, 8, 10, 12)
  var result = for(i <- iList; m = n - i)
    yield if(m % 2 == 0 || m % 3 == 0 || m % 5 == 0 || m % 7 == 0 || (m % 11 == 0 && m != 11))
     (m, i)
  var res = result.filter(x => x != ()).head.toString.replace(',',' ') drop 1 dropRight 1
  print(res)
}

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 LIMIT = n
  val prime = Array.fill(LIMIT)(true)
  prime(0) = false

  Stream.from(2).takeWhile(i => i * i < LIMIT).filter(prime(_)).foreach { i =>
    (i * i until LIMIT by i).foreach(prime(_) = false)
  }
  val primes = prime.indices.filter(prime(_)).toSet

  for (i <- 4 until n) {
    val j = n - i
    if (!primes(i) && !primes(j)) {
      println(s"$i $j")
      System.exit(0)
    }
  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/472/A"/>
 *
 * @author pvasilyev
 * @since 08 Apr 2016
 */
object Problem147 extends App {

  val number = scala.io.StdIn.readInt()

  def isNotPrime(number: Int): Boolean = {
    val upperBound = Math.sqrt(number).toInt + 1
    val range = 2 to upperBound
    for (x <- range) {
      if (number % x == 0) {
        return true
      }
    }
    return false
  }

  def solve(number: Int): String = {
      for (x <- 4 to number / 2) {
        if (isNotPrime(x) && isNotPrime(number - x)) {
          return x.toString() + " " + (number - x).toString()
        }
      }
    ""
  }

  println(solve(number))

}

object DesignTutorial {
	def main(args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextLong;
		if (n % 2 == 0) {
			println(n - 4+ " "+4)
		}
		else {
			println(n - 9+ " "+9)
		}
	}
}

object Main {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);

  def main(args: Array[String]) {
    var Array(n) = READ;
    if (n%2 == 0) println("4 " + (n-4));
    else println("9 " + (n-9));
  }
}

import scala.io.StdIn

/**
 * Created by breezzo on 19.02.17.
 */
object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val primes = new Primes(n)

    for (i <- 4 to n) {
      if (!primes.isPrime(i)) {
        val y = n - i
        if (!primes.isPrime(y)) {
          println(i + " " + y)
          return
        }
      }
    }
  }

  class Primes(val n: Int) {
    val primes = Array.fill(n + 1)(true)
    primes(0) = false
    primes(1) = false

    for (i <- 2 to n if primes(i) && i.toLong * i <= n) {
      for (j <- i * i to n by i) {
        primes(j) = false
      }
    }

    def isPrime(v: Int): Boolean = {
      primes(v)
    }
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-29.
 */
object A472 extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  var com1 = 4
  var com2 = n - com1

  def isComposite(com: Int): Boolean = {
    if (com < 4) {
      false
    } else if (com == 4) {
      true
    } else {
      var i = 2

      while (i < com) {
        if (com % i == 0) {
          return true
        }

        i += 1
      }

      false
    }
  }

  while (!(isComposite(com1) && isComposite(com2))) {
    com1 += 1
    com2 -= 1
  }

  println(com1 + " " + com2)
}

import scala.io.StdIn.readInt
import Math.sqrt

object DesignTutorial {

   def isPrime(p : Int) : Boolean =
    p != 1 && (p == 2 || (2 to sqrt(p*1.0).toInt by 1).toList.forall { p % _ != 0 })

   def main(args: Array[String]) {
     val n = readInt
     Stream.from(4).find { x => !isPrime(x) && !isPrime(n-x) } match {
       case Some(x) => println(x + " " + (n-x))
       case _       => println("should not happen")
     }
   }

}

import scala.io.StdIn._

object Main2 extends App {
  val number = readInt()
  println(s"${number - (number%2+8)} ${number%2+8}")
}

import scala.annotation.tailrec

object Main extends App {

  val n: Int = io.StdIn.readInt()

  def solve(n: Int): String = {
    @tailrec
    def tailRec(i: Int, j: Int): String = {
      if (!isPrime(i) && !isPrime(j)) s"$i $j"
      else tailRec(i - 1, j + 1)
    }

    tailRec(n / 2, n - n / 2)
  }

  def isPrime(n: Int): Boolean = {
    @tailrec
    def isPrimeHelper(x: Int, acc: Boolean): Boolean = {
      if (!acc) false
      else if (x <= 1) true
      else isPrimeHelper(x - 1, n % x != 0 && acc)
    }

    isPrimeHelper(n / 2, acc = true)
  }

  println(solve(n))
}

import java.io._

object Solution extends App {
  val n = readInt

  def isPrime(n:Int):Boolean = {
    def paux(n:Int, i:Int):Boolean = {
      (n % i != 0) && (i*i > n || paux(n, i+2))
    }

    if(n == 1)
      false
    else if(n % 2 == 0)
      false
    else
      paux(n, 3)
  }

  val ans = Stream.range(4, n/2+1).map(a => (a, n-a)).filter{ case(a, b) =>
    !isPrime(a) && !isPrime(b)
  }.head

  println(s"${ans._1} ${ans._2}")
}

import java.io._

object Solution extends App {
  val n = readInt

  def isPrime(n:Int):Boolean = {
    if(n == 1)
      false
    else if(n % 2 == 0)
      false
    else
      Stream.from(3, 2).takeWhile(i => i*i < n + 1).forall(i => n % i != 0)
  }

  val ans = Stream.range(4, n/2+1).map(a => (a, n-a)).filter{ case(a, b) =>
    !isPrime(a) && !isPrime(b)
  }.head

  println(s"${ans._1} ${ans._2}")
}

import scala.io.StdIn

object Task472A {
	def main(args: Array[String]) {
		val n = StdIn.readInt()
		for (i <- 2 to n)
			if (!isPrime(i) && !isPrime(n-i)) {
				println(i + " " + (n - i))
				return
			}
	}

	def isPrime(n: Int): Boolean = {
		if (n % 2 == 0) return false
		var i = 3
		while (i*i <= n) if (n % i == 0) return false else i += 2
		true
	}
}

import scala.math._

object Main extends App{
  val n = readInt
  val iList = List(4, 6, 8, 10, 12)
  var result = for(i <- iList; m = n - i)
    yield if(m % 2 == 0 || m % 3 == 0 || m % 5 == 0 || m % 7 == 0 || m % 11 == 0)
     (m, i)
  var res = result.filter(x => x != ()).head.toString.replace(',',' ') drop 1 dropRight 1
  print(res)
}

/**
 * <a href="http://codeforces.com/problemset/problem/472/A"/>
 *
 * @author pvasilyev
 * @since 08 Apr 2016
 */
object Problem147 extends App {

  val number = scala.io.StdIn.readInt()

  def isNotPrime(number: Int): Boolean = {
    val upperBound = Math.sqrt(number).toInt + 1
    val range = 2 to upperBound
    for (x <- range) {
      if (number % x == 0) {
        return true
      }
    }
    return false
  }

  def solve(number: Int): String = {
      for (x <- 4 until number / 2) {
        if (isNotPrime(x) && isNotPrime(number - x)) {
          return x.toString() + " " + (number - x).toString()
        }
      }
    ""
  }

  println(solve(number))

}

import java.io._

object Solution extends App {
  val n = readInt

  def isPrime(n:Int):Boolean = {
    def paux(n:Int, i:Int):Boolean = {
      (n % i == 0) && (i*i > n || paux(n, i+2))
    }

    if(n == 1)
      false
    else if(n % 2 == 0)
      false
    else
      paux(n, 3)
  }

  val ans = Stream.range(4, n/2+1).map(a => (a, n-a)).filter{ case(a, b) =>
    !isPrime(a) && !isPrime(b)
  }.head

  println(s"${ans._1} ${ans._2}")
}


Luntik has decided to try singing. He has $$$a$$$ one-minute songs, $$$b$$$ two-minute songs and $$$c$$$ three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.He wants to make the absolute difference of durations of the concerts as small as possible. The duration of the concert is the sum of durations of all songs in that concert.Please help Luntik and find the minimal possible difference in minutes between the concerts durations.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$a, b, c$$$ $$$(1 \le a, b, c \le 10^9)$$$ — the number of one-minute, two-minute and three-minute songs.

For each test case print the minimal possible difference in minutes between the concerts durations.

NoteIn the first test case, Luntik can include a one-minute song and a two-minute song into the first concert, and a three-minute song into the second concert. Then the difference will be equal to $$$0$$$.In the second test case, Luntik can include two one-minute songs and a two-minute song and a three-minute song into the first concert, and two three-minute songs into the second concert. The duration of the first concert will be $$$1 + 1 + 2 + 3 = 7$$$, the duration of the second concert will be $$$6$$$. The difference of them is $$$|7-6| = 1$$$.

object A extends App {

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val a = nextInt()
    val b = nextInt()
    val c = nextInt()

    val d =
      if (a == b && b == c) 0
      else {
        val f = a + 2 * b + 3 * c
        val h = f / 2
        (f - 2 * h).abs
      }

    out.println(d)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

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

}

object A extends App {

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val a = nextInt()
    val b = nextInt()
    val c = nextInt()

    val d = ((3 * (c % 2) - 2 * (b % 2)).abs - (a % 2)).abs

    out.println(d)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

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

}


Berland scientists face a very important task - given the parts of short DNA fragments, restore the dinosaur DNA! The genome of a berland dinosaur has noting in common with the genome that we've used to: it can have 26 distinct nucleotide types, a nucleotide of each type can occur at most once. If we assign distinct English letters to all nucleotides, then the genome of a Berland dinosaur will represent a non-empty string consisting of small English letters, such that each letter occurs in it at most once.Scientists have n genome fragments that are represented as substrings (non-empty sequences of consecutive nucleotides) of the sought genome.You face the following problem: help scientists restore the dinosaur genome. It is guaranteed that the input is not contradictory and at least one suitable line always exists. When the scientists found out that you are a strong programmer, they asked you in addition to choose the one with the minimum length. If there are multiple such strings, choose any string.

The first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of genome fragments. Each of the next lines contains one descriptions of a fragment. Each fragment is a non-empty string consisting of distinct small letters of the English alphabet. It is not guaranteed that the given fragments are distinct. Fragments could arbitrarily overlap and one fragment could be a substring of another one. It is guaranteed that there is such string of distinct letters that contains all the given fragments as substrings.

In the single line of the output print the genome of the minimum length that contains all the given parts. All the nucleotides in the genome must be distinct. If there are multiple suitable strings, print the string of the minimum length. If there also are multiple suitable strings, you can print any of them.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next())
  val first = data.map(_.head).toSet
  val filtered = first.filter(ch => !data.map(_.tail).exists(_.contains(ch)))
  val soFar = filtered.map(ch => data.filter(_.head == ch).maxBy(_.length))
  val left = data.filter(i => !filtered.contains(i.head))

  def increase(s: String, left: Seq[String]): String = {
    left.find(str => s.contains(str.head)) match {
      case None => s
      case Some(str) if s.contains(str) =>
        increase(s, left.filter(_ != str))
      case Some(str) =>
        increase(s.takeWhile(_ != str.head) + str, left.filter(_ != str))
    }
  }

  println(soFar.map(i => increase(i, left)).mkString)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()

  def join(str1: String, str2: String, ch: Char) =
    if (str1.isEmpty || str2.contains(str1))
      str2
    else if (str1.contains(str2))
      str1
    else if (!str1.contains(ch)) {
      str1 + str2
    }
    else {
      val index1 = str1.indexOf(ch)
      val index2 = str2.indexOf(ch)
      if (index2 > index1)
        str2.take(index2) + str1.drop(index1)
      else
        str1.take(index1) + str2.drop(index2)
    }

  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next())
  println(('a' to 'z').foldLeft("") {
    case(acc, ch) => data.filter(_.contains(ch)).foldLeft(acc) {
      case (acc, line) => join(acc, line, ch)
    }
  })
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()

  def join(str1: String, str2: String, ch: Char) =
    if (str1.isEmpty || str2.contains(str1))
      str2
    else if (str1.contains(str2))
      str1
    else if (!str1.contains(ch)) {
      str1 + str2
    }
    else {
      val index1 = str1.indexOf(ch)
      val index2 = str2.indexOf(ch)
      if (index2 > index1)
        str2.take(index2) + str1.drop(index1)
      else
        str1.take(index1) + str2.drop(index2)
    }
  val visited = Array.ofDim[Boolean](26)
  val canVisit = Array.ofDim[Boolean](26)

  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next())
  data.head.foreach{
    ch => canVisit(ch - 'a') = true
  }

  println((1 to 26).foldLeft(data.head) {
    case (acc, _) =>
      val ch =
        (0 until 26).find(canVisit).map(i => (i + 'a').toChar).getOrElse {
          val index = (0 until 26).find(i => !visited(i)).get
          (index + 'a').toChar
        }
      visited(ch - 'a') = true
      canVisit(ch - 'a') = false
      val res = data.filter(_.contains(ch)).foldLeft(acc) {
        case (acc, line) => join(acc, line, ch)
      }
      res.foreach {
        ch => if (!visited(ch - 'a')) canVisit(ch - 'a') = true
      }
      res
  })
}


You have $$$n$$$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $$$i$$$-th gift consists of $$$a_i$$$ candies and $$$b_i$$$ oranges.During one move, you can choose some gift $$$1 \le i \le n$$$ and do one of the following operations:  eat exactly one candy from this gift (decrease $$$a_i$$$ by one);  eat exactly one orange from this gift (decrease $$$b_i$$$ by one);  eat exactly one candy and exactly one orange from this gift (decrease both $$$a_i$$$ and $$$b_i$$$ by one). Of course, you can not eat a candy or orange if it's not present in the gift (so neither $$$a_i$$$ nor $$$b_i$$$ can become less than zero).As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: $$$a_1 = a_2 = \dots = a_n$$$ and $$$b_1 = b_2 = \dots = b_n$$$ (and $$$a_i$$$ equals $$$b_i$$$ is not necessary).Your task is to find the minimum number of moves required to equalize all the given gifts.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of gifts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the number of candies in the $$$i$$$-th gift. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the number of oranges in the $$$i$$$-th gift.

For each test case, print one integer: the minimum number of moves required to equalize all the given gifts.

NoteIn the first test case of the example, we can perform the following sequence of moves:  choose the first gift and eat one orange from it, so $$$a = [3, 5, 6]$$$ and $$$b = [2, 2, 3]$$$;  choose the second gift and eat one candy from it, so $$$a = [3, 4, 6]$$$ and $$$b = [2, 2, 3]$$$;  choose the second gift and eat one candy from it, so $$$a = [3, 3, 6]$$$ and $$$b = [2, 2, 3]$$$;  choose the third gift and eat one candy and one orange from it, so $$$a = [3, 3, 5]$$$ and $$$b = [2, 2, 2]$$$;  choose the third gift and eat one candy from it, so $$$a = [3, 3, 4]$$$ and $$$b = [2, 2, 2]$$$;  choose the third gift and eat one candy from it, so $$$a = [3, 3, 3]$$$ and $$$b = [2, 2, 2]$$$.

//package codeforces.contests._1399

object GiftsFixing {
  def main(args: Array[String]): Unit = {
    for (t <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readInt()
      val a, b = io.StdIn.readLine.split(" ").map(_.toInt)

      val minA = a.min
      val minB = b.min

      val answer = (0 until n).foldLeft(0L)((acc, i) => acc + {

        val decA = a(i) - minA
        val decB = b(i) - minB

        decA max decB
      })

      println(answer)
    }
  }
}

import scala.io.Source

object GiftsFixing1399B extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//    val lines: Iterator[String] =
//      Source.fromString("5\n3\n3 5 6\n3 2 3\n5\n1 2 3 4 5\n5 4 3 2 1\n3\n1 1 1\n2 2 2\n6\n1 1000000000 1000000000 1000000000 1000000000 1000000000\n1 1 1 1 1 1\n3\n10 12 8\n7 5 4").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach println

  def handleTC() = {
    if (lines.next.toInt == 1) {
      lines.next; lines.next;
      0L
    } else {
      val as = lines.next.split(" ").map(_.toLong)
      val bs = lines.next.split(" ").map(_.toLong)
      solve(as, bs)
    }
  }

  def solve(as: Array[Long], bs: Array[Long]) = {
    val am = as.min
    val bm = bs.min
    as.zip(bs).map { case (a, b) =>
      Math.max(a-am,b-bm)
    }.sum
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val xs = StdIn.readLine().split(" ").map(_.toLong)
      val ys  = StdIn.readLine().split(" ").map(_.toLong)
      val x = xs.min
      val y = ys.min
      val res = xs.map(_ - x) zip ys.map(_ - y) map {
        case (i, j) => i max j
      }
      println(res.sum)
    }
  }
}

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

import scala.collection.mutable

object B {

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

  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)
    }
    st.nextToken
  }

  def nextInt: Int = Integer.parseInt(next)

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      map.getOrDefault(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = map.firstKey()

    def last(): T = map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Unit = {
    val t = nextInt
    for (_ <- 0 until t) {
      val n = nextInt
      val apples = new Array[Int](n)
      val bananas = new Array[Int](n)
      for (i <- 0 until n) {
        apples(i) = nextInt
      }
      val min_app = apples.sorted.apply(0)
      for (i <- 0 until n) {
        bananas(i) = nextInt
      }
      val min_ban = bananas.sorted.apply(0)
      var moves = 0L
      for (i <- 0 until n) {
        val diff1 = apples(i) - min_app
        val diff2 = bananas(i) - min_ban
        moves += Math.min(diff1, diff2)
        moves += Math.max(diff1, diff2) - Math.min(diff1, diff2)

      }
      out.println(moves)

    }
  }
}

object _1399B extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = io.repeat {
    val n = io.read[Int]
    val candies, oranges = io.read[Vector, Long](n)

    val minCandy = candies.min
    val minOrange = oranges.min

    val ans = candies.zip(oranges) map {
      case (c, o) =>
        val candiesToEat = c - minCandy
        val orangesToEat = o - minOrange
        (candiesToEat min orangesToEat) + (candiesToEat - orangesToEat).abs
    }

    io.write(ans.sum)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.The verse patterns for the given text is a sequence of n integers p1, p2, ..., pn. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to pi.You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.

The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of lines in the text. The second line contains integers p1, ..., pn (0 ≤ pi ≤ 100) — the verse pattern. Next n lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.

If the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).

4
13 11 15 15
to be or not to be that is the question
whether tis nobler in the mind to suffer
the slings and arrows of outrageous fortune
or to take arms against a sea of troubles

NoteIn the first sample, one can split words into syllables in the following way: in-telco-dech al-len-geSince the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one.

import scala.io.StdIn
import scala.math.pow
import scala.collection.mutable._

object Main {
  implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }

  def main(args: Array[String]): Unit = {
    val n = readInt
    val patterns = readLine.split(' ').map(_.toInt)

    var ok = true

    patterns.foreach { pattern =>
      val verse = readLine
      val vowels = verse.replaceAll("[^aeiouy]", "").length()

      if (ok && pattern != vowels) { ok = false }
    }

    println(
      if (ok) "YES" else "NO"
    )
  }
}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

object test extends App {
	val vowels = List('a', 'e', 'i', 'o', 'u', 'y')
	val sc = new Scanner(System.in)
	val n = sc.nextInt()
	val numbers = List.range(0, n).map(x => sc.nextInt())
	sc.nextLine()
	val textLine = List.range(0, n).map(x => sc.nextLine())
	val counts = for (i <- 0 until textLine.length)
		yield textLine(i).count(vowels.contains(_))
	println(
		if (counts == numbers)
			"YES"
		else
			"NO"
	)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val vov = Array[Char]('a', 'e', 'i', 'o', 'u', 'y')
  val lines = in.take(n).map(_.count(vov.contains)).toArray
  if (lines sameElements line)
    println("YES")
  else
    println("NO")
}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {

  val vowels = List('a', 'e', 'i', 'o', 'u', 'y')

  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val xs = List.range(0, n).map { _ => sc.nextInt() }
  sc.nextLine()
  val ys = List.range(0, n).map { _ => sc.nextLine() }
  val counts = for (i <- List.range(0, ys.length)) yield ys(i).count(vowels.contains(_))
  println(
    if(counts == xs) "YES" else "NO"
  )
}

object B 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 vowel = Set('a', 'e', 'i', 'o', 'u', 'y')
  val Array(n) = readInts(1)
  val ps = readInts(n)
  val ss = Array.fill(n){ readLine }

  val ok = (0 until n).forall(i => ss(i).count(vowel) == ps(i))

  println(if (ok) "YES" else "NO")
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _722B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val patterns = read[Vector[Int]]
    val input = patterns.zipWith(i => io.readTillEndOfLine())
    val vowels = "aeiouy".toSet

    val ans = input forall {case (pattern, line) =>
      line.count(vowels) ==  pattern
    }

    write(ans.toEnglish)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.Suppose Ciel and Jiro play optimally, what is the score of the game?

The first line contain an integer n (1 ≤ n ≤ 100). Each of the next n lines contains a description of the pile: the first integer in the line is si (1 ≤ si ≤ 100) — the number of cards in the i-th pile; then follow si positive integers c1, c2, ..., ck, ..., csi (1 ≤ ck ≤ 1000) — the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile.

Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally.

NoteIn the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10.In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3.

/**
 * I've tried to make this piece of code as readable as possible.
 * Please hack me if you can!
 */
import scala.collection._

object C extends App {

  def tokenizeLine = new java.util.StringTokenizer(readLine)

  val n = readInt
  val cs = Array.ofDim[Array[Int]](n)
  val ws = Array.fill(n)(BigInt(0))
  var sum = 0L
  val C = BigInt(1001)

  for (i <- 0 until n) {
    val t = tokenizeLine
    val s = t.nextToken.toInt
    cs(i) = Array.fill(s)(t.nextToken.toInt)
    sum += cs(i).sum
    var mul = BigInt(1)
    for (j <- 0 until (s + 1) / 2) {
      ws(i) += mul * cs(i)(j)
      mul *= C
    }
    ws(i) *= C.pow(50 - s / 2)
  }

  val wis = (ws zipWithIndex).sortBy(- _._1)
//println(wis.mkString(" "))
  var sumA = 0L
  var pos = 1
  for (wi <- wis) {
    wi match {
      case (w, i) => sumA += cs(i).take((cs(i).size + (pos % 2)) / 2).sum
    }
    pos += 1
  }
  val sumB = sum - sumA
  println(s"$sumA $sumB")
}