The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.There are $$$n+1$$$ checkpoints on the trail. They are numbered by $$$0$$$, $$$1$$$, ..., $$$n$$$. A runner must start at checkpoint $$$0$$$ and finish at checkpoint $$$n$$$. No checkpoint is skippable — he must run from checkpoint $$$0$$$ to checkpoint $$$1$$$, then from checkpoint $$$1$$$ to checkpoint $$$2$$$ and so on. Look at the picture in notes section for clarification.Between any two adjacent checkpoints, there are $$$m$$$ different paths to choose. For any $$$1\le i\le n$$$, to run from checkpoint $$$i-1$$$ to checkpoint $$$i$$$, a runner can choose exactly one from the $$$m$$$ possible paths. The length of the $$$j$$$-th path between checkpoint $$$i-1$$$ and $$$i$$$ is $$$b_{i,j}$$$ for any $$$1\le j\le m$$$ and $$$1\le i\le n$$$.To test the trail, we have $$$m$$$ runners. Each runner must run from the checkpoint $$$0$$$ to the checkpoint $$$n$$$ once, visiting all the checkpoints. Every path between every pair of adjacent checkpoints needs to be ran by exactly one runner. If a runner chooses the path of length $$$l_i$$$ between checkpoint $$$i-1$$$ and $$$i$$$ ($$$1\le i\le n$$$), his tiredness is $$$$$$\min_{i=1}^n l_i,$$$$$$ i. e. the minimum length of the paths he takes.Please arrange the paths of the $$$m$$$ runners to minimize the sum of tiredness of them.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n,m \leq 100$$$). The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$b_{i,1}$$$, $$$b_{i,2}$$$, ..., $$$b_{i,m}$$$ ($$$1 \le b_{i,j} \le 10^9$$$). It is guaranteed that the sum of $$$n\cdot m$$$ over all test cases does not exceed $$$10^4$$$.

For each test case, output $$$n$$$ lines. The $$$j$$$-th number in the $$$i$$$-th line should contain the length of the path that runner $$$j$$$ chooses to run from checkpoint $$$i-1$$$ to checkpoint $$$i$$$. There should be exactly $$$m$$$ integers in the $$$i$$$-th line and these integers should form a permuatation of $$$b_{i, 1}$$$, ..., $$$b_{i, m}$$$ for all $$$1\le i\le n$$$. If there are multiple answers, print any.

NoteIn the first case, the sum of tiredness is $$$\min(2,5) + \min(3,3) + \min(4,1) = 6$$$.  In the second case, the sum of tiredness is $$$\min(2,4,3) + \min(3,1,5) = 3$$$.

import scala.collection._
import scala.collection.mutable.TreeSet
import scala.collection.mutable.HashSet
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util._

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

    (0 until t).foreach( _ => {
      val line = readLine().split(" ").map(v => v.toInt)
      val n = line(0)
      val m = line(1)

      val set = TreeSet[(Int, Int, Int)]()(Ordering[(Int, Int, Int)].on((x: (Int, Int, Int)) => (x._1, x._2, x._3)))
      val sets = Array.ofDim[TreeSet[(Int, Int, Int)]](n)

      for (i <- 0 until n) {
        var count = -1
        val routes = readLine().split(" ").map(v => {
          count += 1
          (v.toInt, i, count)
        })

        for (v <- routes) {
          set.add(v)
        }

        sets(i) = TreeSet[(Int, Int, Int)]()

        for (v <- routes) {
          sets(i).add(v)
        }
      }

      val used = mutable.HashSet[(Int, Int, Int)]()
      for (i <- 0 until m) {
        val e = set.head
        used += e
        set.remove(e)
      }

      val runnerpath = Array.ofDim[ArrayBuffer[Int]](m)
      val runnerfoundopt = Array.ofDim[Boolean](m)
      (0 until m).foreach(v => runnerpath(v) = ArrayBuffer[Int]())
      (0 until m).foreach(v => runnerfoundopt(v) = false)

      for (runner <- 0 until m) {
        for (node <- 0 until n) {
          var continue = true
          if (!runnerfoundopt(runner)) {
            for (p <- sets(node) ; if continue) {
              if (used.contains(p)) {
                runnerpath(runner) += p._1
                runnerfoundopt(runner) = true
                used -= p
                sets(node).remove(p)
                continue = false
              }
            }
          }

          if (continue) {
            for (p <- sets(node) ; if continue) {
              if (!used.contains(p)) {
                runnerpath(runner) += p._1
                sets(node).remove(p)
                continue = false
              }
            }
          }
        }
      }

      for (node <- 0 until n) {
        for (runner <- 0 until m) {
          print(runnerpath(runner)(node))

          if (runner != m - 1) {
            print(" ")
          }
        }
        println()
      }
    })
  }
}


You are given two integers $$$x$$$ and $$$y$$$. You want to choose two strictly positive (greater than zero) integers $$$a$$$ and $$$b$$$, and then apply the following operation to $$$x$$$ exactly $$$a$$$ times: replace $$$x$$$ with $$$b \cdot x$$$.You want to find two positive integers $$$a$$$ and $$$b$$$ such that $$$x$$$ becomes equal to $$$y$$$ after this process. If there are multiple possible pairs, you can choose any of them. If there is no such pair, report it.For example:   if $$$x = 3$$$ and $$$y = 75$$$, you may choose $$$a = 2$$$ and $$$b = 5$$$, so that $$$x$$$ becomes equal to $$$3 \cdot 5 \cdot 5 = 75$$$;  if $$$x = 100$$$ and $$$y = 100$$$, you may choose $$$a = 3$$$ and $$$b = 1$$$, so that $$$x$$$ becomes equal to $$$100 \cdot 1 \cdot 1 \cdot 1 = 100$$$;  if $$$x = 42$$$ and $$$y = 13$$$, there is no answer since you cannot decrease $$$x$$$ with the given operations.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of one line containing two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 100$$$).

If it is possible to choose a pair of positive integers $$$a$$$ and $$$b$$$ so that $$$x$$$ becomes $$$y$$$ after the aforementioned process, print these two integers. The integers you print should be not less than $$$1$$$ and not greater than $$$10^9$$$ (it can be shown that if the answer exists, there is a pair of integers $$$a$$$ and $$$b$$$ meeting these constraints). If there are multiple such pairs, print any of them. If it is impossible to choose a pair of integers $$$a$$$ and $$$b$$$ so that $$$x$$$ becomes $$$y$$$, print the integer $$$0$$$ twice.

 import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)
  // ======================================
  def solve(x: Int, y: Int) = {
    if (x > y) println("0 0")
    else if (x == y) println("1 1")
    else if (y % x != 0) println("0 0")
    else println(s"1 ${y / x} ")

  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt

    for (
      i <- 0 until cases;
      a = rsi()
    ) solve(a(0), a(1))
  }
}


Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.Return the maximum number of rows that she can make completely clean.

