Polycarp is a head of a circus troupe. There are $$$n$$$ — an even number — artists in the troupe. It is known whether the $$$i$$$-th artist can perform as a clown (if yes, then $$$c_i = 1$$$, otherwise $$$c_i = 0$$$), and whether they can perform as an acrobat (if yes, then $$$a_i = 1$$$, otherwise $$$a_i = 0$$$).Split the artists into two performances in such a way that:   each artist plays in exactly one performance,  the number of artists in the two performances is equal (i.e. equal to $$$\frac{n}{2}$$$),  the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5\,000$$$, $$$n$$$ is even) — the number of artists in the troupe. The second line contains $$$n$$$ digits $$$c_1 c_2 \ldots c_n$$$, the $$$i$$$-th of which is equal to $$$1$$$ if the $$$i$$$-th artist can perform as a clown, and $$$0$$$ otherwise. The third line contains $$$n$$$ digits $$$a_1 a_2 \ldots a_n$$$, the $$$i$$$-th of which is equal to $$$1$$$, if the $$$i$$$-th artist can perform as an acrobat, and $$$0$$$ otherwise.

Print $$$\frac{n}{2}$$$ distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer $$$-1$$$.

NoteIn the first example, one of the possible divisions into two performances is as follows: in the first performance artists $$$1$$$ and $$$4$$$ should take part. Then the number of artists in the first performance who can perform as clowns is equal to $$$1$$$. And the number of artists in the second performance who can perform as acrobats is $$$1$$$ as well.In the second example, the division is not possible.In the third example, one of the possible divisions is as follows: in the first performance artists $$$3$$$ and $$$4$$$ should take part. Then in the first performance there are $$$2$$$ artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is $$$2$$$ as well.

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 C, A = ns(N).map(_ - '0')

    val Tpe = Array.ofDim[Int](N)
    val T = Array.ofDim[Int](4)
    REP(N) { i =>
      val tpe = if (C(i) == 0 && A(i) == 0) 0
      else if (C(i) == 1 && A(i) == 0) 1
      else if (C(i) == 0 && A(i) == 1) 2
      else 3
      Tpe(i) = tpe
      T(tpe) += 1
    }

    debug(Tpe)

    def isAllGteZero(p: Array[Int]) = {
      var ok = true
      REP(p.length) { i =>
        ok &&= p(i) >= 0
      }
      ok
    }

    val p1, p2 = Array.ofDim[Int](4)
    // クラウン、アクロバットの人数を決める
    REP(T(1) + T(3) + 1) { x =>
      val mxLoop = min(T(1), x) + 1
      REP(mxLoop) { i => // type1の人数
        p1(1) = i
        p1(3) = x - i
        p2(3) = T(3) - p1(3)
        p2(2) = x - p2(3)
        p1(2) = T(2) - p2(2)
        p2(1) = T(1) - p1(1)
        p1(0) = 0
        p2(0) = 0

        // 全部0以上かつ足してN/2以下
        if (isAllGteZero(p1) &&
          isAllGteZero(p2) &&
          sumL(p1) <= N / 2 &&
          sumL(p2) <= N / 2) {

          p1(0) = N / 2 - p1.sum

          debug(p1)
          debug(p2)

          val ans = ArrayBuffer[Int]()
          REP(N) { j =>
            if (p1(Tpe(j)) > 0) {
              p1(Tpe(j)) -= 1
              ans += j + 1
            }
          }
          out.println(ans.mkString(" "))
          return
        }
      }
    }

    out.println(-1)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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


In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners:That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.Your task is to paint a cardiogram by given sequence ai.

The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.

Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print  characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram. Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.

NoteDue to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.http://assets.codeforces.com/rounds/435/1.txthttp://assets.codeforces.com/rounds/435/2.txt

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object C extends App {

  def tokenizeLine = new java.util.StringTokenizer(readLine)
  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) = readInts(1)
  val as = readInts(n)

  var y, minY, maxY = 0
  for (i <- as.indices) {
    if (i % 2 == 0) y += as(i) else y -= as(i)
    minY = minY min y
    maxY = maxY max y
  }

  val res = Array.fill(maxY - minY, as.sum)(' ')

  y = 0
  var x = 0
  for (i <- as.indices) {
    for (j <- 0 until as(i)) {
      if (i % 2 == 0) y += 1 else y -= 1
      res(maxY - y)(x) = if (i % 2 == 0) '/' else '\\'
      x += 1
    }
    if (i % 2 == 0) y += 1 else y -= 1
  }

  res.foreach { s => println(s.mkString) }
}

