Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the $$$i$$$-th integer represents the color of the $$$i$$$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $$$k$$$, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $$$k$$$ to the right.   To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.

The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq k \leq 256$$$), the number of pixels in the image, and the maximum size of a group, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$0 \leq p_i \leq 255$$$), where $$$p_i$$$ is the color of the $$$i$$$-th pixel.

Print $$$n$$$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.

NoteOne possible way to group colors and assign keys for the first sample:Color $$$2$$$ belongs to the group $$$[0,2]$$$, with group key $$$0$$$.Color $$$14$$$ belongs to the group $$$[12,14]$$$, with group key $$$12$$$.Colors $$$3$$$ and $$$4$$$ belong to group $$$[3, 5]$$$, with group key $$$3$$$.Other groups won't affect the result so they are not listed here.

import scala.io.StdIn;

object Main {
  def main(args: Array[String]): Unit = {
    val Array(n, k) = IO.readInts
    val xs = IO.readInts

    var m = Map[Int, Int]()

    def getGroupKey(x: Int) = m.get(x).getOrElse(x)

    val result = for (x <- xs) yield {
      if (m.contains(x)) {
        m(x)
      } else {
        val Some(newKey) =
            ((x - k + 1) to x) find(getGroupKey(_) > Math.max(x - k, -1))
        val newUsed = newKey to x
        m = m ++ (newUsed map (_->newKey))
        newKey
      }
    }

    println(result.mkString(" "))
  }
}

object IO {
  def readInts = readLine split(" ") map (_.toInt)
  def readLongs = readLine split(" ") map (_.toLong)
  def readDoubles = readLine split(" ") map (_.toDouble)
}


The only difference between easy and hard versions is constraints.If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.A session has begun at Beland State University. Many students are taking exams.Polygraph Poligrafovich is going to examine a group of $$$n$$$ students. Students will take the exam one-by-one in order from $$$1$$$-th to $$$n$$$-th. Rules of the exam are following:  The $$$i$$$-th student randomly chooses a ticket.  if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.  if the student finds the ticket easy, he spends exactly $$$t_i$$$ minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.The duration of the whole exam for all students is $$$M$$$ minutes ($$$\max t_i \le M$$$), so students at the end of the list have a greater possibility to run out of time to pass the exam.For each student $$$i$$$, you should count the minimum possible number of students who need to fail the exam so the $$$i$$$-th student has enough time to pass the exam.For each student $$$i$$$, find the answer independently. That is, if when finding the answer for the student $$$i_1$$$ some student $$$j$$$ should leave, then while finding the answer for $$$i_2$$$ ($$$i_2>i_1$$$) the student $$$j$$$ student does not have to go home.

The first line of the input contains two integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le M \le 2 \cdot 10^7$$$) — the number of students and the total duration of the exam in minutes, respectively. The second line of the input contains $$$n$$$ integers $$$t_i$$$ ($$$1 \le t_i \le 100$$$) — time in minutes that $$$i$$$-th student spends to answer to a ticket. It's guaranteed that all values of $$$t_i$$$ are not greater than $$$M$$$.

Print $$$n$$$ numbers: the $$$i$$$-th number must be equal to the minimum number of students who have to leave the exam in order to $$$i$$$-th student has enough time to pass the exam.

NoteThe explanation for the example 1.Please note that the sum of the first five exam times does not exceed $$$M=15$$$ (the sum is $$$1+2+3+4+5=15$$$). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are $$$0$$$.In order for the $$$6$$$-th student to pass the exam, it is necessary that at least $$$2$$$ students must fail it before (for example, the $$$3$$$-rd and $$$4$$$-th, then the $$$6$$$-th will finish its exam in $$$1+2+5+6=14$$$ minutes, which does not exceed $$$M$$$).In order for the $$$7$$$-th student to pass the exam, it is necessary that at least $$$3$$$ students must fail it before (for example, the $$$2$$$-nd, $$$5$$$-th and $$$6$$$-th, then the $$$7$$$-th will finish its exam in $$$1+3+4+7=15$$$ minutes, which does not exceed $$$M$$$).

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

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

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

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

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

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

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

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

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, M = ni()
    val T = na(N)
    val C = Array.ofDim[Int](101)
    val ans = Array.ofDim[Int](N)
    REP(N) { i =>
      var remain = M - T(i)
      var cnt = 0
      REP(100, 1) { j =>
        val unit = min(remain / j, C(j))
        remain -= unit * j
        cnt += unit
      }
      ans(i) = max(0, i - cnt)
      C(T(i)) += 1
    }

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


In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are ai people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.Help platform select such an hour, that the number of people who will participate in the contest is maximum.

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of hours in day. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 10 000), where ai is the number of people in the i-th timezone who want to participate in the contest. The third line contains two space-separated integers s and f (1 ≤ s < f ≤ n).

Output a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.

NoteIn the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate.In second example only people from the third and the fourth timezones will participate.

object CF939C extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val a = Array.fill[Int](n)(sc.nextInt)
  val s, f = sc.nextInt
  val participate = (1 to n) map (checkTime)
  val ans = (nextJoin(0, List(countJoin(0))))
  val am = ans.max
  println(n - (ans lastIndexWhere(_ == am)))

  def checkTime(n:Int) = {
    n >= s && n < f
  }

  def countJoin(j:Int) = {
    ((0 until n) map (i => participate((i + j) % n)) zipWithIndex) filter (_._1) map (i => a(i._2)) sum
  }

  def nextJoin(offset:Int, p:Seq[Int]):Seq[Int] = {
    //println(p, (f-2-offset+n) % n, (s-2-offset+n) % n, a((f-2-offset+n) % n), a((s-2-offset+n) % n))
    val here = p.head - a((f-2-offset+n) % n) + a((s-2-offset+n) % n)
    if(offset == n-1) p else nextJoin(offset+1, here +: p)
  }
}

object CF939C extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val a = Array.fill[Int](n)(sc.nextInt)
  val s, f = sc.nextInt
  val participate = (1 to n) map (checkTime)
  val ans = (nextJoin(0, List(countJoin(0))))
  val am = ans.max
  println(n - (ans indexWhere(_ == am)))

  def checkTime(n:Int) = {
    n >= s && n < f
  }

  def countJoin(j:Int) = {
    ((0 until n) map (i => participate((i + j) % n)) zipWithIndex) filter (_._1) map (i => a(i._2)) sum
  }

  def nextJoin(offset:Int, p:List[Int]):List[Int] = {
    //println(p, (f-2-offset+n) % n, (s-2-offset+n) % n, a((f-2-offset+n) % n), a((s-2-offset+n) % n))
    val here = p.head - a((f-2-offset+n) % n) + a((s-2-offset+n) % n)
    if(offset == n-1) p else nextJoin(offset+1, here +: p)
  }
}

object CF939C extends App{
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val a = Seq.fill[Int](n)(sc.nextInt)
  val s, f = sc.nextInt
  val participate = (1 to n) map (checkTime)
  val ans = (nextJoin(0, Seq(countJoin(0))))
  val am = ans.max
  println((ans indexWhere(_ == am)) + 1)

  def checkTime(n:Int) = {
    n >= s && n < f
  }

  def countJoin(j:Int) = {
    ((0 until n) map (i => participate((i + j) % n)) zipWithIndex) filter (_._1) map (i => a(i._2)) sum
  }

  def nextJoin(offset:Int, p:Seq[Int]):Seq[Int] = {
    //println(p, (f-2-offset+n) % n, (s-2-offset+n) % n, a((f-2-offset+n) % n), a((s-2-offset+n) % n))
    val here = p.head - a((f-2-offset+n) % n) + a((s-2-offset+n) % n)
    if(offset == n-1) p else nextJoin(offset+1, here +: p)
  }
}


Allen wants to enter a fan zone that occupies a round square and has $$$n$$$ entrances.There already is a queue of $$$a_i$$$ people in front of the $$$i$$$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.Allen uses the following strategy to enter the fan zone:   Initially he stands in the end of the queue in front of the first entrance.  Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of entrances. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the number of people in queues. These numbers do not include Allen.

Print a single integer — the number of entrance that Allen will use.

