Let $$$n$$$ be a positive integer. Let $$$a, b, c$$$ be nonnegative integers such that $$$a + b + c = n$$$.Alice and Bob are gonna play rock-paper-scissors $$$n$$$ times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock $$$a$$$ times, paper $$$b$$$ times, and scissors $$$c$$$ times.Alice wins if she beats Bob in at least $$$\lceil \frac{n}{2} \rceil$$$ ($$$\frac{n}{2}$$$ rounded up to the nearest integer) hands, otherwise Alice loses.Note that in rock-paper-scissors:  rock beats scissors;  paper beats rock;  scissors beat paper. The task is, given the sequence of hands that Bob will play, and the numbers $$$a, b, c$$$, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win.If there are multiple answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then, $$$t$$$ testcases follow, each consisting of three lines:    The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).  The second line contains three integers, $$$a, b, c$$$ ($$$0 \le a, b, c \le n$$$). It is guaranteed that $$$a + b + c = n$$$.  The third line contains a string $$$s$$$ of length $$$n$$$. $$$s$$$ is made up of only 'R', 'P', and 'S'. The $$$i$$$-th character is 'R' if for his $$$i$$$-th Bob plays rock, 'P' if paper, and 'S' if scissors.

For each testcase:    If Alice cannot win, print "NO" (without the quotes).  Otherwise, print "YES" (without the quotes). Also, print a string $$$t$$$ of length $$$n$$$ made up of only 'R', 'P', and 'S' — a sequence of hands that Alice can use to win. $$$t$$$ must contain exactly $$$a$$$ 'R's, $$$b$$$ 'P's, and $$$c$$$ 'S's.  If there are multiple answers, print any of them.  The "YES" / "NO" part of the output is case-insensitive (i.e. "yEs", "no" or "YEs" are all valid answers). Note that 'R', 'P' and 'S' are case-sensitive.

NoteIn the first testcase, in the first hand, Alice plays paper and Bob plays rock, so Alice beats Bob. In the second hand, Alice plays scissors and Bob plays paper, so Alice beats Bob. In the third hand, Alice plays rock and Bob plays scissors, so Alice beats Bob. Alice beat Bob 3 times, and $$$3 \ge \lceil \frac{3}{2} \rceil = 2$$$, so Alice wins.In the second testcase, the only sequence of hands that Alice can play is "RRR". Alice beats Bob only in the last hand, so Alice can't win. $$$1 < \lceil \frac{3}{2} \rceil = 2$$$.

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val n = ni()
      var a, b, c = ni()
      val s = ns(n)
      var ans = 0
      val hands = Array.fill[Char](n)('a')
      REP(n) { i =>
        s(i) match {
          case 'R' =>
            if (b > 0) {
              ans += 1
              b -= 1
              hands(i) = 'P'
            }

          case 'P' =>
            if (c > 0) {
              ans += 1
              c -= 1
              hands(i) = 'S'
            }

          case _ =>
            if (a > 0) {
              ans += 1
              a -= 1
              hands(i) = 'R'
            }
        }
      }
      val line = (n + 1) / 2
      val ok = ans >= line
      if (!ok) out.println("NO")
      else {
        out.println("YES")
        REP(n) { i =>
          if (hands(i) == 'a') {
            hands(i) = if (a > 0) {
              a -= 1
              'R'
            } else if (b > 0) {
              b -= 1
              'P'
            } else {
              c -= 1
              'S'
            }
          }
        }
        out.println(hands.mkString)
      }
    }
  }
}

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

  override def apply(implicit io: IO): io.type = repeat {
    val n = io.read[Int]
    var r, p, s = io.read[Int]
    val bob = io.read[String]

    def rock() = when(r > 0) {r -= 1; 'R'}
    def paper() = when(p > 0) {p -= 1; 'P'}
    def scissor() = when(s > 0) {s -= 1; 'S'}

    val ans = Array.fill(n)('X')
    var wins = 0

    for {
      i <- bob.indices
      a <- bob(i) match {
        case 'R' => paper()
        case 'P' => scissor()
        case 'S' => rock()
      }
    } {
      wins += 1
      ans(i) = a
    }

    for {
      i <- ans.indices if ans(i) == 'X'
      a <- rock() orElse paper() orElse scissor()
    } {
      wins -= 1
      ans(i) = a
    }

    if (wins >= 0) {
      io.writeLine("YES").writeLine(ans.mkString)
    } else {
      io.writeLine("NO")
    }
  }
}
/****************************[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(implicit io: IO): io.type
  def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).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)

  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: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  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")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  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 writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  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: 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
      }
    }
  }
}


Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.

The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.

Print a single integer — the required sum modulo 109 + 7.

NoteThere are three non-empty subsets in the first sample test:,  and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.

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 xs = readLongs(n).sorted

  val MOD = 1000000007L
  var res = 0L

  var m = 1L
  for (x <- xs) {
    val y = x * (MOD + m - 1) % MOD
    res = (res + y) % MOD
    m = (m * 2) % MOD
  }

  m = 1L
  for (x <- xs.reverse) {
    val y = x * (MOD + m - 1) % MOD
    res = (MOD + res - y) % MOD
    m = (m * 2) % MOD
  }

  println(res)
}

/**
 * @author tdx
 */
object Main {
  import scala.math._
  import scala.collection.mutable._
  import java.io.{File, FileInputStream, InputStreamReader}
  import java.util.Scanner

  // !!!! CHANGE to LOCAL = true before submit !!!!
    val LOCAL = false
//  val LOCAL = true

