You are given two strings $$$a$$$ and $$$b$$$ consisting of lowercase English letters, both of length $$$n$$$. The characters of both strings have indices from $$$1$$$ to $$$n$$$, inclusive. You are allowed to do the following changes:   Choose any index $$$i$$$ ($$$1 \le i \le n$$$) and swap characters $$$a_i$$$ and $$$b_i$$$;  Choose any index $$$i$$$ ($$$1 \le i \le n$$$) and swap characters $$$a_i$$$ and $$$a_{n - i + 1}$$$;  Choose any index $$$i$$$ ($$$1 \le i \le n$$$) and swap characters $$$b_i$$$ and $$$b_{n - i + 1}$$$. Note that if $$$n$$$ is odd, you are formally allowed to swap $$$a_{\lceil\frac{n}{2}\rceil}$$$ with $$$a_{\lceil\frac{n}{2}\rceil}$$$ (and the same with the string $$$b$$$) but this move is useless. Also you can swap two equal characters but this operation is useless as well.You have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps.In one preprocess move you can replace a character in $$$a$$$ with another character. In other words, in a single preprocess move you can choose any index $$$i$$$ ($$$1 \le i \le n$$$), any character $$$c$$$ and set $$$a_i := c$$$.Your task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings $$$a$$$ and $$$b$$$ equal by applying some number of changes described in the list above.Note that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string $$$b$$$ or make any preprocess moves after the first change is made.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$a$$$ and $$$b$$$. The second line contains the string $$$a$$$ consisting of exactly $$$n$$$ lowercase English letters. The third line contains the string $$$b$$$ consisting of exactly $$$n$$$ lowercase English letters.

Print a single integer — the minimum number of preprocess moves to apply before changes, so that it is possible to make the string $$$a$$$ equal to string $$$b$$$ with a sequence of changes from the list above.

NoteIn the first example preprocess moves are as follows: $$$a_1 := $$$'b', $$$a_3 := $$$'c', $$$a_4 := $$$'a' and $$$a_5:=$$$'b'. Afterwards, $$$a = $$$"bbcabba". Then we can obtain equal strings by the following sequence of changes: $$$swap(a_2, b_2)$$$ and $$$swap(a_2, a_6)$$$. There is no way to use fewer than $$$4$$$ preprocess moves before a sequence of changes to make string equal, so the answer in this example is $$$4$$$.In the second example no preprocess moves are required. We can use the following sequence of changes to make $$$a$$$ and $$$b$$$ equal: $$$swap(b_1, b_5)$$$, $$$swap(a_2, a_4)$$$.

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 A, B = ns(N)

    def test(a0: Int, a1: Int, b0: Int, b1: Int) = {
      val cnt = mutable.Map[Int, Int]().withDefaultValue(0)
      def add(c: Int) { cnt(c) = cnt(c) + 1 }
      add(a0)
      add(a1)
      add(b0)
      add(b1)
      cnt.forall(_._2 % 2 == 0)
    }

    var ans = 0
    REP(N / 2) { i =>
      var ms = 2
      val zip = mutable.Set(A(i), A(N - 1 - i), B(i), B(N - 1 - i)).toSeq.zipWithIndex.toMap

      REP(4) { a0 =>
        REP(4) { a1 =>
          if (test(a0, a1, zip(B(i)), zip(B(N - 1 - i)))) {
            var cnt = 0
            if (a0 != zip(A(i))) cnt += 1
            if (a1 != zip(A(N - 1 - i))) cnt += 1
            ms = min(ms, cnt)
          }
        }
      }
      ans += ms
    }

    if (N % 2 > 0) {
      val i = N / 2
      if (A(i) != B(i)) ans += 1
    }

    out.println(ans)
  }

  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)

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

    val memo = Array.fill[Int](26, 26, 26, 26)(-1)
    def test(a0: Char, a1: Char, b0: Char, b1: Char) = {
      if (memo(a0-'a')(a1-'a')(b0-'a')(b1-'a') == -1) {
        val cnt = mutable.Map[Char, Int]().withDefaultValue(0)
        def add(c: Char) { cnt(c) = cnt(c) + 1 }
        add(a0)
        add(a1)
        add(b0)
        add(b1)
        memo(a0-'a')(a1-'a')(b0-'a')(b1-'a')  = if (cnt.forall(_._2 % 2 == 0)) 1 else 0
      }
      memo(a0-'a')(a1-'a')(b0-'a')(b1-'a') == 1
    }

    var ans = 0
    REP(N / 2) { i =>
      var ms = 2
      REP(26, 'a') { a0 =>
        REP(26, 'a') { a1 =>
          if (test(a0.toChar, a1.toChar, B(i), B(N - 1 - i))) {
            var cnt = 0
            if (a0 != A(i)) cnt += 1
            if (a1 != A(N - 1 - i)) cnt += 1
            ms = min(ms, cnt)
          }
        }
      }
      ans += ms
    }

    if (N % 2 > 0) {
      val i = N / 2
      if (A(i) != B(i)) ans += 1
    }

    out.println(ans)
  }

  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)

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

    val memo = Array.fill[Int](4, 4, 4, 4)(-1)
    def test(a0: Int, a1: Int, b0: Int, b1: Int) = {
      if (memo(a0)(a1)(b0)(b1) == -1) {
        val cnt = mutable.Map[Int, Int]().withDefaultValue(0)
        def add(c: Int) { cnt(c) = cnt(c) + 1 }

        add(a0)
        add(a1)
        add(b0)
        add(b1)
        memo(a0)(a1)(b0)(b1) = if (cnt.forall(_._2 % 2 == 0)) 1 else 0
      }
      memo(a0)(a1)(b0)(b1) == 1
    }

    var ans = 0
    REP(N / 2) { i =>
      var ms = 2
      val zip = mutable.Set(A(i), A(N - 1 - i), B(i), B(N - 1 - i)).toSeq.zipWithIndex.toMap

      REP(4) { a0 =>
        REP(4) { a1 =>
          if (test(a0, a1, zip(B(i)), zip(B(N - 1 - i)))) {
            var cnt = 0
            if (a0 != zip(A(i))) cnt += 1
            if (a1 != zip(A(N - 1 - i))) cnt += 1
            ms = min(ms, cnt)
          }
        }
      }
      ans += ms
    }

    if (N % 2 > 0) {
      val i = N / 2
      if (A(i) != B(i)) ans += 1
    }

    out.println(ans)
  }

  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)

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

    var ans = 0
    REP(N / 2) { i =>
      val cnt = mutable.Map[Char, Int]().withDefaultValue(0)
      def add(c: Char){ cnt(c) = cnt(c) + 1 }
      add(A(i))
      add(A(N - 1 - i))
      add(B(i))
      add(B(N - 1 - i))
      if (cnt.exists(_._2 % 2 > 0)) {
        if (B(i) == B(N - 1 - i)) ans += 1
        else {
          val bs = ArrayBuffer(B(i), B(N - 1 - i))
          bs -= A(i)
          bs -= A(N - 1 - i)
          ans += bs.size
        }
      }
    }

    if (N % 2 > 0) {
      val i = N / 2
      if (A(i) != B(i)) ans += 1
    }

    out.println(ans)
  }

  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)

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

    var ans = 0
    REP(N / 2) { i =>
      val cnt = mutable.Map[Char, Int]().withDefaultValue(0)
      def add(c: Char){ cnt(c) = cnt(c) + 1 }
      add(A(i))
      add(A(N - 1 - i))
      add(B(i))
      add(B(N - 1 - i))
      if (!(cnt.size == 1 || cnt.size == 2 && cnt.forall(_._2 == 2))) {
        val bs = ArrayBuffer(B(i), B(N - 1 - i))
        bs -= A(i)
        bs -= A(N - 1 - i)
        ans += bs.size
      }
    }

    if (N % 2 > 0) {
      val i = N / 2
      if (A(i) != B(i)) ans += 1
    }

    out.println(ans)
  }

  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)

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

    var ans = 0
    REP(N / 2) { i =>
      val cnt = mutable.Map[Char, Int]().withDefaultValue(0)
      def add(c: Char){ cnt(c) = cnt(c) + 1 }
      add(A(i))
      add(A(N - 1 - i))
      add(B(i))
      add(B(N - 1 - i))
      if (cnt.exists(_._2 % 2 > 0)) {
        val bs = ArrayBuffer(B(i), B(N - 1 - i))
        bs -= A(i)
        bs -= A(N - 1 - i)
        ans += bs.size
      }
    }

    if (N % 2 > 0) {
      val i = N / 2
      if (A(i) != B(i)) ans += 1
    }

    out.println(ans)
  }

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


Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:  Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.  Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?

