Oleg the bank client lives in Bankopolia. There are n cities in Bankopolia and some pair of cities are connected directly by bi-directional roads. The cities are numbered from 1 to n. There are a total of m roads in Bankopolia, the i-th road connects cities ui and vi. It is guaranteed that from each city it is possible to travel to any other city using some of the roads.Oleg wants to give a label to each city. Suppose the label of city i is equal to xi. Then, it must hold that for all pairs of cities (u, v) the condition |xu - xv| ≤ 1 holds if and only if there is a road connecting u and v.Oleg wonders if such a labeling is possible. Find an example of such labeling if the task is possible and state that it is impossible otherwise.

The first line of input contains two space-separated integers n and m (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105) — the number of cities and the number of roads. Next, m lines follow. The i-th line contains two space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that there is at most one road between each pair of cities and it is possible to travel from any city to any other city using some roads.

If the required labeling is not possible, output a single line containing the string "NO" (without quotes). Otherwise, output the string "YES" (without quotes) on the first line. On the next line, output n space-separated integers, x1, x2, ..., xn. The condition 1 ≤ xi ≤ 109 must hold for all i, and for all pairs of cities (u, v) the condition |xu - xv| ≤ 1 must hold if and only if there is a road connecting u and v.

NoteFor the first sample, x1 = 2, x2 = 3, x3 = x4 = 1 is a valid labeling. Indeed, (3, 4), (1, 2), (1, 3), (1, 4) are the only pairs of cities with difference of labels not greater than 1, and these are precisely the roads of Bankopolia.For the second sample, all pairs of cities have difference of labels not greater than 1 and all pairs of cities have a road connecting them.For the last sample, it is impossible to construct a labeling satisfying the given constraints.

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Try
import scala.util.hashing.MurmurHash3

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0

  Try {
    val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])
    for (i <- 0 until n) {
      linksBuilder(i) += i
    }
    (1 to m).foreach { i =>
      read()
      a = int() - 1
      b = int() - 1
      linksBuilder(a) += b
      linksBuilder(b) += a
    }

    val links: Array[Array[Int]] = linksBuilder.map(_.result)
    links.foreach(java.util.Arrays.sort)
    val linksXor: Array[Int] = links.map(_.reduceLeft(_ ^ _.hashCode()))
    val heads: Array[Int] = (0 until n).toArray
    def isHead(i: Int): Boolean = heads(i) == i

    for {
      i <- 0 until n
      if isHead(i)
      j <- links(i)
      if j > i
      if isHead(j)
      if linksXor(i) == linksXor(j)
      if links(i) sameElements links(j)
    } heads(j) = i

    val headLinks: Array[Array[Int]] = (0 until n).map { i =>
      if (isHead(i)) {
        links(i).filter(j => isHead(j) && (j != i))
      } else Array.empty[Int]
    } (collection.breakOut)

    val ans = Array.fill(n)(INF)

    @tailrec
    def dfs(cur: Int, prev: Int): Unit = {
      val prevValue = if (prev == -1) 1000000 else ans(prev)
      assert(ans(cur) == INF)
      ans(cur) = prevValue + 1
      val nextOpt = headLinks(cur).find(_ != prev)
      if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)
    }
    val start = (0 until n).filter(isHead).minBy(headLinks(_).length)
    dfs(start, -1)

    for (i <- 0 until n) ans(i) = ans(heads(i))
    assert(ans.forall(_ != INF))
    println("YES")
    println(ans.mkString(" "))
  }.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Try
import scala.util.hashing.MurmurHash3

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0

  Try {
    val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])
    for (i <- 0 until n) { linksBuilder(i) += i }
    (1 to m).foreach { i =>
      read()
      a = int() - 1
      b = int() - 1
      linksBuilder(a) += b
      linksBuilder(b) += a
    }

    val links: Array[Array[Int]] = linksBuilder.map { ab =>
      val arr = ab.result()
      java.util.Arrays.sort(arr)
      arr
    }
    val linksXor: Array[Int] = links.map(_.foldLeft(0)(_ ^ _.hashCode()))
    var heads: Array[Int] = (0 until n).toArray
    def isHead(i: Int): Boolean = heads(i) == i

    for {
      i <- 0 until n
      if isHead(i)
      j <- links(i)
      if j > i
      if isHead(j)
      if linksXor(i) == linksXor(j)
      if links(i) sameElements links(j)
    } heads(j) = i

    val headLinks: Array[Array[Int]] = (0 until n).map { i =>
      if (isHead(i)) {
        links(i).filter(j => isHead(j) && (j != i))
      } else Array.empty[Int]
    } (collection.breakOut)

    var ans = Array.fill(n)(INF)

    @tailrec
    def dfs(cur: Int, prev: Int): Unit = {
      val prevValue = if (prev == -1) 1000000 else ans(prev)
      assert(ans(cur) == INF)
      ans(cur) = prevValue + 1
      val nextOpt = headLinks(cur).find(_ != prev)
      if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)
    }
    val start = (0 until n).filter(isHead).minBy(headLinks(_).length)
    dfs(start, -1)

    for (i <- 0 until n) ans(i) = ans(heads(i))
    assert(ans.forall(_ != INF))
    println("YES")
    println(ans.mkString(" "))
  }.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.Builder