  def D(x: => Unit): Unit = {
    if (LOCAL) {
      try {
        x
      } catch {
        case e: Throwable => println("Error: " + e.getLocalizedMessage)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val MOD = (pow(10, 9) + 7).toInt
    val sc = new Scanner(new InputStreamReader(if (LOCAL) new FileInputStream(new File("input")) else System.in))
    val n = sc.nextInt()
    val arr = ArrayBuffer[Int]()
    for (_ <- 1 to n) {
      arr.append(sc.nextInt())
    }

    val sorted = arr.sorted
    var res = 0L

    D(println(sorted))

    for (i <- 0 until n - 1) {
      res = (res + (powMod(2, i + 1, MOD) - 1) * (powMod(2, n - i - 1, MOD) - 1) % MOD * (sorted(i + 1) - sorted(i))) % MOD
      D(println(i, res))
    }

    println(res)
  }

  def powMod(a: Int, p: Int, MOD: Int): Long = {
    if (p == 0)
      1
    else {
      val half = powMod(a, p / 2, MOD)
      val res = half * half % MOD
      if (p % 2 == 1) {
        res * a % MOD
      } else
        res
    }
  }
}

/**
 * @author tdx
 */
object Main {
  import scala.math._
  import scala.collection.mutable._
  import java.io.{File, FileInputStream, InputStreamReader}
  import java.util.Scanner

  // !!!! CHANGE to LOCAL = true before submit !!!!
    val LOCAL = false
//  val LOCAL = true

  def D(x: => Unit): Unit = {
    if (LOCAL) {
      try {
        x
      } catch {
        case e: Throwable => println("Error: " + e.getLocalizedMessage)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val MOD = (pow(10, 9) + 7).toInt
    val sc = new Scanner(new InputStreamReader(if (LOCAL) new FileInputStream(new File("input")) else System.in))
    val n = sc.nextInt()
    val arr = ArrayBuffer[Int]()
    for (_ <- 1 to n) {
      arr.append(sc.nextInt())
    }

    val sorted = arr.sorted
    var res = 0L

    D(println(sorted))

    for (i <- 0 until n - 1) {
      res = (res + (powMod(2, i + 1, MOD) - 1) * (powMod(2, n - i - 1, MOD) - 1) * (sorted(i + 1) - sorted(i))) % MOD
      D(println(i, res))
    }

    println(res)
  }

  def powMod(a: Int, p: Int, MOD: Int): Long = {
    if (p == 0)
      1
    else {
      val half = powMod(a, p / 2, MOD)
      val res = half.asInstanceOf[Long] * half % MOD
      if (p % 2 == 1) {
        res.asInstanceOf[Long] * a % MOD
      } else
        res
    }
  }
}


You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino "1-4" turns into "4-1").

The first line contains number n (1  ≤  n  ≤  100). Next n lines contains the dominoes. Each of these lines contains two numbers — the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.

Print "No solution", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of n lines print the index of the domino to put in the corresponding position and then, after a space, character "+" (if you don't need to turn the domino) or "–" (if you need to turn it).

import java.util.StringTokenizer

object B {
  var tokenizer = new StringTokenizer("");

  def nextToken(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(readLine);
    }
    tokenizer.nextToken();
  }

  def nextInt: Int = {
    nextToken().toInt;
  }

  var graph: Array[Array[Int]] = new Array(7);
  var dominoes: List[(Int, Int)] = List();

  def dfs(v: Int): List[Int] = {
    var ans: List[Int] = List();
    for (j <- 1 to graph(v)(v)) {
      if (graph(v)(v) > 0) {
        graph(v)(v) = graph(v)(v) - 1;
        ans = dfs(v) ++ ans;
      }
    }

    for (i <- 0 to 6) {
      for (j <- 1 to graph(v)(i)) {
        if (graph(v)(i) > 0) {
          graph(v)(i) = graph(v)(i) - 1;
          graph(i)(v) = graph(i)(v) - 1;
          ans = dfs(i) ++ ans;
        }
      }
    }
    v :: ans;
  }

  def get_type(pair1: (Int, Int), pair2: (Int, Int)): Int = {
    if (pair1 == pair2)
      1;
    else if (pair1.swap == pair2)
      2;
    else
      0;
  }

  def answer(z: List[(Int, Int)], pair: (Int, Int), ind: Int): List[(Int, Int)] = {
    val t = get_type(pair, z.head);
    if (t != 0) {
      if (t == 1) {
        println(ind + " +");
      } else {
        println(ind + " -");
      }
      (-1, -1) :: z.tail;
    } else {
      z.head :: answer(z.tail, pair, ind + 1);
    }
  }

  def main(args: Array[String]) {
    val n = nextInt;

    for (i <- 0 to 6) {
      graph(i) = new Array(7);
      for (j <- 0 to 6) {
        graph(i)(j) = 0;
      }
    }

    for (i <- 1 to n) {
      val a = nextInt;
      val b = nextInt;
      if (a != b) {
        graph(a)(b) = graph(a)(b) + 1;
        graph(b)(a) = graph(b)(a) + 1;
      } else {
        graph(a)(a) = graph(a)(a) + 1;
      }
      dominoes = dominoes ++ List((a, b));
    }

    var start = -1;
    var count = 0;
    for (i <- 0 to 6) {
      var sum = 0;
      for (j <- 0 to 6) {
        sum += graph(i)(j);
      }
      sum += graph(i)(i);
      count += (sum % 2);
    }

    for (i <- 0 to 6) {
      var sum = 0;
      for (j <- 0 to 6) {
        sum += graph(i)(j);
      }
      sum += graph(i)(i);
      if (sum > 0 && start == -1)
        start = i;
      if (sum % 2 == 1)
        start = i;
    }
    if (count != 2 && count != 0) {
      println("No solution");
      return ;
    }
    val cicle: List[Int] = if (start == -1) List() else dfs(start);
    //    println(cicle.toString + " " + n);
    if (cicle.length != n + 1) {
      println("No solution");
      return ;
    }
    for (i <- 0 to (cicle.length - 2)) {
      dominoes = answer(dominoes, (cicle(i), cicle(i + 1)), 1);
    }
  }
}

import java.util.StringTokenizer

object B {
  var tokenizer = new StringTokenizer("");

  def nextToken(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(readLine);
    }
    tokenizer.nextToken();
  }

  def nextInt: Int = {
    nextToken().toInt;
  }

  var graph: Array[Array[Int]] = new Array(7);
  var dominoes: List[(Int, Int)] = List();

  def dfs(v: Int): List[Int] = {
    var ans: List[Int] = List();
    for (i <- 0 to 6) {
      for (j <- 1 to graph(v)(i)) {
        if (graph(v)(i) > 0) {
          graph(v)(i) = graph(v)(i) - 1;
          graph(i)(v) = graph(i)(v) - 1;
          ans = dfs(i) ++ ans;
        }
      }
    }
    v :: ans;
  }

  def get_type(pair1: (Int, Int), pair2: (Int, Int)): Int = {
    if (pair1 == pair2)
      1;
    else if (pair1.swap == pair2)
      2;
    else
      0;
  }

  def answer(z: List[(Int, Int)], pair: (Int, Int), ind: Int): List[(Int, Int)] = {
    val t = get_type(pair, z.head);
    if (t != 0) {
      if (t == 1) {
        println(ind + " +");
      } else {
        println(ind + " -");
      }
      (-1, -1) :: z.tail;
    } else {
      z.head :: answer(z.tail, pair, ind + 1);
    }
  }

  def main(args: Array[String]) {
    val n = nextInt;

    for (i <- 0 to 6) {
      graph(i) = new Array(7);
      for (j <- 0 to 6) {
        graph(i)(j) = 0;
      }
    }

    for (i <- 1 to n) {
      val a = nextInt;
      val b = nextInt;
      if (a != b) {
        graph(a)(b) = graph(a)(b) + 1;
        graph(b)(a) = graph(b)(a) + 1;
      } else {
        graph(a)(a) = graph(a)(a) + 1;
      }
      dominoes = dominoes ++ List((a, b));
    }

    var start = -1;
    var count = 0;
    for (i <- 0 to 6) {
      var sum = 0;
      for (j <- 0 to 6) {
        sum += graph(i)(j);
      }
      count += (sum % 2);
    }

    for (i <- 0 to 6) {
      var sum = 0;
      for (j <- 0 to 6) {
        sum += graph(i)(j);
      }
      if (sum > 0 && start == -1)
        start = i;
      if (sum % 2 == 1)
        start = i;
    }

    if (count != 2 && count != 0) {
      println("No solution");
      return ;
    }
    val cicle: List[Int] = dfs(start);
    for (i <- 0 to (cicle.length - 2)) {
      dominoes = answer(dominoes, (cicle(i), cicle(i + 1)), 1);
    }
  }
}

import java.util.StringTokenizer

object B {
  var tokenizer = new StringTokenizer("");

  def nextToken(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(readLine);
    }
    tokenizer.nextToken();
  }

  def nextInt: Int = {
    nextToken().toInt;
  }

  var graph: Array[Array[Int]] = new Array(7);
  var dominoes: List[(Int, Int)] = List();

  def dfs(v: Int): List[Int] = {
    var ans: List[Int] = List();
    for (i <- 0 to 6) {
      for (j <- 1 to graph(v)(i)) {
        if (graph(v)(i) > 0) {
          graph(v)(i) = graph(v)(i) - 1;
          graph(i)(v) = graph(i)(v) - 1;
          ans = dfs(i) ++ ans;
        }
      }
    }
    v :: ans;
  }

  def get_type(pair1: (Int, Int), pair2: (Int, Int)): Int = {
    if (pair1 == pair2)
      1;
    else if (pair1.swap == pair2)
      2;
    else
      0;
  }

  def answer(z: List[(Int, Int)], pair: (Int, Int), ind: Int): List[(Int, Int)] = {
    val t = get_type(pair, z.head);
    if (t != 0) {
      if (t == 1) {
        println(ind + " +");
      } else {
        println(ind + " -");
      }
      (-1, -1) :: z.tail;
    } else {
      z.head :: answer(z.tail, pair, ind + 1);
    }
  }

  def main(args: Array[String]) {
    val n = nextInt;

    for (i <- 0 to 6) {
      graph(i) = new Array(7);
      for (j <- 0 to 6) {
        graph(i)(j) = 0;
      }
    }

    for (i <- 1 to n) {
      val a = nextInt;
      val b = nextInt;
      if (a != b) {
        graph(a)(b) = graph(a)(b) + 1;
        graph(b)(a) = graph(b)(a) + 1;
      } else {
        graph(a)(a) = graph(a)(a) + 1;
      }
      dominoes = dominoes ++ List((a, b));
    }

    var start = -1;
    var count = 0;
    for (i <- 0 to 6) {
      var sum = 0;
      for (j <- 0 to 6) {
        sum += graph(i)(j);
      }
      sum += graph(i)(i);
      count += (sum % 2);
    }

    for (i <- 0 to 6) {
      var sum = 0;
      for (j <- 0 to 6) {
        sum += graph(i)(j);
      }
      sum += graph(i)(i);
      if (sum > 0 && start == -1)
        start = i;
      if (sum % 2 == 1)
        start = i;
    }

    if (count != 2 && count != 0) {
      println("No solution");
      return ;
    }
    val cicle: List[Int] = dfs(start);
    for (i <- 0 to (cicle.length - 2)) {
      dominoes = answer(dominoes, (cicle(i), cicle(i + 1)), 1);
    }
  }
}

import java.util.StringTokenizer

object B {
  var tokenizer = new StringTokenizer("");