The first line contains a single integer n (1 ≤ n ≤ 3·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial group that is given to Toastman.

Print a single integer — the largest possible score.

NoteConsider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.

//package solutions

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

/**
  * @author traff
  */

object Solution_TaskA extends App {
  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    run(new Scanner(System.in), out)

    out.close()
  }

  def run(scanner: Scanner, writer: PrintWriter): Unit = {
    val n = scanner.nextInt()
    var a = new Array[Int](n)
    for (i <- 1 to n) {
      a(i-1) = scanner.nextInt()
    }

    a = a.sortWith(_ < _)

    var sum: Long  = a.foldLeft(0:Long)((b: Long, i: Int) => b + i)
    var res = sum

    for (i <- 1 until n) {
      res += sum
      sum -= a(i-1)
    }

    writer.println(res)
  }
}

object A461 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readLongs(n).sortBy(identity).reverse

    var res = 0L
    for(i <- input.indices) {
      if(i == 0 || i == 1) {
        res += input(i) * n
      } else {
        res += input(i) * (n-i+1)
      }
    }
    println(res)
  }
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
 * Created by Kuang.Ru on 14-9-18.
 */
object A461 extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  var a = new ArrayBuffer[Long]()
  var j = 0

  while (j < n) {
    a += sc.nextInt()
    j += 1
  }

  val newA = a.sortWith(_ > _)
  var score: Long = 0

  if (n >= 2) {
    score += newA(0) * n + newA(1) * n
    var i = 2

    while (i < n) {
      score += newA(i) * (n - i + 1)
      i += 1
    }
  } else {
    score += newA(0)
  }

  println(score)
}

object main extends App with fastIO {

  val n = nextInt

  var (ans, cnt) = (0l, 1l)
  var a = Array.fill(n)(nextInt) sortBy((i) => i)
  a foreach { (i) => cnt += 1; ans += i * cnt }

  println(ans - a.max)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

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

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

import scala.collection.mutable

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF263_3 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }
  val Array(n) = readInts(1)
  val arr  = readInts(n)

  val sortedArr = arr.sortBy(identity)
  var result = 0L
  var i = 0
  var multiplier = if(n==1) 1L else 2L
  while(i<n){
    result += (sortedArr(i).toLong * multiplier)
    multiplier = (multiplier + 1) min n
    i+=1
  }
  println(result)
}

import scala.io.StdIn.readLine

object Main {
  def main(args: Array[String]): Unit = {
    readLine()
    val a = readLine().split(" ").map(_.toLong)
    val ans = if (a.length == 1) {
      a.head.toLong
    } else {
      a.sorted.zipWithIndex.map { case
        (x, i) => x * (i + 2)
      }.sum - a.max
    }
    println(ans)
  }
}

//package solutions

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

/**
  * @author traff
  */

object Solution_TaskA extends App {
  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    run(new Scanner(System.in), out)

    out.close()
  }

  def run(scanner: Scanner, writer: PrintWriter): Unit = {
    val n = scanner.nextInt()
    var a = new Array[Int](n)
    for (i <- 1 to n) {
      a(i-1) = scanner.nextInt()
    }

    a = a.sortWith(_ < _)

    var sum: Long  = a.sum
    var res = sum

    for (i <- 1 until n) {
      res += sum
      sum -= a(i-1)
    }

    writer.println(res)
  }
}

//package solutions

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

/**
  * @author traff
  */

object Solution_TaskA extends App {
  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    run(new Scanner(System.in), out)

    out.close()
  }

  def run(scanner: Scanner, writer: PrintWriter): Unit = {
    val n = scanner.nextInt()
    var a = new Array[Int](n)
    for (i <- 1 to n) {
      a(i-1) = scanner.nextInt()
    }

    a = a.sortWith(_ < _)

    var sum = a.sum
    var res = sum

    for (i <- 1 until n) {
      res += sum
      sum -= a(i-1)
    }

    writer.println(res)
  }
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
 * Created by Kuang.Ru on 14-9-18.
 */
object A461 extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  var a = new ArrayBuffer[Int]()
  var j = 0

  while (j < n) {
    a += sc.nextInt()
    j += 1
  }

  val newA = a.sortWith(_ > _)
  var score: Long = 0

  if (n >= 2) {
    score += newA(0) * n + newA(1) * n
    var i = 2

    while (i < n) {
      score += newA(i) * (n - i + 1)
      i += 1
    }
  } else {
    score += newA(0)
  }

  println(score)
}

object main extends App with fastIO {

  val n = nextInt

  var (ans, cnt) = (0, 1)
  var a = Array.fill(n)(nextInt) sortBy((i) => i)
  a foreach { (i) => cnt += 1; ans += i * cnt }

  println(ans - a.max)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

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

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object main extends App with fastIO {

  val n = nextInt

  var (ans, cnt) = (0l, 1)
  var a = Array.fill(n)(nextInt) sortBy((i) => i)
  a foreach { (i) => cnt += 1; ans += i * cnt }

  println(ans - a.max)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

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

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

import scala.collection.mutable

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF263_3 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }
  val Array(n) = readInts(1)
  val arr  = readInts(n)

  val sortedArr = arr.sortBy(identity)
  var result = 0L
  var i = 0
  var multiplier = if(n==1) 1 else 2
  while(i<n){
    result += sortedArr(i) * multiplier
    multiplier = (multiplier + 1) min n
    i+=1
  }
  println(result)
}


Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions:  The coordinates of each point in the set are integers.  For any two points from the set, the distance between them is a non-integer. Consider all points (x, y) which satisfy the inequations: 0 ≤ x ≤ n; 0 ≤ y ≤ m; x + y > 0. Choose their subset of maximum size such that it is also a beautiful set of points.

The single line contains two space-separated integers n and m (1 ≤ n, m ≤ 100).

In the first line print a single integer — the size k of the found beautiful set. In each of the next k lines print a pair of space-separated integers — the x- and y- coordinates, respectively, of a point from the set. If there are several optimal solutions, you may print any of them.

NoteConsider the first sample. The distance between points (0, 1) and (1, 2) equals , between (0, 1) and (2, 0) — , between (1, 2) and (2, 0) — . Thus, these points form a beautiful set. You cannot form a beautiful set with more than three points out of the given points. Note that this is not the only solution.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(n, m) = in.next().split(' ').map(_.toInt)
  val squares = (0 to n + m).foldLeft(Set.empty[Int]) {
    case (set, el) => set + el * el
  }
  val min = Math.min(m, n)
  println(min + 1)
  println((0 to min).map(i => s"$i ${min - i}").mkString("\n"))

}

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

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

    println(min+1)
    for(i<-0 to min) println(min-i+" "+i)
}

object Main {
  def main(args: Array[String]) {
    val a = readLine().split(" ").map(_.toInt)
    val min = a.min

    println(min + 1)
    for(i <- 0 to min) println(i + " " + (min - i))
  }
}

import scala.Math._;
import scala.collection.mutable.LinkedList