NoteIn the first example the number of people (not including Allen) changes as follows: $$$[\textbf{2}, 3, 2, 0] \to [1, \textbf{2}, 1, 0] \to [0, 1, \textbf{0}, 0]$$$. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance.In the second example the number of people (not including Allen) changes as follows: $$$[\textbf{10}, 10] \to [9, \textbf{9}] \to [\textbf{8}, 8] \to [7, \textbf{7}] \to [\textbf{6}, 6] \to \\ [5, \textbf{5}] \to [\textbf{4}, 4] \to [3, \textbf{3}] \to [\textbf{2}, 2] \to [1, \textbf{1}] \to [\textbf{0}, 0]$$$.In the third example the number of people (not including Allen) changes as follows: $$$[\textbf{5}, 2, 6, 5, 7, 4] \to [4, \textbf{1}, 5, 4, 6, 3] \to [3, 0, \textbf{4}, 3, 5, 2] \to \\ [2, 0, 3, \textbf{2}, 4, 1] \to [1, 0, 2, 1, \textbf{3}, 0] \to [0, 0, 1, 0, 2, \textbf{0}]$$$.

object Main{
  def main(args: Array[String]) {
    val n = readInt
    val a: Array[Int] = readLine.split(" ").map(_.toInt)
    val min = a.min
    val p = min % n
    for(i <- 0 to (n - 1)){
      if(a((p + i) % n) - min <= i){
        println(((p + i) % n) + 1)
        return
      }
    }
  }
}

import scala.io.StdIn._
import scala.math._
object Task2 extends App {
  def calc(x: Long, y: Long) = x + y.toDouble / pow(10, y.toString.length)
  val n = readLong;
  val qs = readLine.split(' ').map(_.toLong)
  qs.zipWithIndex
    .map { case (q, i) => (ceil((q-i).toDouble / n), i + 1) }
    .minBy(_._1) match { case (_, i) => println (i) }
}

import scala.io.StdIn

object B {

  def main(args: Array[String]): Unit = {
    val entrances = StdIn.readInt()
    val people = StdIn.readLine().split(" ").map(_.toInt)

    var index = 0

    val counts = people.map {count =>
      val i = count - index
      val a = i / entrances
      val r = i % entrances

      index += 1
      if (r > 0) a+1 else a
    }

    val min = counts.min
    val result = counts.indexOf(min) + 1

    println(result)
  }

}

import scala.io.StdIn

object WorldCup {

  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val as: Seq[Int] = StdIn.readLine().split(" ").map(_.toInt)
    println(solve(as))
  }

  private def solve(as: Seq[Int]): Int = {
    as.zipWithIndex.map(tupel => {
      val value = tupel._1
      val index = tupel._2
      val round = Math.ceil((value - index) / as.length.toDouble).toInt + 1
      (round * as.length + index, index)
    }).minBy(tupel => tupel._1)._2 + 1
  }

  private def absMod(p: Int, q: Int): Int = {
    val r = p % q
    if (r < 0) r + q
    else r
  }
}

import scala.io.StdIn._

object Task2 extends App {
  val n = readInt
  val qs = readLine.split(' ').map(_.toInt)
  Iterator.continually(qs)
    .flatten.zipWithIndex
    .map { case (q, i) => (q - i, i + 1) }.find(_._1 <= 0) match {
    case Some((_, i)) => println(i % n)
    case None => println(-1)
  }
}


You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 998244353$$$) — inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.

Print $$$T$$$ lines, each line should contain the answer — two integers $$$x$$$ and $$$y$$$ such that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.

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 = {
    REP(ni()) { _ =>
      val L, R = ni()
      val l = L
      val r = l * 2
      out.println(s"$l $r")
    }

  }

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

import scala.io.StdIn

object FindDivisible extends App {
  val t = StdIn.readLine().toInt

  for (_ <- 1 to t) {
    val lr = StdIn.readLine().split(" ").map(_.toInt)

    println(s"${lr(0)} ${lr(0) * 2}")
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt
    for (_ <- 1 to t) {
      val x = StdIn.readLine().split(' ').map(_.toInt)
      solve(x(0), x(1))
    }
  }

  def solve(l: Int, r: Int): Unit = {
    println(s"${l} ${l * 2}")
  }
}

import scala.io.StdIn

object kimollg extends App {
  //println("Zdorova!")
  val n = scala.io.StdIn.readInt()
  for (i <- 0 until n){
    val inps = StdIn.readLine().split(" ").map(_.toInt)
    println(inps(0)+" "+inps(0)*2)
  }

}

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 = {
    REP(ni()) { _ =>
      val L, R = ni()
      if (abs(L - R) <= 1) out.println(s"$L $R")
      else {
        val l = ((L - 1) / 2 + 1) * 2
        val r = R / 2 * 2
        if (l >= r) {
          out.println(s"$L $R")
        } else {
          out.println(s"$l $r")
        }
      }
    }

  }

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


A and B are preparing themselves for programming contests.The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.