import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0
Try {
  var links = (0 until n).map(_ :: Nil).toArray

  (1 to m).foreach { i =>
    read()
    a = int() - 1
    b = int() - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  links = links.map(_.sorted)
  val ma = mutable.Map.empty[List[Int], List[Int]]
  for {
    (ls, i) <- links.zipWithIndex
  } {
    val list = ma.getOrElse(ls, Nil)
    ma.update(ls, i :: list)
  }

  val heads = ma.values.map(_.head).toSet

  val mb = for {
    (ls, group) <- ma
  } yield group.head -> ls.filter(heads.contains).filterNot(_ == group.head)

  var ans = Array.fill(n)(INF)

  val start = mb.find(_._2.size == 1).get._1

  val stack = new mutable.Stack[(Int, Int)]()
  stack.push((start, -1))
  while (stack.nonEmpty) {
    val (cur, prev) = stack.pop()
    val prevValue = if (prev == -1) 1000000 else ans(prev)
    ans(cur) = prevValue + 1
    mb(cur).filter(_ != prev).foreach(next => stack.push((next, cur)))
  }

  for (head <- heads) ma(links(head)).foreach { i =>
    ans(i) = ans(head)
  }
  assert(ans.forall(_ != INF))
  println("YES")
  println(ans.mkString(" "))
}.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0

  Try {
    val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])
    for (i <- 0 until n) { linksBuilder(i) += i }
    (1 to m).foreach { i =>
      read()
      a = int() - 1
      b = int() - 1
      linksBuilder(a) += b
      linksBuilder(b) += a
    }

    val links: Array[Array[Int]] = linksBuilder.map { ab =>
      val arr = ab.result()
      java.util.Arrays.sort(arr)
      arr
    }
    val linksXor: Array[Int] = links.map(_.foldLeft(0)(_ ^ _.hashCode()))
    var heads: Array[Int] = (0 until n).toArray
    def isHead(i: Int): Boolean = heads(i) == i

    for {
      i <- 0 until n
      if isHead(i)
      j <- links(i)
      if j > i
      if isHead(j)
      if linksXor(i) == linksXor(j)
      if links(i) sameElements links(j)
    } heads(j) = i

    val headLinks: Array[Array[Int]] = (0 until n).map { i =>
      if (isHead(i)) {
        links(i).filter(j => isHead(j) && (j != i))
      } else Array.empty[Int]
    } (collection.breakOut)

    var ans = Array.fill(n)(INF)

    @tailrec
    def dfs(cur: Int, prev: Int): Unit = {
      val prevValue = if (prev == -1) 1000000 else ans(prev)
      assert(ans(cur) != INF)
      ans(cur) = prevValue + 1
      val nextOpt = headLinks(cur).find(_ != prev)
      if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)
    }
    val start = (0 until n).filter(isHead).minBy(headLinks(_).length)
    dfs(start, -1)

    for (i <- 0 until n) ans(i) = ans(heads(i))
    assert(ans.forall(_ != INF))
    println("YES")
    println(ans.mkString(" "))
  }.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.Builder
import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0
Try {
  var links = (0 until n).map(_ :: Nil).toArray

  (1 to m).foreach { i =>
    read()
    a = int() - 1
    b = int() - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  links = links.map(_.sorted)
  val ma = mutable.Map.empty[List[Int], List[Int]]
  for {
    (ls, i) <- links.zipWithIndex
  } {
    val list = ma.getOrElse(ls, Nil)
    ma.update(ls, i :: list)
  }

  val heads = ma.values.map(_.head).toSet

  val mb = for {
    (ls, group) <- ma
  } yield group.head -> ls.filter(heads.contains).filterNot(_ == group.head)

  var ans = Array.fill(n)(INF)

  val start = mb.find(_._2.size == 1).map(_._1).getOrElse(heads.head)

  val stack = new mutable.Stack[(Int, Int)]()
  stack.push((start, -1))
  while (stack.nonEmpty) {
    val (cur, prev) = stack.pop()
    val prevValue = if (prev == -1) 1000000 else ans(prev)
    ans(cur) = prevValue + 1
    mb(cur).filter(_ != prev).foreach(next => stack.push((next, cur)))
  }

  for (head <- heads) ma(links(head)).foreach { i =>
    ans(i) = ans(head)
  }
  assert(ans.forall(_ != INF))
  println("YES")
  println(ans.mkString(" "))
}.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Try
import scala.util.hashing.MurmurHash3

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0

  Try {
    val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])
    for (i <- 0 until n) {
      linksBuilder(i) += i
    }
    (1 to m).foreach { i =>
      read()
      a = int() - 1
      b = int() - 1
      linksBuilder(a) += b
      linksBuilder(b) += a
    }

    val links: Array[Array[Int]] = linksBuilder.map(_.result)
    val linksXor: Array[Int] = links.map(_.reduceLeft(_ ^ _.hashCode()))
    val heads: Array[Int] = (0 until n).toArray
    def isHead(i: Int): Boolean = heads(i) == i

    val sorted: Array[Boolean] = Array.fill(n)(false)
    def ensureSorted(i: Int): Unit = if (!sorted(i)) {
      java.util.Arrays.sort(links(i))
      sorted(i) = true
    }

    def haveSameElements(i: Int, j: Int): Boolean = {
      ensureSorted(i)
      ensureSorted(j)
      links(i) sameElements links(j)
    }

    for {
      i <- 0 until n
      if isHead(i)
      j <- links(i)
      if j > i
      if isHead(j)
      if linksXor(i) == linksXor(j)
      if haveSameElements(i, j)
    } heads(j) = i

    val headLinks: Array[Array[Int]] = (0 until n).map { i =>
      if (isHead(i)) {
        links(i).filter(j => isHead(j) && (j != i))
      } else Array.empty[Int]
    } (collection.breakOut)

    val ans = Array.fill(n)(INF)

    @tailrec
    def dfs(cur: Int, prev: Int): Unit = {
      val prevValue = if (prev == -1) 1000000 else ans(prev)
      assert(ans(cur) == INF)
      ans(cur) = prevValue + 1
      val nextOpt = headLinks(cur).find(_ != prev)
      if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)
    }
    val start = (0 until n).filter(isHead).minBy(headLinks(_).length)
    dfs(start, -1)

    for (i <- 0 until n) ans(i) = ans(heads(i))
    assert(ans.forall(_ != INF))
    println("YES")
    println(ans.mkString(" "))
  }.getOrElse(println("NO"))

}