object App {
	def readInts:Array[Int] = (readLine split " ") map (_.toInt)
                                                  //> readInts: => Array[Int]                              //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)

	def solve(deep: Int, n: Int):Long = {
	  if (deep == n) n
	  else solve(deep + 1, n) + (deep * (n - deep))
	}

	def f1_io() = {
	    val Array(n, m) = readInts
		val a = min(n, m)
		println(a + 1)
		for(i <- 0 to a) {
		  println(i + " " + (m - i))
		}

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

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(n, m) = in.next().split(' ').map(_.toInt)
  val squares = (0 to n + m).foldLeft(Set.empty[Int]) {
    case (set, el) => set + el * el
  }
  val fx = 0
  val fy = 0
  val result1 = (0 to n).foldLeft(List.empty[(Int, Int)]) {
    case(list, i) => (0 to m).foldLeft(list) {
      case (l, el) if el + i == 0 => l
      case (l, el) if l.forall{
        case(x, y) => !squares.contains((x - i)* (x - i) + (y - el) * (y - el))
      } => (i, el) :: l
      case (l, el) => l
    }
  }
  val result2 = (0 to m).foldLeft(List.empty[(Int, Int)]) {
    case(list, i) => (0 to n).foldLeft(list) {
      case (l, el) if el + i == 0 => l
      case (l, el) if l.forall{
        case(x, y) => !squares.contains((x - i)* (x - i) + (y - el) * (y - el))
      } => (el, i) :: l
      case (l, el) => l
    }
  }
  val result = if (result1.length > result2.length) result1 else result2
  println(result.length)
  println(result.map(i => s"${i._1} ${i._2}").mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(n, m) = in.next().split(' ').map(_.toInt)
  val squares = (0 to n + m).foldLeft(Set.empty[Int]) {
    case (set, el) => set + el * el
  }
  val min = Math.min(m, n)
  println(min)
  println((0 to min).map(i => s"$i ${min - i}").mkString("\n"))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(n, m) = in.next().split(' ').map(_.toInt)
  val squares = (0 to n + m).foldLeft(Set.empty[Int]) {
    case (set, el) => set + el * el
  }
  val min = Math.min(m, n)
  println((0 to min).map(i => s"$i ${min - i}").mkString("\n"))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(n, m) = in.next().split(' ').map(_.toInt)
  val squares = (0 to n + m).foldLeft(Set.empty[Int]) {
    case (set, el) => set + el * el
  }
  val fx = 0
  val fy = 0
  val result = (0 to n).foldLeft(List.empty[(Int, Int)]) {
    case(list, i) => (0 to m).foldLeft(list) {
      case (l, el) if l.forall{
        case(x, y) => !squares.contains((x - i)* (x - i) + (y - el) * (y - el))
      } => (i, el) :: l
      case (l, el) => l
    }
  }

  println(result.length)
  println(result.map(i => s"${i._1} ${i._2}").mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(n, m) = in.next().split(' ').map(_.toInt)
  val squares = (0 to n + m).foldLeft(Set.empty[Int]) {
    case (set, el) => set + el * el
  }
  val result1 = (0 to n).foldLeft(List.empty[(Int, Int)]) {
    case(list, i) => (0 to m).foldLeft(list) {
      case (l, el) if el + i == 0 => l
      case (l, el) if l.forall{
        case(x, y) => !squares.contains((x - i)* (x - i) + (y - el) * (y - el))
      } => (i, el) :: l
      case (l, el) => l
    }
  }
  val result2 = (0 to m).foldLeft(List.empty[(Int, Int)]) {
    case(list, i) => (0 to n).foldLeft(list) {
      case (l, el) if el + i == 0 => l
      case (l, el) if l.forall{
        case(x, y) => !squares.contains((x - el)* (x - el) + (y - i) * (y - i))
      } => (el, i) :: l
      case (l, el) => l
    }
  }
  val result = if (result1.length > result2.length) result1 else result2
  println(result.length)
  println(result.map(i => s"${i._1} ${i._2}").mkString("\n"))
}

import scala.Math._;
import scala.collection.mutable.LinkedList

object App {
	def readInts:Array[Int] = (readLine split " ") map (_.toInt)
                                                  //> readInts: => Array[Int]                              //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)

	def solve(deep: Int, n: Int):Long = {
	  if (deep == n) n
	  else solve(deep + 1, n) + (deep * (n - deep))
	}

	def f1_io() : Int = {
	    val Array(n, m) = readInts
		//for(i <- 1 to 100; j <- i to 100; if (ceil(sqrt(i*i + j*j)) == floor(sqrt(i*i + j*j)))) println(i + " " + j + " " + sqrt(i*i + j*j))
	  	//val badPoint = for(i <- 1 to 100; j <- i to 100; if (ceil(sqrt(i*i + j*j)) == floor(sqrt(i*i + j*j)))) yield (i, j)
	  	if (n < m) {
	    val s1 = (for(i <- 1 to n; if ((i - 1) <= m)) yield (i, i - 1)).toList
	  	val s2 = (for(i <- 0 to n; if ((i + 1) <= m)) yield (i, i + 1)).toList
	  	if (s2.length > s1.length) {
	  	  println(s2.length)
	  	  s2.foreach {case (x, y) => println(x + " " + y)}
	  	  return 0;
	  	} else {
	  	  for(i <- 1 to m) {
	  	    var f = true
	  	    s1.foreach {
	  	      case (x, y) => {
	  	        val t = sqrt(x*x + (y-i)*(y-i))
	  	        if (ceil(t) == floor(t)) {
	  	          f = false
	  	        }
	  	      }
	  	    }
	  	    if (f) {
	  	      println(s1.length + 1)
	  	      println(0 + " " + i)
	  	      s1.foreach {case (x, y) => println(x + " " + y)}
	  	      return 0
	  	    }
	  	  }
	  	}
	    println(s2.length)
	  	s2.foreach {case (x, y) => println(x + " " + y)}
	  	}
	  	else {
	  	  println(m + 1)
	  	  for(i <- 0 to m) {
	  	    println(i + " " + (n - i))
	  	  }
	  	}
	    0
	}
  def main(args: Array[String]): Unit = {
	f1_io
  }

}

import scala.Math._;
import scala.collection.mutable.LinkedList

object App {
	def readInts:Array[Int] = (readLine split " ") map (_.toInt)
                                                  //> readInts: => Array[Int]                              //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)

	def solve(deep: Int, n: Int):Long = {
	  if (deep == n) n
	  else solve(deep + 1, n) + (deep * (n - deep))
	}

	def f1_io() = {
	    val Array(n, m) = readInts
		val a = min(n, m)
		println(a + 1)
		for(i <- 0 to a) {
		  println(i + " " + (n - i))
		}

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

}


Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams.Monocarp has $$$n$$$ problems that none of his students have seen yet. The $$$i$$$-th problem has a topic $$$a_i$$$ (an integer from $$$1$$$ to $$$n$$$) and a difficulty $$$b_i$$$ (an integer from $$$1$$$ to $$$n$$$). All problems are different, that is, there are no two tasks that have the same topic and difficulty at the same time.Monocarp decided to select exactly $$$3$$$ problems from $$$n$$$ problems for the problemset. The problems should satisfy at least one of two conditions (possibly, both):  the topics of all three selected problems are different;  the difficulties of all three selected problems are different. Your task is to determine the number of ways to select three problems for the problemset.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 50000$$$) — the number of testcases. The first line of each testcase contains an integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of problems that Monocarp have. In the $$$i$$$-th of the following $$$n$$$ lines, there are two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the topic and the difficulty of the $$$i$$$-th problem. It is guaranteed that there are no two problems that have the same topic and difficulty at the same time. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

Print the number of ways to select three training problems that meet either of the requirements described in the statement.

NoteIn the first example, you can take the following sets of three problems:  problems $$$1$$$, $$$2$$$, $$$4$$$;  problems $$$1$$$, $$$3$$$, $$$4$$$;  problems $$$2$$$, $$$3$$$, $$$4$$$. Thus, the number of ways is equal to three.

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

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

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[(Int, Int)](n+1)
        val a = new Array[Int](n+1)
        val b = new Array[Int](n+1)
        for (i <- 1 to n) {
            arr(i) = (readInt(), readInt())
            a(arr(i)._1) += 1
            b(arr(i)._2) += 1
        }
        var cnt = (n.toLong * (n-1).toLong * (n-2).toLong)/6L
        for (i <- 1 to n) {
            cnt -= (a(arr(i)._1).toLong-1L) * (b(arr(i)._2).toLong-1L)
        }
        writer.println(cnt)
    }
    writer.flush()
}


You have a sequence $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, consisting of integers between $$$1$$$ and $$$m$$$. You also have a string $$$s$$$, consisting of $$$m$$$ characters B.You are going to perform the following $$$n$$$ operations.   At the $$$i$$$-th ($$$1 \le i \le n$$$) operation, you replace either the $$$a_i$$$-th or the $$$(m + 1 - a_i)$$$-th character of $$$s$$$ with A. You can replace the character at any position multiple times through the operations. Find the lexicographically smallest string you can get after these operations.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ of the same length if and only if in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2000$$$). The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 50$$$) — the length of the sequence $$$a$$$ and the length of the string $$$s$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the sequence $$$a$$$.