The first line of input will be a single integer n (1 ≤ n ≤ 100). The next n lines will describe the state of the room. The i-th line will contain a binary string with n characters denoting the state of the i-th row of the room. The j-th character on this line is '1' if the j-th square in the i-th row is clean, and '0' if it is dirty.

The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.

NoteIn the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.In the second sample, everything is already clean, so Ohana doesn't need to do anything.

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter

object CF554B {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

  def next():String = {
      while (!st.hasMoreTokens()){
        val currentLine = reader.readLine
            st=new StringTokenizer(currentLine)
      }
      return st.nextToken
  }

  def nextInt():Int = {
      return next.toInt
  }

  def nextLong():Long = {
      return next.toLong
  }
  def nextDouble:Double = {
          return next.toDouble
      }
  }

  def main(args: Array[String]): Unit = {
    val in = new InputReader(System.in)
    val m = in.nextInt()
    val a = Array.fill(m){ in.next() }
    val cntEquals = a.map{ s => a.filter { x => x.equals(s) }.size }
    println( maxElem(cntEquals) )
  }

  def maxElem(cntEquals: Array[Int]) : Int= {
    var max = 0
    for( i <- 0 until cntEquals.length ) {
      max = Math.max(max,cntEquals(i))
    }
    return max
  }
}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter
import java.io.FileInputStream
import java.io.PrintStream
import java.io.FileOutputStream

object CF554B {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

  def next():String = {
      while (!st.hasMoreTokens()){
        val currentLine = reader.readLine
            st=new StringTokenizer(currentLine)
      }
      return st.nextToken
  }

  def nextInt():Int = {
      return next.toInt
  }

  def nextLong():Long = {
      return next.toLong
  }
  def nextDouble:Double = {
          return next.toDouble
      }
  }

  def main(args: Array[String]): Unit = {
    val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
    var in = new InputReader(System.in)
    var out = System.out
    if ( !isOnlineJudge ) {
      in = new InputReader(new FileInputStream("input.txt"))
      out = new PrintStream(new FileOutputStream("output.txt"))
    }

    val m = in.nextInt()
    val a = Array.fill(m){ in.next() }
    val eqs = a.map{ s => a.filter { x => x.equals(s) }.size }
    out.println(eqs.foldLeft(0)( (mx,x) => if ( x > mx) x else mx))
  }

}

object B554 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(read)
    val map = cu.Map[String, Int]().withDefaultValue(0)
    in.foreach(x => map(x) += 1)
    println(map.values.max)
  }

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

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

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

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

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

}

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

import scala.collection.mutable

object B {

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

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

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

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

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

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

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

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

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

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

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

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    var ans = 0
    val arr = new Array[Array[Char]](n)
    for (i <- 0 until n) {
      arr(i) = next.toCharArray
    }
    for (i <- 0 until n) {
      var cnt = 0
      for (j <- 0 until n) {
        if (arr(i)(j) == '1')
          cnt += 1
      }
      if (cnt == n) {
        ans += 1
      }
    }
    val diff = new MultiHashSet[String]
    for (i <- 0 until n) {
      diff.add(new String(arr(i)))
    }
    val it = diff.map.iterator
    while (it.hasNext) {
      ans = Math.max(ans, it.next()._2)
    }
    out.println(ans)
    return 0
  }
}

object _554B extends CodeForcesApp {
  import scala.annotation.tailrec, scala.collection.mutable

  override type Input = IndexedSeq[IndexedSeq[Boolean]]
  override type Output = Int

  val clean = true
  val dirty = !clean

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    val n = nextInt
    nextLine
    Array.fill(n) {nextLine map {
      case '0' => clean
      case '1' => dirty
    }}
  }

  override def solve(input: Input) = {
    val needed = input map {row =>
      for {
        (room, index) <- row.zipWithIndex if room == dirty
      } yield index
    }
    val collisions = needed.groupBy(_.toSet).mapValues(_.size)
    collisions.values.max
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  import CodeForcesApp._
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
/********************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
}
/**********************************[ lib ]************************************/
object CodeForcesApp {
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = collection.mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type ==>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None
/*******************************[ constants ]*********************************/
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus = 1000000007
}

object _554B extends CodeForcesApp {
  import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable

  override type Input = List[String]
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(next)
  }

  override def solve(input: Input) = input.groupBy(identity).mapValues(_.size).values.max

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  import CodeForcesApp._
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
}
/********************************[ lib ]************************************/
object CodeForcesApp {
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = collection.mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type ==>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /********************************[ constants ]************************************/
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus = 1000000007
}

object _554B extends CodeForcesApp {
  import scala.annotation.tailrec, scala.collection.mutable

  override type Input = IndexedSeq[IndexedSeq[Boolean]]
  override type Output = Int

  val clean = true
  val dirty = !clean

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    val n = nextInt
    nextLine
    Array.fill(n) {nextLine.map(_ == '1')}
  }

  override def solve(input: Input) = {
    val needed = input map {row =>
      for {
        (room, index) <- row.zipWithIndex if room == clean
      } yield index
    }
    val collisions = needed.groupBy(_.toSet).mapValues(_.size)
    collisions.values.max
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  import CodeForcesApp._
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
}
/********************************[ lib ]************************************/
object CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type ==>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
}


You are given an array of n elements, you must make it a co-prime array in as few moves as possible.In each move you can insert any positive integral number you want not greater than 109 in any place in the array.An array is co-prime if any two adjacent numbers of it are co-prime.In the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of elements in the given array. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