import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val in = new Scanner(System.in)
    val n = in.nextInt
    val a = new Array[Int](n)
    for (i <- 0 to n - 1)
      a(i) = in.nextInt

    val x = new Array[Int](n + 1)
    val y = new Array[Int](n + 1)
    x(0) = 0
    y(0) = 0
    for (i <- 1 to n) {
      x(i) = x(i - 1) + a(i - 1)
      y(i) = y(i - 1) + (if (i % 2 == 0) -1 else 1) * a(i - 1)
    }

    var minY = 0;
    var maxY = 0;
    for (i <- 0 to n) {
      minY = Math.min(minY, y(i))
      maxY = Math.max(maxY, y(i))
    }

    val ans = new Array[Array[Char]](maxY - minY)
    for (i <- 0 to maxY - minY - 1) {
      ans(i) = new Array[Char](x(n))
      for (j <- 0 to ans(i).length - 1)
        ans(i)(j) = ' '
    }

    var curj = 0
    for (i <- 0 to n - 1) {
      if (y(i) < y(i + 1)) {
        val c = '/';
        for (j <- y(i) to y(i + 1) - 1) {
          ans(j - minY)(curj) = c
          curj = curj + 1
        }
      } else {
        val c = '\\';
        var curi = y(i) - 1
        for (j <- y(i + 1) to y(i) - 1) {
          ans(curi - minY)(curj) = c
          curj = curj + 1
          curi = curi - 1
        }
      }
    }

    for (i <- 0 to maxY - minY - 1) {
      println(ans(maxY - minY - 1 - i).mkString)
    }

  }
}

import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val in = new Scanner(System.in)
    val n = in.nextInt
    val a = new Array[Int](n)
    for (i <- 0 to n - 1)
      a(i) = in.nextInt

    val x = new Array[Int](n + 1)
    val y = new Array[Int](n + 1)
    x(0) = 0
    y(0) = 0
    for (i <- 1 to n) {
      x(i) = x(i - 1) + a(i - 1)
      y(i) = y(i - 1) + (if (i % 2 == 0) -1 else 1) * a(i - 1)

      println(x(i) + " " + y(i))
    }

    var minY = 0;
    var maxY = 0;
    for (i <- 0 to n) {
      minY = Math.min(minY, y(i))
      maxY = Math.max(maxY, y(i))
    }

    val ans = new Array[Array[Char]](maxY - minY)
    for (i <- 0 to maxY - minY - 1) {
      ans(i) = new Array[Char](x(n))
      for (j <- 0 to ans(i).length - 1)
        ans(i)(j) = ' '
    }

    var curj = 0
    for (i <- 0 to n - 1) {
      if (y(i) < y(i + 1)) {
        val c = '/';
        for (j <- y(i) to y(i + 1) - 1) {
          ans(j - minY)(curj) = c
          curj = curj + 1
        }
      } else {
        val c = '\\';
        var curi = y(i) - 1
        for (j <- y(i + 1) to y(i) - 1) {
          ans(curi - minY)(curj) = c
          curj = curj + 1
          curi = curi - 1
        }
      }
    }

    for (i <- 0 to maxY - minY - 1) {
      for (j <- 0 to ans(i).length - 1)
        print(ans(maxY - minY - 1 - i)(j))
      println
    }

  }
}


Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence  -  Minimum_element_of_subsequence  ≥ dPikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print  - 1.

The only line of input consists of two space separated integers X and d (1 ≤ X, d ≤ 109).

Output should consist of two lines. First line should contain a single integer n (1 ≤ n ≤ 10 000)— the number of integers in the final array. Second line should consist of n space separated integers — a1, a2, ... , an (1 ≤ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them.

NoteIn the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence  -  Minimum_element_of_subsequence  ≥ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid.Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence  -  Minimum_element_of_subsequence  ≥ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.

object Solution {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val X, d = sc.nextLong
    lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)

    val xs = bm.takeWhile(_ <= X).foldLeft((List[Long](), 1L)) {
      case ((acc, d1), bm) =>
        if ((X & bm) != 0) {
          (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)
        } else {
          (acc, d1)
        }
    }
    println(xs._1.length)
    print(xs._1.head)
    xs._1.tail.foreach(x => printf(" %d", x))
  }

  import scala.math.log
  def log2(x: Double): Double = log(x) / log(2)
}

object Solution {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val X, d = sc.nextInt
    lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)

    val xs = bm.takeWhile(_ <= X).foldLeft((List[Int](), 1)) {
      case ((acc, d1), bm) =>
        if ((X & bm) != 0) {
          (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)
        } else {
          (acc, d1)
        }
    }
    print(xs._1.head)
    xs._1.tail.foreach(x => printf(" %d", x))
  }

  import scala.math.log
  def log2(x: Double): Double = log(x) / log(2)
}

object Solution {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val X, d = sc.nextInt
    lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)

    val xs = bm.takeWhile(_ <= X).foldLeft((List[Int](), 1)) {
      case ((acc, d1), bm) =>
        if ((X & bm) != 0) {
          (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)
        } else {
          (acc, d1)
        }
    }
    print(xs._1.length)
    xs._1.foreach(x => printf("%d ", x))
  }

  import scala.math.log
  def log2(x: Double): Double = log(x) / log(2)
}

object Solution {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val X, d = sc.nextInt
    lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)

    val xs = bm.takeWhile(_ <= X).foldLeft((List[Int](), 1)) {
      case ((acc, d1), bm) =>
        if ((X & bm) != 0) {
          (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)
        } else {
          (acc, d1)
        }
    }
    println(xs._1.length)
    print(xs._1.head)
    xs._1.tail.foreach(x => printf(" %d", x))
  }

  import scala.math.log
  def log2(x: Double): Double = log(x) / log(2)
}