You are given integer $$$n$$$. You have to arrange numbers from $$$1$$$ to $$$2n$$$, using each of them exactly once, on the circle, so that the following condition would be satisfied:For every $$$n$$$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $$$2n$$$ numbers differ not more than by $$$1$$$.For example, choose $$$n = 3$$$. On the left you can see an example of a valid arrangement: $$$1 + 4 + 5 = 10$$$, $$$4 + 5 + 2 = 11$$$, $$$5 + 2 + 3 = 10$$$, $$$2 + 3 + 6 = 11$$$, $$$3 + 6 + 1 = 10$$$, $$$6 + 1 + 4 = 11$$$, any two numbers differ by at most $$$1$$$. On the right you can see an invalid arrangement: for example, $$$5 + 1 + 6 = 12$$$, and $$$3 + 2 + 4 = 9$$$, $$$9$$$ and $$$12$$$ differ more than by $$$1$$$.

The first and the only line contain one integer $$$n$$$ ($$$1 \le n \le 10^5$$$).

If there is no solution, output "NO" in the first line.  If there is a solution, output "YES" in the first line. In the second line output $$$2n$$$ numbers — numbers from $$$1$$$ to $$$2n$$$ in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.

NoteExample from the statement is shown for the first example. It can be proved that there is no solution in the second example.

object A 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) = readInts(1)

  val res = Array.ofDim[Int](2 * n)

  var l = 1
  var r = 2 * n
  for (i <- 0 until n) {
    if (i % 2 == 0) {
      res(i) = l
      l += 1
      res(i + n) = l
      l += 1
    } else {
      res(i) = r
      r -= 1
      res(i + n) = r
      r -= 1
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n % 2 == 1) {
    println("YES")
    println(res.mkString(" "))
  } else println("NO")

  Console.flush
}


You are given four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$. You should build a sequence $$$a_0, a_1, a_2, \dots, a_n$$$ where $$$a_0 = 0$$$ and for each $$$i \ge 1$$$ you can choose:   either $$$a_i = a_{i - 1} + x$$$  or $$$a_i = a_{i - 1} - y$$$. Your goal is to build such a sequence $$$a$$$ that $$$a_i \le B$$$ for all $$$i$$$ and $$$\sum\limits_{i=0}^{n}{a_i}$$$ is maximum possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$t$$$ cases follow. The first and only line of each test case contains four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le B, x, y \le 10^9$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the maximum possible $$$\sum\limits_{i=0}^{n}{a_i}$$$.

NoteIn the first test case, the optimal sequence $$$a$$$ is $$$[0, 1, 2, 3, 4, 5]$$$.In the second test case, the optimal sequence $$$a$$$ is $$$[0, 10^9, 0, 10^9, 0, 10^9, 0, 10^9]$$$.In the third test case, the optimal sequence $$$a$$$ is $$$[0, -3, -6, 1, -2]$$$.

import scala.io.StdIn.readLine

object Solution {

  def solve(n: Int, b: Int, x: Int, y: Int) = {

    def recur(i: Int, prev: Long): Long = {
      if (i == 0) 0
      else {
        val curr = if (prev + x > b) prev - y else prev + x
        curr + recur(i - 1, curr)
      }
    }

    recur(n, 0)
  }

  def main(args: Array[String]): Unit = {
    val cases = readLine().toInt
    for (
      i <- 0 until cases;
      text = readLine().split("\\s+").map(_.toInt)
    ) println(solve(text(0), text(1), text(2), text(3)))

  }

}


You have a string $$$s$$$ consisting of $$$n$$$ characters. Each character is either 0 or 1.You can perform operations on the string. Each operation consists of two steps:  select an integer $$$i$$$ from $$$1$$$ to the length of the string $$$s$$$, then delete the character $$$s_i$$$ (the string length gets reduced by $$$1$$$, the indices of characters to the right of the deleted one also get reduced by $$$1$$$);  if the string $$$s$$$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix). Note that both steps are mandatory in each operation, and their order cannot be changed.For example, if you have a string $$$s =$$$ 111010, the first operation can be one of the following:  select $$$i = 1$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010;  select $$$i = 2$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010;  select $$$i = 3$$$: we'll get 111010 $$$\rightarrow$$$ 11010 $$$\rightarrow$$$ 010;  select $$$i = 4$$$: we'll get 111010 $$$\rightarrow$$$ 11110 $$$\rightarrow$$$ 0;  select $$$i = 5$$$: we'll get 111010 $$$\rightarrow$$$ 11100 $$$\rightarrow$$$ 00;  select $$$i = 6$$$: we'll get 111010 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 01. You finish performing operations when the string $$$s$$$ becomes empty. What is the maximum number of operations you can perform?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains string $$$s$$$ of $$$n$$$ characters. Each character is either 0 or 1. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum number of operations you can perform.