Print integer k on the first line — the least number of elements needed to add to the array a to make it co-prime. The second line should contain n + k integers aj — the elements of the array a after adding k elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array a by adding k elements to it. If there are multiple answers you can print any one of them.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)

  def factorize(a : Int): Set[Int] = {
    if (a == 1) Set.empty
    else if (a % 2 == 0) Set(2) ++ factorize(a / 2)
    else (3 to Math.sqrt(a).toInt by 2)
      .find(i => a % i == 0)
      .map(i => Set(i) ++ factorize(a / i))
      .getOrElse(Set(a))
  }

  if (n == 1) {
    println(0)
    println(data.head)
  }
  else {
    val factors = data.map(i => factorize(i))
    val result = data.head :: factors.zip(data).sliding(2).flatMap{
      case Array((s1, v1), (s2, v2)) =>
        if (s1.intersect(s2).nonEmpty)
          List(1 , v2)
        else
          List(v2)
    }.toList
    println(result.length - n)
    println(result.mkString(" "))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)

  def factorize(a : Int): Set[Int] = {
    if (a % 2 == 0) Set(a) ++ factorize(a / 2)
    else (3 to Math.sqrt(a).toInt by 2).find(i => a % i == 0).map(i => Set(i) ++ factorize(a / i)).getOrElse(Set.empty)
  }

  if (n == 1) {
    println(0)
    println(data.head)
  }
  else {
    val factors = data.map(i => factorize(i))
    val result = data.head :: factors.zip(data).sliding(2).flatMap{
      case Array((s1, v1), (s2, v2)) =>
        if (s1.intersect(s2).nonEmpty)
          List(1 , v2)
        else
          List(v2)
    }.toList
    println(result.length - n)
    println(result.mkString(" "))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)

  def factorize(a : Int): Set[Int] = {
    if (a % 2 == 0) Set(a) ++ factorize(a / 2)
    else (3 to a by 2).find(i => a % i == 0).map(i => Set(i) ++ factorize(a / i)).getOrElse(Set.empty)
  }

  if (n == 1) {
    println(0)
    println(data.head)
  }
  else {
    val factors = data.map(i => factorize(i))
    val result = data.head :: factors.zip(data).sliding(2).flatMap{
      case Array((s1, v1), (s2, v2)) =>
        if (s1.intersect(s2).nonEmpty)
          List(1 , v2)
        else
          List(v2)
    }.toList
    println(result.length - n)
    println(result.mkString(" "))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)

  def factorize(a : Int): Set[Int] = {
    if (a % 2 == 0) Set(a) ++ factorize(a / 2)
    else (3 to a by 2).find(i => a % i == 0).map(i => Set(i) ++ factorize(a / i)).getOrElse(Set.empty)
  }

  if (n == 1) {
    println(1)
    println(data.head)
  }
  else {
    val factors = data.map(i => factorize(i))
    val result = data.head :: factors.zip(data).sliding(2).flatMap{
      case Array((s1, v1), (s2, v2)) =>
        if (s1.intersect(s2).nonEmpty)
          List(1 , v2)
        else
          List(v2)
    }.toList
    println(result.length - n)
    println(result.mkString(" "))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)

  def factorize(a : Int): Set[Int] = {
    if (a == 1) Set.empty
    else if (a % 2 == 0) Set(a) ++ factorize(a / 2)
    else (3 to Math.sqrt(a).toInt by 2)
      .find(i => a % i == 0)
      .map(i => Set(i) ++ factorize(a / i))
      .getOrElse(Set(a))
  }

  if (n == 1) {
    println(0)
    println(data.head)
  }
  else {
    val factors = data.map(i => factorize(i))
    val result = data.head :: factors.zip(data).sliding(2).flatMap{
      case Array((s1, v1), (s2, v2)) =>
        if (s1.intersect(s2).nonEmpty)
          List(1 , v2)
        else
          List(v2)
    }.toList
    println(result.length - n)
    println(result.mkString(" "))
  }
}


Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.Help Yaroslav.

The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the array elements.

In the single line print "YES" (without the quotes) if Yaroslav can obtain the array he needs, and "NO" (without the quotes) otherwise.

NoteIn the first sample the initial array fits well.In the second sample Yaroslav can get array: 1, 2, 1. He can swap the last and the second last elements to obtain it.In the third sample Yarosav can't get the array he needs.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").groupBy(x => x).map(_._2.length)
  val max = data.max
  if (data.max == 1)
    println("YES")
  else if (n == 2 && data.max == 2)
    println("NO")
  else if (max * 2 > data.sum + 1)
    println("NO")
  else
    println("YES")
}

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

object P296A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  def solve(): String = A.groupBy(identity).toSeq.map(_._2.size).sortWith(_ > _).toList match {
      case 1 :: Nil    => "YES"
      case _ :: Nil    => "NO"
      case x :: y :: _ => if (x < N / 2 + N % 2 + 1) "YES"
                          else "NO"
    }

  out.println(solve)
  out.close
}

import java.util.Scanner

object YarPerm {
  def main(args: Array[String]) {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    val nums = List.fill(n)(scan.nextInt)
    val d = nums.distinct
    val f = d.map(x => nums.count(y => y== x))
    val m = f.max
    println(if (2*m <=n || (n%2==1 && 2*m==n+1))"YES" else "NO")
  }
}

object A {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);

  def main(args: Array[String]) {
    var Array(n) = READ;
    var a:Array[Int] = READ;
    a = a map(x=>a.count(x==_));
    a = a filter(_ > (n+1)/2);

    println(if (a isEmpty) "YES" else "NO");
  }
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)
  def readLine = reader.readLine

  val n = readInt
  val a = readInts
  def ans = if(n - a.groupBy(x => x).values.map(_.size).max < n / 2) "NO" else "YES"

  def main(a: Array[String]) {
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)
    val half = (a.size + 1) / 2
    if (map.values.find(_ > half).isDefined) println("NO")
    else println("YES")
  }
}

object CF179Div2A {
  def main(args:Array[String]){
    val n = readLine.toInt;
    val ar = readLine.split(" ").map(_.toInt);
    val ex = (1 to 1000).map(x=> ar.filter(_ == x).length).forall(_ <= (n+1)/2);
    if(ex) println("YES") else println("NO");
  }
}

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

object P296A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  def solve(): String = A.groupBy(identity).toSeq.sortWith(_._1 > _._1).toList match {
      case (1, _) :: Nil => "YES"
      case (x, y) :: _   => if (y.size < N / 2 + N % 1 + 1) "YES"
                            else "NO"
  }

  out.println(solve)
  out.close
}

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

object P296A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  def solve(): String = A.groupBy(identity).toSeq.sortWith(_._1 < _._1).toList match {
      case (1, _) :: Nil => "YES"
      case (x, _) :: _   => if (x < N / 2 + N % 1 + 1) "YES"
                            else "NO"
  }

  out.println(solve)
  out.close
}

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

object P296A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  def solve(): String = A.groupBy(identity).toSeq.map(_._2.size).sortWith(_ > _).toList match {
      case _ :: Nil    => "YES"
      case x :: y :: _ => if (x < N / 2 + N % 1 + 1) "YES"
                          else "NO"
    }

  out.println(solve)
  out.close
}

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

object P296A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  def solve(): String = A.groupBy(identity).toSeq.map(_._2.size).sortWith(_ > _).toList match {
      case _ :: Nil    => "YES"
      case x :: y :: _ => {
        if (x < N / 2 + N % 2 + 1) "YES"
        else "NO"
      }
    }

  out.println(solve)
  out.close
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)
    val half = (a.size + 1) / 2
    if (map.values.find(_ > half).isDefined) println("NO")
    else println("NO")
  }
}