object Solution {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val X, d = sc.nextInt
    lazy val bm: Stream[Long] = 1L #:: bm.map(_ << 1)

    val xs = bm.takeWhile(_ <= X).foldLeft((List[Int](), 1)) {
      case ((acc, d1), bm) =>
        if ((X & bm) != 0) {
          (d1 + d + 1 :: List.fill(log2(bm).toInt)(d1) ++ acc, d1 + 2*d + 2)
        } else {
          (acc, d1)
        }
    }

    xs._1.foreach(x => printf("%d ", x))
  }

  import scala.math.log
  def log2(x: Double): Double = log(x) / log(2)
}


Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≤ k ≤ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≤ i < j ≤ n) such that f(1, i, ai) > f(j, n, aj).Help Pashmak with the test.

The first line of the input contains an integer n (1 ≤ n ≤ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a single integer — the answer to the problem.

object D459 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val arr = readInts(n)

    val map = cu.Map.empty[Int, Int].withDefaultValue(0)
    val left = new Array[Int](n)
    val right = new Array[Int](n)
    for(i <- 0 until n) {
      left(i) = map(arr(i))
      map(arr(i)) += 1
    }
    map.clear()
    for(i <- n-1 to 0 by -1) {
      right(i) = map(arr(i))
      map(arr(i)) += 1
    }

    var ret = 0L
    val fenwickTree = new FenwickTree(n+10)
    for(i <- n-1 to 0 by -1) {
      ret += fenwickTree.get(left(i))
      fenwickTree.add(right(i)+1, 1)
    }
    out.println(ret)

    out.close()
  }

  class FenwickTree(n: Int) {
    private val sum = new Array[Int](n+1)
    def get(r: Int): Int = {
      var idx = r
      var ret = 0
      while(idx > 0) {
        ret += sum(idx)
        idx -= Integer.lowestOneBit(idx)
      }
      ret
    }
    def add(r: Int, value: Int) {
      var idx = r
      while(idx <= n) {
        sum(idx) += value
        idx += Integer.lowestOneBit(idx)
      }
    }
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object D {

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

  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 solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    if (n == 1) {
      out.println(0)
      return 1
    }
    val f1i = new Array[Int](n - 1)
    val map = scala.collection.mutable.Map[Int, Int]()
    f1i(0) = 1
    map.put(a(0), 1)
    for (i <- 1 to n - 2) {
      val num = map.getOrElse(a(i), 0) + 1
      map.put(a(i), num)
      f1i(i) = num
    }
    map.clear
    val fjn = new Array[Int](n - 1)
    fjn(n - 2) = 1
    map.put(a(n - 1), 1)
    for (i <- n - 3 to 0 by -1) {
      val num = map.getOrElse(a(i + 1), 0) + 1
      map.put(a(i + 1), num)
      fjn(i) = num
    }
    map.clear
    object SegmentTree {

      val N = Math.pow(2, 21).toInt
      //      val N = 8
      val tree = new Array[Int](2 * N)

      def build(a: Array[Int]): Unit = {
        for (i <- N until tree.length) {
          tree(i) = a(i - N)
        }
        for (i <- N - 1 to 1 by -1) {
          tree(i) = tree(2 * i) + tree(2 * i + 1)
        }
      }

      def sum(l: Int, r: Int): Int = {
        var sum = 0
        var left = l + N
        var right = r + N
        while (left < right) {
          if (left % 2 == 1) {
            sum += tree(left)
            left += 1
          }
          if (right % 2 != 1) {
            sum += tree(right)
            right -= 1
          }
          left /= 2
          right /= 2
        }
        if (left == right) {
          return sum + tree(left)
        }
        return sum
      }

      def dec(pos: Int): Unit = {
        var i = pos + N
        while (i > 0) {
          tree(i) -= 1
          i /= 2
        }
      }
    }
    val ranges = new Array[Int](SegmentTree.N)
    for (i <- 0 until fjn.length) {
      ranges(fjn(i)) += 1
    }
    SegmentTree.build(ranges)
    var ans: Long = 0
    for (i <- 0 until f1i.length) {
      ans += SegmentTree.sum(0, f1i(i) - 1)
      SegmentTree.dec(fjn(i))
    }
    out.println(ans)
    return 1
  }

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


Word $$$s$$$ of length $$$n$$$ is called $$$k$$$-complete if   $$$s$$$ is a palindrome, i.e. $$$s_i=s_{n+1-i}$$$ for all $$$1 \le i \le n$$$;  $$$s$$$ has a period of $$$k$$$, i.e. $$$s_i=s_{k+i}$$$ for all $$$1 \le i \le n-k$$$. For example, "abaaba" is a $$$3$$$-complete word, while "abccba" is not.Bob is given a word $$$s$$$ of length $$$n$$$ consisting of only lowercase Latin letters and an integer $$$k$$$, such that $$$n$$$ is divisible by $$$k$$$. He wants to convert $$$s$$$ to any $$$k$$$-complete word.To do this Bob can choose some $$$i$$$ ($$$1 \le i \le n$$$) and replace the letter at position $$$i$$$ with some other lowercase Latin letter.So now Bob wants to know the minimum number of letters he has to replace to convert $$$s$$$ to any $$$k$$$-complete word.Note that Bob can do zero changes if the word $$$s$$$ is already $$$k$$$-complete.You are required to answer $$$t$$$ test cases independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t\le 10^5$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$, $$$n$$$ is divisible by $$$k$$$). The second line of each test case contains a word $$$s$$$ of length $$$n$$$. It is guaranteed that word $$$s$$$ only contains lowercase Latin letters. And it is guaranteed that the sum of $$$n$$$ over all test cases will not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer, representing the minimum number of characters he has to replace to convert $$$s$$$ to any $$$k$$$-complete word.