  def nextToken(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(readLine);
    }
    tokenizer.nextToken();
  }

  def nextInt: Int = {
    nextToken().toInt;
  }

  var graph: Array[Array[Int]] = new Array(7);
  var dominoes: List[(Int, Int)] = List();

  def dfs(v: Int): List[Int] = {
    var ans: List[Int] = List();
    for (j <- 1 to graph(v)(v)) {
      if (graph(v)(v) > 0) {
        graph(v)(v) = graph(v)(v) - 1;
        ans = dfs(v) ++ ans;
      }
    }

    for (i <- 0 to 6) {
      for (j <- 1 to graph(v)(i)) {
        if (graph(v)(i) > 0) {
          graph(v)(i) = graph(v)(i) - 1;
          graph(i)(v) = graph(i)(v) - 1;
          ans = dfs(i) ++ ans;
        }
      }
    }
    v :: ans;
  }

  def get_type(pair1: (Int, Int), pair2: (Int, Int)): Int = {
    if (pair1 == pair2)
      1;
    else if (pair1.swap == pair2)
      2;
    else
      0;
  }

  def answer(z: List[(Int, Int)], pair: (Int, Int), ind: Int): List[(Int, Int)] = {
    val t = get_type(pair, z.head);
    if (t != 0) {
      if (t == 1) {
        println(ind + " +");
      } else {
        println(ind + " -");
      }
      (-1, -1) :: z.tail;
    } else {
      z.head :: answer(z.tail, pair, ind + 1);
    }
  }

  def main(args: Array[String]) {
    val n = nextInt;

    for (i <- 0 to 6) {
      graph(i) = new Array(7);
      for (j <- 0 to 6) {
        graph(i)(j) = 0;
      }
    }

    for (i <- 1 to n) {
      val a = nextInt;
      val b = nextInt;
      if (a != b) {
        graph(a)(b) = graph(a)(b) + 1;
        graph(b)(a) = graph(b)(a) + 1;
      } else {
        graph(a)(a) = graph(a)(a) + 1;
      }
      dominoes = dominoes ++ List((a, b));
    }

    var start = -1;
    var count = 0;
    for (i <- 0 to 6) {
      var sum = 0;
      for (j <- 0 to 6) {
        sum += graph(i)(j);
      }
      sum += graph(i)(i);
      count += (sum % 2);
    }

    for (i <- 0 to 6) {
      var sum = 0;
      for (j <- 0 to 6) {
        sum += graph(i)(j);
      }
      sum += graph(i)(i);
      if (sum > 0 && start == -1)
        start = i;
      if (sum % 2 == 1)
        start = i;
    }
    if (count != 2 && count != 0) {
      println("No solution");
      return ;
    }
    val cicle: List[Int] = if (start == -1) List() else dfs(start);
    //println(cicle.toString);
    if (cicle.length != count + 2) {
      println("No solution");
      return ;
    }
    for (i <- 0 to (cicle.length - 2)) {
      dominoes = answer(dominoes, (cicle(i), cicle(i + 1)), 1);
    }
  }
}


The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.

The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.

Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.

NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.

import scala.io.StdIn._
object A extends App{
  val Array(n,m) = readLine().split(" ").map(_.toInt)
  val cand = for (i <- 0 until m) yield {
    readLine().split(" ").map(_.toLong).zipWithIndex.maxBy(_._1)._2
  }
  val static = cand.groupBy(+_).mapValues(_.length).toSeq
  val mv = static.maxBy(_._2)._2
  println(static.filter(_._2 == mv).minBy(_._1)._1 + 1)
}