You are given a permutation $$$p_1, p_2, \dots , p_n$$$ (an array where each integer from $$$1$$$ to $$$n$$$ appears exactly once). The weight of the $$$i$$$-th element of this permutation is $$$a_i$$$.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements $$$p_1, p_2, \dots , p_k$$$, the second — $$$p_{k+1}, p_{k+2}, \dots , p_n$$$, where $$$1 \le k < n$$$.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay $$$a_i$$$ dollars to move the element $$$p_i$$$.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if $$$p = [3, 1, 2]$$$ and $$$a = [7, 1, 4]$$$, then the optimal strategy is: separate $$$p$$$ into two parts $$$[3, 1]$$$ and $$$[2]$$$ and then move the $$$2$$$-element into first set (it costs $$$4$$$). And if $$$p = [3, 5, 1, 6, 2, 4]$$$, $$$a = [9, 1, 9, 9, 1, 9]$$$, then the optimal strategy is: separate $$$p$$$ into two parts $$$[3, 5, 1]$$$ and $$$[6, 2, 4]$$$, and then move the $$$2$$$-element into first set (it costs $$$1$$$), and $$$5$$$-element into second set (it also costs $$$1$$$).Calculate the minimum number of dollars you have to spend.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of permutation. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots , p_n$$$ ($$$1 \le p_i \le n$$$). It's guaranteed that this sequence contains each element from $$$1$$$ to $$$n$$$ exactly once. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print one integer — the minimum number of dollars you have to spend.

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)

    val n = in.nextInt()
    val p: Array[Int] = (1 to n).map(_ => in.nextInt()-1).toArray
    val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray

    val pos: Array[Int] = Array.fill(n)(0)
    p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}

    val st = new SegmentTree(n)

    val initialBuild = w.scanLeft(0L)(_ + _).tail

    st.build(initialBuild)

    val initialRes = st.query(0,n-1)

    val res = (0 until n).foldLeft(initialRes){
      case (currentRes, v) => {
        val k = pos(v)
        //0 k> += w(k)
        //[k oo] -= w(k)

        if(k>0)
          st.update(0,k,w(k))
        if(k<n)
          st.update(k,n,-w(k))

        Math.min(currentRes,st.query(0,n-1))

      }
    }
    out.println(res)

  }

  trait Node[A,T]{ self: A =>
    def + (other: A): A
    def value: T
    def addLazy(lazyVal: Long): A
  }
  trait LazyValue[A,L]{ self: A =>
    def value: Option[L]
    def + (other: A): A
  }

  class SegmentTree(maxN: Int){
    val defaultLazy = 0L
    val minimos = Array.fill(maxN*4)(0L)

    val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)
    var N: Int = 0
    def build(nodes: Array[Long]): Unit = {
      N = nodes.length
      build(nodes,0,N,0)
      lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)
    }
    private def build(nodes: Array[Long], l: Int, r: Int, v: Int): Unit ={

      if(l+1 == r){
        minimos(v) = nodes(l)

      }else{
        val m = (l+r)/2
        build(nodes,l,m,v*2+1)
        build(nodes,m,r,v*2+2)
        minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))

      }
    }

    def query(left: Int, right: Int): Long = query(0,0,N,left,right)
    private def query(v: Int, l: Int, r: Int, L: Int, R: Int): Long = {

      if(L >= R){
        Long.MaxValue
      }else{
        push(v,l,r)
        if(l == l && r == R)
          minimos(v)
        else{
          val mid = (l+r)/2
          val a = query(v*2+1,l,mid,L,Math.min(R,mid))
          val b = query(v*2+2,mid,r,Math.max(L,mid),R)
          Math.min(a,b)
        }
      }

    }

    def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)

    private def push(v: Int, l: Int, r: Int): Unit = {
      if(lazyValue(v) != 0){
        if(r-l > 1){
          lazyValue(v*2+1) += lazyValue(v)
          minimos(v*2+1) += lazyValue(v)

          lazyValue(v*2+2) += lazyValue(v)
          minimos(v*2+2) += lazyValue(v)

        }
        lazyValue(v) = 0
      }

    }

    private def update(v: Int, l: Int, r: Int, L: Int, R: Int, x: Long): Unit = {

      if(L < R){

        if(l == L && r == R){
          lazyValue(v) += x
          minimos(v) += x
          push(v,l,r)
        }else{

          push(v,l,r)
          val mid = (l+r)/2
          update(v*2+1,l,mid,L,Math.min(mid,R),x)
          update(v*2+2,mid,r,Math.max(mid,L),R,x)
          minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))

        }

      }

    }

  }

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

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)

    val n = in.nextInt()
    val p: Array[Int] = (1 to n).map(_ => in.nextInt()-1).toArray
    val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray

    val pos: Array[Int] = Array.fill(n)(0)
    p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}

    val st = new SegmentTree(n)

    val initialBuild = w.scanLeft(0L)(_ + _).tail

    st.build(initialBuild)

    val res = (0 until n).foldLeft(Long.MaxValue){
      case (currentRes, v) => {
        val k = pos(v)
        //0 k> += w(k)
        //[k oo] -= w(k)

        if(k>0)
          st.update(0,k,w(k))
        if(k<n)
          st.update(k,n,-w(k))

        Math.min(currentRes,st.query(0,n-1))

      }
    }
    out.println(res)

  }

  trait Node[A,T]{ self: A =>
    def + (other: A): A
    def value: T
    def addLazy(lazyVal: Long): A
  }
  trait LazyValue[A,L]{ self: A =>
    def value: Option[L]
    def + (other: A): A
  }

  class SegmentTree(maxN: Int){
    val defaultLazy = 0L
    val minimos = Array.fill(maxN*4)(0L)

    val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)
    var N: Int = 0
    def build(nodes: Array[Long]): Unit = {
      N = nodes.length
      build(nodes,0,N,0)
      lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)
    }
    private def build(nodes: Array[Long], l: Int, r: Int, v: Int): Unit ={

      if(l+1 == r){
        minimos(v) = nodes(l)

      }else{
        val m = (l+r)/2
        build(nodes,l,m,v*2+1)
        build(nodes,m,r,v*2+2)
        minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))

      }
    }

    def query(left: Int, right: Int): Long = query(0,0,N,left,right)
    private def query(v: Int, l: Int, r: Int, L: Int, R: Int): Long = {

      if(L >= R){
        Long.MaxValue
      }else{
        push(v,l,r)
        if(l == l && r == R)
          minimos(v)
        else{
          val mid = (l+r)/2
          val a = query(v*2+1,l,mid,L,Math.min(R,mid))
          val b = query(v*2+2,mid,r,Math.max(L,mid),R)
          Math.min(a,b)
        }
      }

    }

    def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)

    private def push(v: Int, l: Int, r: Int): Unit = {
      if(lazyValue(v) != 0){
        if(r-l > 1){
          lazyValue(v*2+1) += lazyValue(v)
          minimos(v*2+1) += lazyValue(v)

          lazyValue(v*2+2) += lazyValue(v)
          minimos(v*2+2) += lazyValue(v)

        }
        lazyValue(v) = 0
      }

    }

    private def update(v: Int, l: Int, r: Int, L: Int, R: Int, x: Long): Unit = {

      if(L < R){

        if(l == L && r == R){
          lazyValue(v) += x
          minimos(v) += x
          push(v,l,r)
        }else{

          push(v,l,r)
          val mid = (l+r)/2
          update(v*2+1,l,mid,L,Math.min(mid,R),x)
          update(v*2+2,mid,r,Math.max(mid,L),R,x)
          minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))

        }

      }

    }

  }

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

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)

    val n = in.nextInt()
    val p: Array[Int] = (1 to n).map(_ => in.nextInt()-1).toArray
    val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray

    val pos: Array[Int] = Array.fill(n)(0)
    p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}

    val st = new SegmentTree(n)

    val initialBuild = w.scanLeft(0L)(_ + _).tail

    st.build(initialBuild)

    val res = (0 until n).foldLeft(Long.MaxValue){
      case (currentRes, v) => {
        val k = pos(v)
        //0 k> += w(k)
        //[k oo] -= w(k)

        if(k>0)
          st.update(0,k,w(k))
        if(k<n)
          st.update(k,n,-w(k))

        Math.min(currentRes,st.query(0,n-1))

      }
    }
    out.println(res)

  }

  trait Node[A,T]{ self: A =>
    def + (other: A): A
    def value: T
    def addLazy(lazyVal: Long): A
  }
  trait LazyValue[A,L]{ self: A =>
    def value: Option[L]
    def + (other: A): A
  }

  class SegmentTree(maxN: Int){
    val defaultLazy = 0L
    val minimos = Array.fill(maxN*4)(0L)

    val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)
    var N: Int = 0
    def build(nodes: Array[Long]): Unit = {
      N = nodes.length
      build(nodes,0,N,0)
      lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)
    }
    private def build(nodes: Array[Long], left: Int, right: Int, n: Int): Unit ={

      if(left+1 == right){
        minimos(n) = nodes(left)

      }else{
        val m = (left+right)/2
        build(nodes,left,m,n*2+1)
        build(nodes,m,right,n*2+2)
        minimos(n) = Math.min(minimos(n*2+1),minimos(n*2+2))

      }
    }

    def query(left: Int, right: Int): Long = query(0,0,N,left,right)
    private def query(n: Int,n0: Int, nn: Int, left: Int, right: Int): Long = {

      minimos(n) = minimos(n) + lazyValue(n)
//      override def addLazy(lazyVal: Long): MinSumLengthNode = MinSumLengthNode(min+lazyVal,sum+lazyVal*len,len)

      if(n0+1 != nn){
        push(n)
      }

      lazyValue(n) = defaultLazy

      if(n0 == left && nn == right) {

        minimos(n)

      } else{
        val m = (n0+nn)/2
        if(left >= m){
          query(n*2+2,m,nn,left,right)
        }else{
          if( right <= m){
            query(n*2+1,n0,m,left,right)
          }else{
            val a = query(n*2+1,n0,m,left,m)
            val b = query(n*2+2,m,nn,m,right)
            Math.min(a,b)
          }
        }

      }
    }

    def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)

    private def push(n: Int): Unit = {
      lazyValue(n*2+1) = lazyValue(n*2+1) + lazyValue(n)
      lazyValue(n*2+2) = lazyValue(n*2+2) + lazyValue(n)

    }

    private def update(n: Int,n0: Int, nn: Int, left: Int, right: Int, valueToUpdate: Long): Unit = {

      minimos(n) = minimos(n) + lazyValue(n)

      if(n0+1 != nn){
        push(n)
      }

      lazyValue(n) = defaultLazy

      if(n0 == left && nn == right) {
        minimos(n) = minimos(n) + valueToUpdate

        if(n0+1 != nn){
          lazyValue(n) = valueToUpdate
          push(n)
          lazyValue(n) = defaultLazy
        }

      } else{
        val m = (n0+nn)/2

        push(n)

        if(left >= m){

          update(n*2+2,m,nn,left,right,valueToUpdate)

        }else{
          if( right <= m){

            update(n*2+1,n0,m,left,right,valueToUpdate)
          }else{
            update(n*2+1,n0,m,left,m,valueToUpdate)
            update(n*2+2,m,nn,m,right,valueToUpdate)

          }
        }
        val a0 = minimos(n*2+1) + lazyValue(n*2+1)
        val a1 = minimos(n*2+2) + lazyValue(n*2+2)

        minimos(n) = Math.min(a0,a1)
      }

    }

  }

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

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  //solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)

    val n = in.nextInt()
    val p: Array[Int] = (1 to n).map(_ => in.nextInt()).toArray
    val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray

    val pos: Array[Int] = Array.fill(n+1)(0)
    p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}

    val st = new SegmentTree(n+2)

    val initialBuild = w.scanLeft(0L)(_ + _).tail

    st.build(initialBuild)

    val res = (1 to n).foldLeft(Long.MaxValue){
      case (currentRes, v) => {
        val k = pos(v)
        //0 k> += w(k)
        //[k oo] -= w(k)

        if(k>0)
          st.update(0,k,w(k))
        if(k<n)
          st.update(k,n,-w(k))

        Math.min(currentRes,st.query(0,n-1))

      }
    }
    out.println(res)

  }

  trait Node[A,T]{ self: A =>
    def + (other: A): A
    def value: T
    def addLazy(lazyVal: Long): A
  }
  trait LazyValue[A,L]{ self: A =>
    def value: Option[L]
    def + (other: A): A
  }

  class SegmentTree(maxN: Int){
    val defaultLazy = 0L
    val minimos = Array.fill(maxN*4+2)(0L)
    val sumas = Array.fill(maxN*4+2)(0L)
    val longitudes = Array.fill(maxN*4+2)(0)

    val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)
    var N: Int = 0
    def build(nodes: Array[Long]): Unit = {
      N = nodes.length
      build(nodes,0,N,0)
      lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)
    }
    private def build(nodes: Array[Long], left: Int, right: Int, n: Int): Unit ={

      if(left+1 == right){
        minimos(n) = nodes(left)
        sumas(n) = nodes(left)
        longitudes(n) = 1
      }else{
        val m = (left+right)/2
        build(nodes,left,m,n*2+1)
        build(nodes,m,right,n*2+2)
        minimos(n) = Math.min(minimos(n*2+1),minimos(n*2+2))
        sumas(n) = sumas(n*2+1)+sumas(n*2+2)
        longitudes(n) = longitudes(n*2+1)+longitudes(n*2+2)
      }
    }

    def query(left: Int, right: Int): Long = query(0,0,N,left,right)
    private def query(n: Int,n0: Int, nn: Int, left: Int, right: Int): Long = {

      minimos(n) = minimos(n) + lazyValue(n)
      sumas(n) = sumas(n)+lazyValue(n)*longitudes(n)
//      override def addLazy(lazyVal: Long): MinSumLengthNode = MinSumLengthNode(min+lazyVal,sum+lazyVal*len,len)

      if(n0+1 != nn){
        push(n)
      }

      lazyValue(n) = defaultLazy

      if(n0 == left && nn == right) {

        minimos(n)

      } else{
        val m = (n0+nn)/2
        if(left >= m){
          query(n*2+2,m,nn,left,right)
        }else{
          if( right <= m){
            query(n*2+1,n0,m,left,right)
          }else{
            val a = query(n*2+1,n0,m,left,m)
            val b = query(n*2+2,m,nn,m,right)
            Math.min(a,b)
          }
        }

      }
    }

    def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)

    private def push(n: Int): Unit = {
      lazyValue(n*2+1) = lazyValue(n*2+1) + lazyValue(n)
      lazyValue(n*2+2) = lazyValue(n*2+2) + lazyValue(n)

    }

    private def update(n: Int,n0: Int, nn: Int, left: Int, right: Int, valueToUpdate: Long): Unit = {

      minimos(n) = minimos(n) + lazyValue(n)
      sumas(n) = sumas(n)+lazyValue(n)*longitudes(n)

      if(n0+1 != nn){
        push(n)
      }

      lazyValue(n) = defaultLazy

      if(n0 == left && nn == right) {
        minimos(n) = minimos(n) + valueToUpdate
        sumas(n) = sumas(n)+valueToUpdate*longitudes(n)

        if(n0+1 != nn){
          lazyValue(n) = valueToUpdate
          push(n)
          lazyValue(n) = defaultLazy
        }

      } else{
        val m = (n0+nn)/2

        push(n)

        if(left >= m){

          update(n*2+2,m,nn,left,right,valueToUpdate)

        }else{
          if( right <= m){

            update(n*2+1,n0,m,left,right,valueToUpdate)
          }else{
            update(n*2+1,n0,m,left,m,valueToUpdate)
            update(n*2+2,m,nn,m,right,valueToUpdate)

          }
        }
        val a0 = minimos(n*2+1) + lazyValue(n*2+1)
        val a1 = minimos(n*2+2) + lazyValue(n*2+2)

        val b0 = sumas(n*2+1)+longitudes(n*2+1)*lazyValue(n*2+1)
        val b1 = sumas(n*2+2)+longitudes(n*2+2)*lazyValue(n*2+2)

        minimos(n) = Math.min(a0,a1)
        sumas(n) = b0+b1
      }

    }

  }

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

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)

    val n = in.nextInt()
    val p: Array[Int] = (1 to n).map(_ => in.nextInt()).toArray
    val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray

    val pos: Array[Int] = Array.fill(n+1)(0)
    p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}

    val st = new SegmentTree(n+2)

    val initialBuild = w.scanLeft(0L)(_ + _).tail

    st.build(initialBuild)

    val res = (1 to n).foldLeft(Long.MaxValue){
      case (currentRes, v) => {
        val k = pos(v)
        //0 k> += w(k)
        //[k oo] -= w(k)

        if(k>0)
          st.update(0,k,w(k))
        if(k<n)
          st.update(k,n,-w(k))

        Math.min(currentRes,st.query(0,n-1))

      }
    }
    out.println(res)

  }

  trait Node[A,T]{ self: A =>
    def + (other: A): A
    def value: T
    def addLazy(lazyVal: Long): A
  }
  trait LazyValue[A,L]{ self: A =>
    def value: Option[L]
    def + (other: A): A
  }

  class SegmentTree(maxN: Int){
    val defaultLazy = 0L
    val minimos = Array.fill(maxN*4+2)(0L)
    val sumas = Array.fill(maxN*4+2)(0L)
    val longitudes = Array.fill(maxN*4+2)(0)

    val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)
    var N: Int = 0
    def build(nodes: Array[Long]): Unit = {
      N = nodes.length
      build(nodes,0,N,0)
      lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)
    }
    private def build(nodes: Array[Long], left: Int, right: Int, n: Int): Unit ={

      if(left+1 == right){
        minimos(n) = nodes(left)
        sumas(n) = nodes(left)
        longitudes(n) = 1
      }else{
        val m = (left+right)/2
        build(nodes,left,m,n*2+1)
        build(nodes,m,right,n*2+2)
        minimos(n) = Math.min(minimos(n*2+1),minimos(n*2+2))
        sumas(n) = sumas(n*2+1)+sumas(n*2+2)
        longitudes(n) = longitudes(n*2+1)+longitudes(n*2+2)
      }
    }

    def query(left: Int, right: Int): Long = query(0,0,N,left,right)
    private def query(n: Int,n0: Int, nn: Int, left: Int, right: Int): Long = {

      minimos(n) = minimos(n) + lazyValue(n)
      sumas(n) = sumas(n)+lazyValue(n)*longitudes(n)
//      override def addLazy(lazyVal: Long): MinSumLengthNode = MinSumLengthNode(min+lazyVal,sum+lazyVal*len,len)

      if(n0+1 != nn){
        push(n)
      }

      lazyValue(n) = defaultLazy

      if(n0 == left && nn == right) {

        minimos(n)

      } else{
        val m = (n0+nn)/2
        if(left >= m){
          query(n*2+2,m,nn,left,right)
        }else{
          if( right <= m){
            query(n*2+1,n0,m,left,right)
          }else{
            val a = query(n*2+1,n0,m,left,m)
            val b = query(n*2+2,m,nn,m,right)
            Math.min(a,b)
          }
        }

      }
    }

    def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)

    private def push(n: Int): Unit = {
      lazyValue(n*2+1) = lazyValue(n*2+1) + lazyValue(n)
      lazyValue(n*2+2) = lazyValue(n*2+2) + lazyValue(n)

    }

    private def update(n: Int,n0: Int, nn: Int, left: Int, right: Int, valueToUpdate: Long): Unit = {

      minimos(n) = minimos(n) + lazyValue(n)
      sumas(n) = sumas(n)+lazyValue(n)*longitudes(n)

      if(n0+1 != nn){
        push(n)
      }

      lazyValue(n) = defaultLazy

      if(n0 == left && nn == right) {
        minimos(n) = minimos(n) + valueToUpdate
        sumas(n) = sumas(n)+valueToUpdate*longitudes(n)

        if(n0+1 != nn){
          lazyValue(n) = valueToUpdate
          push(n)
          lazyValue(n) = defaultLazy
        }

      } else{
        val m = (n0+nn)/2

        push(n)

        if(left >= m){

          update(n*2+2,m,nn,left,right,valueToUpdate)

        }else{
          if( right <= m){

            update(n*2+1,n0,m,left,right,valueToUpdate)
          }else{
            update(n*2+1,n0,m,left,m,valueToUpdate)
            update(n*2+2,m,nn,m,right,valueToUpdate)

          }
        }
        val a0 = minimos(n*2+1) + lazyValue(n*2+1)
        val a1 = minimos(n*2+2) + lazyValue(n*2+2)

        val b0 = sumas(n*2+1)+longitudes(n*2+1)*lazyValue(n*2+1)
        val b1 = sumas(n*2+2)+longitudes(n*2+2)*lazyValue(n*2+2)

        minimos(n) = Math.min(a0,a1)
        sumas(n) = b0+b1
      }

    }

  }

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

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  //solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)

    val n = in.nextInt()
    val p: Array[Int] = (1 to n).map(_ => in.nextInt()-1).toArray
    val w: Array[Long] = (1 to n).map(_ => in.nextLong()).toArray

    val pos: Array[Int] = Array.fill(n)(0)
    p.zipWithIndex.foreach{case (pi,i) => pos(pi) = i}

    val st = new SegmentTree(n)

    val initialBuild = w.scanLeft(0L)(_ + _).tail

    st.build(initialBuild)

    val res = (0 until n).foldLeft(Long.MaxValue){
      case (currentRes, v) => {
        val k = pos(v)
        //0 k> += w(k)
        //[k oo] -= w(k)

        if(k>0)
          st.update(0,k,w(k))
        if(k<n)
          st.update(k,n,-w(k))

        Math.min(currentRes,st.query(0,n-1))

      }
    }
    out.println(res)

  }

  trait Node[A,T]{ self: A =>
    def + (other: A): A
    def value: T
    def addLazy(lazyVal: Long): A
  }
  trait LazyValue[A,L]{ self: A =>
    def value: Option[L]
    def + (other: A): A
  }

  class SegmentTree(maxN: Int){
    val defaultLazy = 0L
    val minimos = Array.fill(maxN*4)(0L)

    val lazyValue: Array[Long] = Array.fill(maxN*4+2)(defaultLazy)
    var N: Int = 0
    def build(nodes: Array[Long]): Unit = {
      N = nodes.length
      build(nodes,0,N,0)
      lazyValue.indices.foreach(i => lazyValue(i) = defaultLazy)
    }
    private def build(nodes: Array[Long], l: Int, r: Int, v: Int): Unit ={

      if(l+1 == r){
        minimos(v) = nodes(l)

      }else{
        val m = (l+r)/2
        build(nodes,l,m,v*2+1)
        build(nodes,m,r,v*2+2)
        minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))

      }
    }

    def query(left: Int, right: Int): Long = query(0,0,N,left,right)
    private def query(v: Int, l: Int, r: Int, L: Int, R: Int): Long = {

      if(L >= R){
        Long.MaxValue
      }else{
        push(v,l,r)
        if(l == l && r == R)
          minimos(v)
        else{
          val mid = (l+r)/2
          val a = query(v*2+1,l,mid,L,Math.min(R,mid))
          val b = query(v*2+2,mid,r,Math.max(L,mid),R)
          Math.min(a,b)
        }
      }

    }

    def update(i: Int, j: Int, valueToAdd: Long): Unit = update(0,0,N,i,j,valueToAdd)

    private def push(v: Int, l: Int, r: Int): Unit = {
      if(lazyValue(v) != 0){
        if(r-l > 1){
          lazyValue(v*2+1) += lazyValue(v)
          minimos(v*2+1) += lazyValue(v)

          lazyValue(v*2+2) += lazyValue(v)
          minimos(v*2+2) += lazyValue(v)

        }
        lazyValue(v) = 0
      }

    }

    private def update(v: Int, l: Int, r: Int, L: Int, R: Int, x: Long): Unit = {

      if(L < R){

        if(l == L && r == R){
          lazyValue(v) += x
          minimos(v) += x
          push(v,l,r)
        }else{

          push(v,l,r)
          val mid = (l+r)/2
          update(v*2+1,l,mid,L,Math.min(mid,R),x)
          update(v*2+2,mid,r,Math.max(mid,L),R,x)
          minimos(v) = Math.min(minimos(v*2+1),minimos(v*2+2))

        }

      }

    }

  }

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