4
6 2
abaaba
6 3
abaaba
36 9
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp

NoteIn the first test case, one optimal solution is aaaaaa.In the second test case, the given word itself is $$$k$$$-complete.

object C extends App {

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

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val s           = scala.io.StdIn.readLine()

    val t = (k + 1) / 2

    val ans = s.zipWithIndex
      .foldLeft(Array.fill(t)(List.empty[Char])) {
        case (ls, (s, i)) =>
          ls((i % k).min(k - i % k - 1)) ::= s
          ls
      }
      .foldLeft(0)(
        _ + _.groupBy(identity).values.toList.sortBy(_.length)(Ordering.Int.reverse).tail.foldLeft(0)(_ + _.length)
      )

    println(ans)

  }

}


Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?

In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n,  - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it.

Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.

NoteThe following image represents possible process of removing leaves from the tree:

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

object _682C extends CodeForcesApp {
  override def apply(io: IO) = {import io._
    val a = read[Vector[Long]]
    val n = a.length
    val graph = mmap[Int] to mutable.Map.empty[Int, Long]

    def addEdge(u: Int, v: Int, d: Long) = {
      graph.getOrElseUpdate(u, mutable.Map.empty[Int, Long])(v) = d
    }

    1 until n foreach { u =>
      val v = read[Int] - 1
      val d = read[Long]
      addEdge(u, v, d)
      addEdge(v, u, d)
    }

    val visited = mutable.Set.empty[Int]
    def check(u: Int, distance: Long): Unit = {
      //debug(u+1, visited, distance, a(u))
      if(distance <= a(u)) {
        visited += u
        graph(u) foreach {
          case (v, d) if !visited(v) => check(v, d + (distance max 0))
          case _ =>
        }
      }
    }

    check(0, 0)
    write(n - visited.size)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = mmap[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = if(x) "yes" else "no"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def mmap[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]
  def memoize[A, B](f: A => B): A ==> B = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  @inline 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)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

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

object _682C extends CodeForcesApp {
  override def apply(io: IO) = {import io._
    val a = read[Vector[Long]]
    val n = a.length
    val graph = mmap[Int] to mutable.Map.empty[Int, Long]

    1 until n foreach { u =>
      val v = read[Int] - 1
      val d = read[Long]
      graph(u)(v) = d
      graph(v)(u) = d
    }

    val visited = mutable.Set.empty[Int]
    def check(u: Int, distance: Long): Unit = if(!visited(u) && distance <= a(u)) {
      visited += u
      graph(u) foreach {
        case (v, d) => check(v, d + (distance max 0))
      }
    }

    check(0, 0)
    write(n - visited.size)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = mmap[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = if(x) "yes" else "no"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def mmap[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]
  def memoize[A, B](f: A => B): A ==> B = mmap[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  @inline 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)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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


INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.2. The i-th element of the array is subtracted from the result of the previous step modulo 256.3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.You are given the text printed using this method. Restore the array used to produce this text.

The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.

Output the initial array, which was used to produce text, one integer per line.

NoteLet's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.

object Main {

    def reverseBits(x : Int) : Int = {
        var res = 0
        var k = x

        for(i <- 0 until 8) {
            res = (res << 1) | (k & 1)
            k >>= 1
        }

        res
    }

    def mod(a : Int, b : Int) : Int = {
        return (a % b + b) % b
    }

    def main(args : Array[String]) {
        var last = 0;
        readLine foreach (x => {
                val curr = reverseBits(x toInt)
                println(mod(last - curr, 256))
                last = curr
            }
        )
    }
}


You are given two arrays $$$a$$$ and $$$b$$$, each contains $$$n$$$ integers.You want to create a new array $$$c$$$ as follows: choose some real (i.e. not necessarily integer) number $$$d$$$, and then for every $$$i \in [1, n]$$$ let $$$c_i := d \cdot a_i + b_i$$$.Your goal is to maximize the number of zeroes in array $$$c$$$. What is the largest possible answer, if you choose $$$d$$$ optimally?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$-10^9 \le b_i \le 10^9$$$).

Print one integer — the maximum number of zeroes in array $$$c$$$, if you choose $$$d$$$ optimally.

NoteIn the first example, we may choose $$$d = -2$$$.In the second example, we may choose $$$d = -\frac{1}{13}$$$.In the third example, we cannot obtain any zero in array $$$c$$$, no matter which $$$d$$$ we choose.In the fourth example, we may choose $$$d = 6$$$.

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)

  case class Fraction(a: Int, b: Int)
  object Fraction {
    // bが正になるようにそろえる
    def make(a: Int, b: Int): Fraction = {
      val (aa, bb) = if (b < 0) (-a, -b) else (a, b)
      val g = gcd(aa, bb)
      Fraction(aa / g, bb / g)
    }
  }

  def solve(): Unit = {
    val N = ni()
    val A, B = na(N)

    var online = 0
    var zeros = 0
    var d_zero = 0
    val cnt = mutable.Map[Fraction, Int]().withDefaultValue(0)
    REP(N) { i =>
      if (B(i) == 0) {
        if (A(i) == 0) zeros += 1
        else d_zero += 1
      }
      else if (A(i) != 0) {
        val f = Fraction.make(B(i), A(i))
        debug(f.toString)
        val v = cnt(f) + 1
        cnt(f) = v
        online = max(v, online)
      }
    }

    debug(s"online:$online d_zero:$d_zero zero:$zeros")
    val ans = max(online, d_zero) + zeros
    out.println(ans)
  }

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

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

import scala.concurrent.Future
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt)
  val b = in.nextLine.split(' ').map(_.toInt)
  val zeros = a.zip(b).filter(_._1 == 0).count(_._2 == 0)
  val c = a.zip(b).filter(p => p._1 != 0).map(norm).groupBy(x => x).map(_._2.size)

  def norm(pair: (Int, Int)): (Int, Int) = {
    val g = gcd(pair._1.abs, pair._2.abs)
    var x = pair._1 / g
    var y = pair._2 / g
    if (x < 0) {
      x = x.abs
      y = -y
    }
    (x, y)
  }
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  if (c.isEmpty)
    out.print(zeros)
  else
    out.print(c.max + zeros)

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

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)