For each test case, print a string of length $$$m$$$ — the lexicographically smallest string you can get. Each character of the string should be either capital English letter A or capital English letter B.

NoteIn the first test case, the sequence $$$a = [1, 1, 3, 1]$$$. One of the possible solutions is the following.   At the $$$1$$$-st operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ becomes ABBBB.  At the $$$2$$$-nd operation, you can replace the $$$5$$$-th character of $$$s$$$ with A (since $$$m+1-a_2=5$$$). After it, $$$s$$$ becomes ABBBA.  At the $$$3$$$-rd operation, you can replace the $$$3$$$-rd character of $$$s$$$ with A. After it, $$$s$$$ becomes ABABA.  At the $$$4$$$-th operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ remains equal to ABABA.  The resulting string is ABABA. It is impossible to produce a lexicographically smaller string.In the second test case, you are going to perform only one operation. You can replace either the $$$2$$$-nd character or $$$4$$$-th character of $$$s$$$ with A. You can get strings BABBB and BBBAB after the operation. The string BABBB is the lexicographically smallest among these strings.In the third test case, the only string you can get is A.In the fourth test case, you can replace the $$$1$$$-st and $$$2$$$-nd characters of $$$s$$$ with A to get AABB.In the fifth test case, you can replace the $$$1$$$-st and $$$3$$$-rd characters of $$$s$$$ with A to get ABABBBB.

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val m = tokenizer.nextToken().toInt
      val A = new Array[String](m)
      for (i <- 0 until m){
        A(i)="B"
      }
      tokenizer = new StringTokenizer(input.readLine())
      for (i <- 1 to n){
        val p = tokenizer.nextToken().toInt
        if (p > m / 2) {
          if (A(m-p) == "A") {
            A(p-1) = "A"
          }
          else A(m-p) = "A"
        }
        else {
          if (A(p-1) == "A") {
            A(m-p) = "A"
          }
          else A(p-1) = "A"
        }
      }
      println(A.mkString)
    }
  }
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
      val t = readInt()
      for (_ <- 1 to t) {
          val Array(n, m): Array[Int] = readLine().split(" ").map(_.toInt)
          val A: Array[Int] = readLine().split(" ").map(_.toInt)
          val B: Array[String] = Array.fill(m)("B")
          for (i <- 0 until n) {
              val a_i: Int = A(i)-1
              val a_i_rev: Int = m-(a_i+1)
              if (a_i < a_i_rev) {
                  if (B(a_i) == "B") {
                      B(a_i) = "A"
                  } else {
                      B(a_i_rev) = "A"
                  }
              }
              else {
                  if (B(a_i_rev) == "B") {
                      B(a_i_rev) = "A"
                  } else {
                      B(a_i) = "A"
                  }
              }
          }
          println(B.mkString(""))
      }
  }
}


You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x < m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a < m \le 10^{10}$$$).

Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.

NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.

object Main extends App {
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val sb = new StringBuilder
    val numCasos = in.nextInt()
    (1 to numCasos).foreach{ _ =>
      val (a,m) = (in.nextLong(),in.nextLong())
      val g = gcd(a,m)
      val number = m/g
      val res = phi(number)
      sb.append(res).append(System.lineSeparator())
    }
    out.print(sb.toString())
  }
  def phi(numer: Long): Long = {
    var ans = numer
    var m = numer
    var i: Long = 2L
    while(i*i <= m){
      if(m%i == 0){
        ans -= ans/i
        while(m%i == 0)
          m /= i

      }
      i += 1L
    }
    if(m > 1) ans-=ans/m
    ans

  }
  def gcd(a: Long,b: Long): Long = {
    if(b == 0)
      a
    else
      gcd(b,a%b)
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main  extends App {
  import java.io._
  import java.util.StringTokenizer
  //solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val sb = new StringBuilder
    val numCasos = in.nextInt()
    (1 to numCasos).foreach{ _ =>
      val (a,m) = (in.nextLong(),in.nextLong())
      val g = gcd(a,m)
      val number = m/g
      val res = phi(number)
      sb.append(res).append(System.lineSeparator())
    }
    out.print(sb.toString())
  }
  def phi(numer: Long): Long = {
    var ans = numer
    var m = numer
    val is = Stream.from(2).takeWhile(i => (i.toLong)*(i.toLong) <=m).toList
    is.foreach{ i =>
      if(m%i == 0){
        ans -= ans/i
        while(m%i == 0)
          m /= i

      }
    }
    if(m > 1) ans-=ans/m
    ans

  }
  def gcd(a: Long,b: Long): Long = {
    if(b == 0)
      a
    else
      gcd(b,a%b)
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".You are given a string s, consisting of lowercase Latin letters and characters "?". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = «aba», then the string "a??" is good, and the string «?bc» is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).

The first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters "?". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.

Print the single number representing the number of good substrings of string s. Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.

NoteConsider the first sample test. Here the string s has two good substrings: "b??" (after we replace the question marks we get "baa"), "???" (after we replace the question marks we get "baa").Let's consider the second sample test. Here the string s has two good substrings: "ab?" ("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a").

import scala.util.control.Breaks._
object Main144C {
  def main(args: Array[String]) {
    val s = readLine
    val p = readLine
    val p_counts = Array.ofDim[Int](26)
    for (c <- p)
      p_counts(c-'a') += 1
    val s_counts = Array.ofDim[Int](26)
    var result = 0
    for (i <- 0 to (s.length - 1)) {
      if (s(i) != '?')
        s_counts(s(i) -'a') += 1
      if (i >= p.length && s(i-p.length) != '?')
        s_counts(s(i - p.length)-'a') -= 1
      var acceptable = i >= p.length - 1
      for (i <- 0 to 25)
        if (s_counts(i) > p_counts(i))
          acceptable = false
      if (acceptable)
        result += 1
    }
    println(result)
  }
}


You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.A polyline defined by points p1, p2, p3, p4 consists of the line segments p1 p2, p2 p3, p3 p4, and its length is the sum of the lengths of the individual line segments.

The only line of the input contains two integers n and m (0 ≤ n, m ≤ 1000). It is guaranteed that grid contains at least 4 different points.

Print 4 lines with two integers per line separated by space — coordinates of points p1, p2, p3, p4 in order which represent the longest possible polyline. Judge program compares your answer and jury's answer with 10 - 6 precision.

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

/**
 * Created by arseny on 27.07.14.
 */
object B extends App {
  val home = true
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextDouble
    val m = nextDouble
    if (n == 0.0 || m == 0.0) {
      if (n == 0) {
        out.println(s"0 ${1}")
        out.println(s"0 ${m.toInt}")
        out.println(s"0 ${0}")
        out.println(s"0 ${(m - 1).toInt}")
      }
      if (m == 0) {
        out.println(s"${1} 0")
        out.println(s"${n.toInt} 0")
        out.println(s"${0} 0")
        out.println(s"${(n - 1).toInt} 0")
      }
    } else {

      def length(x: (Double, Double), y: (Double, Double)) = {
        Math.sqrt((x._1 - y._1) * (x._1 - y._1) + (x._2 - y._2) * (x._2 - y._2))
      }

      var X = (0.0, 0.0)
      var Y = (0.0, 0.0)
      var p = (0.0, 0.0)
      var q = (0.0, 0.0)
      var best = 0.0

      def chooseBest(x: (Double, Double), y: (Double, Double)) = {
        for (i <- 0 to n.toInt) {
          for (j <- 0 to m.toInt) {
            val z = i.toDouble
            val t = j.toDouble
            if (length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y) >= best) {
              if (x != (z, 0.0) && x != (0.0, t) && y != (z, 0.0) && y != (0.0, t)) {
                p = (z, 0.0)
                q = (0.0, t)
                X = x
                Y = y
                best = length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y)
              }
            }
            if (length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y) >= best) {
              if (x != (z, m) && x != (0.0, t) && y != (z, m) && y != (0.0, t)) {
                p = (z, m)
                q = (0.0, t)
                X = x
                Y = y
                best = length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y)
              }
            }
            if (length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y) >= best) {
              if (x != (z, 0.0) && x != (n, t) && y != (z, 0.0) && y != (n, t)) {
                p = (z, 0.0)
                q = (n, t)
                X = x
                Y = y
                best = length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y)
              }
            }
            if (length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y) >= best) {
              if (x != (z, m) && x != (n, t) && y != (z, m) && y != (n, t)) {
                p = (z, m)
                q = (n, t)
                X = x
                Y = y
                best = length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y)
              }
            }
          }
        }
      }

      chooseBest((0.0, 0.0), (n, m))
      chooseBest((0.0, 0.0), (n, 0))
      chooseBest((0.0, 0.0), (0, m))

      chooseBest((1, 0), (n - 1, m))
      chooseBest((0, 1), (n, m - 1))

      out.println(s"${X._1.toInt} ${X._2.toInt}")
      out.println(s"${p._1.toInt} ${p._2.toInt}")
      out.println(s"${q._1.toInt} ${q._2.toInt}")
      out.println(s"${Y._1.toInt} ${Y._2.toInt}")

      //out.println(best)
    }
  }

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

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
object B extends App {

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