NoteIn the first test case, you can, for example, select $$$i = 2$$$ and get string 010 after the first operation. After that, you can select $$$i = 3$$$ and get string 1. Finally, you can only select $$$i = 1$$$ and get empty string.

object D {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      var n = nextInt
      val s = nextLine
      var lim = s.length
      var a, b, res = 0
      val deleted = Array.fill(n)(false)
      while (n > 0) {
        while (a < lim - 1 && s(a) != s(a + 1)) {
          a += 1
        }
        n -= 1
        deleted(a) = true
        a += 1
        if (a == lim) {
          lim -= 1
          a -= 2
        }
//        if (a == b) {
//          b += 1
//        }
//        println(a, n, lim)
        if (n > 0) {
          while (b < s.length && deleted(b)) {
            b += 1
          }
          val b0 = b
          while (b <= lim && b < s.length && s(b) == s(b0)) {
            if (!deleted(b)) n -= 1
            b += 1
          }
//          println(b, b0)
          if (a < b) a = b
        }
//        println(a, b, n, lim)
        res += 1
      }

      out.println(res)

      out.flush()
    }
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object D {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      var n = nextInt
      val s = nextLine
      var lim = s.length
      var a, b, res = 0
      while (n > 0) {
        while (a < lim - 1 && s(a) != s(a + 1)) {
          a += 1
        }
        n -= 1
        if (a == lim - 1) {
          lim -= 1
          a -= 1
        }
        if (a == b) {
          b += 1
        }
//        println(a, n, lim)
        if (n > 0) {
          val b0 = b
          while (b <= lim && b < s.length && s(b) == s(b0)) {
            b += 1
          }
          n -= (b - b0)
//          println(b, b0)
          if (a < b) a = b
        }
//        println(a, b, n, lim)
        res += 1
      }

      out.println(res)

      out.flush()
    }
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}


The BFS algorithm is defined as follows.  Consider an undirected graph with vertices numbered from $$$1$$$ to $$$n$$$. Initialize $$$q$$$ as a new queue containing only vertex $$$1$$$, mark the vertex $$$1$$$ as used.  Extract a vertex $$$v$$$ from the head of the queue $$$q$$$.  Print the index of vertex $$$v$$$.  Iterate in arbitrary order through all such vertices $$$u$$$ that $$$u$$$ is a neighbor of $$$v$$$ and is not marked yet as used. Mark the vertex $$$u$$$ as used and insert it into the tail of the queue $$$q$$$.  If the queue is not empty, continue from step 2.  Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex $$$1$$$. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) which denotes the number of nodes in the tree.  The following $$$n - 1$$$ lines describe the edges of the tree. Each of them contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) — the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the sequence to check.

Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).

NoteBoth sample tests have the same tree in them.In this tree, there are two valid BFS orderings:   $$$1, 2, 3, 4$$$,  $$$1, 3, 2, 4$$$. The ordering $$$1, 2, 4, 3$$$ doesn't correspond to any valid BFS order.

object 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)
  val sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val F, T = Array.ofDim[Int](N)
    rep(N - 1) { i =>
      F(i) = ni() - 1
      T(i) = ni() - 1
    }
    val t = packTree(N, F, T)
    val o = map(N)(_ => ni() - 1)
    val o_i = Array.ofDim[Int](N)
    rep(N) { i =>
      o_i(o(i)) = i
    }

    val (d, p) = traceBfs(t)

    var ok = true
    rep(N - 1) { i =>
      ok &= d(o(i)) < d(o(i + 1)) || d(o(i)) == d(o(i + 1)) && o_i(p(o(i))) <= o_i(p(o(i + 1)))
    }

    val ans = if (ok) "Yes" else "No"

    out.println(ans)
  }

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

  /**
    * @return (depth, parent)
    */
  def traceBfs(g: Array[Array[Int]]): (Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    p(0) = -1
    val d = Array.fill[Int](n)(INF)
    d(0) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      rep(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p)
  }

  def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def 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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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

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

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

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

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

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

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

import java.util.StringTokenizer

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

object D extends App with Reader {
  read()
  val n = int()
  val links = Array.fill(n+1)(new mutable.ArrayBuffer[Int]())

  for (i <- 1 until n) {
    read()
    val s = int()
    val f = int()
    links(s) += f
    links(f) += s
  }

  read()
  val queue = Array.fill(n)(int())

  def isCorrect(): Boolean = {
    val visited = Array.fill(n+1)(false)

    if (queue(0) != 1) return false
    var checked = 1
    visited(1) = true

    for (i <- queue) {
      val next = links(i).filterNot(visited).toSet
      for (i <- 1 to next.size) {
        if (!next.contains(queue(checked))) return false
        visited(queue(checked)) = true
        checked += 1
      }
    }
    return true
  }

  println(if (isCorrect()) "Yes" else "No")
}

trait Reader {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(StdIn.readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong
}

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

object C extends App {

  case class Point(x: Int, segId: Int, isBegin: Boolean)

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val edges = Array.fill(n)(new collection.mutable.ArrayBuffer[Int]())
    (1 until n).foreach { _ =>
      val x = in.nextInt - 1
      val y = in.nextInt - 1
      edges(x) += y
      edges(y) += x
    }
    val dist = Array.fill(n)(0)
    val pred = Array.fill(n)(0)
    val q = collection.mutable.Queue[Int]()
    dist(0) = 1
    q.enqueue(0)
    while (q.nonEmpty) {
      val c = q.dequeue()
      edges(c).foreach { e =>
        if (dist(e) == 0) {
          dist(e) = dist(c) + 1
          pred(e) = c
          q.enqueue(e)
        }
      }
    }
    //dist.foreach(println)
    var lastDist = 1
    var ok = true
    val qq = collection.mutable.Queue[Int]()
    Array.fill(n)(in.nextInt).foreach { i =>
      val d = dist(i - 1)
      if (lastDist > d)
        ok = false
      lastDist = d

      qq.enqueue(i - 1)
      while (qq.nonEmpty && qq.front != pred(i - 1)) {
        qq.dequeue()
      }
      if (qq.isEmpty) ok = false
    }