The first line contains integer n (1 ≤ n ≤ 105) — the number of rooms in the University. The next n - 1 lines describe the corridors. The i-th of these lines (1 ≤ i ≤ n - 1) contains two integers ai and bi (1 ≤ ai, bi ≤ n), showing that the i-th corridor connects rooms ai and bi. The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Next m lines describe the queries. The j-th of these lines (1 ≤ j ≤ m) contains two integers xj and yj (1 ≤ xj, yj ≤ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.

In the i-th (1 ≤ i ≤ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.

Notein the first sample there is only one room at the same distance from rooms number 2 and 3 — room number 1.

import java.io._

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  trait GraphLike {
    def n: Int

    def adj: Array[List[Int]]
  }

  class UndirectedGraph(val n: Int) extends GraphLike {

    val adj = Array.fill(n)(List[Int]())

    def apply(i: Int) = adj(i)

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  trait TreeFeatures {
    this: GraphLike =>

    val lgn = (1 to 32).find(x => (1 << x) >= n).get
    val parent = new Array[Int](n)
    val depth = new Array[Int](n)
    val subtreeSize = new Array[Int](n)
    val dp = Array.ofDim[Int](lgn, n)

    private def computeLCA(): Unit = {
      (0 until n).foreach { i =>
        dp(0)(i) = parent(i)
        var j = 1
        while ((1 << j) < n) {
          dp(j)(i) = -1
          j += 1
        }
      }

      var j = 1
      while ((1 << j) < n) {
        (0 until n).foreach { i =>
          if (dp(j - 1)(i) != -1)
            dp(j)(i) = dp(j - 1)(dp(j - 1)(i))
        }
        j += 1
      }
    }

    def computeFeatures(root: Int) = {

      def dfs(u: Int, pu: Int): Unit = {
        subtreeSize(u) = 1
        adj(u).foreach { v =>
          if (v != pu) {
            parent(v) = u
            depth(v) = depth(u) + 1
            dfs(v, u)
            subtreeSize(u) += subtreeSize(v)
          }
        }
      }

      parent(root) = -1
      dfs(root, -1)

      computeLCA()
    }

    def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {
      (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v
    }

    //    def lca(u: Int, v: Int): Int = {
    //
    //      if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)
    //      else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))
    //      else if (u==v) u
    //      else parent(((lgn-1) to 0 by -1).foldLeft((u, v)) {
    //        (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t
    //      }._1)
    //    }

    def lca(pp: Int, qq: Int): Int = {
      var tmp, log, i = 0
      var p = pp
      var q = qq

      if (depth(p) < depth(q)) {
        tmp = p
        p = q
        q = tmp
      }

      log = 1
      while ((1 << log) <= depth(p)) log += 1
      log -= 1

      i = log
      while (i >= 0) {
        if (depth(p) - (1 << i) >= depth(q)) p = dp(i)(p)
        i -= 1
      }

      if (p == q) {
        p
      } else {
        i = log
        while (i >= 0) {
          if (dp(i)(p) != -1 && dp(i)(p) != dp(i)(q)) {
            p = dp(i)(p)
            q = dp(i)(q)
          }
          i -= 1
        }
        parent(p)
      }
    }

  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val t = new UndirectedGraph(n) with TreeFeatures

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      t.addEdge(u - 1, v - 1)
    }

    t.computeFeatures(0)

    val m = in.readLine().toInt

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {

        val w = t.lca(u, v)
        val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (t.depth(u) == t.depth(v)) {
            val x = t.ancestor(u, d / 2 - 1)
            val y = t.ancestor(v, d / 2 - 1)
            out.println(n - t.subtreeSize(x) - t.subtreeSize(y))
          } else {
            val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)
            val y = t.ancestor(yTmp, d / 2 - 1)
            out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

import scala.annotation.tailrec

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  trait GraphLike {
    def n: Int

    def adj: Array[List[Int]]
  }

  class UndirectedGraph(val n: Int) extends GraphLike {

    val adj = Array.fill(n)(List[Int]())

    def apply(i: Int) = adj(i)

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  trait TreeFeatures {
    this: GraphLike =>

    val lgn = (1 to 32).find(x => (1 << x) >= n).get
    val parent = new Array[Int](n)
    val depth = new Array[Int](n)
    val subtreeSize = new Array[Int](n)
    val dp = Array.ofDim[Int](lgn, n)

    private def computeLCA(): Unit = {
      (0 until n).foreach { i =>
        dp(0)(i) = parent(i)
        var j = 1
        while ((1 << j) < n) {
          dp(j)(i) = -1
          j += 1
        }
      }

      var j = 1
      while ((1 << j) < n) {
        (0 until n).foreach { i =>
          if (dp(j - 1)(i) != -1)
            dp(j)(i) = dp(j - 1)(dp(j - 1)(i))
        }
        j += 1
      }
    }

    def computeFeatures(root: Int) = {

      def dfs(u: Int, pu: Int): Unit = {
        subtreeSize(u) = 1
        adj(u).foreach { v =>
          if (v != pu) {
            parent(v) = u
            depth(v) = depth(u) + 1
            dfs(v, u)
            subtreeSize(u) += subtreeSize(v)
          }
        }
      }

      parent(root) = -1
      dfs(root, -1)

      computeLCA()
    }

    def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {
      (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v
    }

    @tailrec final def lca(u: Int, v: Int): Int = {
      if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)
      else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))
      else if (u == v) u
      else parent(((lgn - 1) to 0 by -1).foldLeft((u, v)) {
        (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t
      }._1)
    }

    //    def lca(pp: Int, qq: Int): Int = {
    //      var tmp, log, i = 0
    //      var p = pp
    //      var q = qq
    //
    //      if (depth(p) < depth(q)) {
    //        tmp = p
    //        p = q
    //        q = tmp
    //      }
    //
    //      log = 1
    //      while ((1 << log) <= depth(p)) log += 1
    //      log -= 1
    //
    //      i = log
    //      while (i >= 0) {
    //        if (depth(p) - (1 << i) >= depth(q)) p = dp(i)(p)
    //        i -= 1
    //      }
    //
    //      if (p == q) {
    //        p
    //      } else {
    //        i = log
    //        while (i >= 0) {
    //          if (dp(i)(p) != -1 && dp(i)(p) != dp(i)(q)) {
    //            p = dp(i)(p)
    //            q = dp(i)(q)
    //          }
    //          i -= 1
    //        }
    //        parent(p)
    //      }
    //    }
    //

  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val t = new UndirectedGraph(n) with TreeFeatures

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      t.addEdge(u - 1, v - 1)
    }

    t.computeFeatures(0)

    val m = in.readLine().toInt

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {

        val w = t.lca(u, v)
        val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (t.depth(u) == t.depth(v)) {
            val x = t.ancestor(u, d / 2 - 1)
            val y = t.ancestor(v, d / 2 - 1)
            out.println(n - t.subtreeSize(x) - t.subtreeSize(y))
          } else {
            val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)
            val y = t.ancestor(yTmp, d / 2 - 1)
            out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  val LOGN = 18

  trait GraphLike {
    def n: Int

    def adj: Array[List[Int]]
  }

  class UndirectedGraph(val n: Int) extends GraphLike {

    val adj = Array.fill(n)(List[Int]())

    def apply(i: Int) = adj(i)

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  trait TreeFeatures {
    this: GraphLike =>

    val parent = new Array[Int](n)
    val depth = new Array[Int](n)
    val subtreeSize = new Array[Int](n)
    val dp = Array.ofDim[Int](LOGN, n)

    private def computeLCA(): Unit = {
      (0 until n).foreach { i =>
        dp(0)(i) = parent(i)
        var j = 1
        while ((1 << j) < n) {
          dp(j)(i) = -1
          j += 1
        }
      }

      var j = 1
      while ((1 << j) < n) {
        (0 until n).foreach { i =>
          if (dp(j - 1)(i) != -1)
            dp(j)(i) = dp(j - 1)(dp(j - 1)(i))
        }
        j += 1
      }
    }

    def computeFeatures(root: Int) = {

      def dfs(u: Int, pu: Int): Unit = {
        subtreeSize(u) = 1
        adj(u).foreach { v =>
          if (v != pu) {
            parent(v) = u
            depth(v) = depth(u) + 1
            dfs(v, u)
            subtreeSize(u) += subtreeSize(v)
          }
        }
      }

      parent(root) = -1
      dfs(root, -1)

      computeLCA()
    }

    def ancestor(u: Int, count: Int) = (0 until LOGN).foldLeft(u) {
      (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v
    }

    def lca(pp: Int, qq: Int) = {
      var tmp, log, i = 0
      var p = pp
      var q = qq

      if (depth(p) < depth(q)) {
        tmp = p
        p = q
        q = tmp
      }

      log = 1
      while ((1 << log) <= depth(p)) log += 1
      log -= 1

      i = log
      while (i >= 0) {
        if (depth(p) - (1 << i) >= depth(q)) p = dp(i)(p)
        i -= 1
      }

      if (p == q) {
        p
      } else {
        i = log
        while (i >= 0) {
          if (dp(i)(p) != -1 && dp(i)(p) != dp(i)(q)) {
            p = dp(i)(p)
            q = dp(i)(q)
          }
          i -= 1
        }
        parent(p)
      }
    }

  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val t = new UndirectedGraph(n) with TreeFeatures

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      t.addEdge(u - 1, v - 1)
    }

    t.computeFeatures(0)

    val m = in.readLine().toInt

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {

        val w = t.lca(u, v)
        val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (t.depth(u) == t.depth(v)) {
            val x = t.ancestor(u, d / 2 - 1)
            val y = t.ancestor(v, d / 2 - 1)
            out.println(n - t.subtreeSize(x) - t.subtreeSize(y))
          } else {
            val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)
            val y = t.ancestor(yTmp, d / 2 - 1)
            out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

object Main {

  trait GraphLike {
    def n: Int

    def adj: Array[List[Int]]
  }

  class UndirectedGraph(val n: Int) extends GraphLike {

    val adj = Array.fill(n)(List[Int]())

    def apply(i: Int) = adj(i)

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  trait TreeFeatures {
    this: GraphLike =>

    def features(root: Int) = {
      val t = new Array[Int](n)
      val h = new Array[Int](n)
      val sz = new Array[Int](n)

      def dfs(u: Int, pu: Int): Unit = {
        sz(u) = 1
        adj(u).foreach { v =>
          if (v != pu) {
            t(v) = u
            h(v) = h(u) + 1
            dfs(v, u)
            sz(u) += sz(v)
          }
        }
      }

      t(root) = -1
      dfs(root, -1)
      (t, h, sz)
    }

  }

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  val LOGN = 18

  def lca(pp: Int, qq: Int, n: Int, dp: Array[Array[Int]], h: Array[Int], t: Array[Int]) = {
    var tmp, log, i = 0
    var p = pp
    var q = qq

    if (h(p) < h(q)) {
      tmp = p
      p = q
      q = tmp
    }

    log = 1
    while ((1 << log) <= h(p)) log += 1
    log -= 1

    i = log
    while (i >= 0) {
      if (h(p) - (1 << i) >= h(q)) p = dp(p)(i)
      i -= 1
    }

    if (p == q) {
      p
    } else {
      i = log
      while (i >= 0) {
        if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {
          p = dp(p)(i)
          q = dp(q)(i)
        }
        i -= 1
      }
      t(p)
    }
  }

  def ancestor(u: Int, d: Int, dp: Array[Array[Int]]) = {
    var x = u
    var rd = d
    var i = LOGN
    while (i >= 0) {
      if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {
        rd -= (1 << i)
        x = dp(x)(i)
      }
      i -= 1
    }
    x
  }

  def getLcaTable(n: Int, t: Array[Int]) = {

    val dp = Array.ofDim[Int](n, LOGN)

    (0 until n).foreach { i =>
      dp(i)(0) = t(i)
      var j = 1
      while ((1 << j) < n) {
        dp(i)(j) = -1
        j += 1
      }
    }

    var j = 1
    while ((1 << j) < n) {
      (0 until n).foreach { i =>
        if (dp(i)(j - 1) != -1)
          dp(i)(j) = dp(dp(i)(j - 1))(j - 1)
      }
      j += 1
    }

    dp
  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val g = new UndirectedGraph(n) with TreeFeatures

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      g.addEdge(u - 1, v - 1)
    }

    val (t, h, sz) = g.features(0)
    val dp = getLcaTable(n, t)

    val m = in.readLine().toInt

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {
        val w = lca(u, v, n, dp, h, t)
        val d = h(u) + h(v) - 2 * h(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (h(u) == h(v)) {
            val x = ancestor(u, d / 2 - 1, dp)
            val y = ancestor(v, d / 2 - 1, dp)
            out.println(n - sz(x) - sz(y))
          } else {
            val (_, yTmp) = if (h(u) > h(v)) (v, u) else (u, v)
            val y = ancestor(yTmp, d / 2 - 1, dp)
            out.println(sz(t(y)) - sz(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  val LOGN = 18

  trait GraphLike {
    def n: Int

    def adj: Array[List[Int]]
  }

  class UndirectedGraph(val n: Int) extends GraphLike {

    val adj = Array.fill(n)(List[Int]())

    def apply(i: Int) = adj(i)

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  trait TreeFeatures {
    this: GraphLike =>

    val parent = new Array[Int](n)
    val depth = new Array[Int](n)
    val subtreeSize = new Array[Int](n)
    val dp = Array.ofDim[Int](n, LOGN)

    private def computeLCA(): Unit = {
      (0 until n).foreach { i =>
        dp(i)(0) = parent(i)
        var j = 1
        while ((1 << j) < n) {
          dp(i)(j) = -1
          j += 1
        }
      }

      var j = 1
      while ((1 << j) < n) {
        (0 until n).foreach { i =>
          if (dp(i)(j - 1) != -1)
            dp(i)(j) = dp(dp(i)(j - 1))(j - 1)
        }
        j += 1
      }
    }

    def computeFeatures(root: Int) = {

      def dfs(u: Int, pu: Int): Unit = {
        subtreeSize(u) = 1
        adj(u).foreach { v =>
          if (v != pu) {
            parent(v) = u
            depth(v) = depth(u) + 1
            dfs(v, u)
            subtreeSize(u) += subtreeSize(v)
          }
        }
      }

      parent(root) = -1
      dfs(root, -1)

      computeLCA()
    }

    def ancestor(u: Int, d: Int) = {
      var x = u
      var rd = d
      var i = LOGN
      while (i >= 0) {
        if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {
          rd -= (1 << i)
          x = dp(x)(i)
        }
        i -= 1
      }
      x
    }

    def lca(pp: Int, qq: Int) = {
      var tmp, log, i = 0
      var p = pp
      var q = qq

      if (depth(p) < depth(q)) {
        tmp = p
        p = q
        q = tmp
      }

      log = 1
      while ((1 << log) <= depth(p)) log += 1
      log -= 1

      i = log
      while (i >= 0) {
        if (depth(p) - (1 << i) >= depth(q)) p = dp(p)(i)
        i -= 1
      }

      if (p == q) {
        p
      } else {
        i = log
        while (i >= 0) {
          if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {
            p = dp(p)(i)
            q = dp(q)(i)
          }
          i -= 1
        }
        parent(p)
      }
    }

  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val t = new UndirectedGraph(n) with TreeFeatures

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      t.addEdge(u - 1, v - 1)
    }

    t.computeFeatures(0)

    val m = in.readLine().toInt

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {

        val w = t.lca(u, v)
        val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (t.depth(u) == t.depth(v)) {
            val x = t.ancestor(u, d / 2 - 1)
            val y = t.ancestor(v, d / 2 - 1)
            out.println(n - t.subtreeSize(x) - t.subtreeSize(y))
          } else {
            val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)
            val y = t.ancestor(yTmp, d / 2 - 1)
            out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

import scala.annotation.tailrec

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  object TraverseUtil {

    def FOR(from: Int, to: Int)(f: Int => Unit): Unit = {
      var i = from
      while (i <= to) {
        f(i)
        i += 1
      }
    }

  }

  import TraverseUtil._

  class UndirectedGraph(val n: Int) {

    val adj = Array.fill(n)(List[Int]())

    def apply(i: Int) = adj(i)

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  trait TreeFeatures {
    this: UndirectedGraph =>

    val lgn = (1 to 32).find(x => (1 << x) >= n).get
    val parent = new Array[Int](n)
    val depth = new Array[Int](n)
    val subtreeSize = new Array[Int](n)
    val dp = Array.ofDim[Int](lgn, n)

    private def computeLCA(): Unit = {

      FOR(0, n - 1) { i =>
        dp(0)(i) = parent(i)
        var j = 1
        while ((1 << j) < n) {
          dp(j)(i) = -1
          j += 1
        }
      }

      var j = 1
      while ((1 << j) < n) {
        FOR(0, n - 1) { i =>
          if (dp(j - 1)(i) != -1)
            dp(j)(i) = dp(j - 1)(dp(j - 1)(i))
        }
        j += 1
      }
    }

    def computeFeatures(root: Int) = {

      def dfs(u: Int, pu: Int): Unit = {
        subtreeSize(u) = 1
        adj(u).foreach { v =>
          if (v != pu) {
            parent(v) = u
            depth(v) = depth(u) + 1
            dfs(v, u)
            subtreeSize(u) += subtreeSize(v)
          }
        }
      }

      parent(root) = -1
      dfs(root, -1)

      computeLCA()
    }

    def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {
      (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v
    }

    @tailrec final def lca(u: Int, v: Int): Int = {
      if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)
      else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))
      else if (u == v) u
      else parent(((lgn - 1) to 0 by -1).foldLeft((u, v)) {
        (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t
      }._1)
    }
  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val t = new UndirectedGraph(n) with TreeFeatures

    FOR(1, n-1) { _ =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt - 1)
      t.addEdge(u, v)
    }

    t.computeFeatures(0)

    val m = in.readLine().toInt

    FOR(1,m) { _ =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt - 1)

      if (u == v) {
        out.println(n)
      } else {

        val w = t.lca(u, v)
        val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (t.depth(u) == t.depth(v)) {
            val x = t.ancestor(u, d / 2 - 1)
            val y = t.ancestor(v, d / 2 - 1)
            out.println(n - t.subtreeSize(x) - t.subtreeSize(y))
          } else {
            val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)
            val y = t.ancestor(yTmp, d / 2 - 1)
            out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  val LOGN = 18

  trait GraphLike {
    def n: Int

    def adj: Array[List[Int]]
  }

  class UndirectedGraph(val n: Int) extends GraphLike {

    val adj = Array.fill(n)(List[Int]())

    def apply(i: Int) = adj(i)

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  trait TreeFeatures {
    this: GraphLike =>

    val parent = new Array[Int](n)
    val depth = new Array[Int](n)
    val subtreeSize = new Array[Int](n)
    val dp = Array.ofDim[Int](n, LOGN)

    private def computeLCA(): Unit = {
      (0 until n).foreach { i =>
        dp(i)(0) = parent(i)
        var j = 1
        while ((1 << j) < n) {
          dp(i)(j) = -1
          j += 1
        }
      }

      var j = 1
      while ((1 << j) < n) {
        (0 until n).foreach { i =>
          if (dp(i)(j - 1) != -1)
            dp(i)(j) = dp(dp(i)(j - 1))(j - 1)
        }
        j += 1
      }
    }

    def computeFeatures(root: Int) = {

      def dfs(u: Int, pu: Int): Unit = {
        subtreeSize(u) = 1
        adj(u).foreach { v =>
          if (v != pu) {
            parent(v) = u
            depth(v) = depth(u) + 1
            dfs(v, u)
            subtreeSize(u) += subtreeSize(v)
          }
        }
      }

      parent(root) = -1
      dfs(root, -1)

      computeLCA()
    }

    def ancestor(u: Int, count: Int) = {

      (0 until LOGN).foldLeft(u) {
        (v, i) => if (((count >> i) & 1) == 1) dp(v)(i) else v
      }

//      var x = u
//      var rd = count
//      var i = LOGN
//      while (i >= 0) {
//        if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {
//          rd -= (1 << i)
//          x = dp(x)(i)
//        }
//        i -= 1
//      }
//      x
    }

    def lca(pp: Int, qq: Int) = {
      var tmp, log, i = 0
      var p = pp
      var q = qq

      if (depth(p) < depth(q)) {
        tmp = p
        p = q
        q = tmp
      }

      log = 1
      while ((1 << log) <= depth(p)) log += 1
      log -= 1

      i = log
      while (i >= 0) {
        if (depth(p) - (1 << i) >= depth(q)) p = dp(p)(i)
        i -= 1
      }

      if (p == q) {
        p
      } else {
        i = log
        while (i >= 0) {
          if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {
            p = dp(p)(i)
            q = dp(q)(i)
          }
          i -= 1
        }
        parent(p)
      }
    }

  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val t = new UndirectedGraph(n) with TreeFeatures

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      t.addEdge(u - 1, v - 1)
    }

    t.computeFeatures(0)

    val m = in.readLine().toInt

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {

        val w = t.lca(u, v)
        val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (t.depth(u) == t.depth(v)) {
            val x = t.ancestor(u, d / 2 - 1)
            val y = t.ancestor(v, d / 2 - 1)
            out.println(n - t.subtreeSize(x) - t.subtreeSize(y))
          } else {
            val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)
            val y = t.ancestor(yTmp, d / 2 - 1)
            out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  val LOGN = 18

  var adj: Array[List[Int]] = null
  var t: Array[Int] = null
  var h: Array[Int] = null
  var sz: Array[Int] = null

  def dfs(u: Int, pu: Int): Unit = {
    sz(u) = 1
    adj(u).foreach { v =>
      if (v != pu) {
        t(v) = u
        h(v) = h(u) + 1
        dfs(v, u)
        sz(u) += sz(v)
      }
    }
  }

  def lca(pp: Int, qq: Int, n: Int, dp: Array[Array[Int]]) = {
    var tmp, log, i = 0
    var p = pp
    var q = qq

    if (h(p) < h(q)) {
      tmp = p
      p = q
      q = tmp
    }

    log = 1
    while ((1 << log) <= h(p)) log += 1
    log -= 1

    i = log
    while (i >= 0) {
      if (h(p) - (1 << i) >= h(q)) p = dp(p)(i)
      i -= 1
    }

    if (p == q) {
      p
    } else {
      i = log
      while (i >= 0) {
        if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {
          p = dp(p)(i)
          q = dp(q)(i)
        }
        i -= 1
      }
      t(p)
    }
  }

  def ancestor(u: Int, d: Int, dp: Array[Array[Int]]) = {
    var x = u
    var rd = d
    var i = LOGN
    while (i >= 0) {
      if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {
        rd -= (1 << i)
        x = dp(x)(i)
      }
      i -= 1
    }
    x
  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt
    adj = new Array[List[Int]](n)
    t = new Array[Int](n)
    h = new Array[Int](n)
    sz = new Array[Int](n)

    (0 until n).foreach { i => adj(i) = Nil}

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      adj(u - 1) = (v - 1) :: adj(u - 1)
      adj(v - 1) = (u - 1) :: adj(v - 1)
    }

    val m = in.readLine().toInt

    t(0) = -1

    dfs(0, -1)

    val dp = Array.ofDim[Int](n, LOGN)

    (0 until n).foreach { i =>
      dp(i)(0) = t(i)
      var j = 1
      while ((1 << j) < n) {
        dp(i)(j) = -1
        j += 1
      }
    }

    var j = 1
    while ((1 << j) < n) {
      (0 until n).foreach { i =>
        if (dp(i)(j - 1) != -1)
          dp(i)(j) = dp(dp(i)(j - 1))(j - 1)
      }
      j += 1
    }

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {
        val w = lca(u, v, n, dp)
        val d = h(u) + h(v) - 2 * h(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (h(u) == h(v)) {
            val x = ancestor(u, d / 2 - 1, dp)
            val y = ancestor(v, d / 2 - 1, dp)
            out.println(n - sz(x) - sz(y))
          } else {
            val (_, yTmp) = if (h(u) > h(v)) (v, u) else (u, v)
            val y = ancestor(yTmp, d / 2 - 1, dp)
            out.println(sz(t(y)) - sz(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

import scala.annotation.tailrec

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  class UndirectedGraph(val n: Int) {

    val adj = Array.fill(n)(List[Int]())

    def apply(i: Int) = adj(i)

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  trait TreeFeatures {
    this: UndirectedGraph =>

    val lgn = (1 to 32).find(x => (1 << x) >= n).get
    val parent = new Array[Int](n)
    val depth = new Array[Int](n)
    val subtreeSize = new Array[Int](n)
    val dp = Array.ofDim[Int](lgn, n)

    private def computeLCA(): Unit = {
      (0 until n).foreach { i =>
        dp(0)(i) = parent(i)
        var j = 1
        while ((1 << j) < n) {
          dp(j)(i) = -1
          j += 1
        }
      }

      var j = 1
      while ((1 << j) < n) {
        (0 until n).foreach { i =>
          if (dp(j - 1)(i) != -1)
            dp(j)(i) = dp(j - 1)(dp(j - 1)(i))
        }
        j += 1
      }
    }

    def computeFeatures(root: Int) = {

      def dfs(u: Int, pu: Int): Unit = {
        subtreeSize(u) = 1
        adj(u).foreach { v =>
          if (v != pu) {
            parent(v) = u
            depth(v) = depth(u) + 1
            dfs(v, u)
            subtreeSize(u) += subtreeSize(v)
          }
        }
      }

      parent(root) = -1
      dfs(root, -1)

      computeLCA()
    }

    def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {
      (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v
    }

    @tailrec final def lca(u: Int, v: Int): Int = {
      if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)
      else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))
      else if (u == v) u
      else parent(((lgn - 1) to 0 by -1).foldLeft((u, v)) {
        (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t
      }._1)
    }
  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val t = new UndirectedGraph(n) with TreeFeatures

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      t.addEdge(u - 1, v - 1)
    }

    t.computeFeatures(0)

    val m = in.readLine().toInt

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {

        val w = t.lca(u, v)
        val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (t.depth(u) == t.depth(v)) {
            val x = t.ancestor(u, d / 2 - 1)
            val y = t.ancestor(v, d / 2 - 1)
            out.println(n - t.subtreeSize(x) - t.subtreeSize(y))
          } else {
            val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)
            val y = t.ancestor(yTmp, d / 2 - 1)
            out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  trait GraphLike {
    def n: Int

    def adj: Array[List[Int]]
  }

  class UndirectedGraph(val n: Int) extends GraphLike {

    val adj = Array.fill(n)(List[Int]())

    def apply(i: Int) = adj(i)

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  trait TreeFeatures {
    this: GraphLike =>

    val lgn = (1 to 32).find(x => (1 << x) >= n).get
    val parent = new Array[Int](n)
    val depth = new Array[Int](n)
    val subtreeSize = new Array[Int](n)
    val dp = Array.ofDim[Int](lgn, n)

    private def computeLCA(): Unit = {
      (0 until n).foreach { i =>
        dp(0)(i) = parent(i)
        var j = 1
        while ((1 << j) < n) {
          dp(j)(i) = -1
          j += 1
        }
      }

      var j = 1
      while ((1 << j) < n) {
        (0 until n).foreach { i =>
          if (dp(j - 1)(i) != -1)
            dp(j)(i) = dp(j - 1)(dp(j - 1)(i))
        }
        j += 1
      }
    }

    def computeFeatures(root: Int) = {

      def dfs(u: Int, pu: Int): Unit = {
        subtreeSize(u) = 1
        adj(u).foreach { v =>
          if (v != pu) {
            parent(v) = u
            depth(v) = depth(u) + 1
            dfs(v, u)
            subtreeSize(u) += subtreeSize(v)
          }
        }
      }

      parent(root) = -1
      dfs(root, -1)

      computeLCA()
    }

    def ancestor(u: Int, count: Int) = (0 until lgn).foldLeft(u) {
      (v, i) => if (((count >> i) & 1) == 1) dp(i)(v) else v
    }

    def lca(u: Int, v: Int): Int = {
      if (depth(u) > depth(v)) lca(ancestor(u, depth(u) - depth(v)), v)
      else if (depth(u) < depth(v)) lca(u, ancestor(v, depth(v) - depth(u)))
      else if (u == v) u
      else parent(((lgn - 1) to 0 by -1).foldLeft((u, v)) {
        (t, i) => if (dp(i)(t._1) != dp(i)(t._2)) (dp(i)(t._1), dp(i)(t._2)) else t
      }._1)
    }

  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt

    val t = new UndirectedGraph(n) with TreeFeatures

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      t.addEdge(u - 1, v - 1)
    }

    t.computeFeatures(0)

    val m = in.readLine().toInt

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {

        val w = t.lca(u, v)
        val d = t.depth(u) + t.depth(v) - 2 * t.depth(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (t.depth(u) == t.depth(v)) {
            val x = t.ancestor(u, d / 2 - 1)
            val y = t.ancestor(v, d / 2 - 1)
            out.println(n - t.subtreeSize(x) - t.subtreeSize(y))
          } else {
            val (_, yTmp) = if (t.depth(u) > t.depth(v)) (v, u) else (u, v)
            val y = t.ancestor(yTmp, d / 2 - 1)
            out.println(t.subtreeSize(t.parent(y)) - t.subtreeSize(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

object Main {

  class UndirectedGraph(n: Int) {
    val adj = Array.fill(n)(List[Int]())

    def addEdge(u: Int, v: Int): Unit = {
      adj(u) = v :: adj(u)
      adj(v) = u :: adj(v)
    }

  }

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  val LOGN = 18

  var t: Array[Int] = null
  var h: Array[Int] = null
  var sz: Array[Int] = null

  def dfs(u: Int, pu: Int)(implicit g: UndirectedGraph): Unit = {
    sz(u) = 1
    g.adj(u).foreach { v =>
      if (v != pu) {
        t(v) = u
        h(v) = h(u) + 1
        dfs(v, u)
        sz(u) += sz(v)
      }
    }
  }

  def lca(pp: Int, qq: Int, n: Int, dp: Array[Array[Int]]) = {
    var tmp, log, i = 0
    var p = pp
    var q = qq

    if (h(p) < h(q)) {
      tmp = p
      p = q
      q = tmp
    }

    log = 1
    while ((1 << log) <= h(p)) log += 1
    log -= 1

    i = log
    while (i >= 0) {
      if (h(p) - (1 << i) >= h(q)) p = dp(p)(i)
      i -= 1
    }

    if (p == q) {
      p
    } else {
      i = log
      while (i >= 0) {
        if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {
          p = dp(p)(i)
          q = dp(q)(i)
        }
        i -= 1
      }
      t(p)
    }
  }

  def ancestor(u: Int, d: Int, dp: Array[Array[Int]]) = {
    var x = u
    var rd = d
    var i = LOGN
    while (i >= 0) {
      if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {
        rd -= (1 << i)
        x = dp(x)(i)
      }
      i -= 1
    }
    x
  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt
    implicit val g = new UndirectedGraph(n)
    t = new Array[Int](n)
    h = new Array[Int](n)
    sz = new Array[Int](n)

//    (0 until n).foreach { i => adj(i) = Nil}

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      g.addEdge(u - 1, v - 1)
    }

    val m = in.readLine().toInt

    t(0) = -1

    dfs(0, -1)

    val dp = Array.ofDim[Int](n, LOGN)

    (0 until n).foreach { i =>
      dp(i)(0) = t(i)
      var j = 1
      while ((1 << j) < n) {
        dp(i)(j) = -1
        j += 1
      }
    }

    var j = 1
    while ((1 << j) < n) {
      (0 until n).foreach { i =>
        if (dp(i)(j - 1) != -1)
          dp(i)(j) = dp(dp(i)(j - 1))(j - 1)
      }
      j += 1
    }

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1

      if (u == v) {
        out.println(n)
      } else {
        val w = lca(u, v, n, dp)
        val d = h(u) + h(v) - 2 * h(w)

        if (d % 2 == 1) {
          out.println(0)
        } else {

          if (h(u) == h(v)) {
            val x = ancestor(u, d / 2 - 1, dp)
            val y = ancestor(v, d / 2 - 1, dp)
            out.println(n - sz(x) - sz(y))
          } else {
            val (_, yTmp) = if (h(u) > h(v)) (v, u) else (u, v)
            val y = ancestor(yTmp, d / 2 - 1, dp)
            out.println(sz(t(y)) - sz(y))
          }

        }
      }
    }

    out.close()
  }

}

import java.io._

object Main {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)

  val LOGN = 18

  var adj: Array[List[Int]] = null
  var t: Array[Int] = null
  var h: Array[Int] = null
  var sz: Array[Int] = null

  def dfs(u: Int, pu: Int): Unit = {
    sz(u) = 1
    adj(u).foreach { v =>
      if (v != pu) {
        t(v) = u
        h(v) = h(u) + 1
        dfs(v, u)
        sz(u) += sz(v)
      }
    }
  }

  def lca(pp: Int, qq: Int, n: Int, dp: Array[Array[Int]]) = {
    var tmp, log, i = 0
    var p = pp
    var q = qq

    if (h(p) < h(q)) {
      tmp = p
      p = q
      q = tmp
    }

    log = 1
    while ((1 << log) <= h(p)) log += 1
    log -= 1

    i = log
    while (i >= 0) {
      if (h(p) - (1 << i) >= h(q)) p = dp(p)(i)
      i -= 1
    }

    if (p == q) {
      p
    } else {
      i = log
      while (i >= 0) {
        if (dp(p)(i) != -1 && dp(p)(i) != dp(q)(i)) {
          p = dp(p)(i)
          q = dp(q)(i)
        }
        i -= 1
      }
      t(p)
    }
  }

  def goup(u: Int, d: Int, dp: Array[Array[Int]]) = {
    var x = u
    var rd = d
    var i = LOGN
    while (i >= 0) {
      if (rd - (1 << i) >= 0 && dp(x)(i) != -1) {
        rd -= (1 << i)
        x = dp(x)(i)
      }
      i -= 1
    }
    x
  }

  def main(args: Array[String]) {

    val n = in.readLine().toInt
    adj = new Array[List[Int]](n)
    t = new Array[Int](n)
    h = new Array[Int](n)
    sz = new Array[Int](n)

    (0 until n).foreach { i => adj(i) = Nil}

    (1 until n).foreach { i =>
      val Array(u, v) = in.readLine().split(" +").map(_.toInt)
      adj(u - 1) = (v - 1) :: adj(u - 1)
      adj(v - 1) = (u - 1) :: adj(v - 1)
    }

    val m = in.readLine().toInt

    t(0) = -1

    dfs(0, -1)

    val dp = Array.ofDim[Int](n, LOGN)

    (0 until n).foreach { i =>
      dp(i)(0) = t(i)
      var j = 1
      while ((1 << j) < n) {
        dp(i)(j) = -1
        j += 1
      }
    }

    var j = 1
    while ((1 << j) < n) {
      (0 until n).foreach { i =>
        if (dp(i)(j - 1) != -1)
          dp(i)(j) = dp(dp(i)(j - 1))(j - 1)
      }
      j += 1
    }

    (1 to m).foreach { _ =>
      val Array(uu, vv) = in.readLine().split(" +").map(_.toInt)

      val u = uu - 1
      val v = vv - 1
      val w = lca(u, v, n, dp)
      val d = h(u) + h(v) - 2 * h(w)

      if (u == v) {
        out.println(n)
      } else if (d % 2 == 1) {
        out.println(0)
      } else {

        if (w == v) {
          val stu = sz(u) - 1
          val stv = n - sz(goup(u, d - 1, dp)) - 1
          out.println(n - d - stu - stv)
        } else if (w == u) {
          val stu = n - sz(goup(v, d - 1, dp)) - 1
          val stv = sz(v) - 1
          out.println(n - d - stu - stv)
        } else {
          val stu = sz(u) - 1
          val stv = sz(v) - 1
          out.println(n - d - stu - stv)
        }
      }
    }

    out.close()
  }

}


One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.

The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).

In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  if (n >= 2 * k + 1) {
    val res = (1 to n).flatMap { i =>
      (1 to k).map { j =>
        if (i + j > n)
          (i, i + j - n)
        else
          (i, i + j)
      }
    }
    println(n * k)
    println(res.map(t => s"${t._1} ${t._2}").mkString("\n"))
  }
  else println(-1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  if (n >= k + 1) {
    val res = (1 to n).flatMap { i =>
      (1 to k).map { j =>
        if (i + j > n)
          (i, i + j - n)
        else
          (i, i + j)
      }
    }
    println(n * k)
    println(res.map(t => s"${t._1} ${t._2}").mkString("\n"))
  }
  else println(-1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  if (n >= k + 1) {
    val res = (1 to n).flatMap { i =>
      (1 to k).map { j =>
        if (i + j > n)
          (i, i + j - n)
        else
          (i, i + j)
      }
    }
    println(res.map(t => s"${t._1} ${t._2}").mkString("\n"))
  }
  else println(-1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  if (n >= k * (k - 1) / 2) {
    val res = (1 to n).flatMap { i =>
      (1 to k).map { j =>
        if (i + j > n)
          (i, i + j - n)
        else
          (i, i + j)
      }
    }
    println(n * k)
    println(res.map(t => s"${t._1} ${t._2}").mkString("\n"))
  }
  else println(-1)
}


You have a long stick, consisting of $$$m$$$ segments enumerated from $$$1$$$ to $$$m$$$. Each segment is $$$1$$$ centimeter long. Sadly, some segments are broken and need to be repaired.You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $$$t$$$ placed at some position $$$s$$$ will cover segments $$$s, s+1, \ldots, s+t-1$$$.You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.Time is money, so you want to cut at most $$$k$$$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$n \le m \le 10^9$$$, $$$1 \le k \le n$$$) — the number of broken segments, the length of the stick and the maximum number of pieces you can use. The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le m$$$) — the positions of the broken segments. These integers are given in increasing order, that is, $$$b_1 < b_2 < \ldots < b_n$$$.

Print the minimum total length of the pieces.

NoteIn the first example, you can use a piece of length $$$11$$$ to cover the broken segments $$$20$$$ and $$$30$$$, and another piece of length $$$6$$$ to cover $$$75$$$ and $$$80$$$, for a total length of $$$17$$$.In the second example, you can use a piece of length $$$4$$$ to cover broken segments $$$1$$$, $$$2$$$ and $$$4$$$, and two pieces of length $$$1$$$ to cover broken segments $$$60$$$ and $$$87$$$.

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

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

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

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

  def solve(): Unit = {
    val N, M, K = ni()
    val A = na(N)
    val D = Array.ofDim[Int](N - 1)
    REP(N - 1) { i =>
      D(i) = A(i + 1) - A(i) - 1
    }
    sort(D)
    val ans = N + D.take(N - K).sum
    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

object B extends App {

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

  val Array(n, m, k) = readInts(3)
  val bs = readInts(n).map(_ - 1)

  val len = if (n == 1) 1
  else {
    val gaps = bs.sliding(2).map { case Array(l, r) => r - l - 1 }.toArray.sorted
    n + gaps.take(n - k).sum
  }

  println(len)
}

object B extends App {

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

  val Array(n, m, k) = readInts(3)
  val bs = readInts(n).map(_ - 1)

  case class Gap(l: Int, r: Int) {
    def len = r - l
  }
  val gaps = (1 until n).map(i => Gap(bs(i - 1), bs(i))).sortBy(_.len)

  var len = n
  var count = n

  for (gap <- gaps) {
    if (count > k) {
      len += gap.len - 1
      count -= 1
    }
  }

  println(len)
}


This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation exactly once: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$. Can he succeed?Note that he has to perform this operation exactly once. He has to perform this operation.

The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$), the length of the strings $$$s$$$ and $$$t$$$.  Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.

For each test case, output "Yes" if Ujan can make the two strings equal and "No" otherwise. You can print each letter in any case (upper or lower).

NoteIn the first test case, Ujan can swap characters $$$s_1$$$ and $$$t_4$$$, obtaining the word "house".In the second test case, it is not possible to make the strings equal using exactly one swap of $$$s_i$$$ and $$$t_j$$$.

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

object Main extends App {

    val k = StdIn.readLine.toInt
    for (_ <- 0 until k) {
        val n = StdIn.readLine.toInt
        val st1 = StdIn.readLine
        val st2 = StdIn.readLine

        var diff1 = new ListBuffer[Char]
        var diff2 = new ListBuffer[Char]
        var isDiff = false
        for (
            i <- 0 until n
            if !isDiff
        ) {
            if (st1(i) != st2(i)) {
                if (diff1.length == 2) {
                    isDiff = true
                } else {
                    diff1 += st1(i)
                    diff2 += st2(i)
                }
            }
        }

        if (!isDiff) {
            if (
//                (diff1.length == 2 && diff1.intersect(diff2).length == 2) ||
                (diff1.length == 2 && diff1(0) == diff1(1) && diff2(0) == diff2(1)) ||
                (diff1.length == 0)
            ) {
                println("Yes")
            } else {
                println("No")
            }

        } else {
            println("No")
        }

    }

}

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

  override def solve(io: IO) = io.repeat {
    val _, s, t = io.read[String]

    val diffs = s.zip(t).collect({case (a, b) if a != b => (a, b)}).toList

    val ans = diffs match {
      case Nil => true
      case (a1, b1) :: (a2, b2) :: Nil => a1 == a2 && b1 == b2
      case _ => false
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn

object StringSwap {

  def checkAllSwaps(t: Int, c: Int, s1: String, s2: String): String = {
    if (s1.length != c || s2.length != c) {
      "No"  // mismatched sizes
    } else if (s1 == s2) {
      "Yes"  // identical
    } else {
      var i1 = 0
      while (i1 < c && s1.charAt(i1) == s2.charAt(i1)) i1 = i1 + 1
      var i2 = i1 + 1
      while (i2 < c && s1.charAt(i2) == s2.charAt(i2)) i2 = i2 + 1
      var i3 = i2 + 1
      while (i3 < c && s1.charAt(i3) == s2.charAt(i3)) i3 = i3 + 1
      if (i3 < c) {
        "No"  // more than 2 positions different
      } else if (i1 < c && i2 < c) {
        if (s1.charAt(i1) == s1.charAt(i2) && s2.charAt(i1) == s2.charAt(i2)) {
          "Yes"
        } else {
          "No"
        }
      } else {
        "No" // only 1 position different
      }
    }
  }

  def main(args: Array[String]) {
    var line = StdIn.readLine()
    if (line != null) {
      val testCount = line.toInt
      line = StdIn.readLine()
      for (testNum <- 1 to testCount) {
        if (line != null) {
          val charCount = line.toInt
          line = StdIn.readLine()
          if (line != null) {
            val str1 = line
            line = StdIn.readLine()
            if (line != null) {
              val str2 = line
              val result = checkAllSwaps(testNum, charCount, str1, str2)
              println(result)
              line = StdIn.readLine
            }
          }
        }
      }
    }
  }
}

object B {

  def main(args: Array[String]): Unit = {
    val k = scala.io.StdIn.readInt()
    val result = for (i <- 1 to k) yield test()
    println(result.mkString("\n"))
  }

  def test(): String = {
    val n = scala.io.StdIn.readInt()
    val s1 = scala.io.StdIn.readLine()
    val s2 = scala.io.StdIn.readLine()
    val diff = for (i <- 0 until n; c1 = s1(i); c2 = s2(i) if c1 != c2) yield (c1, c2)
    if (diff.length == 2 && (diff(0) == diff(1))) "Yes"
    else "No"
  }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_599_B1 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    //runTest(Test.sa1)
    //debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val K = readLine.int

    for(k <- 1 to K) {
      val n = readLine.int
      val s = readLine.string
      val t = readLine.string

      var diffs = List[Int]()
      for (i <- 0 until n) {
        if (s(i) != t(i)) diffs ::= i
      }
      var res =
      if (diffs.length == 2) {
        val i1 = diffs(0)
        val i2 = diffs(1)
        if (s(i1) == s(i2) && t(i1) == t(i2)) {
          "Yes"
        } else {
          "No"
        }
      } else {
        "No"
      }

      outLn(res)
    }

//    debug("n = " + n)

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

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
"""

val sa2 = """
101
"""

val sa3 = """
10100
"""
 }
}

import scala.io.StdIn

object Main extends App{

    val k = StdIn.readLine.toInt
    for (i <- 0 until k) {
        val n = StdIn.readLine.toInt
        val st1 = StdIn.readLine
        val st2 = StdIn.readLine

        val dif = st1.diff(st2)
        if ( dif.length == 2 || dif.length == 0)
            println("Yes")
        else
            println("No")
    }

}

import scala.io.StdIn

object Main extends App{

    val k = StdIn.readLine.toInt
    for (i <- 0 until k) {
        val n = StdIn.readLine.toInt
        val st1 = StdIn.readLine
        val st2 = StdIn.readLine

        val dif = st1.diff(st2)
        if ( dif.length == 2 )
            println("Yes")
        else
            println("No")
    }

}

import scala.io.StdIn

object StringSwap {

  def checkSingleSwap(s1: StringBuilder, s2: StringBuilder, i: Int, j: Int): Boolean = {
    val c1 = s1.charAt(i)
    val c2 = s2.charAt(j)
    s1.setCharAt(i, c2)
    s2.setCharAt(j, c1)
    val ss1 = s1.mkString
    val ss2 = s2.mkString
    s1.setCharAt(i, c1)
    s2.setCharAt(j, c2)
    //println(s"check: $ss1, $ss2")
    ss1 == ss2
  }

  def checkAllSwaps(t: Int, c: Int, str1: String, str2: String): String = {
    //println(s"$t swap: $c, $str1, $str2")
    if (str1.length == c && str2.length == c) {
      val s1 = new StringBuilder(str1)
      val s2 = new StringBuilder(str2)
      for (i <- 0 until c) {
        for (j <- 0 until c) {
          if (checkSingleSwap(s1, s2, i, j)) {
            return "Yes"
          }
        }
      }
    }
    "No"
  }

  def main(args: Array[String]) {
    var line = StdIn.readLine()
    if (line != null) {
      val testCount = line.toInt
      line = StdIn.readLine()
      for (testNum <- 1 until testCount) {
        if (line != null) {
          val charCount = line.toInt
          line = StdIn.readLine()
          if (line != null) {
            val str1 = line
            line = StdIn.readLine()
            if (line != null) {
              val str2 = line
              val result = checkAllSwaps(testNum, charCount, str1, str2)
              println(result)
              line = StdIn.readLine
            }
          }
        }
      }
    }
  }
}

import scala.io.StdIn

object StringSwap {

  def checkAllSwaps(t: Int, c: Int, s1: String, s2: String): String = {
    if (s1.length != c || s2.length != c) {
      "No"
    } else if (s1 == s2) {
      "Yes"
    } else {
      var i1 = 0
      while (i1 < c && s1.charAt(i1) == s2.charAt(i1)) i1 = i1 + 1
      var i2 = i1 + 1
      while (i2 < c && s1.charAt(i2) == s2.charAt(i2)) i2 = i2 + 1
      if (i1 < c && i2 < c) {
        if (s1.charAt(i1) == s1.charAt(i2) && s2.charAt(i1) == s2.charAt(i2)) {
          "Yes"
        } else {
          "No"
        }
      } else {
        "No"
      }
    }
  }

  def main(args: Array[String]) {
    var line = StdIn.readLine()
    if (line != null) {
      val testCount = line.toInt
      line = StdIn.readLine()
      for (testNum <- 1 to testCount) {
        if (line != null) {
          val charCount = line.toInt
          line = StdIn.readLine()
          if (line != null) {
            val str1 = line
            line = StdIn.readLine()
            if (line != null) {
              val str2 = line
              val result = checkAllSwaps(testNum, charCount, str1, str2)
              println(result)
              line = StdIn.readLine
            }
          }
        }
      }
    }
  }
}

object B {

  def main(args: Array[String]): Unit = {
    val k = scala.io.StdIn.readInt()
    val result = for (i <- 1 to k) yield test()
    println(result.mkString("\n"))
  }

  def test(): String = {
    val n = scala.io.StdIn.readInt()
    val s1 = scala.io.StdIn.readLine()
    val s2 = scala.io.StdIn.readLine()
    val diff = for (i <- 0 until n; c1 = s1(i); c2 = s2(i) if c1 != c2) yield (c1, c2)
    if (diff.length == 2 && (diff(0) == diff(1) || diff(0) == diff(1).swap)) "Yes"
    else "No"
  }
}


You are given an array $$$a$$$ with $$$n$$$ integers. You can perform the following operation at most $$$k$$$ times:  Choose two indices $$$i$$$ and $$$j$$$, in which $$$i \,\bmod\, k = j \,\bmod\, k$$$ ($$$1 \le i < j \le n$$$).  Swap $$$a_i$$$ and $$$a_j$$$. After performing all operations, you have to select $$$k$$$ consecutive elements, and the sum of the $$$k$$$ elements becomes your score. Find the maximum score you can get.Here $$$x \bmod y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 600$$$) — the number of test cases. Each test case consists of two lines.  The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$) — the length of the array and the number in the statement above. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$)  — the array itself.

For each test case, print the maximum score you can get, one per line.

NoteIn the first test case, we can get a score of $$$11$$$ if we select $$$a_1, a_2$$$ without performing any operations.In the third test case, we can get a score of $$$15$$$ if we first swap $$$a_1$$$ with $$$a_4$$$ and then select $$$a_3, a_4, a_5$$$.

object main {

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

    var t = io.StdIn.readInt()

    def loopts(ts: Int): Unit = {
        if ( ts < t ){
            var Array(n, k) = io.StdIn.readLine().split(" ").map(_.toInt)
            var a:Array[Int] = new Array[Int](n)
            a = io.StdIn.readLine().split(" ").map(_.toInt)

            def loopi( i: Int, acc: Long ):Long = {
                if ( i < k ){
                    var Array(mx, mxp) =
                    {
                        def loopj(pos: Int, mx: Int, mxp: Int):Array[Int] = {
                            if ( pos < n ){
                                if ( mx < a(pos) ){
                                    loopj(pos+k, a(pos), pos)
                                }
                                else
                                    loopj( pos+k, mx, mxp )
                            }
                            else
                                Array( mx, mxp )
                        };loopj( i, 0, i )
                    }
                    loopi(i+1, acc+mx)
                }
                else
                    acc
            }

            println( loopi(0, 0) )
            loopts(ts+1)
        }
    }

    loopts(0)
  }

}

object _1733A extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val n, k = io.nextInt()
    val as = IndexedSeq.fill(n)(io.nextLong())
    val ans = (0 until k).map(i => (i until n by k).map(as).max)
    io.printLine(ans.sum)
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): this.type = { out.print(xs.mkString(" ")); this }
  def printLine(xs: Any*): this.type = { out.println(xs.mkString(" ")); this }
  def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }

  override def close() = out.close()
}