  case class Fraction(a: Int, b: Int)
  object Fraction {
    // bが正になるようにそろえる
    def make(a: Int, b: Int): Fraction = {
      val (aa, bb) = if (b < 0) (-a, -b) else (a, b)
      val g = gcd(aa, bb)
      Fraction(aa / g, bb / g)
    }
  }

  def solve(): Unit = {
    val N = ni()
    val A, B = na(N)

    var online = 0
    var zeros = 0
    val cnt = mutable.Map[Fraction, Int]().withDefaultValue(0)
    REP(N) { i =>
      if (B(i) == 0) {
        if (A(i) == 0) zeros += 1
      }
      else if (A(i) != 0) {
        val f = Fraction.make(B(i), A(i))
        debug(f.toString)
        val v = cnt(f) + 1
        cnt(f) = v
        online = max(v, online)
      }
    }

    val ans = online + zeros
    out.println(ans)
  }

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

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

  case class Fraction(a: Int, b: Int)
  object Fraction {
    // bが正になるようにそろえる
    def make(a: Int, b: Int): Fraction = {
      val (aa, bb) = if (b < 0) (-a, -b) else (a, b)
      val g = gcd(aa, bb)
      Fraction(aa / g, bb / g)
    }
  }

  def solve(): Unit = {
    val N = ni()
    val A, B = na(N)

    var online = 0
    var zeros = 0
    val cnt = mutable.Map[Fraction, Int]().withDefaultValue(0)
    REP(N) { i =>
      if (B(i) == 0) zeros += 1
      else if (A(i) != 0) {
        val f = Fraction.make(B(i), A(i))
        debug(f.toString)
        val v = cnt(f) + 1
        cnt(f) = v
        online = max(v, online)
      }
    }

    val ans = online + zeros
    out.println(ans)
  }

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

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

import scala.concurrent.Future
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt)
  val b = in.nextLine.split(' ').map(_.toInt)
  val zeros = a.zip(b).filter(_._1 == 0).filter(_._2 == 0).size
  val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)

  def norm(pair: (Int, Int)): (Int, Int) = {
    val g = gcd(pair._1, pair._2)
    var x = pair._1 / g
    var y = pair._2 / g
    if (x < 0 && y > 0) {
      x = x.abs
      y = -y
    }
    (x, y)
  }
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  if (c.isEmpty)
    out.print(zeros)
  else
    out.print(c.max + zeros)

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

import scala.concurrent.Future
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt)
  val b = in.nextLine.split(' ').map(_.toInt)
  val c = a.zip(b).map(norm).groupBy(x => x).map(_._2.size).max

  def norm(pair: (Int, Int)): (Int, Int) = {
    val g = gcd(pair._1, pair._2)
    if (pair._1 == 0 || pair._2 == 0) {
      pair
    } else {
      var x = pair._1 / g
      var y = pair._2 / g
      if (x < 0) {
        x = x.abs
        y = -y
      }
      (x, y)
    }
  }
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  out.print(c)

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