object A570 {
  @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 main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val votes = Array.fill(m)(readLongs(n))

    val winner1 = votes.map(_.zipWithIndex.map{case(k, v) => (k, n-v-1)}.sortBy(identity).last._2)
    val winner2 = winner1.groupBy(identity).mapValues(_.length).toArray.map{case (x, y) => (y,x)}.sortBy(identity)

    println(n - winner2.last._2)
  }
}

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

import scala.collection.mutable

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)

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

    def count(x: T): Int = {
      return 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)
      }
      return true
    }
  }

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

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

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

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

    def last(): T = return 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)
      }
      return 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: Int = {
    val n = nextInt
    val m = nextInt
    val votes = new Array[Array[Int]](m)
    for (i <- 0 until m) {
      votes(i) = new Array[Int](n)
      for (j <- 0 until n) {
        votes(i)(j) = nextInt
      }
    }
    val res = new Array[(Int, Int)](m)
    for (i <- 0 until m) {
      var max = Int.MinValue
      var ind = -1
      for (j <- 0 until n) {
        if (max < votes(i)(j)) {
          ind = j
          max = votes(i)(j)
        }
      }
      res(i) = (max, ind)
    }
    val fnl = new Array[Int](n)
    for (i <- 0 until m) {
      fnl(res(i)._2) += 1
    }
    val max = fnl.reduceLeft(_ max _)
    for (i <- 0 until n) {
      if (fnl(i) == max) {
        out.println(i + 1)
        return 0
      }
    }
    return 0
  }
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val f = Array.ofDim[Int](m, n)
    for (i <- 0 to m-1) {
      f(i) = readLine().split(" ").map(_.toInt)
    }

    val result = f.map { c => c.zipWithIndex.find(_._1 == c.max).get._2 }
                  .groupBy[Int](c=>c).map { case(c, arr) => (c, arr.length) }
                  .maxBy { case(c, v) => (v, -c) }

    println(result._1+1)
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _570A extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  val data = IndexedSeq.fill(m, n)(nextInt)

  val round1 = data map {votes => votes.indexOf(votes.max)}

  val round2 = round1.groupBy(identity).mapValues(_.size)

  val ranked = round2.toList map {case (candidate, cities) => -cities -> candidate}

  //debug(ranked)

  ranked.min._2 + 1
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object A extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val winners = for {
    i <- 0 until m
  } yield {
    val votes = readLine().split(" ").map(_.toLong)
    votes.zipWithIndex.maxBy(_._1)._2
  }

  val x = winners.groupBy(identity).mapValues(_.length).toSeq
  val max = x.maxBy(_._2)._2
  println(x.filter(_._2 == max).map(_._1).min + 1)
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object Elections {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }

   def main(args: Array[String]) {
     val (can,cities) = readTuple()
     val winners = for {
       i <- 1 to cities
       v = readInts
       m = v.max
       winner = v.indexOf(m)
     } yield winner
     val tmp = winners.groupBy { x => x }.mapValues { _.size }.toList
       .sortBy{ case (cand,votes) => (-votes,cand)}
     //println(tmp)
     println(tmp.head._1 + 1)

   }

}

import java.util.Scanner

object PA extends App {
    var in = new Scanner(System.in)
    val n = in.nextInt()
    val m = in.nextInt()
    val d = Array.ofDim[Int](m, n)
    for{
        i <- 0 until m
        j <- 0 until n
    } d(i)(j) = in.nextInt()
    def maxv(ar:Array[Int]):Int = {
        var v = 0
        var idx = 0
        for(i <- 0 until ar.length if ar(i) > v){
            idx = i
            v = ar(i)
        }
        idx+1
    }
    val sum = Array.fill[Int](111)(0)
    for(i <- d.map(maxv))
        sum(i) += 1
    var ans = 0
    var mv = 0
    for(i <- 0 until sum.length if sum(i) > mv){
        ans = i
        mv = sum(i)
    }
    println(ans)
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val f = Array.ofDim[Int](m, n)
    for (i <- 0 to m-1) {
      f(i) = readLine().split(" ").map(_.toInt)
    }

    val result = f.map { c => c.zipWithIndex.find(_._1 == c.max).get._2 }
                  .groupBy[Int](c=>c).map { case(c, arr) => (c, arr.length) }
                  .maxBy {
                    case(c, v) =>
                      var all = 0
                      for (i <- 0 to m-1) {
                        all += f(i)(c)
                      }
                      (v, all, -c)
                  }

    println(result._1+1)
  }
}

import scala.io.StdIn._

object A extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)

  val total = Array.ofDim[Long](n)

  var globalMax = Long.MinValue
  var globalMaxIdx = 0

  for (i <- 0 until m) {
    val votes = readLine().split(" ").map(_.toInt)
    var maxIdx = 0
    var maxVotes = Long.MinValue

    for (j <- votes.indices) {
      if (votes(j) > maxVotes) {
        maxVotes = votes(j)
        maxIdx = j
      }
    }

    total(maxIdx) += 1
    if (total(maxIdx) > globalMax) {
      globalMax = total(maxIdx)
      globalMaxIdx = maxIdx
    }
  }

  println(globalMaxIdx + 1)
}


When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins s and t are considered similar if we can transform s to t via a sequence of operations of the following types:   transform lowercase letters to uppercase and vice versa;  change letter «O» (uppercase latin letter) to digit «0» and vice versa;  change digit «1» (one) to any letter among «l» (lowercase latin «L»), «I» (uppercase latin «i») and vice versa, or change one of these letters to other. For example, logins «Codeforces» and «codef0rces» as well as «OO0OOO00O0OOO0O00OOO0OO_lol» and «OO0OOO0O00OOO0O00OO0OOO_1oI» are considered similar whereas «Codeforces» and «Code_forces» are not.You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.

The first line contains a non-empty string s consisting of lower and uppercase latin letters, digits and underline symbols («_») with length not exceeding 50  — the login itself. The second line contains a single integer n (1 ≤ n ≤ 1 000) — the number of existing logins. The next n lines describe the existing logins, following the same constraints as the user login (refer to the first line of the input). It's guaranteed that no two existing logins are similar.

Print «Yes» (without quotes), if user can register via this login, i.e. none of the existing logins is similar with it. Otherwise print «No» (without quotes).

NoteIn the second sample case the user wants to create a login consisting of three zeros. It's impossible due to collision with the third among the existing.In the third sample case the new login is similar with the second one.

object A {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val newLogin = sc.next.toLowerCase
    val len = newLogin.length
    val n = sc.nextInt()
    for (_ <- 1 to n) {
      val s = sc.next
      if (s.length == len && isSimilar(s)) {
        print("No")
        return
      }
    }
    print("Yes")