  val Array(n, m) = readInts(2)

  if (n == 0) {
    println(s"0 1")
    println(s"0 $m")
    println(s"0 0")
    println(s"0 ${m - 1}")
  } else if (m == 0) {
    println(s"1 0")
    println(s"$n 0")
    println(s"0 0")
    println(s"${n - 1} 0")
  } else if (n <= m) {
    var best = -1d
    var bestI = 0
    var bestJ = 0
    for (i <- 1 to n) {
      val d1 = Math.sqrt(m * m + (n - i) * (n - i))
      for (j <- 0 until n) {
        val d2 = Math.sqrt(m * m + (j - i) * (j - i))
        if (d1 + d2 > best) {
          best = d1 + d2
          bestI = i
          bestJ = j
        }
      }
    }
    val other = 2d * Math.sqrt(m * m + (n - 1) * (n - 1))
    if (best > other) {
      println(s"0 0")
      println(s"$n $m")
      println(s"$bestI 0")
      println(s"$bestJ $m")
    } else {
      println(s"1 0")
      println(s"$n $m")
      println(s"0 0")
      println(s"${n - 1} $m")
    }
  } else {
    var best = -1d
    var bestI = 0
    var bestJ = 0
    for (i <- 1 to m) {
      val d1 = Math.sqrt(n * n + (m - i) * (m - i))
      for (j <- 0 until m) {
        val d2 = Math.sqrt(n * n + (j - i) * (j - i))
        if (d1 + d2 > best) {
          best = d1 + d2
          bestI = i
          bestJ = j
        }
      }
    }
    val other = 2d * Math.sqrt(n * n + (m - 1) * (m - 1))
    if (best > other) {
      println(s"0 0")
      println(s"$n $m")
      println(s"0 $bestI")
      println(s"$n $bestJ")
    } else {
      println(s"0 1")
      println(s"$n $m")
      println(s"0 0")
      println(s"$n ${m - 1}")
    }
  }

}

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

/**
 * Created by arseny on 27.07.14.
 */
object B extends App {
  val home = true
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextDouble
    val m = nextDouble
    if (n == 0.0 || m == 0.0) {
      if (n == 0) {
        out.println(s"0 ${1}")
        out.println(s"0 ${m.toInt}")
        out.println(s"0 ${0}")
        out.println(s"0 ${(m - 1).toInt}")
      }
      if (m == 0) {
        out.println(s"${1} 0")
        out.println(s"${n.toInt} 0")
        out.println(s"${0} 0")
        out.println(s"${(n - 1).toInt} 0")
      }
    } else {

      def length(x: (Double, Double), y: (Double, Double)) = {
        Math.sqrt((x._1 - y._1) * (x._1 - y._1) + (x._2 - y._2) * (x._2 - y._2))
      }

      var X = (0.0, 0.0)
      var Y = (0.0, 0.0)
      var p = (0.0, 0.0)
      var q = (0.0, 0.0)
      var best = 0.0

      def chooseBest(x: (Double, Double), y: (Double, Double)) = {
        for (i <- 0 to n.toInt) {
          for (j <- 0 to m.toInt) {
            val z = i.toDouble
            val t = j.toDouble
            if (length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y) >= best) {
              if (x != (z, 0.0) && x != (0.0, t) && y != (z, 0.0) && y != (0.0, t)) {
                p = (z, 0.0)
                q = (0.0, t)
                X = x
                Y = y
                best = length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y)
              }
            }
            if (length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y) >= best) {
              if (x != (z, m) && x != (0.0, t) && y != (z, m) && y != (0.0, t)) {
                p = (z, m)
                q = (0.0, t)
                X = x
                Y = y
                best = length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y)
              }
            }
            if (length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y) >= best) {
              if (x != (z, 0.0) && x != (n, t) && y != (z, 0.0) && y != (n, t)) {
                p = (z, 0.0)
                q = (n, t)
                X = x
                Y = y
                best = length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y)
              }
            }
            if (length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y) >= best) {
              if (x != (z, m) && x != (n, t) && y != (z, m) && y != (n, t)) {
                p = (z, m)
                q = (n, t)
                X = x
                Y = y
                best = length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y)
              }
            }
          }
        }
      }

      chooseBest((0.0, 0.0), (n, m))
      chooseBest((0.0, 0.0), (n, 0))
      chooseBest((0.0, 0.0), (0, m))

      out.println(s"${X._1.toInt} ${X._2.toInt}")
      out.println(s"${p._1.toInt} ${p._2.toInt}")
      out.println(s"${q._1.toInt} ${q._2.toInt}")
      out.println(s"${Y._1.toInt} ${Y._2.toInt}")

      //out.println(best)
    }
  }

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

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

/**
 * Created by arseny on 27.07.14.
 */