    if (ok) println("Yes")
    else println("No")
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object 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)
  val sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val F, T = Array.ofDim[Int](N)
    rep(N - 1) { i =>
      F(i) = ni() - 1
      T(i) = ni() - 1
    }
    val t = packTree(N, F, T)
    val o = map(N)(_ => ni() - 1)

    val INF = 1e9.toInt
    val bfs = Array.ofDim[Int](N)
    val d = Array.fill[Int](N)(INF)
    d(0) = 0
    var cur = 0
    var last = 1
    while(cur < last) {
      val v = bfs(cur)
      val us = t(v)
      rep(us.length) { i =>
        val u = us(i)
        if (d(u) == INF) {
          bfs(last) = u
          d(u) = d(v) + 1
          last += 1
        }
      }
      cur += 1
    }

    var ok = o.distinct.length == N
    rep(N - 1) { i =>
      ok &= d(o(i)) <= d(o(i + 1))
    }

    val ans = if (ok) "Yes" else "No"

    out.println(ans)
  }

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

  def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def 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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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

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

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

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

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

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

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

object 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)
  val sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val F, T = Array.ofDim[Int](N)
    rep(N - 1) { i =>
      F(i) = ni() - 1
      T(i) = ni() - 1
    }
    val t = packTree(N, F, T)
    val o = map(N)(_ => ni() - 1)

    val INF = 1e9.toInt
    val bfs = Array.ofDim[Int](N)
    val d = Array.fill[Int](N)(INF)
    d(0) = 0
    var cur = 0
    var last = 1
    while(cur < last) {
      val v = bfs(cur)
      val us = t(v)
      rep(us.length) { i =>
        val u = us(i)
        if (d(u) == INF) {
          bfs(last) = u
          d(u) = d(v) + 1
          last += 1
        }
      }
      cur += 1
    }

    var ok = true
    rep(N - 1) { i =>
      ok &= o(i) <= o(i + 1)
    }

    val ans = if (ok) "Yes" else "No"

    out.println(ans)
  }

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

  def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def 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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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

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

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

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

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

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

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

object 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)
  val sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val F, T = Array.ofDim[Int](N)
    rep(N - 1) { i =>
      F(i) = ni() - 1
      T(i) = ni() - 1
    }
    val t = packTree(N, F, T)
    val o = map(N)(_ => ni() - 1)

    val INF = 1e9.toInt
    val bfs = Array.ofDim[Int](N)
    val d = Array.fill[Int](N)(INF)
    d(0) = 0
    var cur = 0
    var last = 1
    while(cur < last) {
      val v = bfs(cur)
      val us = t(v)
      rep(us.length) { i =>
        val u = us(i)
        if (d(u) == INF) {
          bfs(last) = u
          d(u) = d(v) + 1
          last += 1
        }
      }
      cur += 1
    }

    var ok = o.distinct.length == N
    rep(N - 1) { i =>
      ok &= o(i) <= o(i + 1)
    }

    val ans = if (ok) "Yes" else "No"

    out.println(ans)
  }

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

  def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def 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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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

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

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

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

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

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

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

import java.util.StringTokenizer

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

object D extends App with Reader {
  read()
  val n = int()
  val links = Array.fill(n+1)(new mutable.ArrayBuffer[Int]())

  for (i <- 1 until n) {
    read()
    val s = int()
    val f = int()
    links(s) += f
    links(f) += s
  }

  read()
  val queue = Array.fill(n)(int())

  def isCorrect(): Boolean = {
    val visited = Array.fill(n+1)(false)
    val rank = Array.fill(n+1)(0)
    val q = new mutable.Queue[Int]()
    var currentRank = 0

    for (i <- queue) {
      if (visited(i)) return false
      if (i != 1) {
        val prevs = links(i).filter(visited(_))
        if (prevs.isEmpty) return false
        val ranks = prevs.map(rank(_))
        val min = ranks.min
        val max = ranks.max
        if (max == min) {
          if (currentRank == min) {
            currentRank += 1
          } else if (currentRank != min + 1) {
            return false
          }
        } else if (max == min + 1) {
          if (currentRank != max) {
            return false
          }
        } else {
          return false
        }
      }
      rank(i) = currentRank
      visited(i) = true
    }
    return true
  }

  println(if (isCorrect()) "Yes" else "No")
}

trait Reader {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(StdIn.readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong
}

import java.util.StringTokenizer

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

object D extends App with Reader {
  read()
  val n = int()
  val links = Array.fill(n+1)(new mutable.ArrayBuffer[Int]())

  for (i <- 1 until n) {
    read()
    val s = int()
    val f = int()
    links(s) += f
    links(f) += s
  }

  read()
  val queue = Array.fill(n)(int())