    def isSimilar(str: String): Boolean = {
      def similarChars(c1: Char, c2: Char): Boolean = {
        if (c1 == c2) true else
          c1 match {
            case 'o' => c2 == '0'
            case '0' => c2 == 'o'
            case '1' => c2 == 'i' || c2 == 'l'
            case 'i' => c2 == '1' || c2 == 'l'
            case 'l' => c2 == 'i' || c2 == '1'
            case _ => false
          }
      }

      newLogin.zip(str.toLowerCase).forall(t => similarChars(t._1, t._2))
    }
  }

}


You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.

The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.

Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

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

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val S = ns(N).map(_-'0')
    val n = N / 3
    val d = Array.fill[Int](3)(-n)
    REP(N) { i =>
      d(S(i)) += 1
    }

    REP(N) { i =>
      if (d(0) < 0 && S(i) != 0 && d(S(i)) > 0) {
        d(0) += 1
        d(S(i)) -= 1
        S(i) = 0
      }
    }

    REP_r(N) { i =>
      if (d(2) < 0 && S(i) != 2 && d(S(i)) > 0) {
        d(2) += 1
        d(S(i)) -= 1
        S(i) = 2
      }
    }

    // この時点で1以外は+になっている
    // <-の方向で0を1にする
    REP_r(N) { i =>
      if (d(1) < 0 && S(i) == 0 && d(0) > 0) {
        d(1) += 1
        d(0) -= 1
        S(i) = 1
      }
    }

    // ->の方向で2を1にする
    REP(N) { i =>
      if (d(1) < 0 && S(i) == 2 && d(2) > 0) {
        d(1) += 1
        d(2) -= 1
        S(i) = 1
      }
    }

    out.println(S.mkString)
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

object CF_531_3_D {

  type In  = (Int, String)
  type Out = String

  def solve0(in: In): Out = {
    val (n, s) = in
???
  }

  def solve(in: In): Out = {
  val (n, s) = in

  val target = n / 3
  val counts = List('0','1','2').map(i => (i, s.count(_ == i)))

  val replacees = for {
    (char, count) <- counts
    if count > target
    c <- Seq.fill(count - target)(char)
  } yield c

  val replacements = for {
    (char, count) <- counts
    if count < target
    c <- Seq.fill(target - count)(char)
  } yield c

  val (startPairs, endPairs) = replacees.zip(replacements).partition(p => p._1 > p._2)
  val startMap = startPairs.groupBy(_._1).mapValues(_.map(_._2)).withDefaultValue(Seq.empty)
  val endMap = endPairs.groupBy(_._1).mapValues(_.map(_._2).reverse).withDefaultValue(Seq.empty)

  def loop(ps: Map[Char, Seq[Char]], input: List[Char], output: List[Char]): List[Char] = input match {
    case Nil       => output
    case c +: tail => ps(c) match {
      case Seq()               => loop(ps, tail, c :: output)
      case replacement +: rest => loop(ps + (c -> rest), tail, replacement :: output)
    }
  }

    val fromStart = loop(startMap, s.toList, Nil)
    val fromEnd = loop(endMap, fromStart, Nil)
    val result = fromEnd
    result.mkString
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.nextLine})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object CF_531_3_D {

  type In  = (Int, String)
  type Out = String

  def solve(in: In): Out = {
    val (n, s) = in

    val target = n/3
//    val counts = s.groupBy(identity).mapValues(_.length).toSeq.sorted

    val counts = Seq('0','1','2').map(i => (i, s.count(_ == i)))

    val replacees = for {
      (char, count) <- counts
      if count > target
      c <- Seq.fill(count - target)(char)
    } yield c

    val replacements = for {
      (char, count) <- counts
      if count < target
      c <- Seq.fill(target - count)(char)
    } yield c

    val (startPairs, endPairs) = replacees.zip(replacements).partition(p => p._1 > p._2)

    def loop(ps: Seq[(Char, Char)], input: String, output: String): String = ps match {
      case Seq() => output + input
      case Seq((replacee, replacement), _*) =>
        if(input.head == replacee)
          loop(ps.tail, input.tail, output + replacement)
        else
          loop(ps, input.tail, output + input.head)
    }

    val fromStart = loop(startPairs, s, "")
    val fromEnd = loop(endPairs.reverse, fromStart.reverse, "")
    fromEnd.reverse

  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.nextLine})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}


At the store, the salespeople want to make all prices round. In this problem, a number that is a power of $$$10$$$ is called a round number. For example, the numbers $$$10^0 = 1$$$, $$$10^1 = 10$$$, $$$10^2 = 100$$$ are round numbers, but $$$20$$$, $$$110$$$ and $$$256$$$ are not round numbers. So, if an item is worth $$$m$$$ bourles (the value of the item is not greater than $$$10^9$$$), the sellers want to change its value to the nearest round number that is not greater than $$$m$$$. They ask you: by how many bourles should you decrease the value of the item to make it worth exactly $$$10^k$$$ bourles, where the value of $$$k$$$ — is the maximum possible ($$$k$$$ — any non-negative integer).For example, let the item have a value of $$$178$$$-bourles. Then the new price of the item will be $$$100$$$, and the answer will be $$$178-100=78$$$.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases . Each test case is a string containing a single integer $$$m$$$ ($$$1 \le m \le 10^9$$$) — the price of the item.

For each test case, output on a separate line a single integer $$$d$$$ ($$$0 \le d < m$$$) such that if you reduce the cost of the item by $$$d$$$ bourles, the cost of the item will be the maximal possible round number. More formally: $$$m - d = 10^k$$$, where $$$k$$$ — the maximum possible non-negative integer.

object p1 extends App{
  val i = io.StdIn.readInt()

  for (_ <- 1 to i) {
    val num = io.StdIn.readInt()
    println(num - findRound(num))
  }

  def findRound(i: Int) = {
    var pow = 0

    while (math.pow(10, pow +1 ) <= i) {
      pow += 1;
    }
    math.pow(10, pow).asInstanceOf[Int]
  }
}


One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.

The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.

Output one integer — the number of different variants of group composition.

/**
  * Created by octavian on 18/02/2016.
  */
object Selection {

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("src/selection.in"))
    //System.setOut(new PrintStream(new FileOutputStream("src/selection.out")))
    var n = readInt()
    val res: BigInt = comb(5, n) + comb(6, n) + comb(7, n)
    println(res)
  }

  def comb(k: Int, n: Int): BigInt = {
    //println("k is: " + k)
    //println("n is: " + n)
    var res: BigInt = 1
    for(i <- (n - k + 1) to n) {
      //println("i is: " + i)
      res *= i
      //println("res became " + res)
    }
    for(i <- 2 to k) {
      //println("i is: " + i)
      res /= i
      //println("res became " + res)
    }
    return res
  }

}

import java.util.Scanner

object Main {

  def sqr(x: Long) = x * x

  def powmod(x: Long, n: Long, p: Long): Long = {
    if (n == 1) x
    else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p
    else sqr(powmod(x, n / 2, p)) % p
  }