object B extends App {
  val home = true
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextDouble
    val m = nextDouble
    if (n == 0.0 || m == 0.0) {
      if (n == 0) {
        out.println(s"0 ${1}")
        out.println(s"0 ${m.toInt}")
        out.println(s"0 ${0}")
        out.println(s"0 ${(m - 1).toInt}")
      }
      if (m == 0) {
        out.println(s"${1} 0")
        out.println(s"${m.toInt} 0")
        out.println(s"${0} 0")
        out.println(s"${(m - 1).toInt} 0")
      }
    } else {

      def length(x: (Double, Double), y: (Double, Double)) = {
        Math.sqrt((x._1 - y._1) * (x._1 - y._1) + (x._2 - y._2) * (x._2 - y._2))
      }

      var X = (0.0, 0.0)
      var Y = (0.0, 0.0)
      var p = (0.0, 0.0)
      var q = (0.0, 0.0)
      var best = 0.0

      def chooseBest(x: (Double, Double), y: (Double, Double)) = {
        for (i <- 0 to n.toInt) {
          for (j <- 0 to m.toInt) {
            val z = i.toDouble
            val t = j.toDouble
            if (length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y) >= best) {
              if (x != (z, 0.0) && x != (0.0, t) && y != (z, 0.0) && y != (0.0, t)) {
                p = (z, 0.0)
                q = (0.0, t)
                X = x
                Y = y
                best = length(x, (z, 0.0)) + length((z, 0.0), (0.0, t)) + length((0.0, t), y)
              }
            }
            if (length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y) >= best) {
              if (x != (z, m) && x != (0.0, t) && y != (z, m) && y != (0.0, t)) {
                p = (z, m)
                q = (0.0, t)
                X = x
                Y = y
                best = length(x, (z, m)) + length((z, m), (0.0, t)) + length((0.0, t), y)
              }
            }
            if (length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y) >= best) {
              if (x != (z, 0.0) && x != (n, t) && y != (z, 0.0) && y != (n, t)) {
                p = (z, 0.0)
                q = (n, t)
                X = x
                Y = y
                best = length(x, (z, 0.0)) + length((z, 0.0), (n, t)) + length((n, t), y)
              }
            }
            if (length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y) >= best) {
              if (x != (z, m) && x != (n, t) && y != (z, m) && y != (n, t)) {
                p = (z, m)
                q = (n, t)
                X = x
                Y = y
                best = length(x, (z, m)) + length((z, m), (n, t)) + length((n, t), y)
              }
            }
          }
        }
      }

      chooseBest((0.0, 0.0), (n, m))
      chooseBest((0.0, 0.0), (n, 0))
      chooseBest((0.0, 0.0), (0, m))

      out.println(s"${X._1.toInt} ${X._2.toInt}")
      out.println(s"${p._1.toInt} ${p._2.toInt}")
      out.println(s"${q._1.toInt} ${q._2.toInt}")
      out.println(s"${Y._1.toInt} ${Y._2.toInt}")

      //out.println(best)
    }
  }

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

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
object B extends App {

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

  val Array(n, m) = readInts(2)

  if (n == 0) {
    println(s"0 1")
    println(s"0 $m")
    println(s"0 0")
    println(s"0 ${m - 1}")
  } else if (m == 0) {
    println(s"1 0")
    println(s"$n 0")
    println(s"0 0")
    println(s"${n - 1} 0")
  } else if (n <= m) {
    var best = -1d
    var bestI = 0
    var bestJ = 0
    for (i <- 1 to n) {
      val d1 = Math.sqrt(m * m + (n - i) * (n - i))
      for (j <- 0 until n) {
        val d2 = Math.sqrt(m * m + (j - i) * (j - i))
        if (d1 + d2 > best) {
          best = d1 + d2
          bestI = i
          bestJ = j
        }
      }
    }
    val other = 2d * Math.sqrt(m * m + (n - 1) * (n - 1))
    if (best > other) {
      println(s"0 0")
      println(s"$n $m")
      println(s"$bestI 0")
      println(s"$bestJ $m")
    } else {
      println(s"1 0")
      println(s"$n $m")
      println(s"0 0")
      println(s"${n - 1} $m")
    }
  } else {
    var best = -1d
    var bestI = 0
    var bestJ = 0
    for (i <- 1 to m) {
      val d1 = Math.sqrt(n * n + (m - i) * (m - i))
      for (j <- 0 until m) {
        val d2 = Math.sqrt(n * n + (j - i) * (j - i))
        if (d1 + d2 > best) {
          best = d1 + d2
          bestI = i
          bestJ = j
        }
      }
    }
    val other = 2d * Math.sqrt(m * m + (n - 1) * (n - 1))
    if (best > other) {
      println(s"0 0")
      println(s"$n $m")
      println(s"0 $bestI")
      println(s"$n $bestJ")
    } else {
      println(s"0 1")
      println(s"$n $m")
      println(s"0 0")
      println(s"$n ${m - 1}")
    }
  }

}


There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.

The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.

In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.

import java.util.StringTokenizer;
object Tri {
  var st:StringTokenizer=new StringTokenizer("");
  def newst={st=new StringTokenizer(readLine);}
  def newint:Int={st.nextToken.toInt;}
  def gcd(a:Int,b:Int):Int = {
    if (a<b) {gcd(b,a);} else if (b==0) {a;} else {gcd(b,a%b);}
  }
  def main(args:Array[String]) {
    newst; var a=newint; var b=newint; var g=gcd(a,b);
    for (x<-1 to g; y<-1 to g) {
      var z = x*x + y*y;
      if ((x>y) && (g%(x*x + y*y) == 0)) {
	var m:Int=1;
	if (a*(x*x-y*y)==b*2*x*y) {m=(-1);}
	/* if negativing does not solve the problem, then
	 * we will have a=b. But if a=b, the current angle
	 * should be 45, but the current cos is rational.
	 * cos 45 isn't rational. Contradiction. So negativing
	 * solves the problem, if at all possible.
	 */
	println("YES");
	println("0 0");
	println(a*(x*x - y*y)/z + " " + a*2*x*y/z);
	println(m*b*2*x*y/z + " " + m*b*(y*y-x*x)/z);
	System.exit(0);
      }
    }
    println("NO");
  }
}

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 A, B = ni()
    def pythagorean(x: Int) = {
      val res = ArrayBuffer[(Int, Int)]()
      REP(x, 1) { a =>
        val bSqr = (x + a) * (x - a)
        val b = math.sqrt(bSqr).toInt
        if (b * b == bSqr && b > 0) res += a -> b
      }
      res
    }

    val as = pythagorean(A) // pos-X -> pos-Y の部分
    val bs = pythagorean(B) // neg-Y -> pos-X の部分

    (for {
      (ax, ay) <- as
      (bx, by) <- bs
      if ax * bx + ay * -by == 0 && ax != bx
    } yield (ax -> ay, bx -> by)).headOption match {
      case Some(((ax, ay), (bx, by))) =>
        out.println("YES")
        out.println("0 0")
        out.println(s"$ax $ay")
        out.println(s"$bx -$by")

      case None =>
        out.println("NO")
    }
  }

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

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

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

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

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

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

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

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

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

object A extends App {

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

  val Array(a, b) = readInts(2)

  for (x1 <- 1 until a; y1 <- 1 until a) if (x1 * x1 + y1 * y1 == a * a) {
    val x2 = -y1 * b / a
    val y2 = x1 * b / a
    if (x2 * x2 + y2 * y2 == b * b && y2 != y1) {
      println("YES")
      println("0 0")
      println(s"$x1 $y1")
      println(s"$x2 $y2")
      exit
    }
  }

  println("NO")
}

import java.util.StringTokenizer;
object Tri {
  var st:StringTokenizer=new StringTokenizer("");
  def newst={st=new StringTokenizer(readLine);}
  def newint:Int={st.nextToken.toInt;}
  def gcd(a:Int,b:Int):Int = {
    if (a<b) {gcd(b,a);} else if (b==0) {a;} else {gcd(b,a%b);}
  }
  def main(args:Array[String]) {
    newst; var a=newint; var b=newint; var g=gcd(a,b);
    for (x<-1 to g; y<-1 to g) {
      if ((x>y) && (g%(x*x + y*y) == 0)) {
	var z=x*x + y*y;
	println("YES");
	println("0 0");
	println(a*(x*x - y*y)/z + " " + a*2*x*y/z);
	println(b*2*x*y/z + " " + b*(y*y-x*x)/z);
	System.exit(0);
      }
    }
    println("NO");
  }
}

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