import scala.concurrent.Future
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt)
  val b = in.nextLine.split(' ').map(_.toInt)
  val zeros = a.zip(b).filter(_._1 == 0).count(_._2 == 0)
  val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)

  def norm(pair: (Int, Int)): (Int, Int) = {
    val g = gcd(pair._1.abs, pair._2.abs)
    var x = pair._1 / g
    var y = pair._2 / g
    if (x < 0 && y > 0) {
      x = x.abs
      y = -y
    }
    (x, y)
  }
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  if (c.isEmpty)
    out.print(zeros)
  else
    out.print(c.max + zeros)

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

import scala.concurrent.Future
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt)
  val b = in.nextLine.split(' ').map(_.toInt)
  val zeros = a.zip(b).filter(_._1 == 0).count(_._2 == 0)
  val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)

  def norm(pair: (Int, Int)): (Int, Int) = {
    val g = gcd(pair._1.abs, pair._2.abs)
    var x = pair._1 / g
    var y = pair._2 / g
    if (x < 0) {
      x = x.abs
      y = -y
    }
    (x, y)
  }
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  if (c.isEmpty)
    out.print(zeros)
  else
    out.print(c.max + zeros)

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

import scala.concurrent.Future
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt)
  val b = in.nextLine.split(' ').map(_.toInt)
  val c = a.zip(b).map(norm).groupBy(x => x).map(_._2.size).max

  def norm(pair: (Int, Int)): (Int, Int) = {
    val g = gcd(pair._1, pair._2)
    if (g == 0) {
      pair
    } else {
      var x = pair._1 / g
      var y = pair._2 / g
      if (x < 0) {
        x = x.abs
        y = -y
      }
      (x, y)
    }
  }
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  out.print(c)

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

import scala.concurrent.Future
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt)
  val b = in.nextLine.split(' ').map(_.toInt)
  val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)

  def norm(pair: (Int, Int)): (Int, Int) = {
    val g = gcd(pair._1, pair._2)
    var x = pair._1 / g
    var y = pair._2 / g
    if (x < 0) {
      x = x.abs
      y = -y
    }
    (x, y)
  }
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  if (c.isEmpty)
    out.print(0)
  else
    out.print(c.max)

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

import scala.concurrent.Future
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt)
  val b = in.nextLine.split(' ').map(_.toInt)
  val zeros = a.zip(b).filter(_._1 == 0).filter(_._2 == 0).size
  val c = a.zip(b).filter(p => p._1 != 0 && p._2 != 0).map(norm).groupBy(x => x).map(_._2.size)

  def norm(pair: (Int, Int)): (Int, Int) = {
    val g = gcd(pair._1, pair._2)
    var x = pair._1 / g
    var y = pair._2 / g
    if (x < 0) {
      x = x.abs
      y = -y
    }
    (x, y)
  }
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  if (c.isEmpty)
    out.print(zeros)
  else
    out.print(c.max + zeros)

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}


This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $$$n$$$ stations, enumerated from $$$1$$$ through $$$n$$$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $$$i$$$ is station $$$i+1$$$ if $$$1 \leq i < n$$$ or station $$$1$$$ if $$$i = n$$$. It takes the train $$$1$$$ second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver $$$m$$$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $$$1$$$ through $$$m$$$. Candy $$$i$$$ ($$$1 \leq i \leq m$$$), now at station $$$a_i$$$, should be delivered to station $$$b_i$$$ ($$$a_i \neq b_i$$$).    The blue numbers on the candies correspond to $$$b_i$$$ values. The image corresponds to the $$$1$$$-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.

The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100$$$; $$$1 \leq m \leq 200$$$) — the number of stations and the number of candies, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$; $$$a_i \neq b_i$$$) — the station that initially contains candy $$$i$$$ and the destination station of the candy, respectively.

In the first and only line, print $$$n$$$ space-separated integers, the $$$i$$$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $$$i$$$.