Bob is playing with $$$6$$$-sided dice. A net of such standard cube is shown below.He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.For example, the number of visible pips on the tower below is $$$29$$$ — the number visible on the top is $$$1$$$, from the south $$$5$$$ and $$$3$$$, from the west $$$4$$$ and $$$2$$$, from the north $$$2$$$ and $$$4$$$ and from the east $$$3$$$ and $$$5$$$.The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.Bob also has $$$t$$$ favourite integers $$$x_i$$$, and for every such integer his goal is to build such a tower that the number of visible pips is exactly $$$x_i$$$. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of favourite integers of Bob.  The second line contains $$$t$$$ space-separated integers $$$x_i$$$ ($$$1 \leq x_i \leq 10^{18}$$$) — Bob's favourite integers.

For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).

NoteThe first example is mentioned in the problem statement.In the second example, one can build the tower by flipping the top dice from the previous tower.In the third example, one can use a single die that has $$$5$$$ on top.The fourth example is impossible.

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

  override def solve(io: IO) = io.repeat {
    val x = io.read[Long]
    val ans = (15 to 20).exists(top => (x - top) >= 0 && (x - top)%14 == 0)
    io.write(ans.toEnglish.toUpperCase)
  }
}
/****************************[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
      }
    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val x = io.read[Long]
    val ans = 1 <= x%14 && x%14 <= 6
    io.write(ans.toEnglish.toUpperCase)
  }
}
/****************************[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
      }
    }
  }
}


A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are not adjacent.Formally, consider positions of all letters in the string in the alphabet. These positions should form contiguous segment, i.e. they should come one by one without any gaps. And all letters in the string should be distinct (duplicates are not allowed).You are given a sequence of strings. For each string, if it is diverse, print "Yes". Otherwise, print "No".

The first line contains integer $$$n$$$ ($$$1 \le n \le 100$$$), denoting the number of strings to process. The following $$$n$$$ lines contains strings, one string per line. Each string contains only lowercase Latin letters, its length is between $$$1$$$ and $$$100$$$, inclusive.

Print $$$n$$$ lines, one line per a string in the input. The line should contain "Yes" if the corresponding string is diverse and "No" if the corresponding string is not diverse. You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.

object A1144Strings extends App {
    import scala.io.StdIn.{readInt, readLine}
  (0 until readInt()).map(_ => readLine.toCharArray.sorted) map{x =>
    x.map(_ - x.head).zipWithIndex.exists(x => x._1 != x._2)
  } foreach {if(_) println("No") else println("Yes")}
}

object a1144 {
  def solve(str: String) : String = {
    val s = str.sorted
    if (s zip s.tail forall(i => i._2 - i._1 == 1))  "Yes" else "No"
  }

  def main(args: Array[String]): Unit = {
    println(scala.io.Source.stdin getLines() drop 1 map solve mkString "\n")
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()

    for (i <- 0 until n){
      val str = stdin.readLine().sorted
      var res = true
      for (i <- str.indices if i+1 < str.length){
        if (math.abs(str(i) - str(i+1)) > 1) res = false
      }
      if (str.groupBy(identity).map(x => x._2.length).count(_ > 1) > 0 ) res = false
      val ans = if (res) "Yes" else "No"
      println(ans)
    }
  }
}

import java.util.Scanner

import scala.collection.mutable.ListBuffer

object Main {

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = Integer.parseInt(sc.nextLine())
    val list = new ListBuffer[String]

    for(i <- 1 to n ){
      val elem: String = sc .nextLine()
      list += elem
    }

    list.map({s =>
      s.max - s.min == s.length - 1 && s.distinct.length == s.length
    })
      .map(elem => if(elem) println("Yes") else println("No"))
  }
}

/**
  * @author ShankarShastri
  *         Algorithm: DiverseString (http://codeforces.com/contest/1144/problem/A)
  */