object A extends App {

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

  val Array(a, b) = readInts(2)

  for (x1 <- 1 until a; y1 <- 1 until a) if (x1 * x1 + y1 * y1 == a * a) {
    val x2 = -y1 * b / a
    val y2 = x1 * b / a
    if (x2 * x2 + y2 * y2 == b * b) {
      println("YES")
      println("0 0")
      println(s"$x1 $y1")
      println(s"$x2 $y2")
      exit
    }
  }

  println("NO")
}


Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.Help Vasya to recover the initial set of cards with numbers.

The single line contains three space-separated integers: n (2 ≤ n ≤ 100) — the initial number of cards on the table, d (|d| ≤ 104) — the number on the card that was left on the table after all the magical actions, and l (1 ≤ l ≤ 100) — the limits for the initial integers.

If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.

import java.util.Scanner

object B extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  val d = sc.nextInt
  val el = sc.nextInt
  val lines = Iterator.iterate((0, d, n)) {
    case (a, d0, n0) => if (n0 <= 0) (-1, -1, -1)
			else if (n0 == 1) (d0, d0, 0)
			else if (d0 < 0) (1, 1 - d0, n0 - 1)
			else if (d0 == 0) (1, 1, n0 - 1)
			else if (el > d0) (d0 + 1, 1, n0 - 1)
			else (el, el - d0, n0 - 1)
  }.takeWhile {case (_, _, n0) => n0 >= 0}.toList.tail
  // println(lines.mkString("->"))
  val last_val = lines.last._1
  if (last_val <= 0 || last_val > el) {
    println(-1)
  } else {
    println(lines.map(p => p._1).mkString(" "))
  }
}


DZY loves chessboard, and he enjoys playing with it.He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.You task is to find any suitable placement of chessmen on the given chessboard.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either "." or "-". A "." means that the corresponding cell (in the i-th row and the j-th column) is good, while a "-" means it is bad.

Output must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell. If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.

NoteIn the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are.

import java.util.StringTokenizer

object _445A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val m = next.toInt
  val a = (1 to n).map(i => next.toArray).toArray
  for (i <- 0 until n)
    for (j <- 0 until m)
      if (a(i)(j) == '.') a(i)(j) = if ((i + j) % 2 == 0) 'W' else 'B'

  a.foreach(i => println(i.mkString))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  Range(0, n).foreach { i =>
    println(in.next().zipWithIndex.map{
      case('.', index) if (i + index) % 2 == 0 => 'B'
      case('.', index) => 'W'
      case(ch, _) => ch
    }.mkString)
  }

}

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

  val n, m = sc.nextInt()
  val board = Array.fill(n)(sc.next)

  println(new A(n, m, board).answer.mkString("\n"))
}

class A(n: Int, m: Int, board: Array[String]) {
  def answer: Array[String] = {
    val cahrs = for{
      (line, y) <- board.zipWithIndex
      (char, x) <- line.zipWithIndex
    } yield char match {
        case '.' => if ((x+y) % 2 == 0) 'B' else 'W'
        case '-' => '-'
      }

    cahrs.grouped(m).map(_.mkString("")).toArray
  }
}

object A445 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val in = Array.fill(n)(read.toCharArray)
    def isValid(i: Int, j: Int): Boolean = {
      i >= 0 && i < n && j >=0 && j < m
    }
    val delta = Array((1,0), (0,1), (-1,0), (0,-1))
    for(i <- 0 until n; j <- 0 until m if in(i)(j) == '.') {
      if((i+j)%2 == 0)
        in(i)(j) = 'B'
      else
        in(i)(j) = 'W'
    }
    println(in.map(_.mkString("")).mkString("\n"))
  }

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

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

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

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

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

}

import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object Main extends App {

  val Array(n,m) = readLine.split(" ").map(_.toInt)
  val board = HashSet((0 to (n-1)).flatMap({ i =>
    val good = readLine.map({ case '.' => true case '-' => false }).zipWithIndex.filter(_._1)
    good.map(_._2).map((i, _))
  }):_*)

  val draw = HashMap[(Int, Int), Boolean]()

  def isValid(pos: (Int,Int)): Boolean = pos match { case (i,j) =>
    (i >= 0) && (i < n) && (j >= 0) && (j < m) && board.contains((i,j))
  }

  def setColor(value: Boolean)(pos: (Int, Int)): Unit = {
    board -= pos
    draw += (pos -> value)
    val (i,j) = pos
    val ns = List((i-1, j), (i+1, j), (i, j-1), (i, j+1)).filter(isValid(_))
    ns foreach setColor(!value)
  }

  while(board.size > 0) {
    setColor(true)(board.head)
  }

  (0 to (n-1)) foreach { i =>
    println((0 to (m-1)).map(j => {
      draw.get((i,j)).map({ case true => "W" case false => "B" }).getOrElse("-")
    }).mkString)
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  Range(0, m).foreach { i =>
    println(in.next().zipWithIndex.map{
      case('.', index) if (i + index) % 2 == 0 => 'B'
      case('.', index) => 'W'
      case(ch, _) => ch
    }.mkString)
  }

}

object A445 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val in = Array.fill(n)(read.toCharArray)
    def isValid(i: Int, j: Int): Boolean = {
      i >= 0 && i < n && j >=0 && j < m
    }
    val delta = Array((1,0), (0,1), (-1,0), (0,-1))
    for(i <- 0 until n; j <- 0 until m if in(i)(j) == '.') {
      var b = 0
      var w = 0
      delta.foreach {
        case (dx, dy) if isValid(i+dx, j+dy)=>
          if(in(i+dx)(j+dy) == 'B') {
            b += 1
          }
          if(in(i+dx)(j+dy) == 'W') {
            w += 1
          }
        case _ =>
      }
      if(in(i)(j) == '.') {
        if(w > 0)
          in(i)(j) = 'B'
        else
          in(i)(j) = 'W'
      }
    }
    println(in.map(_.mkString("")).mkString("\n"))
  }

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

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

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

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

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

}

import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object Main extends App {

  val Array(n,m) = readLine.split(" ").map(_.toInt)
  val board = HashSet((0 to (n-1)).flatMap({ i =>
    val good = readLine.map({ case '.' => true case '-' => false }).zipWithIndex.filter(_._1)
    good.map(_._2).map((i, _))
  }):_*)

  val draw = HashMap[(Int, Int), Boolean]()

  def isValid(i: Int, j: Int): Boolean = {
    (i >= 0) && (i < n) && (j >= 0) && (j < n) && board.contains((i,j))
  }

  def setColor(pos: (Int, Int), value: Boolean): Unit = {
    board -= pos
    draw += (pos -> value)
    val (i,j) = pos
    for {
     di <- (-1 to 1)
     dj <- (-1 to 1)
     if Math.abs(di + dj) == 1
     if isValid(i+di, j+dj)
    } yield setColor((i+di, j+dj), !value)
  }

  while(board.size > 0) {
    setColor(board.head, true)
  }

  (0 to (n-1)) foreach { i =>
    println((0 to (m-1)).map(j => draw.get((i,j)).map({ case true => "W" case false => "B" }).getOrElse("-")).mkString)
  }

}