  def C(n: Long, k: Long) = {
    var res = BigInt(1)
    for (i <- n - k + 1 to n) {
      res = res * i
    }
    for (i <- 1 to k.toInt) {
      res = res / i
    }
    res
  }

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

    val n = in.nextInt()

    val result = C(n, 5) + C(n, 6) + C(n, 7)

    println(result)
  }
}

import java.util.Scanner

object problem extends App {
  val in = new Scanner(System.in)
  val n = in.nextLong()
  var res: Long = 0
  res += n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5
  res += n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * (n - 5) / 6
  res += n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * (n - 5) / 6 * (n - 6) / 7
  println(res)
}

import scala.io.StdIn

object SelectionOfPersonnel {

  def main(args: Array[String]) {
    def f(s : BigInt, n : BigInt) : BigInt = {
      if (s == n) n
      else s * f(s + 1, n)
    }
    val n = StdIn.readInt()
    val a = f(n - 4, n) / f(1, 5)
    val b = f(n - 5, n) / f(1, 6)
    val c = f(n - 6, n) / f(1, 7)
    print(a + b + c)
  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer
//import java.math.BigDecimal

object Bitz_F {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
    is = new ByteArrayInputStream(Test.t6.trim.getBytes("ISO-8859-1"))
    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int

    val res = comb(n, 5) + comb(n, 6) + comb(n, 7)
    println(res.toLong)

    //---------------------------- parameters reading end ----------------------

  }

  def comb(n: Int, k: Int) = {
//    fact(n) / (fact(k) * fact(n - k))
    factLast(n, k)  / fact(k)
  }
  def fact(v: Int) = {
    var res = 1l;
    for (i <- 2 to v) {
      res *= i
//      db(res)
    }
    res
  }

  def factLast(v:Int, k:Int):BigDecimal = {
    var res = BigDecimal(1);
//    var res = (v-k+1).toDouble / fact(k);
    for (i <- (v-k+1) to v) {
      res *= i
//      db(res)
    }
    res
  }

//
//  def comb2(n: Int, k: Int):Long = {
//    var res = 1L;
//    for(i <- n to n-k by -1 ) {
//      res *= i
//    }
//    res
//  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
321
"""//66715035255088

val t6 = """
624
"""//7147161340917624

}

}

/**
  * Created by octavian on 18/02/2016.
  */
object Selection {

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("src/selection.in"))
    //System.setOut(new PrintStream(new FileOutputStream("src/selection.out")))
    var n = readInt()
    val res: Long = comb(5, n) + comb(6, n) + comb(7, n)
    println(res)
  }

  def comb(k: Int, n: Int): Long = {
    var res: Long = 1
    for(i <- (n - k + 1) to n) {
      res *= i
    }
    for(i <- 2 to k) {
      res /= i
    }
    return res
  }

}

import java.util.Scanner

object Main {

  def sqr(x: Long) = x * x

  def powmod(x: Long, n: Long, p: Long): Long = {
    if (n == 1) x
    else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p
    else sqr(powmod(x, n / 2, p)) % p
  }

  def C(n: Long, k: Long) = {
    var res = 1L
    for (i <- n - k + 1 to n) {
      res = res * i
    }
    for (i <- 1 to k.toInt) {
      res = res / i
    }
    res
  }

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

    val n = in.nextInt()

    val result = C(n, 5) + C(n, 6) + C(n, 7)

    println(result)
  }
}

import scala.io.StdIn

object SelectionOfPersonnel {

  def main(args: Array[String]) {
    def fact(n : Long) : Long = {
      if (n <= 1) 1
      else n * fact(n - 1)
    }
    def f(s : Long, n : Long) : Long = {
      if (s == n) n
      else s * f(s + 1, n)
    }
    val n = StdIn.readInt()
    val a = f(n - 4, n) / fact(5)
    val b = f(n - 5, n) / fact(6)
    val c = f(n - 6, n) / fact(7)
    print(a + b + c)
  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer
//import java.math.BigDecimal

object Bitz_F {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int

    val res = comb(n, 5) + comb(n, 6) + comb(n, 7)
    println(res)

    //---------------------------- parameters reading end ----------------------

  }

  def comb(n: Int, k: Int) = {
//    fact(n) / (fact(k) * fact(n - k))
    factLast(n, k) / fact(k)
  }
  def fact(v: Int) = {
    var res = 1l;
    for (i <- 2 to v) {
      res *= i
//      println(res)
    }
    res
  }

  def factLast(v:Int, k:Int):Long = {
    var res = 1l;
    for (i <- (v-k+1) to v) {
      res *= i
//      println(res)
    }
    res
  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
321
"""

}

}


Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer — the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?

The first line contains integer n (1 ≤ n ≤ 100). The second line contains 2·n space-separated integers ai (10 ≤ ai ≤ 99), denoting the numbers on the cubes.

In the first line print a single number — the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2·n numbers bi (1 ≤ bi ≤ 2). The numbers mean: the i-th cube belongs to the bi-th heap in your division. If there are multiple optimal ways to split the cubes into the heaps, print any of them.