  def isCorrect(): Boolean = {
    val visited = Array.fill(n+1)(false)
    val rank = Array.fill(n+1)(0)
    val q = new mutable.Queue[Int]()
    var currentRank = 0

    for (i <- queue) {
      if (visited(i)) return false
      if (i != 1) {
        val prevs = links(i).filter(visited(_))
        if (prevs.isEmpty) return false
        val ranks = prevs.map(rank(_))
        val min = ranks.min
        val max = ranks.max
        if (max == min) {
          if (currentRank == min) {
            currentRank += 1
          } else if (currentRank != min + 1) {
            return false
          }
        } else if (max == min + 1) {
          if (currentRank != max) {
            return false
          }
        } else {
          return false
        }
      }
      rank(i) = currentRank
      visited(i) = true
    }
    return true
  }

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

trait Reader {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(StdIn.readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong
}

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

object C extends App {

  case class Point(x: Int, segId: Int, isBegin: Boolean)

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val edges = Array.fill(n)(new collection.mutable.ArrayBuffer[Int]())
    (1 until n).foreach { _ =>
      val x = in.nextInt - 1
      val y = in.nextInt - 1
      edges(x) += y
      edges(y) += x
    }
    val dist = Array.fill(n)(0)
    val q = collection.mutable.Queue[Int]()
    dist(0) = 1
    q.enqueue(0)
    while (q.nonEmpty) {
      val c = q.dequeue()
      edges(c).foreach { e =>
        if (dist(e) == 0) {
          dist(e) = dist(c) + 1
          q.enqueue(e)
        }
      }
    }
    //dist.foreach(println)
    var lastDist = 1
    var ok = true
    Array.fill(n)(in.nextInt).foreach { i =>
      val d = dist(i - 1)
      if (lastDist > d)
        ok = false
      lastDist = d
    }

    if (ok) println("Yes")
    else println("No")
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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

object D extends App {

  def countLen(x: Long): Int = {
    var l = 0
    var xx = x
    while (xx > 0) {
      xx = xx / 10
      l += 1
    }
    l
  }

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val t = 123
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Long = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}


You are given a positive integer $$$x$$$. Find any such $$$2$$$ positive integers $$$a$$$ and $$$b$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$.As a reminder, $$$GCD(a,b)$$$ is the greatest integer that divides both $$$a$$$ and $$$b$$$. Similarly, $$$LCM(a,b)$$$ is the smallest integer such that both $$$a$$$ and $$$b$$$ divide it.It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of testcases. Each testcase consists of one line containing a single integer, $$$x$$$ $$$(2 \le x \le 10^9)$$$.

For each testcase, output a pair of positive integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9)$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$. It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.

NoteIn the first testcase of the sample, $$$GCD(1,1)+LCM(1,1)=1+1=2$$$.In the second testcase of the sample, $$$GCD(6,4)+LCM(6,4)=2+12=14$$$.

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C628A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

    def nextInt(): Int = Integer.parseInt(next())

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C628A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val x = ni()
      out.println(s"1 ${x-1}")
    }
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val x = in.nextInt()
      out.println(s"1 ${x-1}")
    }

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

import java.io.PrintWriter

import scala.collection.mutable
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString(): String = reader.readLine()

    def multiTest(f: () => Unit): Unit = {
        var t = readInt()
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(): Unit = {
        val x = readInt()
        println(s"1 ${x - 1}")

    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
    }
}


You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and edges, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied.

Print $$$n-1$$$ lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge $$$(v, u)$$$ is considered the same as the edge $$$(u, v)$$$). If there are multiple possible answers, print any of them.

NotePicture corresponding to the first example: In this example the number of edges of spanning tree incident to the vertex $$$3$$$ is $$$3$$$. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.Picture corresponding to the second example: In this example the number of edges of spanning tree incident to the vertex $$$1$$$ is $$$3$$$. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.Picture corresponding to the third example: In this example the number of edges of spanning tree incident to the vertex $$$2$$$ is $$$4$$$. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex $$$5$$$ instead of $$$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 = {
    val N, M = ni()
    val (from, to) = na2(M, -1)
    val g = packUGraph(N, from, to)
    val mxV = g.zipWithIndex.maxBy(_._1.length)._2

    case class Edge(v: Int, u: Int)
    val ans = new ArrayBuffer[Edge]()

    val uf = new UnionFind(N)
    REP(g(mxV).length) { i =>
      val u = g(mxV)(i)
      uf.unite(mxV, u)
      ans += Edge(mxV, u)
    }

    REP(M) { i =>
      if (uf.find(from(i)) != uf.find(to(i))) {
        uf.unite(from(i), to(i))
        ans += Edge(from(i), to(i))
      }
    }

    REP(N - 1) { i =>
      val e = ans(i)
      out.println(s"${e.v+1} ${e.u+1}")
    }
  }

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    REP(n) (i => par(i) = i)
    val rank: Array[Int] = Array.fill[Int](n)(1) // 集合の要素数
    private val visits = Array.ofDim[Int](n) // 訪れた場所をfind毎に用意するのがもったいないのでつかいまわす

    def find(x: Int): Int = {
      var ptr = 0
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          visits(ptr) = x
          ptr += 1
          step(par(x))
        }
      }

      val res = step(x)
      REP(ptr){ i => par(visits(i)) = res }
      res
    }

    def unite(x: Int, y: Int): Int = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 == y1) x1
      else {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
          y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += rank(y1)
          x1
        }
      }
    }

    /**
      * xを解決する必要がないときは直にrankをみる
      */
    def cntNodes(x: Int): Int = rank(find(x))
  }

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

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

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

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

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

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

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

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

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

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

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

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

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


Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to n and the number of a hill is equal to the distance in meters between it and the island. The distance between the n-th hill and the shore is also 1 meter.Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is d, the frog will jump from the island on the hill d, then — on the hill 2d, then 3d and so on until they get to the shore (i.e. find itself beyond the hill n).However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible.