NoteConsider the second sample.If the train started at station $$$1$$$, the optimal strategy is as follows.  Load the first candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the first candy.  Proceed to station $$$1$$$. This step takes $$$1$$$ second.  Load the second candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the second candy.  Proceed to station $$$1$$$. This step takes $$$1$$$ second.  Load the third candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the third candy. Hence, the train needs $$$5$$$ seconds to complete the tasks.If the train were to start at station $$$2$$$, however, it would need to move to station $$$1$$$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $$$5+1 = 6$$$ seconds.

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, M = ni()
    val C = Array.ofDim[Int](N)
    val last = Array.fill[Int](N)(-1)

    def dist(i: Int, j: Int): Int = (j + N - i) % N

    def compare(i: Int, j1: Int, j2: Int): Int = {
      Integer.compare(dist(i, j1), dist(i, j2))
    }

    REP(M) { _ =>
      val a, b = ni() - 1
      C(a) += 1

      // 最後に持ち出す飴は時計回りでちかいものがいい
      if (last(a) == -1 || compare(a, b, last(a)) < 0) {
        last(a) = b
      }
    }

    debug("C")
    debug(C)
    debug("last")
    debug(last)

    val ans = ArrayBuffer[Int]()
    REP(N) { i =>
      val (mx, mxIx) = C.zipWithIndex.maxBy { case (cnt, j) => (cnt, dist(i, j)) }

      debug(s"i:$i mx:$mx mxIx:$mxIx")

      // 一番最後に飴をとるときからちょうど一周前からシミュレーションする
      var move = max(-1, (mx - 2) * N + dist(i, mxIx)) // 最初に１歩進むので-1が下限なのが妥当
      var j = (i + move) % N
      val loaded = Array.ofDim[Boolean](N)
      var lastCandyLoaded = false
      var candyCnt = 0

      // 積む飴がまだ残っているか、キャンディをまだ積んでいるなら周回をつづける
      while(!lastCandyLoaded || candyCnt > 0) {
        j = (j + 1) % N
        move += 1
        val m = move / N + 1 // 周回

        debug(s"step $j $move m:$m")

        // この周回でまだ載せるキャンディーが残っているなら載せる。ただし同じ種類なら意味ないので無視する
        if (C(j) >= m && !loaded(last(j))) {
          debug(s"load ${last(j)}")
          loaded(last(j)) = true
          candyCnt += 1
        }

        // 降ろす
        if (loaded(j)) {
          debug(s"unload")
          loaded(j) = false
          candyCnt -= 1
        }

        if (j == mxIx) lastCandyLoaded = true
      }

      ans += move
    }

    out.println(ans.mkString(" "))
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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


You are given two strings $$$s$$$ and $$$t$$$. Both strings have length $$$n$$$ and consist of lowercase Latin letters. The characters in the strings are numbered from $$$1$$$ to $$$n$$$.You can successively perform the following move any number of times (possibly, zero):  swap any two adjacent (neighboring) characters of $$$s$$$ (i.e. for any $$$i = \{1, 2, \dots, n - 1\}$$$ you can swap $$$s_i$$$ and $$$s_{i + 1})$$$. You can't apply a move to the string $$$t$$$. The moves are applied to the string $$$s$$$ one after another.Your task is to obtain the string $$$t$$$ from the string $$$s$$$. Find any way to do it with at most $$$10^4$$$ such moves.You do not have to minimize the number of moves, just find any sequence of moves of length $$$10^4$$$ or less to transform $$$s$$$ into $$$t$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of strings $$$s$$$ and $$$t$$$. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of the input contains the string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters.

If it is impossible to obtain the string $$$t$$$ using moves, print "-1". Otherwise in the first line print one integer $$$k$$$ — the number of moves to transform $$$s$$$ to $$$t$$$. Note that $$$k$$$ must be an integer number between $$$0$$$ and $$$10^4$$$ inclusive. In the second line print $$$k$$$ integers $$$c_j$$$ ($$$1 \le c_j < n$$$), where $$$c_j$$$ means that on the $$$j$$$-th move you swap characters $$$s_{c_j}$$$ and $$$s_{c_j + 1}$$$. If you do not need to apply any moves, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.

NoteIn the first example the string $$$s$$$ changes as follows: "abcdef" $$$\rightarrow$$$ "abdcef" $$$\rightarrow$$$ "abdcfe" $$$\rightarrow$$$ "abdfce" $$$\rightarrow$$$ "abdfec".In the second example there is no way to transform the string $$$s$$$ into the string $$$t$$$ through any allowed moves.

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val s, t = sc.next().toCharArray

    val s1 = s.clone()
    val t1 = t.clone()
    Sorting.quickSort(s1)
    Sorting.quickSort(t1)

    def swap(a: Int, b: Int): Unit = {
      val tmp = s(a)
      s(a) = s(b)
      s(b) = tmp
    }

    val swaps = ArrayBuffer[Int]()
    if (!util.Arrays.equals(s1, t1)) {
      out.println(-1)
    } else {
      rep(N) { i =>
        if (s(i) != t(i)) {
          val ix = s.indexOf(t(i), i + 1)
          (i until ix).reverse foreach { j =>
            swap(j, j + 1)
            swaps += j + 1
          }
        }
      }
      out.println(swaps.length)
      out.println(swaps.mkString(" "))
    }
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  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)
  }
  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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object CF501B extends App {

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

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve = {
    in.nextInt
    val s = in.next.toCharArray
    val t = in.next.toCharArray

    var dropped = 0

    if (s.sorted.zip(t.sorted).forall(x => x._1 == x._2)) {

      def findMoves(s: Array[Char], t: Array[Char], moves: List[Int]): List[Int] = {
        if (s.length == 0)
          return moves
        if (s(0) == t(0)) {
          dropped += 1
          return findMoves(s.tail, t.tail, moves)
        }

        val newMove = s.indexOf(t(0)) - 1
        findMoves(swap(s, newMove), t, moves :+ (newMove + dropped))
      }

      def swap(s: Array[Char], i: Int): Array[Char] = {
        val tmp = s(i)
        s(i) = s(i+1)
        s(i+1) = tmp
        return s
      }

      val moves = findMoves(s, t, List[Int]()).map(_+1) // 0 to 1 indexed
      out.println(moves.length)
      out.println(moves.mkString(" "))
    }
    else {
      out.println("-1")
    }
  }

  solve
  out.flush
  out.close
}

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