NoteIn the first test case Valera can put the first cube in the first heap, and second cube — in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.In the second test case Valera can obtain numbers 1313, 1345, 2413, 2445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  val double = source.groupBy(x => x).filter(_._2.length > 1).keySet
  val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)
  println(count)
  println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {
    case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)
      else (c1, c2 + 1, f1, f2, 2 :: res, set)
    case ((c1, c2, f1, f2, res, set), el) if !set.contains(el) =>
      (c1, c2, f1, f2, 2 :: res, set + (el -> 1))
    case ((c1, c2, f1, f2, res, set), el) if set(el) == 1 =>
      (c1, c2, f1, f2, 1 :: res, set + (el -> (set(el) + 1)))
    case ((c1, c2, f1, f2, res, set), el) if f2 <= f1 =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set(el) + 1)))
    case ((c1, c2, f1, f2, res, set), el) =>
      (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))
  }._5.reverse.mkString(" "))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  val double = source.groupBy(x => x).filter(_._2.length > 1).keySet
  val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)
  println(count)
  println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {
    case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)
      else (c1, c2 + 1, f1, f2, 2 :: res, set)
    case ((c1, c2, f1, f2, res, set), el) if !set.contains(el) =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> 1))
    case ((c1, c2, f1, f2, res, set), el) if set(el) == 1 =>
      (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))
    case ((c1, c2, f1, f2, res, set), el) if f2 >= f1 =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set(el) + 1)))
    case ((c1, c2, f1, f2, res, set), el) =>
      (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))
  }._5.reverse.mkString(" "))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  val double = source.groupBy(x => x).filter(_._2.length > 1).keySet
  val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)
  println(count)
  println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {
    case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)
      else (c1, c2 + 1, f1, f2, 2 :: res, set)
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 < f2 =>
      (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) =>
      (c1, c2, f1, f2 + 1, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
  }._5.reverse.mkString(" "))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  println(source.foldLeft((0, 0, List.empty[Int], Set.empty[Int])) {
    case ((c1, c2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, 1 :: res, set)
      else (c1, c2 + 1, 2 :: res, set)
    case ((c1, c2, res, set), el) if set.contains(el) =>
      (c1, c2 + 1, 2 :: res, set)
    case ((c1, c2, res, set), el) =>
      (c1 + 1, c2, 1 :: res, set + el)
  }._3.reverse.mkString(" "))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  val double = source.groupBy(x => x).filter(_._2.length > 1).keySet
  val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)
  println(count)
  println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {
    case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, f1 + 1, f2, 1 :: res, set)
      else (c1, c2 + 1, f1, f2 + 1, 2 :: res, set)
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>
      (c1, c2 + 1, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 <= f2 =>
      (c1 + 1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) =>
      (c1, c2 + 1, f1, f2 + 1, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
  }._5.reverse.mkString(" "))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  val double = source.groupBy(x => x).filter(_._2.length > 1).keySet
  val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)
  println(count)
  println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {
    case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, f1 + 1, f2, 1 :: res, set)
      else (c1, c2 + 1, f1, f2 + 1, 2 :: res, set)
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 < f2 =>
      (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) =>
      (c1, c2, f1, f2 + 1, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
  }._5.reverse.mkString(" "))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  val double = source.groupBy(x => x).filter(_._2.length > 1).keySet
  val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)
  println(count)
  println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {
    case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, f1 + 1, f2, 1 :: res, set)
      else (c1, c2 + 1, f1, f2 + 1, 2 :: res, set)
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 <= f2 =>
      (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) =>
      (c1, c2, f1, f2 + 1, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
  }._5.reverse.mkString(" "))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  val double = source.groupBy(x => x).filter(_._2.length > 1).keySet
  val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)
  println(count)
  println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {
    case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)
      else (c1, c2 + 1, f1, f2, 2 :: res, set)
    case ((c1, c2, f1, f2, res, set), el) if !set.contains(el) =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> 1))
    case ((c1, c2, f1, f2, res, set), el) if set(el) == 1 =>
      (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))
    case ((c1, c2, f1, f2, res, set), el) if f2 <= f1 =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set(el) + 1)))
    case ((c1, c2, f1, f2, res, set), el) =>
      (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set(el) + 1)))
  }._5.reverse.mkString(" "))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  val double = source.groupBy(x => x).filter(_._2.length > 1).keySet
  val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)
  println(count)
  println(source.foldLeft((0, 0, List.empty[Int], Set.empty[Int])) {
    case ((c1, c2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, 1 :: res, set)
      else (c1, c2 + 1, 2 :: res, set)
    case ((c1, c2, res, set), el) if set.contains(el) =>
      (c1, c2 + 1, 2 :: res, set)
    case ((c1, c2, res, set), el) =>
      (c1 + 1, c2, 1 :: res, set + el)
  }._3.reverse.mkString(" "))

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val source = in.next().split(" ").map(_.toInt)
  val unique = source.groupBy(x => x).filter(_._2.length == 1).keySet
  val double = source.groupBy(x => x).filter(_._2.length > 1).keySet
  val count: Long = (unique.size + double.size * 2) / 2 * ((unique.size + double.size * 2 + 1) / 2)
  println(count)
  println(source.foldLeft((0, 0, 0, 0, List.empty[Int], Map.empty[Int, Int])) {
    case ((c1, c2, f1, f2, res, set), el) if unique.contains(el) =>
      if (c1 <= c2) (c1 + 1, c2, f1, f2, 1 :: res, set)
      else (c1, c2 + 1, f1, f2, 2 :: res, set)
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 0 =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) if set.getOrElse(el, 0) == 1 || f1 < f2 =>
      (c1, c2, f1 + 1, f2, 1 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
    case ((c1, c2, f1, f2, res, set), el) =>
      (c1, c2, f1, f2 + 1, 2 :: res, set + (el -> (set.getOrElse(el, 0) + 1)))
  }._5.reverse.mkString(" "))

}


Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:   Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units;  Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.

The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100).

In the single line print a single number — the answer to the problem.

NoteConsider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units.The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, l, r, ql, qr) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val leftSum = data.scanLeft(0l){case(acc, el) => acc + el}
  val maxSum = leftSum.last
  println((0 to n).foldLeft(Long.MaxValue) {
    case(acc, i) =>
      val sum = leftSum(i) * l + (maxSum - leftSum(i)) * r
      val res = if ( i > n - i ) (2 * i - n - 1) * ql
        else if ( i < n - i ) (n - 2 * i - 1) * qr
        else 0

      Math.min(acc, sum + res)
  })
}

import scala.collection._

object A extends App {

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

  val Array(n, l, r, ql, qr) = readInts(5)
  val ws = readInts(n)
  val sums = ws.scan(0)(_ + _)
  val sum = sums.last

  var i = 0
  var minCost = Int.MaxValue
  val half = (n + 1) / 2

  while (i <= n) {
    val j = n - i
    val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < j) (j - i - 1) * qr else if (i > j) (i - j - 1) * ql else 0)
    if (cost < minCost) minCost = cost
    i += 1
  }

  println(minCost)
}

import scala.collection._

object A extends App {

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

  val Array(n, l, r, ql, qr) = readInts(5)
  val ws = readInts(n)
  val sums = ws.scan(0)(_ + _)
  val sum = sums.last

  var i = 0
  var minCost = Int.MaxValue
  val half = (n + 1) / 2

  while (i <= n) {
    val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < half) (half - i - 1) * qr else (i - half) * ql)
    if (cost < minCost) minCost = cost
    i += 1
  }

  println(minCost)
}

import scala.collection._

object A extends App {

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

  val Array(n, l, r, ql, qr) = readInts(5)
  val ws = readInts(n)
  val sums = ws.scan(0)(_ + _)
  val sum = sums.last

  var i = 0
  var minCost = Int.MaxValue
  val half = n / 2

  while (i <= n) {

    val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < half) (half - i) * qr else (i - half) * ql)

    if (cost < minCost) minCost = cost

    i += 1
  }

  println(minCost)
}

import scala.collection._

object A extends App {

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

  val Array(n, l, r, ql, qr) = readInts(5)
  val ws = readInts(n)
  val sums = ws.scan(0)(_ + _)
  val sum = sums.last

  var i = 0
  var minCost = Int.MaxValue
  val half = (n + 1) / 2

  while (i <= n) {
    val cost = sums(i) * l + (sum - sums(i)) * r + (if (i < half) (half - i) * qr else (i - half) * ql)
    if (cost < minCost) minCost = cost
    i += 1
  }

  println(minCost)
}