The first line contains three integers n, m and k (1 ≤ n ≤ 109, 1 ≤ m, k ≤ 100) — the number of hills, frogs and mosquitoes respectively. The second line contains m integers di (1 ≤ di ≤ 109) — the lengths of the frogs’ jumps. The third line contains k integers — the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces.

In the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line — their numbers in increasing order separated by spaces. The frogs are numbered from 1 to m in the order of the jump length given in the input data.

object P039F extends App {
  readLine()
  val frog = readLine().split(' ').map(_.toInt)
  val mosq = readLine().split(' ').map(_.toInt)
  val killed = frog.map(x => (mosq.count(_ % x == 0)))
  val minValue = killed.min
  val cand = killed.zipWithIndex.filter(_._1 == minValue)
  println(cand.size)
  cand.foreach(x => printf("%d ", x._2+1))
}

object PacifistFrogs39F  extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val m = scanner.nextInt()
    val k = scanner.nextInt()
    val distances = (1 to m).map(_ => scanner.nextInt()).toArray
    val mosquitos = (1 to k).map(_ => scanner.nextInt())
    val result = (0 until m).map{ frog =>
      val d = distances(frog)
      (frog,mosquitos.count(place => place % d == 0))
    }
    val minCount = result.minBy(_._2)._2
    val bestFrogs = result.filter(_._2 == minCount)
    out.println(bestFrogs.length)
    out.println(bestFrogs.map{case (frog,count) =>  frog+1}.mkString(" "))
  }
}

object P039F extends App {
  readLine()
  val frog = readLine().split(' ').map(_.toInt)
  val mosq = readLine().split(' ').map(_.toInt)
  val killed = frog.map(x => (mosq.count(_ % x == 0)))
  val maxValue = killed.min
  killed.zipWithIndex.filter(_._1 == maxValue).foreach(x=>printf("%d ",x._2+1))
}


There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order. You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.

The first line contains a string of length 26 consisting of distinct lowercase English letters. This is the first layout. The second line contains a string of length 26 consisting of distinct lowercase English letters. This is the second layout. The third line contains a non-empty string s consisting of lowercase and uppercase English letters and digits. This is the text typed in the first layout. The length of s does not exceed 1000.

//package vandit

import java.util.Scanner

/**
  * Created by vjain on 13/07/17.
  */
object Solution {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val firstLayout : String = sc.next
    val secondLayout : String = sc.next
    val word : String = sc.next
    var transform : collection.mutable.Map[Char,Char] = collection.mutable.Map()

    for(pos <- 0 to firstLayout.size-1){
      transform.put(firstLayout.charAt(pos),secondLayout.charAt(pos))
      transform.put((firstLayout.charAt(pos)-32).toChar,(secondLayout.charAt(pos)-32).toChar)
    }
    for(pos <- 0 to word.size-1)
      print(transform.get(word.charAt(pos)).getOrElse(word.charAt(pos)))

  }
}

import scala.io._

object A1 {
  def main(args: Array[String]): Unit = {
    var lines = Source.stdin.getLines().take(3).toArray
    lines(0) = lines(0) + lines(0).toUpperCase() + "0123456789"
    lines(1) = lines(1) + lines(1).toUpperCase() + "0123456789"
    println(lines(2).map(p=>lines(1).charAt(lines(0).indexOf(p))))
  }
}

object B extends App {

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

  val _a, _b, t = readLine

  val a = _a + _a.toUpperCase
  val b = _b + _b.toUpperCase

  val res = new StringBuilder

  for (c <- t) {
    val i = a.indexOf(c)
    res += (if (i < 0) c else b(i))
  }

  println(res.toString())
}

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

/**
  * @author Aydar Gizatullin a.k.a. lightning95 on 30.05.17.
  */

object Main2 {

  def main(args: Array[String]) {
    val in = scala.io.StdIn
    val s1 = in readLine
    val s2 = in readLine
    val t = in readLine()
    println(t.map(x =>
      if (Character.isDigit(x))
        x
      else {
        val up = Character.isUpperCase(x)
        val pos = s1.indexOf(Character.toLowerCase(x))
        val res = if (up)
          Character.toUpperCase(s2.charAt(pos))
        else
          s2.charAt(pos)
        res
      }))
  }

}


IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.Today, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. "It would look much better when I'll swap some of them!" — thought the girl — "but how to do it?". After a while, she got an idea. IA will look at all prefixes with lengths from $$$1$$$ to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first and the only line contains a string $$$s$$$ ($$$1 \le |s| \le 1000$$$), describing the initial string formed by magnets. The string $$$s$$$ consists only of characters 'a' and 'b'.

Output exactly $$$|s|$$$ integers. If IA should reverse the $$$i$$$-th prefix (that is, the substring from $$$1$$$ to $$$i$$$), the $$$i$$$-th integer should be equal to $$$1$$$, and it should be equal to $$$0$$$ otherwise. If there are multiple possible sequences leading to the optimal answer, print any of them.

NoteIn the first example, IA can reverse the second and the third prefix and get a string "abbb". She cannot get better result, since it is also lexicographically smallest string obtainable by permuting characters of the initial string.In the second example, she can reverse any subset of prefixes — all letters are 'a'.

//package codeforces

object SmallestWord {