While performing complex market analysis William encountered the following problem:For a given array $$$a$$$ of size $$$n$$$ and a natural number $$$e$$$, calculate the number of pairs of natural numbers $$$(i, k)$$$ which satisfy the following conditions:   $$$1 \le i, k$$$  $$$i + e \cdot k \le n$$$.  Product $$$a_i \cdot a_{i + e} \cdot a_{i + 2 \cdot e} \cdot \ldots \cdot a_{i + k \cdot e} $$$ is a prime number. A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$e$$$ $$$(1 \le e \le n \le 2 \cdot 10^5)$$$, the number of items in the array and number $$$e$$$, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^6)$$$, the contents of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output the answer in the following format: Output one line containing the number of pairs of numbers $$$(i, k)$$$ which satisfy the conditions.

NoteIn the first example test case two pairs satisfy the conditions:   $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \cdot a_{5} = 2$$$ which is a prime number.  $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \cdot a_{6} = 19$$$ which is a prime number. In the second example test case there are no pairs that satisfy the conditions.In the third example test case four pairs satisfy the conditions:   $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \cdot a_{4} = 2$$$ which is a prime number.  $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \cdot a_{4} \cdot a_{7} = 2$$$ which is a prime number.  $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \cdot a_{6} = 2$$$ which is a prime number.  $$$i = 6, k = 1$$$, for which the product is: $$$a_{6} \cdot a_{9} = 2$$$ which is a prime number. In the fourth example test case there are no pairs that satisfy the conditions.In the fifth example test case five pairs satisfy the conditions:   $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \cdot a_{2} = 2$$$ which is a prime number.  $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \cdot a_{2} \cdot a_{3} = 2$$$ which is a prime number.  $$$i = 1, k = 3$$$, for which the product is: $$$a_{1} \cdot a_{2} \cdot a_{3} \cdot a_{4} = 2$$$ which is a prime number.  $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \cdot a_{3} = 2$$$ which is a prime number.  $$$i = 2, k = 2$$$, for which the product is: $$$a_{2} \cdot a_{3} \cdot a_{4} = 2$$$ which is a prime number. In the sixth example test case there are no pairs that satisfy the conditions.

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

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

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * a.compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 1000010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()
    val mark = new Array[Boolean](maxn)
    var tmp = 0
    mark(1) = true
    for (i <- 2 until maxn)
        if (!mark(i)) {
            tmp = 2 * i
            while (tmp < maxn) {
                mark(tmp) = true
                tmp += i
            }
        }

    for (tt <- 1 to t) {
        val n = readInt()
        val k = readInt()
        val l = new Array[Long](n+1)
        val r = new Array[Long](n+1)
        val arr = new Array[Int](n+1)
        for (i <- 1 to n) {
            arr(i) = readInt()
        }
        for (i <- 1 to n) {
            if (arr(i) == 1) {
                l(i) = 1L
                r(i) = 1L
            }
        }
        for(i <- k+1 to n) {
            if (arr(i-k) == 1)
                l(i) += l(i-k)
        }
        for (i <- (1 to n-k).reverse) {
            if (arr(i + k) == 1)
                r(i) += r(i+k)
        }
        var cnt = 0L
        for (i <- 1 to n) {
            if (!mark(arr(i))) {
                cnt += (l(i)+1L) * (r(i)+1L) - 1L
            }
        }
        writer.println(cnt)

        def check(kk: Int): Boolean = {
            return true
        }
        def bs(st:Int, en:Int): Int = {
            if (en - st <= 1) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}


Ilya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of cards Ilya has. Each of the next n lines contains two non-negative space-separated integers — ai and bi (0 ≤ ai, bi ≤ 104) — the numbers, written at the top and the bottom of the i-th card correspondingly.

Print the single number — the maximum number of points you can score in one round by the described rules.

NoteIn the first sample none of two cards brings extra moves, so you should play the one that will bring more points.In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards.

import java.util.Scanner

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 29.02.12
 * Time: 2:06
 * To change this template use File | Settings | File Templates.
 */

object B {
  val input = new Scanner(System.in)

  def main(args: Array[String]) {
    val count = input.nextInt
    val cards = (1 to count).map(_ => Card(input.nextInt, input.nextInt)).sorted
    def calc():Int = {
      var points = 0
      var steps = 1
      for (Card(value, step) <- cards) {
        steps -= 1
        steps += step
        points += value
        if(steps == 0 ) return points
      }
      return points
    }
    val x = calc()
    println(x)
  }

  case class Card(value: Int, step: Int) extends Comparable[Card] {
    def compareTo(o: Card) = this.step.compareTo(o.step) match {
      case 0 => -this.value.compareTo(o.value)
      case some => -some
    }
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val r = (1 to n).map(_ => in.next().split(' ').map(_.toInt)).toList
  val (counter, sum) = r.filter(_.last > 0).foldLeft((1, 0)) {
    case ((c, s), e) =>
      (c + e.last - 1, s + e.head)
  }
  println(sum + r.filter(_.last == 0).map(_.head).sorted.takeRight(counter).sum)
}

object Main
{
	def main(args:Array[String])
	{
		val n = readInt
		val lol = (0 until n).map(i => readLine.split(" ").map(j => j.toInt)).toList

		val notzeroarray = lol.filter(i => i(1) > 0).map(i => i(0))
		val b = lol.map(i => i(1)).sum - notzeroarray.length + 1
		val notzeropts = notzeroarray.sum

		val zeroarray = lol.filter(i => i(1) == 0).map(i => i(0)).sort((s, t) => s > t)

		var carts = 0;
		if (b > zeroarray.length)
			carts = zeroarray.length
		else carts = b

		val zeropts = (0 until carts).map(i => zeroarray(i)).sum

		println(notzeropts + zeropts)
	}
}

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

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

  // two non negative integer top/bottom ... a_i/b_i
  // A_i point and additional opportunity to play b_i additional cards

  def solve(): Int = {
    val N = sc.nextInt
    val C = List.fill(N, 2)(sc.nextInt)

    val C0 = C.filter(_(1) == 0).map(_(0)).sorted(Ordering.Int.reverse)
    val C1 = C.filter(_(1) > 0).map(_(0))

    // # of additional cards for C0
    val n  = C.transpose.toList(1).map { (i: Int) => (i - 1) max 0 }.sum + 1

    C1.sum + C0.take(n).sum
  }

  out.println(solve)
  out.close
}

object B {
  def main(args: Array[String]): Unit = {
   val cards = scala.io.Source.stdin.getLines().toList.tail.map(s => {val a = s.split(" "); (a(0).toInt, a(1).toInt)})
   val good = cards.filter(_._2>0)
   val toplay = good.map(_._2-1).sum+1

   System.out.println(good.map(_._1).sum+cards.filter(_._2==0).map(_._1).sort(_>_).take(toplay).sum)
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))

    val t = a.filter(_.apply(1) != 0).foldLeft((0, 1)) { (acc, e) =>
      (acc._1 + e(0), acc._2 + e(1) - 1)
    }
    val sum = a.filter(_.apply(1) == 0).map(_.apply(0)).sorted.reverse.take(t._2).sum
    println(t._1 + sum)
  }
}

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

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

  // two non negative integer top/bottom ... a_i/b_i
  // A_i point and additional opportunity to play b_i additional cards

  def solve(): Int = {
    val N = sc.nextInt
    val C = List.fill(N, 2)(sc.nextInt)

    val n = C.transpose.toList(1).sum + 1 // the number of playable cards
    C.transpose.toList(0).sorted(Ordering.Int.reverse).take(n).sum
  }

  out.println(solve)
  out.close
}

object B {
  def main(args: Array[String]): Unit = {
   val cards = scala.io.Source.stdin.getLines().toList.tail.map(s => {val a = s.split(" "); (a(0).toInt, a(1).toInt)})
   val good = cards.filter(_._2>0)
   val toplay = good.map(_._2).sum+1

   System.out.println(good.map(_._1).sum+cards.filter(_._2==0).map(_._1).sort(_>_).take(toplay).sum)
  }
}