Monocarp has got two strings $$$s$$$ and $$$t$$$ having equal length. Both strings consist of lowercase Latin letters "a" and "b". Monocarp wants to make these two strings $$$s$$$ and $$$t$$$ equal to each other. He can do the following operation any number of times: choose an index $$$pos_1$$$ in the string $$$s$$$, choose an index $$$pos_2$$$ in the string $$$t$$$, and swap $$$s_{pos_1}$$$ with $$$t_{pos_2}$$$.You have to determine the minimum number of operations Monocarp has to perform to make $$$s$$$ and $$$t$$$ equal, and print any optimal sequence of operations — or say that it is impossible to make these strings equal.

The first line contains one integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^{5})$$$ — the length of $$$s$$$ and $$$t$$$. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters "a" and "b".  The third line contains one string $$$t$$$ consisting of $$$n$$$ characters "a" and "b".

If it is impossible to make these strings equal, print $$$-1$$$. Otherwise, in the first line print $$$k$$$ — the minimum number of operations required to make the strings equal. In each of the next $$$k$$$ lines print two integers — the index in the string $$$s$$$ and the index in the string $$$t$$$ that should be used in the corresponding swap operation.

NoteIn the first example two operations are enough. For example, you can swap the third letter in $$$s$$$ with the third letter in $$$t$$$. Then $$$s = $$$ "abbb", $$$t = $$$ "aaab". Then swap the third letter in $$$s$$$ and the second letter in $$$t$$$. Then both $$$s$$$ and $$$t$$$ are equal to "abab".In the second example it's impossible to make two strings equal.

object Main extends App {
  import scala.io.StdIn._
  val n = readInt()
  val s = readLine.trim
  val t = readLine.trim
  if ((s.count(_ == 'a') + t.count(_ == 'a')) % 2 != 0) {
    println(-1)
  }else {
    val diffA = (0 until n).filter(i ⇒ s(i) == 'a' && s(i) != t(i))
    val diffB = (0 until n).filter(i ⇒ s(i) == 'b' && s(i) != t(i))
    println((diffA.length + 1) / 2 + (diffB.length + 1) / 2)
    for (i ← diffA.indices by 2 if diffA.indices.contains(i + 1)) {
      println(s"${diffA(i) + 1} ${diffA(i + 1) + 1}")
    }
    for (i ← diffB.indices by 2 if diffB.indices.contains(i + 1)) {
      println(s"${diffB(i) + 1} ${diffB(i + 1) + 1}")
    }
    if (diffA.length % 2 == 1) {
      println(s"${diffA.last + 1} ${diffA.last + 1}")
      println(s"${diffA.last + 1} ${diffB.last + 1}")
    }
  }
}


Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$ — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$) — the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$) — the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.

Print one number — maximal value of $$$c$$$.

NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

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

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    import java.util
    val N, K = ni()
    val S, T = ns(N)

    def start = {
      var i = 0
      while(i < N && S(i) == T(i)) i += 1
      i
    }

    def count = {
      val s = start
      var ans = 0L
      ans += s // 手前まで一緒だったノードの個数
      ans += (N - s) * 2 // a, bに別れた後のS, Tのパス上のノード数
      var k = 2L // 最初は左の端、右の端の分kを使う
      val D = new BIT(N + 1, 0)(_ + _)
      def add(depth: Int): Unit = {
        // depthに1追加
        D.add(depth, 1)
        D.add(depth + 1, -1)
      }

      s + 1 until N foreach { i =>
        if (S(i) == 'a') add(i)
        if (T(i) == 'b') add(i)
      }

      var depth = 0
      while(depth < N && k < K) {
        val cnt = min(D.sum(depth + 1), K - k)
        k += cnt
        ans += cnt.toLong * (N - depth)
        D.add(depth + 1, cnt)
        depth += 1
      }
      ans
    }

    if (K == 1 || util.Arrays.equals(S, T)) out.println(N)
    else out.println(count)
  }

  class BIT(n: Int, zero: Long)(f: (Long, Long) => Long) {
    def this(n: Int) = this(n, 0)(_ + _)

    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val bit = if (zero != 0) Array.fill[Long](N + 1)(zero) else Array.ofDim[Long](N + 1)

    /**
      * 1 index
      * addとindex違うよ
      * cumsumなんかといっしょ
      */
    def sum(i: Int): Long = {
      assert(i <= n)
      var x = i
      var s: Long = 0
      while(x > 0) {
        s = f(s, bit(x))
        x -= x & -x
      }
      s
    }

    /**
      * 0 index
      */
    def add(i: Int, a: Long): Unit = {
      assert(i < n)
      var x = i + 1
      while(x <= N) {
        bit(x) = f(bit(x), a)
        x += x & -x
      }
    }

    def sumAll: Long = sum(n)

    /**
      * [l, r)
      */
    def query(l: Int, r: Int)(sub: (Long, Long) => Long): Long = {
      assert(r > l)
      sub(sum(r), sum(l))
    }
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

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

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    import java.util
    val N, K = ni()
    val S, T = ns(N)

    def start = {
      var i = 0
      while(i < N && S(i) == T(i)) i += 1
      i
    }

    def count = {
      val s = start
      var ans = 0L
      ans += s // 手前まで一緒だったノードの個数
      ans += (N - s) * 2 // a, bに別れた後のS, Tのパス上のノード数
      var k = 2 // 最初は左の端、右の端の分kを使う
      val D = Array.ofDim[Int](N + 1)

      s + 1 until N foreach { i =>
        if (S(i) == 'a') D(i) += 1
        if (T(i) == 'b') D(i) += 1
      }

      var depth = 0
      while(depth < N && k < K) {
        val cnt = min(D(depth), K - k)
        k += cnt
        ans += cnt.toLong * (N - depth)
        D(depth + 1) += cnt * 2
        depth += 1
      }
      ans
    }

    if (K == 1 || util.Arrays.equals(S, T)) out.println(N)
    else out.println(count)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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


You are given four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$. Timur and three other people are running a marathon. The value $$$a$$$ is the distance that Timur has run and $$$b$$$, $$$c$$$, $$$d$$$ correspond to the distances the other three participants ran. Output the number of participants in front of Timur.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of each test case consists of four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \leq a, b, c, d \leq 10^4$$$).

For each test case, output a single integer — the number of participants in front of Timur.

NoteFor the first test case, there are $$$2$$$ people in front of Timur, specifically the participants who ran distances of $$$3$$$ and $$$4$$$. The other participant is not in front of Timur because he ran a shorter distance than Timur.For the second test case, no one is in front of Timur, since he ran a distance of $$$10000$$$ while all others ran a distance of $$$0$$$, $$$1$$$, and $$$2$$$ respectively.For the third test case, only the second person is in front of Timur, who ran a total distance of $$$600$$$ while Timur ran a distance of $$$500$$$.

import scala.io.StdIn
import scala.math.BigDecimal.double2bigDecimal

object Main {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()

    for(_ <- 0 until t) {
      val part = StdIn.readLine().split(" ").map(_.toInt)

      val timur = part(0)

      println(part.drop(1).count(x => x > timur))
    }
  }
}