  def main(args: Array[String]): Unit = {
    val input = io.StdIn.readLine

    for (i <- 0 to input.length - 2) {
      if (input(i) == input(i+1)) print("0 ")
      else print("1 ")
    }

    if(input.last == 'a') print("1") else print("0")
  }

}

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 S = ns()
    val N = S.length
    val ans = Array.fill[List[Int]](N + 1, 2)(Nil) // 0: 左寄せ, 1: 右寄せ
    rep(N) { i =>
      S(i) match {
        case 'a' =>
          ans(i + 1)(0) = 1 :: ans(i)(1)
          ans(i + 1)(1) = 0 :: ans(i)(1)

        case 'b' =>
          ans(i + 1)(0) = 0 :: ans(i)(0)
          ans(i + 1)(1) = 1 :: ans(i)(0)
      }
    }

    out.println(ans(N)(0).toArray.reverse.mkString(" "))
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  def solve(in: InputReader): Unit = {
    val s = in.next.toCharArray
    (0 until s.size - 1).foreach { i =>

      if (s(i) != s(i + 1)) {
        (0 to (i / 2)).foreach { j =>
          val t = s(j)
          s(j) = s(i - j)
          s(i - j) = t
        }
        print("1 ")
      } else {
        print("0 ")
      }
    }

    if (s(s.size - 1) == 'a')
      println("1")
    else
      println("0")
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}


Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers li and ri for each of the days — the indices of socks to wear on the day i (obviously, li stands for the left foot and ri for the right). Each sock is painted in one of k colors.When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paint — one for each of k colors.Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.

The first line of input contains three integers n, m and k (2 ≤ n ≤ 200 000, 0 ≤ m ≤ 200 000, 1 ≤ k ≤ 200 000) — the number of socks, the number of days and the number of available colors respectively. The second line contain n integers c1, c2, ..., cn (1 ≤ ci ≤ k) — current colors of Arseniy's socks. Each of the following m lines contains two integers li and ri (1 ≤ li, ri ≤ n, li ≠ ri) — indices of socks which Arseniy should wear during the i-th day.

Print one integer — the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.

NoteIn the first sample, Arseniy can repaint the first and the third socks to the second color.In the second sample, there is no need to change any colors.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val colors = in.next().split(' ').map(_.toInt)
  val socks = Array.range(0, n)
  val size = Array.fill(n){1}

  def parent(i: Int): Int = {
    if (socks(i) == i)
      i
    else
      parent(socks(i))
  }

  (1 to m).foreach { _ =>
    val Array(f, s) = in.next().split(' ').map(_.toInt - 1)
    val fParent = parent(f)
    val sParent = parent(s)
    if (fParent != sParent) {
      if (size(fParent) > size(sParent)) {
        size(fParent) += size(sParent)
        size(sParent) = 0
        socks(sParent) = fParent
      } else {
        size(sParent) += size(fParent)
        size(fParent) = 0
        socks(fParent) = sParent
      }
    }
  }

  val res = socks.indices.map{i => (parent(i), colors(i))}.groupBy(_._1).filter(_._2.length > 1).map(i => i._2.length - i._2.groupBy(_._2).map(_._2.length).max)
  println(res.sum)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val colors = in.next().split(' ').map(_.toInt)
  val socks = Array.range(0, n)
  val size = Array.fill(n){1}

  def parent(i: Int): Int = {
    if (socks(i) == i)
      i
    else
      parent(socks(i))
  }

  (1 to m).foreach { _ =>
    val Array(f, s) = in.next().split(' ').map(_.toInt - 1)
    val fParent = parent(f)
    val sParent = parent(s)
    if (fParent != sParent) {
      if (size(fParent) > size(sParent)) {
        size(fParent) += size(sParent)
        size(sParent) = 0
        socks(sParent) = fParent
      } else {
        size(sParent) += size(fParent)
        size(fParent) = 0
        socks(fParent) = sParent
      }
    }
  }

  val res = socks.indices.map{i => (parent(i), colors(i))}.groupBy(_._1).filter(_._2.length > 1).map(i => i._2.length - i._2.groupBy(_._2).head._2.length)
  println(res.sum)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val colors = in.next().split(' ').map(_.toInt)
  val socks = Array.range(0, n)
  val size = Array.fill(n){1}

  def parent(i: Int): Int = {
    if (socks(i) == i)
      i
    else
      parent(socks(i))
  }

  (1 to m).foreach { _ =>
    val Array(f, s) = in.next().split(' ').map(_.toInt - 1)
    val fParent = parent(f)
    val sParent = parent(s)
    if (fParent != sParent) {
      if (size(fParent) > size(sParent)) {
        size(fParent) += size(sParent)
        size(sParent) = 0
        socks(sParent) = fParent
      } else {
        size(sParent) += size(fParent)
        size(fParent) = 0
        socks(fParent) = sParent
      }
    }
  }

  val res = socks.indices.map{i => (parent(i), colors(i))}.groupBy(_._1).map(i => i._2.length - i._2.groupBy(_._2).head._2.length)
  println(res.sum)

}


Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.Consider that m (m ≤ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.After occupying all the window seats (for m > 2n) the non-window seats are occupied:1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat.  The seating for n = 9 and m = 36. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.

The only line contains two integers, n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 4n) — the number of pairs of rows and the number of passengers.

Print m distinct integers from 1 to m — the order in which the passengers will get off the bus.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  println((1 to n).foldLeft(List.empty[List[Int]]) {
    case (acc, i) =>
      val shift = (i - 1) * 2
      List(2 * n + 1 + shift, 1 + shift, 2 * n + 2 + shift, 2 + shift).filter(_ <= m) :: acc
  }.reverse.flatten.mkString(" "))
}