import scala.io.StdIn._
import scala.annotation.tailrec

object DiverseString {
  def loop[T](n: Int)(block: => T) = (1 to n).foreach(_ => block)

  def main(args: Array[String]): Unit = {
    val t = readLine.toInt
    val alphaStr = "abcdefghijklmnopqrstuvwxyz"
    loop(t) {
      val s = readLine.sorted
      if (s.length > 26) {
        println("No")
      } else {
        s.headOption match {
          case None => println("No")
          case Some(l) =>
            alphaStr.indexOf(l) match {
              case e if (e + s.length > 26) => println("No")
              case e if (s.diff(alphaStr.substring(e, (e + s.length))).length == 0 && e != -1) => println("Yes")
              case _ => println("No")
            }
        }
      }
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val strings = io.read[List[String]]

    val ans = strings
      .map({s =>
        s.max - s.min == s.length - 1 &&
        s.distinct.length == s.length
      })
      .map(t => if (t) "Yes" else "No")

    io.writeLines(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

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

/**
  * @author ShankarShastri
  *         Algorithm: DiverseString (http://codeforces.com/contest/1144/problem/A)
  */

import scala.io.StdIn._
import scala.annotation.tailrec

object DiverseString {
  def loop[T](n: Int)(block: => T) = (1 to n).foreach(_ => block)
  def main(args: Array[String]): Unit = {
    val t = readLine.toInt
    val alphaStr = "abcdefghijklmnopqrstuvwxyz"
    loop(t) {
      val s = readLine.sorted
      if (s.length > 26) {
        println("Yes")
      } else {
        s.headOption match {
          case None => println("No")
          case Some(l) =>
            alphaStr.indexOf(l) match {
              case e if (s.diff(alphaStr.substring(e, (e + s.length))).length == 0 && e != -1) => println("Yes")
              case _ => println("No")
            }
        }
      }
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val strings = io.read[List[String]]

    val ans = strings
      .map(s => s.max - s.min == s.length - 1)
      .map(t => if (t) "Yes" else "No")

    io.writeLines(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

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


Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.

Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.

NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$.  $$$|a_1 - a_2| = |6 - 6| = 0$$$;  $$$|a_2 - a_3| = |6 - 9| = 3$$$;  $$$|a_3 - a_4| = |9 - 6| = 3$$$;  $$$|a_4 - a_5| = |6 - 3| = 3$$$;  $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.

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 B619(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 B619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val a = na(n)
      var l = 0L
      var h = 1e10.toLong
      while (h - l > 2) {
        val m1 = l + (h - l) / 3
        val m2 = l + ((h - l) * 2) / 3

        if(checker(m1, a, n) > checker(m2, a , n)) {
          l = m1 + 1
        } else h = m2
      }
      var m = Long.MaxValue
      var id = l
      for(i <- l to h) {
        val x = checker(i, a, n)
        if(x < m) {
          m = x; id = i
        }
      }
      out.println(s"$m $id")
    }
  }

  def checker(k: Long, a: Array[Int], n: Int): Long = {
    var mx = -1L
    REP(n) { i =>
      if(i > 0) {
        val x = if(a(i-1) != -1) a(i-1) else k
        val y = if(a(i) != -1) a(i) else k
        mx = Math.max(mx, Math.abs(x - y))
      }
    }
    mx
  }
}

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 numCases = in.nextInt()
    (1 to numCases).foreach{_ =>
      val n = in.nextInt()
      val a = (1 to n).map(_ => in.nextInt()).toArray
      val mm0 = a.indices.foldLeft((Int.MaxValue,Int.MinValue)){ case ((min,max), i) =>
        if(a(i) == -1){
            if(i>0 && a(i-1) != -1)
              (Math.min(min,a(i-1)),Math.max(max,a(i-1)))
            else
              (min,max)
        }else{
          (min,max)
        }

      }
      val mm1 = a.indices.foldLeft(mm0){ case ((min,max), i) =>
        if(a(i) == -1){
          if(i+1<n && a(i+1) != -1)
            (Math.min(min,a(i+1)),Math.max(max,a(i+1)))
          else
            (min,max)
        }else{
          (min,max)
        }

      }

      val (min,max) = mm1
      val (bestM,bestK) = if(min == Int.MaxValue){
        (0,0)
      }else{
        val m = ((max-min)+1)/2
        val k = min + m

        val acualM = a.zip(a.tail).foldLeft(m){case (currentValue,(p,q)) => {
          val (preal,qreal) = (if(p == -1) k else p,if(q == -1) k else q)
          Math.max(currentValue,Math.abs(preal-qreal))
        }}

        (acualM,k)
      }
      out.println(s"$bestM $bestK")

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