object A {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val s = StdIn.readLine().toCharArray.toBuffer
    val t = StdIn.readLine().toCharArray.toBuffer

    val sm = s.groupBy(c => c).mapValues(_.length)
    val tm = t.groupBy(c => c).mapValues(_.length)

    val notPossible = (sm.keySet diff tm.keySet).nonEmpty || sm.keySet.exists(c => sm(c) != tm(c))

    if (notPossible) {
      println(-1)
    } else {
      if (s == t) {
        println(0)
      } else {
        var rmvd = 1
        val r = new ArrayBuffer[Int]()
        var i = 0
        while (i < t.length) {
          if (s(i) != t(i)) {
            val tmp = new ArrayBuffer[Int]()
            tmp += (i + rmvd)
            var j = i + 1
            while (s(j) != t(i)) {
              tmp += (j + rmvd)
              j += 1
            }

            s.remove(j)
            t.remove(i)
            rmvd += 1
            r ++= tmp.reverse
          } else {
            i += 1
          }
        }
        println(r.length)
        println(r.mkString(" "))
      }
    }
  }
}

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val s, t = sc.next().toCharArray

    val s1 = s.clone()
    val t1 = t.clone()
    Sorting.quickSort(s1)
    Sorting.quickSort(t1)

    def swap(a: Int, b: Int): Unit = {
      val tmp = s(a)
      s(a) = s(b)
      s(b) = tmp
    }

    val swaps = ArrayBuffer[Int]()
    if (!util.Arrays.equals(s1, t1)) {
      out.println(-1)
    } else {
      rep(N) { i =>
        if (s(i) != t(i)) {
          val ix = s.indexOf(t(i))
          (i until ix).reverse foreach { j =>
            swap(j, j + 1)
            swaps += j + 1
          }
        }
      }
      out.println(swaps.length)
      out.println(swaps.mkString(" "))
    }
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  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)
  }
  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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}


One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.

The first line of the input contains an integer n (1 ≤ n ≤ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn’t exceed 100.

For each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG>.< I don't know!" if liouzhou_101 can’t recognize whose sentence it is. He can’t recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions.

5
I will go to play with you lala.
wow, welcome.
miao.lala.
miao.
miao .

Freda's
OMG>.< I don't know!
OMG>.< I don't know!
Rainbow's
OMG>.< I don't know!

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val map = Map(2 -> "OMG>.< I don't know!", 1 -> "Rainbow's", 0 -> "Freda's")
  println((1 to in.next().toInt).map{_ =>
    val v = in.next()
    val m = v.startsWith("miao.")
    val r = v.endsWith("lala.")
    if (m == r) 2
    else if (m) 1
    else 0
  }.map(map).mkString("\n"))
}

object A312 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    for(_ <- 1 to n) {
      val str = read
      if(str.startsWith("miao") && str.endsWith("lala.")) {
        out.println("OMG>.< I don't know!")
      } else if (str.startsWith("miao.")) {
        out.println("Rainbow's")
      } else if (str.endsWith("lala.")) {
        out.println("Freda's")
      } else {
        out.println("OMG>.< I don't know!")
      }
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

// package R185d2

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

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

  def isFreda(str: String): Boolean =
    str.matches(""".*lala\.$""")

  def isRainbow(str: String): Boolean =
    str.matches("""miao\..*""")

  def answer(str: String): String =
    (isFreda(str), isRainbow(str)) match {
      case (true, false) => "Freda's"
      case (false, true) => "Rainbow's"
      case _ => "OMG>.< I don't know!"
    }

  for (i <- 0 until sc.nextLine.toInt)
    out.println(answer(sc.nextLine))

  out.close
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    for(_ <- 1 to n) {
      val s = readLine()
      val st = s.startsWith("miao.")
      val end = s.endsWith("lala.")
      if (st && !end) println("Rainbow's")
      else if(end && !st) println("Freda's")
      else println("OMG>.< I don't know!")
    }
  }
}

import scala.io.Source
object A extends App {
  val size = readLine().toInt;
  for (_ <- 1 to size) {
    check(readLine())
  }

  def check(str: String) {
    var flag_lala = str.endsWith("lala.");
    var flag_rainbow = str.startsWith("miao.");
    if ((flag_lala ^ flag_rainbow) == false) {
      println("OMG>.< I don't know!");
    } else {
      if (flag_lala) {
        println("Freda's");
      } else {
        println("Rainbow's");
      }
    }
  }

}

//package R185d2

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

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

  def answer: String = {
    val Freda = """(?:.* )?lala\.$""".r
    val Rainbow = """(?:.* )?miao\.$""".r
    sc.nextLine match {
      case Freda() => "Freda's"
      case Rainbow() => "Rainbow's"
      case _ => "OMG>.< I don't know!"
    }
  }

  for (i <- 0 until sc.nextLine.toInt)
    out.println(answer)

  out.close
}