There are $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. For the one move you can choose any even value $$$c$$$ and divide by two all elements that equal $$$c$$$.For example, if $$$a=[6,8,12,6,3,12]$$$ and you choose $$$c=6$$$, and $$$a$$$ is transformed into $$$a=[3,8,12,3,3,12]$$$ after the move.You need to find the minimal number of moves for transforming $$$a$$$ to an array of only odd integers (each element shouldn't be divisible by $$$2$$$).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of integers in the sequence $$$a$$$. The second line contains positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$.

For $$$t$$$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $$$2$$$).

NoteIn the first test case of the example, the optimal sequence of moves can be as follows:  before making moves $$$a=[40, 6, 40, 3, 20, 1]$$$;  choose $$$c=6$$$;  now $$$a=[40, 3, 40, 3, 20, 1]$$$;  choose $$$c=40$$$;  now $$$a=[20, 3, 20, 3, 20, 1]$$$;  choose $$$c=20$$$;  now $$$a=[10, 3, 10, 3, 10, 1]$$$;  choose $$$c=10$$$;  now $$$a=[5, 3, 5, 3, 5, 1]$$$ — all numbers are odd. Thus, all numbers became odd after $$$4$$$ moves. In $$$3$$$ or fewer moves, you cannot make them all odd.

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val n = readLong
        val as = readLine.split(" ").map(_.toInt)
        val x: Map[Int, Int] = as.foldLeft(Map[Int, Int]()){
            case (m, i) => {
                val (c, n) = f2(i, 0)
                m.lift(c) match {
                    case Some(x) => if (x > n) m else m + (c -> n)
                    case None => m + (c -> n)
                }
            }
        }
        println(x.values.foldLeft(0)(_ + _))
    }

    def f2(i: Int, c: Int): (Int, Int) = {
        if (i % 2 != 0) (i, c) else f2(i / 2, c + 1)
    }

  }

import scala.collection.mutable

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

  val t = nextInt
  for (_ <- 1 to t) {
    val n = nextInt
    val as = nextInts(n)
    val map = mutable.Map.empty[Int, Int]
    var i = 0
    while (i < n) {
      var a = as(i)
      var p = 0
      while ((a & 1) == 0) {
        p += 1
        a >>>= 1
      }
      if (p > 0) {
        if (map.contains(a)) {
          if (map(a) < p) map(a) = p
        } else map(a) = p
      }
      i += 1
    }
    val res = map.valuesIterator.sum
    out.println(res)
  }

  out.flush()

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


Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?

The first line contains string a, the second line contains string b, and the third line contains string c (1 ≤ |a|, |b|, |c| ≤ 105, where |s| denotes the length of string s). All three strings consist only of lowercase English letters.  It is possible that b and c coincide.

Find one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.

NoteIn the third sample, this optimal solutions has three non-overlaping substrings equal to either b or c on positions 1 – 2 (ab), 3 – 4 (ab), 5 – 7 (aca). In this sample, there exist many other optimal solutions, one of them would be acaababbcc.

import java.util.Scanner
import scala.math
import scala.util.control.Breaks._
import java.lang.Exception

object CF551B extends App {
  var in = new Scanner(System.in)
  val a = in.next()
  val b = in.next()
  val c = in.next()
  val ca = ('a' to 'z').map(x => a.count { y => x == y })
  val cb = ('a' to 'z').map(x => b.count { y => x == y })
  val cc = ('a' to 'z').map(x => c.count { y => x == y })
  var bestX = 0
  var bestY = 0
  try {
  for (x <- 0 to 100000) {
    var y = 100000
    for (i <- 0 to 25) {
      val tmp = ca(i) - cb(i) * x
      if (tmp < 0)
        y = -1
      else {
        if (cc(i) > 0)
          y = Math.min(y, tmp / cc(i))
      }
    }
    if (y < 0)
      throw new Exception()
    if (y >= 0 && x + y > bestX + bestY) {
      bestX = x
      bestY = y
    }
  }
  } catch {
    case _ =>
  }

  for (x <- 1 to bestX)
    print(b)
  for (y <- 1 to bestY)
    print(c)
  for (i <- 0 to 25) {
    val rest = ca(i) - cb(i) * bestX - cc(i) * bestY
    for (j <- 1 to rest)
      print((97 + i).toChar)
  }
}

import java.util.Scanner
import scala.math
import scala.util.control.Breaks._
import java.lang.Exception

object CF551B extends App {
  //var in = new Scanner(System.in)
  val a = readLine()
  val b = readLine()
  val c = readLine()
  val ca = ('a' to 'z').map(x => a.count { y => x == y })
  val cb = ('a' to 'z').map(x => b.count { y => x == y })
  val cc = ('a' to 'z').map(x => c.count { y => x == y })
  var bestX = 0
  var bestY = 0
  try {
  for (x <- 0 to 100000) {
    var y = 100000
    for (i <- 0 to 25) {
      val tmp = ca(i) - cb(i) * x
      if (tmp < 0)
        y = -1
      else {
        if (cc(i) > 0)
          y = Math.min(y, tmp / cc(i))
      }
    }
    if (y < 0)
      throw new Exception()
    if (y >= 0 && x + y > bestX + bestY) {
      bestX = x
      bestY = y
    }
  }
  } catch {
    case _ =>
  }

  for (x <- 1 to bestX)
    print(b)
  for (y <- 1 to bestY)
    print(c)
  for (i <- 0 to 25) {
    val rest = ca(i) - cb(i) * bestX - cc(i) * bestY
    for (j <- 1 to rest)
      print((97 + i).toChar)
  }
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  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]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val A=nextString
    val B=nextString
    val C=nextString
    val a=Array.fill(26)(0)
    val b=Array.fill(26)(0)
    val c=Array.fill(26)(0)
    val ascii0='a'.toInt
    for(i<-0 until A.length()){
      a(A(i).toInt-ascii0)+=1
    }
    for(i<-0 until B.length()){
      b(B(i).toInt-ascii0)+=1
    }
    for(i<-0 until C.length()){
      c(C(i).toInt-ascii0)+=1
    }
    var max= -3
    var maxcurrent= -1
    var nb=0
    while(maxcurrent>=max){
      max=maxcurrent
      var nc=Int.MaxValue

      for(i<-0 until 26){
        if(a(i)<nb*b(i))
          {
            nc= -nb-1
          }
          else if(c(i)>0){

          val ncc=(a(i)-nb*b(i))/c(i)
          if(ncc<nc){
            nc=ncc
          }

        }
      }
      maxcurrent=nc+nb
      nb+=1
//      out.println(maxcurrent)
    }
    nb-=2

    for(i<-0 until nb){out.print(B)}
    for(i<-0 until max-nb){out.print(C)}
    for(i<-0 until 26){
      out.print((i+ascii0).toChar.toString*(a(i)-nb*b(i)-(max-nb)*c(i)))
    }
    out.println
    //code ends here
    out.flush
    out.close
  }
}

import java.util.Scanner
import scala.math

object CF551B extends App {
  var in = new Scanner(System.in)
  val a = in.next()
  val b = in.next()
  val c = in.next()
  val ca = ('a' to 'z').map(x => a.count { y => x == y })
  val cb = ('a' to 'z').map(x => b.count { y => x == y })
  val cc = ('a' to 'z').map(x => c.count { y => x == y })
  var bestX = 0
  var bestY = 0
  for (x <- 0 to 100000) {
    var y = 100000
    for (i <- 0 to 25) {
      val tmp = ca(i) - cb(i) * x
      if (tmp < 0)
        y = -1
      else {
        if (cc(i) > 0)
          y = Math.min(y, tmp / cc(i))
      }
    }
    if (y >= 0 && x + y > bestX + bestY) {
      bestX = x
      bestY = y
    }
  }
  var str = ""
  for (x <- 1 to bestX) str += b
  for (y <- 1 to bestY) str += c
  for (i <- 0 to 25) {
    val rest = ca(i) - cb(i) * bestX + cc(i) * bestY
    for (j <- 1 to rest)
      str += (97 + i).toChar;
  }
  println(str)
}

import java.util.Scanner
import scala.math

object CF551B extends App {
  var in = new Scanner(System.in)
  val a = in.next()
  val b = in.next()
  val c = in.next()
  val ca = ('a' to 'z').map(x => a.count { y => x == y })
  val cb = ('a' to 'z').map(x => b.count { y => x == y })
  val cc = ('a' to 'z').map(x => c.count { y => x == y })
  var bestX = 0
  var bestY = 0
  for (x <- 0 to 100000) {
    var y = 100000
    for (i <- 0 to 25) {
      val tmp = ca(i) - cb(i) * x
      if (tmp < 0)
        y = -1
      else {
        if (cc(i) > 0)
          y = Math.min(y, tmp / cc(i))
      }
    }
    if (y >= 0 && x + y > bestX + bestY) {
      bestX = x
      bestY = y
    }
  }
  println(bestX, bestY)
  var str = ""
  for (x <- 1 to bestX) str += b
  for (y <- 1 to bestY) str += c
  for (i <- 0 to 25) {
    val rest = ca(i) - cb(i) * bestX - cc(i) * bestY
    for (j <- 1 to rest)
      str += (97 + i).toChar;
  }
  println(str)
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  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]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val A=nextString
    val B=nextString
    val C=nextString
    val a=Array.fill(26)(0)
    val b=Array.fill(26)(0)
    val c=Array.fill(26)(0)
    val ascii0='a'.toInt
    for(i<-0 until A.length()){
      a(A(i).toInt-ascii0)+=1
    }
    for(i<-0 until B.length()){
      b(B(i).toInt-ascii0)+=1
    }
    for(i<-0 until C.length()){
      c(C(i).toInt-ascii0)+=1
    }
    var max= -3
    var maxcurrent= -1
    var nb=0
    while(maxcurrent>=max){
      max=maxcurrent
      var nc=Int.MaxValue

      for(i<-0 until 26){
        if(a(i)<nb*b(i))
          {
            nc= -nb-1
            if(i==13){
      //        out.println(a(i)+" "+(nb*b(i)))
            }

          }
        if(c(i)>0){

          val ncc=(a(i)-nb*b(i))/c(i)
          if(ncc<nc){
            nc=ncc
          }

        }
      }
      maxcurrent=nc+nb
      nb+=1

//      out.println(maxcurrent)
    }
    nb-=1
    if(maxcurrent< 0){
      nb-= 1
    }
    for(i<-0 until nb){out.print(B)}
    for(i<-0 until max-nb){out.print(C)}
    for(i<-0 until 26){
      out.print((i+ascii0).toChar.toString*(a(i)-nb*b(i)-(max-nb)*c(i)))
    }
    out.println
    //code ends here
    out.flush
    out.close
  }
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  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]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val A=nextString
    val B=nextString
    val C=nextString
    val a=Array.fill(26)(0)
    val b=Array.fill(26)(0)
    val c=Array.fill(26)(0)
    val ascii0='a'.toInt
    for(i<-0 until A.length()){
      a(A(i).toInt-ascii0)+=1
    }
    for(i<-0 until B.length()){
      b(B(i).toInt-ascii0)+=1
    }
    for(i<-0 until C.length()){
      c(C(i).toInt-ascii0)+=1
    }
    var max= -3
    var maxcurrent= -1
    var nb=0
    while(maxcurrent>=max){
      max=maxcurrent
      var nc=Int.MaxValue

      for(i<-0 until 26){
        if(a(i)<nb*b(i))
          {
            nc= -nb-1
          }
          else if(c(i)>0){

          val ncc=(a(i)-nb*b(i))/c(i)
          if(ncc<nc){
            nc=ncc
          }

        }
      }
      maxcurrent=nc+nb
      nb+=1
//      out.println(maxcurrent)
    }
    nb-=1
    if(maxcurrent< 0){
      nb-= 1
    }
    for(i<-0 until nb){out.print(B)}
    for(i<-0 until max-nb){out.print(C)}
    for(i<-0 until 26){
      out.print((i+ascii0).toChar.toString*(a(i)-nb*b(i)-(max-nb)*c(i)))
    }
    out.println
    //code ends here
    out.flush
    out.close
  }
}


You are both a shop keeper and a shop assistant at a small nearby shop. You have $$$n$$$ goods, the $$$i$$$-th good costs $$$a_i$$$ coins.You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all $$$n$$$ goods you have.However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all $$$n$$$ goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.So you need to find the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100)$$$ — the number of goods. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$), where $$$a_i$$$ is the price of the $$$i$$$-th good.

For each query, print the answer for it — the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.

import scala.io.StdIn._

object taskA {
  def main(args: Array[String]): Unit = {
    var q = scala.io.StdIn.readInt()
    while(q > 0) {
      val n : Int = readInt()
      val array : Array[Int] = readLine().split(" ").map(_.toInt)
      val sum : Double = array.sum
      val ans : Int = Math.ceil(sum/n).toInt
      println(ans)
      q -= 1
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val input = io.read[Seq[Seq[Int]]]
    val ans = input.map(prices => (prices.sum*1.0/prices.size).ceil.toInt)
    io.writeAll(ans, separator = "\n")
  }
}
/****************************[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 = apply(new IO(System.in, System.out)).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: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

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

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

object Ex1 extends App {
  import scala.annotation.tailrec
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  import scala.io.Codec

  /**
   * Faster Scanner in Scala by wrick
   * https://codeforces.com/blog/entry/21074
   *
   * Scala implementation of a faster java.util.Scanner
   * See: http://codeforces.com/blog/entry/7018
   */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))
    def this(reader: Reader) = this(new BufferedReader(reader))
    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
      current
    }

    /**
     * Unlike Java's scanner which returns till end of current line, this actually returns the next line
     * @see line() if you want the Java behaviour
     */
    def nextLine(): String = {
      current = None   // reset
      reader.readLine()
    }
    def lineNumber: Int = reader.getLineNumber
    def line(): String = tokenizer().get.nextToken("\n\r")
    def nextString(): String = next()
    def nextChar(): Char = next().ensuring(_.length == 1).head
    def nextBoolean(): Boolean = next().toBoolean
    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
    def nextFloat(): Float = next().toFloat
    def nextDouble(): Double = next().toDouble
    def nextBigDecimal(): BigDecimal = BigDecimal(next())
    override def next() = tokenizer().get.nextToken()
    override def hasNext = tokenizer().nonEmpty
    override def close() = reader.close()
  }

  def read2(): Seq[Seq[Int]] = {
    val in = new Scanner(System.in)
    val q = in.nextInt()
    (0 until q).map { _ =>
      val n = in.nextInt()
      (0 until n).map(_ => in.nextInt())
    }
  }

  def res(list: Seq[Int]) = {
    val sum = list.sum
    val len = list.length
    if (sum % len == 0) sum / len
    else sum / len + 1
  }

  read2().foreach(x => println(res(x)))

}


You are given an array $$$a_1, a_2, \ldots, a_n$$$.In one operation you can choose two elements $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array.

Print "YES" if it is possible to make all elements zero, otherwise print "NO".

NoteIn the first example, you can make all elements equal to zero in $$$3$$$ operations:   Decrease $$$a_1$$$ and $$$a_2$$$,  Decrease $$$a_3$$$ and $$$a_4$$$,  Decrease $$$a_3$$$ and $$$a_4$$$ In the second example, one can show that it is impossible to make all elements equal to zero.

import scala.io.StdIn._

object B_1201 extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toLong).sorted

  if (A.sum % 2 == 1 || A.init.sum < A.last) println("NO")
  else println("YES")

}

import scala.io.StdIn._

object B_1201 extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toInt).sorted

  if (A.sum % 2 == 1 || A.init.sum < A.last) println("NO")
  else println("YES")

}


Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions:  The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.  No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n).  Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.

A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters.

In a single line print the required string. If there isn't such string, print "-1" (without the quotes).

import scala.collection.mutable.StringBuilder
import java.util.Scanner

object Strings extends App {

	val scanner = new Scanner( System.in )

	val n = scanner.nextInt
	val k = scanner.nextInt

	if( n < k || n > 1 && k == 1 )
		println( "-1" )
	else {
		// initialize the string with default "abab..." value
		val sb = new StringBuilder( "ab" * ( n / 2 ) + "a" * ( n % 2 ))
		// fill the rest with k-2 different characters
		for( i <- ( k - 1 to 2 by -1 ))
			sb( n - k + i ) = ( 'a' + i ).toChar
		println( sb.result )
	}
}

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

  def main(args: Array[String]) {
    var Array(n, k) = READ
    if (n < k || k == 1) {
      println(if (n*k == 1) 'a' else -1);
      return;
    }
    var result:StringBuilder = new StringBuilder;
    for (i <- 1 to n-k+2) result.append(if (i%2 == 1)  'a' else 'b');
    for (i <- 1 to k-2) result.append(('a'+i+1).toChar)
    println(result)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  if (k > n || (n > 1 && k == 1)) println(-1)
  else if (n == 1) println("a")
  else {
    println(((1 to n - k + 2).map(i => if (i % 2 == 1) 'a' else 'b').toList
      ::: ('c' until ('c' + k - 2).toChar).toList).mkString(""))
  }
}

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object A288 extends App {

  def solve() = {
    val Array(n, k): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    if (n < k) {
      println("-1")
    } else if (k == 1) {
      if (n == 1) {
        println("a")
      } else {
        println("-1")
      }
    } else if (k == 2) {
      println(("a b " * n).split(" ").take(n).mkString(""))
    } else {
      val answer: Array[Char] = Array.ofDim[Char](n)
      for (j <- k.to(3, -1)) {
        answer(n - 1 - k + j) = ('a'.toInt + j - 1).toChar
      }
      var i = 0
      while (i < n - k + 2) {
        if (i % 2 == 0) {
          answer(i) = 'a'
        } else {
          answer(i) = 'b'
        }
        i += 1
      }
      println(answer.mkString(""))
    }
  }

  solve()

}

import io.Source
import java.io.PrintWriter

object CF288A {

  def solve(in: In, out: PrintWriter) {
    val n, k = in().toInt
    if (n < k || k == 1 && n > 1) {
      out.println("-1")
    } else {
      for (i <- 0 until math.min(n, n - (k - 2))) {
        out.print(if (i % 2 == 0) 'a' else 'b')
      }
      for (i <- 2 until k) {
        out.print((i + 'a').toChar)
      }
      out.println()
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

object A extends App
{
    val Array(n, k) = readLine.split(" ").map(_.toInt)
    if (n < k || (k==1 && n>1))
        println(-1)
    else
    {
        for (i <- 0 until math.min(n,n-k+2))
            print(if ((i&1)==0) 'a' else 'b')
        for (ch <- 'c' until ('a'+k).toChar)
            print(ch)
        println()
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  if (k > n || (n > 1 && k == 1)) println(-1)
  else {
    println(((1 to n - k + 2).map(i => if (i % 2 == 1) 'a' else 'b').toList
      ::: ('c' until ('c' + k - 2).toChar).toList).mkString(""))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  if (k > n) println(-1)
  else {
    println(((1 to n - k + 2).map(i => if (i % 2 == 1) 'a' else 'b').toList
      ::: ('c' until ('c' + k - 2).toChar).toList).mkString(""))
  }
}

object A extends App
{
    val Array(n, k) = readLine.split(" ").map(_.toInt)
    if (n < k)
        println(-1)
    else
    {
        for (i <- 0 until math.min(n,n-k+2))
            print(if ((i&1)==0) 'a' else 'b')
        for (ch <- 'c' until ('a'+k).toChar)
            print(ch)
        println()
    }
}

object A extends App
{
    val Array(n, k) = readLine.split(" ").map(_.toInt)
    if (k > n)
        println(-1)
    else
    {
        for (i <- 0 until n-k+2)
            print(if ((i&1)==0) 'a' else 'b')
        for (ch <- 'c' until ('a'+k).toChar)
            print(ch)
        println()
    }
}


Ezzat has an array of $$$n$$$ integers (maybe negative). He wants to split it into two non-empty subsequences $$$a$$$ and $$$b$$$, such that every element from the array belongs to exactly one subsequence, and the value of $$$f(a) + f(b)$$$ is the maximum possible value, where $$$f(x)$$$ is the average of the subsequence $$$x$$$. A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements.The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.For example, the average of $$$[1,5,6]$$$ is $$$(1+5+6)/3 = 12/3 = 4$$$, so $$$f([1,5,6]) = 4$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$)— the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test case, print a single value — the maximum value that Ezzat can achieve. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

import scala.io.StdIn._
import scala.util.Sorting

object _1557A {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0 ){
      t -= 1
      val n = readInt()
      val ar = readLine().split(" ").map(_.toDouble)
      Sorting.quickSort(ar)
      val sum : Double = (ar.sum - ar(n - 1)) / (n - 1.0);
      println(sum + ar(n - 1))
    }
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt).sorted(Ordering[Int].reverse)

    val ans = an.head + an.tail.foldLeft(0L)(_ + _) / (n - 1.0)

    println(ans)
  }
}

import scala.io.StdIn._
import scala.util.Sorting

object _1557A {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0 ){
      t -= 1
      val n = readInt()
      val ar = readLine().split(" ").map(_.toInt)
      Sorting.quickSort(ar)
//      println(ar.mkString(", "))
      val sum : Double = (ar.sum - ar(n - 1)) / (n - 1.0);
      println(sum + ar(n - 1))
    }
  }
}


Suppose you are living with two cats: A and B. There are $$$n$$$ napping spots where both cats usually sleep.Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:   Cat A changes its napping place in order: $$$n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots$$$ In other words, at the first hour it's on the spot $$$n$$$ and then goes in decreasing order cyclically;  Cat B changes its napping place in order: $$$1, 2, 3, \dots, n - 1, n, 1, 2, \dots$$$ In other words, at the first hour it's on the spot $$$1$$$ and then goes in increasing order cyclically. The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot $$$x$$$ then the A takes this place and B moves to the next place in its order (if $$$x < n$$$ then to $$$x + 1$$$, but if $$$x = n$$$ then to $$$1$$$). Cat B follows his order, so it won't return to the skipped spot $$$x$$$ after A frees it, but will move to the spot $$$x + 2$$$ and so on.Calculate, where cat B will be at hour $$$k$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$) — the number of spots and hour $$$k$$$.

For each test case, print one integer — the index of the spot where cat B will sleep at hour $$$k$$$.

NoteIn the first and second test cases $$$n = 2$$$, so:   at the $$$1$$$-st hour, A is on spot $$$2$$$ and B is on $$$1$$$;  at the $$$2$$$-nd hour, A moves to spot $$$1$$$ and B — to $$$2$$$.  If $$$n = 3$$$ then:   at the $$$1$$$-st hour, A is on spot $$$3$$$ and B is on $$$1$$$;  at the $$$2$$$-nd hour, A moves to spot $$$2$$$; B'd like to move from $$$1$$$ to $$$2$$$, but this spot is occupied, so it moves to $$$3$$$;  at the $$$3$$$-rd hour, A moves to spot $$$1$$$; B also would like to move from $$$3$$$ to $$$1$$$, but this spot is occupied, so it moves to $$$2$$$. In the sixth test case:   A's spots at each hour are $$$[5, 4, 3, 2, 1]$$$;  B's spots at each hour are $$$[1, 2, 4, 5, 2]$$$.

import scala.io.StdIn._

object Cat_Cycle extends App{
  val t = readInt()
  var n = 0
  var k = 0
  for (i <- 1 to t) {
    val Array(x, y) = readLine().split(" ").map(_.toInt)
    n = x // Number of spots
    k = y // Hours
    var A = n
    var B = 1
    if (n % 2 == 0) {
      if (k % n == 0) {
        println(n)
      }
      else {
        println(k % n)
      }
    }
    else {
      val step = n / 2
      val meets = (k - 1) / step
      if ((B * k) % n == 0) B = n else B = (B * k) % n
      B += meets
      if (B % n == 0) B = n else B = B % n
      println(B)
    }
  }
}

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

    for (_ <- 1 to nextInt) {
      val n, k = nextInt
      val b = if (n % 2 == 0) (k - 1) % n
      else (k + (k - 1) / (n / 2) - 1) % n

      out.println(b + 1)
    }

    out.flush()
  }

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

object B {
  import scala.io.{StdIn => in}

  def main(args: Array[String]): Unit = {
    val tests = in.readInt()
    (1 to tests).foreach { _ =>
      val Array(n, k) = in.readLine().split(' ').map(_.toInt)
      println((k - 1 + n % 2 * (k - 1) / (n / 2)) % n + 1)
    }
  }
}

//package codeforces.contests._1487

object CatCycle {

  def main(args: Array[String]): Unit = {
    println({
      for (_ <- 1 to io.StdIn.readInt()) yield {
        val Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)

        if ((n % 2) == 0) ((k - 1) % n)
        else {
          // 0 based
          val w      = (k-1) / (n - 1)
          val offset = (k - 1) % (n - 1)
          val start  = w % n

          (if (offset < n / 2) (start + offset) % n else (start + offset + 1) % n)
        }

      } + 1
    }.mkString("\n"))
  }
}

import scala.io.StdIn._

object Cat_Cycle extends App{
  val t = readInt()
  var n = 0
  var k = 0
  for (i <- 1 to t) {
    val Array(x, y) = readLine().split(" ").map(_.toInt)
    n = x // Number of spots
    k = y // Hours
    var A = n
    var B = 1
    if (n % 2 == 0) {
      if (k % n == 0) {
        println(n)
      }
      else {
        println(k % n)
      }
    }
    else {
      val step = n / 2
      val meets = (k - 1) / step
      if ((B * k) % n == 0) B = n else B = (B * k) % n
      B += meets
      if (B % n == 0) B == n else B = B % n
      println(B)
    }
  }
}

import scala.io.StdIn._

object test extends App {
  val t = readInt()
  var n = 0;
  var k = 0
  for (i <- 1 to t) {
    val Array(x, y) = readLine().split(" ").map(_.toInt)
    n = x // Number of spots
    k = y // Hours
    if (n % 2 == 0) {
      if (k % n == 0) {
        println(n)
      }
      else {
        println(k % n)
      }
    }
    else {
      var A = n
      var B = 1
      for (j <- 1 until k) {
        A -= 1
        B += 1
        if (A < 1) {
          A += n
        }
        if (B > n) {
          B -= n
        }
        if (A == B) {
          B += 1
        }
      }
      println(B)
    }
  }

}

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

    for (_ <- 1 to nextInt) {
      val n, k = nextInt
      var a = n - 1
      var b = 0
      if (n % 2 == 0) {
        b = (k - 1) % n
      } else {
        var rep = -1
        var step = 0
        while (step < k - 1) {
          val d = Math.min(k - step -1, (a - b - 1) / 2)
          if (a == n - 1 && b == 0 && step > 0 && step * 2 < k) {
            println(step, rep, a, b)
            if (rep == -1) {
              rep = step
            } else {
              step += (k - step - 1) / rep * rep
            }
          } else if (d > 0) {
            a -= d
            b += d
            step += d
          } else if (b + 2 == a) {
            a -= 1
            b += 2
            step += 1
          } else {
            val dd = Math.min(k - step-1, (n - 1) / 2)
            a = (a + n - dd) % n
            b = (b + n + dd) % n
            if (b == a) b = (b + 1) % n
            step += dd
          }
//          println(step, a, b)
        }
      }
//      println(b + 1)
      out.println(b + 1)
    }

    out.flush()
  }

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


You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied:  The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string;  The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because:  the second half of the string ("aaaa") consists of only the character 'a';  the first half of the string ("cdbb") is 'b'-good string, because:   the second half of the string ("bb") consists of only the character 'b';  the first half of the string ("cd") is 'c'-good string, because:   the first half of the string ("c") consists of only the character 'c';  the second half of the string ("d") is 'd'-good string.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) — the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.

6
8
bbdcaaaa
8
asdfghjk
8
ceaaaabb
8
bbaaddcc
1
z
2
ac

object D extends App {
  import scala.io.StdIn._

  implicit class StringOps(str: String) {
    def countSlice(from: Int, until: Int, p: Char => Boolean): Int = {
      @scala.annotation.tailrec
      def go(i: Int, c: Int = 0): Int =
        if (i == until) c
        else go(i + 1, c + (if (p(str(i))) 1 else 0))

      go(from)
    }
  }

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    def count(c: Char, from: Int, size: Int): Int =
      size match {
        case 1 =>
          if (c == sn(from)) 0 else 1
        case _ =>
          val l = sn.countSlice(from, from + size / 2, _ != c) + count((c + 1).toChar, from + size / 2, size / 2)
          val r = sn.countSlice(from + size / 2, from + size, _ != c) + count((c + 1).toChar, from, size / 2)
          l min r
      }

    val ans = count('a', 0, n)

    println(ans)
  }
}

object D extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    def good(c: Char, from: Int, size: Int): Int =
      size match {
        case 1 => if (c == sn(from)) 0 else 1
        case _ =>
          val (l, r) = sn.slice(from, from + size).zipWithIndex.foldLeft(((0, 0), (0, 0))) {
            case ((l, r), (s, i)) if s == c     => if (i < size / 2) ((l._1 + 1, l._2), r) else (l, (r._1 + 1, r._2))
            case ((l, r), (s, i)) if s == c + 1 => if (i < size / 2) ((l._1, l._2 + 1), r) else (l, (r._1, r._2 + 1))
            case ((l, r), _)                    => (l, r)
          }

          if (l._1 + r._2 >= r._1 + l._2)
            size / 2 - l._1 + good((c + 1).toChar, from + size / 2, size / 2)
          else
            size / 2 - r._1 + good((c + 1).toChar, from, size / 2)
      }

    val ans = good('a', 0, n)

    println(ans)
  }
}


According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE

The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.

Print a single number which is the number of people Vasya should check to guarantee the law enforcement.

NoteIn the sample test the second and fifth clients should be checked.

object Solver {
    def main(args: Array[String]) {
        var total = 0
        var n = Console.readLine.toInt
        var drinks = Set("ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE")

        for (i <- 1 to n) {
            var input = Console.readLine
            var suspicious = if ( input.forall(_.isDigit) ) input.toInt < 18 else drinks.contains(input)
            if (suspicious) total += 1
        }
        println(total)
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val drinks = List("ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE",
    "TEQUILA", "VODKA", "WHISKEY", "WINE")
  println((1 to n).count{
    _ => val str = in.next()
      if (str.forall(_.isDigit))
        str.toInt < 18
      else
        drinks.contains(str)
  })
}

object A56 {

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

  def main(args: Array[String]): Unit = {
    val Array(tests) = readInts(1)
    var res = 0
    val alcohol = Array("ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE")
    for(_ <- 1 to tests) {
      val str = read
      if(alcohol.contains(str))
        res += 1
      else {
        util.Try{str.toInt}.foreach { int=>
          if(int < 18)
            res += 1
        }
      }
    }
    out.println(res)
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

/**
  * Created by John Compitello on 7/26/16.
  */
object Main {
  def main(args: Array[String]) = {
    val drinkList: List[String] = List("ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM",
      "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE")
    val lines: Array[String] = (for (ln <- io.Source.stdin.getLines) yield ln).toArray
    val numClients = lines(0).toInt
    val clientList = lines.tail

    val (numList, nameList): (Array[String], Array[String]) = clientList.partition(isANumber)

    println(numList.map(_ toInt).filter(_ < 18).length + nameList.filter(x => drinkList contains x).length)
  }

  //Must check people in client list who are either drinking alcohol or under 18.
  def isANumber(x: String): Boolean = x forall Character.isDigit
}


The new generation external memory contains an array of integers $$$a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$$$.This type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back into the same place.Technically, each cyclic shift consists of two consecutive actions:   You may select arbitrary indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) as the boundaries of the segment.  Then you replace the segment $$$a[l \ldots r]$$$ with it's cyclic shift to the left by an arbitrary offset $$$d$$$. The concept of a cyclic shift can be also explained by following relations: the sequence $$$[1, 4, 1, 3]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$1$$$ and the sequence $$$[4, 1, 3, 1]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$2$$$. For example, if $$$a = [1, \color{blue}{3, 2, 8}, 5]$$$, then choosing $$$l = 2$$$, $$$r = 4$$$ and $$$d = 2$$$ yields a segment $$$a[2 \ldots 4] = [3, 2, 8]$$$. This segment is then shifted by the offset $$$d = 2$$$ to the left, and you get a segment $$$[8, 3, 2]$$$ which then takes the place of of the original elements of the segment. In the end you get $$$a = [1, \color{blue}{8, 3, 2}, 5]$$$.Sort the given array $$$a$$$ using no more than $$$n$$$ cyclic shifts of any of its segments. Note that you don't need to minimize the number of cyclic shifts. Any method that requires $$$n$$$ or less cyclic shifts will be accepted.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain the descriptions of the test cases.  The first line of each test case description contains an integer $$$n$$$ ($$$2 \leq n \leq 50$$$) — the length of the array. The second line consists of space-separated elements of the array $$$a_i$$$ ($$$-10^9 \leq a_i \leq 10^9$$$). Elements of array $$$a$$$ may repeat and don't have to be unique.

Print $$$t$$$ answers to all input test cases.  The first line of the answer of each test case should contain an integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of actions to sort the array. The next $$$k$$$ lines should contain descriptions of the actions formatted as "$$$l$$$ $$$r$$$ $$$d$$$" (without quotes) where $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) are the boundaries of the segment being shifted, while $$$d$$$ ($$$1 \le d \le r - l$$$) is the offset value. Please remember that only the cyclic shifts to the left are considered so the chosen segment will be shifted by the offset $$$d$$$ to the to the left. Note that you are not required to find the minimum number of cyclic shifts needed for sorting. Any sorting method where the number of shifts does not exceed $$$n$$$ will be accepted. If the given array $$$a$$$ is already sorted, one of the possible answers is $$$k = 0$$$ and an empty sequence of cyclic shifts. If there are several possible answers, you may print any of them.

NoteExplanation of the fourth data set in the example:   The segment $$$a[2 \ldots 4]$$$ is selected and is shifted to the left by $$$2$$$: $$$[2, \color{blue}{5, 1, 4}, 3] \longrightarrow [2, \color{blue}{4, 5, 1}, 3]$$$  The segment $$$a[1 \ldots 5]$$$ is then selected and is shifted to the left by $$$3$$$: $$$[\color{blue}{2, 4, 5, 1, 3}] \longrightarrow [\color{blue}{1, 3, 2, 4, 5}]$$$  After that the segment $$$a[1 \ldots 2]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\color{blue}{1, 3}, 2, 4, 5] \longrightarrow [\color{blue}{3, 1}, 2, 4, 5]$$$  And in the end the segment $$$a[1 \ldots 3]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\color{blue}{3, 1, 2}, 4, 5] \longrightarrow [\color{blue}{1, 2, 3}, 4, 5]$$$

object B extends App {

  type Shift = (Int, Int, Int)

  def shiftingSort(an: IndexedSeq[Int]): List[Shift] = {
    val bn = an.zipWithIndex.sorted

    bn.indices
      .foldLeft(List.empty[Shift]) { (shifts, i) =>
        val j = shifts.foldRight(bn(i)._2) {
          case ((l, r, d), j) if l <= j && j <= r =>
            val size = r - l + 1
            l + (j - l - d + size) % size
          case (_, j)                             => j
        }

        if (i == j) shifts else (i, j, j - i) :: shifts
      }
      .reverse
  }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val shifts = shiftingSort(an)

    println(shifts.length)
    println(shifts.map { case (l, r, d) => s"${l + 1} ${r + 1} $d" }.mkString("\n"))
  }
}

object B extends App {

  type Shift = (Int, Int, Int)

  def shiftingSort(an: IndexedSeq[Int]): List[Shift] = {
    val bn = an.zipWithIndex.sorted

    bn.indices
      .foldLeft(List.empty[Shift]) { (shifts, i) =>
        val j = shifts.reverse.foldLeft(bn(i)._2) {
          case (j, (l, r, d)) if l <= j && j <= r => l + (j - l - d + r - l + 1) % (r - l + 1)
          case (j, _)                             => j
        }

        if (i == j) shifts else (i, j, j - i) :: shifts
      }
      .reverse
  }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val shifts = shiftingSort(an)

    println(shifts.length)
    println(shifts.map { case (l, r, d) => s"${l + 1} ${r + 1} $d" }.mkString("\n"))
  }
}

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

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

    case class myType(left: Int, right: Int, index: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (left < that.left || (left == that.left && right < that.right))
                return -1
            else if (left == that.left && right == that.right)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val ans = new ArrayBuffer[(Int, Int, Int)]()
        val arr = new Array[Int](n)
        for (i <- 1 to n)
            arr(i-1) = readInt()
        for (i <- 0 until n) {
            var mm = arr(i)
            var po = i
            for (j <- i until n)
                if (arr(j) < mm) {
                    mm = arr(j)
                    po = j
                }
            if (po != i) {
                ans.append((i+1, po+1, po-i))
                for (j <- (i until po).reverse)
                    arr(j+1) = arr(j)
                arr(i) = mm
            }
        }
        writer.println(ans.length)
        for (mv <- ans)
            writer.println(mv._1 + " " + mv._2 + " " + mv._3)
    }
    writer.flush()
}

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

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

    case class myType(left: Int, right: Int, index: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (left < that.left || (left == that.left && right < that.right))
                return -1
            else if (left == that.left && right == that.right)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val ans = new ArrayBuffer[(Int, Int, Int)]()
        val arr = new Array[Int](n)
        for (i <- 1 to n)
            arr(i-1) = readInt()
        for (i <- 0 until n) {
            var mm = arr(i)
            var po = i
            for (j <- i until n)
                if (arr(j) < mm) {
                    mm = arr(j)
                    po = j
                }
            if (po != i) {
                ans.append((i+1, po+1, po-i))
                for (j <- i until po)
                    arr(j+1) = arr(j)
                arr(i) = mm
            }
        }
        writer.println(ans.length)
        for (mv <- ans)
            writer.println(mv._1 + " " + mv._2 + " " + mv._3)
    }
    writer.flush()
}


Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as:  a1 = p, where p is some integer;  ai = ai - 1 + ( - 1)i + 1·q (i > 1), where q is some integer. Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression.Sequence s1,  s2,  ...,  sk is a subsequence of sequence b1,  b2,  ...,  bn, if there is such increasing sequence of indexes i1, i2, ..., ik (1  ≤  i1  <  i2  < ...   <  ik  ≤  n), that bij  =  sj. In other words, sequence s can be obtained from b by crossing out some elements.

The first line contains integer n (1 ≤ n ≤ 4000). The next line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106).

Print a single integer — the length of the required longest subsequence.

NoteIn the first test the sequence actually is the suitable subsequence. In the second test the following subsequence fits: 10, 20, 10.

import collection.mutable.Map

object test5 extends App {
    val n=readInt
    val b=readLine.split(" ").map(_.toInt)
    val x=new Array[Int](n)
    val map=Map[Int,Int]()
    b.zipWithIndex.foreach {case (v,i)=>{
            if(!map.contains(v)) map(v)=map.size
            x(i)=map(v)
        }
    }

    val dp=Array.ofDim[Int](n,n)
    for(i<-0 until n) java.util.Arrays.fill(dp(i),1)

    var max=1
    for(i<-1 until n; j<-0 until i){
        dp(i)(x(j))=dp(j)(x(i))+1
        max=math.max(max, dp(i)(x(j)))
    }

    println(max)
}

import collection.mutable.Map

object test5 extends App {
    val n=readInt
    val b=readLine.split(" ").map(_.toInt)
    var max=1
    val dp=new Array[Map[Int,Int]](n)
    for(i<-0 until n) dp(i)=Map[Int,Int]()

    for(i<-1 until n; j<-i-1 to 0 by -1){
        var q=b(i)-b(j)
        if(!dp(i).contains(q) && dp(j).contains(q) && dp(j)(q)%2==0){
            dp(i)(q)=dp(j)(q)+1
            max=math.max(max,dp(i)(q))
        }

        if(!dp(i).contains(q)){
            if(dp(j).contains(-q) && dp(j)(-q)%2==1)
                dp(i)(-q)=dp(j)(-q)+1
            else
                dp(i)(-q)=2
            max=math.max(max,dp(i)(-q))
        }
    }

    println(max)
}

import collection.mutable.Map

object test5 extends App {
    val n=readInt
    val b=readLine.split(" ").map(_.toInt)
    var max=1
    val dp=new Array[Map[Int,Int]](n)
    for(i<-0 until n) dp(i)=Map[Int,Int]()

    for(i<-1 until n; j<-i-1 to 0 by -1){
        var q=b(i)-b(j)
        if(!dp(i).contains(q) && dp(j).contains(q) && dp(j)(q)%2==0){
            dp(i)(q)=dp(j)(q)+1
            max=math.max(max,dp(i)(q))
        }

        if(!dp(i).contains(-q)){
            if(dp(j).contains(-q) && dp(j)(-q)%2==1)
                dp(i)(-q)=dp(j)(-q)+1
            else
                dp(i)(-q)=2
            max=math.max(max,dp(i)(-q))
        }
    }

    println(max)
}

import collection.mutable.Map

object test5 extends App {
    val n=readInt
    val b=readLine.split(" ").map(_.toInt)
    var max=0
    val dp=new Array[Map[Int,Int]](n)
    for(i<-0 until n) dp(i)=Map[Int,Int]()

    for(i<-1 until n; j<-i-1 to 0 by -1){
        var q=b(i)-b(j)
        if(dp(j).contains(q) && dp(j)(q)%2==0){
            dp(i)(q)=math.max(dp(i).getOrElse(q, 0),dp(j)(q)+1)
            max=math.max(max,dp(i)(q))
        }
        if(dp(j).contains(-q) && dp(j)(-q)%2==1)
            dp(i)(-q)=math.max(dp(i).getOrElse(-q,0),dp(j)(-q)+1)
        else
            dp(i)(-q)=math.max(dp(i).getOrElse(-q,0),2)

        max=math.max(max,dp(i)(-q))
    }

    println(max)
}

object test5 extends App {
    val n=readInt
    val b=readLine.split(" ").map(_.toInt)
    var max=0
    var q=0
    var count=1

    val getQ=(i:Int)=>{
        val ret=b(i)-b(i-1)
        if(i%2==0) ret else -ret
    }

    for(i<-1 until n){
        if(getQ(i)==q){
            count+=1
        }
        else{
            q=getQ(i)
            max=math.max(max,count)
            count=2
        }
    }
    max=math.max(max,count)
    println(max)
}

import collection.mutable.Map

object test5 extends App {
    val n=readInt
    val b=readLine.split(" ").map(_.toInt)
    var max=1
    val dp=new Array[Map[Int,Int]](n)
    for(i<-0 until n) dp(i)=Map[Int,Int]()

    for(i<-1 until n; j<-i-1 to 0 by -1){
        var q=b(i)-b(j)
        if(!dp(i).contains(q)){
            if(dp(j).contains(q) && dp(j)(q)%2==0){
                dp(i)(q)=dp(j)(q)+1
                max=math.max(max,dp(i)(q))
            }
        }

        if(!dp(i).contains(-q)){
            if(dp(j).contains(-q) && dp(j)(-q)%2==1)
                dp(i)(-q)=dp(j)(-q)+1
            else
                dp(i)(-q)=2
            max=math.max(max,dp(i)(-q))
        }
    }

    println(max)
}


...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.It is guaranteed that the graph contains no multiple edges and self-loops.

The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ ). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.

Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.

NoteLet us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).A rooted tree is a tree where one vertex is selected to be the root.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  var graph = Set.empty[Set[Int]]
  var list = List.empty[(Int, Int)]
  (1 to m).foreach{ _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
    list ::= (Math.max(a, b),  Math.min(a, b))
    val first = graph.find(_.contains(a))
    val second = graph.find(_.contains(b))
    if (first.isEmpty && second.isEmpty)
      graph += Set(a, b)
    else if (first.isEmpty && second.isDefined) {
      graph -= second.get
      graph += (second.get + a)
    } else if (first.isDefined && second.isEmpty) {
      graph -= first.get
      graph += (first.get + b)
    } else if (first != second) {
      graph -= first.get
      graph -= second.get
      graph += (first.get ++ second.get)
    }
  }
  if (n == m && graph.size == 1 && graph.head.size == n) {
    println("FHTAGN!")
  } else {
    println("NO")
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  var graph = Set.empty[Set[Int]]
  var list = List.empty[(Int, Int)]
  (1 to m).foreach{ _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
    list ::= (Math.max(a, b),  Math.min(a, b))
    val first = graph.find(_.contains(a))
    val second = graph.find(_.contains(b))
    if (first.isEmpty && second.isEmpty)
      graph += Set(a, b)
    else if (first.isEmpty && second.isDefined) {
      graph -= second.get
      graph += (second.get + a)
    } else if (first.isDefined && second.isEmpty) {
      graph -= first.get
      graph += (first.get + b)
    } else if (first != second) {
      graph -= first.get
      graph -= second.get
      graph += (first.get ++ second.get)
    }
  }
  if (n == m && graph.size == 1 && graph.size == n) {
    println("FHTAGN!")
  } else {
    println("NO")
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  var graph = Set.empty[Set[Int]]
  (1 to m).foreach{ _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
    val first = graph.find(_.contains(a))
    val second = graph.find(_.contains(b))
    if (first.isEmpty && second.isEmpty)
      graph += Set(a, b)
    else if (first.isEmpty && second.isDefined) {
      graph -= second.get
      graph += (second.get + a)
    } else if (first.isDefined && second.isEmpty) {
      graph -= first.get
      graph += (first.get + b)
    } else if (first != second) {
      graph -= first.get
      graph -= second.get
      graph += (first.get ++ second.get)
    }
  }
  if (n == m && graph.size == 1) {
    println("FHTAGN!")
  } else {
    println("NO")
  }

}


There are n cities in Berland, each of them has a unique id — an integer from 1 to n, the capital is the one with id 1. Now there is a serious problem in Berland with roads — there are no roads.That is why there was a decision to build n - 1 roads so that there will be exactly one simple path between each pair of cities.In the construction plan t integers a1, a2, ..., at were stated, where t equals to the distance from the capital to the most distant city, concerning new roads. ai equals the number of cities which should be at the distance i from the capital. The distance between two cities is the number of roads one has to pass on the way from one city to another. Also, it was decided that among all the cities except the capital there should be exactly k cities with exactly one road going from each of them. Such cities are dead-ends and can't be economically attractive. In calculation of these cities the capital is not taken into consideration regardless of the number of roads from it. Your task is to offer a plan of road's construction which satisfies all the described conditions or to inform that it is impossible.

The first line contains three positive numbers n, t and k (2 ≤ n ≤ 2·105, 1 ≤ t, k < n) — the distance to the most distant city from the capital and the number of cities which should be dead-ends (the capital in this number is not taken into consideration).  The second line contains a sequence of t integers a1, a2, ..., at (1 ≤ ai < n), the i-th number is the number of cities which should be at the distance i from the capital. It is guaranteed that the sum of all the values ai equals n - 1.

If it is impossible to built roads which satisfy all conditions, print -1. Otherwise, in the first line print one integer n — the number of cities in Berland. In the each of the next n - 1 line print two integers — the ids of cities that are connected by a road. Each road should be printed exactly once. You can print the roads and the cities connected by a road in any order. If there are multiple answers, print any of them. Remember that the capital has id 1.

import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.util.StringTokenizer

import scala.util.Try

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

  read()
  val n = int()
  val t = int()
  val k = int()
  read()
  val a = 1 +: Array.fill(t)(int()) :+ 0

  Try {
    val kmin = (0 to t).foldLeft(0)((sum, i) => sum + Math.max(0, a(i)-a(i+1)))
    assert(kmin <= k)
    var dk = k - kmin

    val lines = new Array[Int](n+1)
    val heads = new Array[Int](t+1)
    var j = 1
    for (i <- 0 to t) {
      heads(i) = j
      j += a(i)
    }
    var l = 0
    for (i <- 1 to n) {
      if (heads(l) + a(l) <= i) l += 1
      lines(i) = l
    }

    val links = new Array[Int](n+1)
    for (i <- 2 to n) {
      l = lines(i)
      if (i == heads(l)) {
        links(i) = heads(l-1)
      } else {
        val z = i - heads(l) + heads(l - 1)
        val onPrev = lines(z) == l - 1
        if (dk > 0) {
          links(i) = heads(l-1)
          if (onPrev) dk -= 1
        } else {
          if (onPrev) links(i) = z
          else links(i) = heads(l-1)
        }
      }
    }
    assert(dk == 0)

    val out = new BufferedWriter(new OutputStreamWriter(System.out))
    out.write(n + "\n")
    for (i <- 2 to n) out.write(links(i) + " " + i + "\n")
    out.close()

  }.getOrElse(println(-1))
}

import java.util.StringTokenizer

import scala.util.Try

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

  read()
  val n = int()
  val t = int()
  val k = int()
  read()
  val a = 1 +: Array.fill(t)(int()) :+ 0

  Try {
    val kmin = (0 to t).foldLeft(0)((sum, i) => sum + Math.max(0, a(i)-a(i+1)))
    assert(kmin <= k)
    var dk = k - kmin

    val lines = new Array[Int](n+1)
    val heads = new Array[Int](t+1)
    var j = 1
    for (i <- 0 to t) {
      heads(i) = j
      j += a(i)
    }
    var l = 0
    for (i <- 1 to n) {
      if (heads(l) + a(l) <= i) l += 1
      lines(i) = l
    }

    val links = new Array[Int](n+1)
    for (i <- 2 to n) {
      l = lines(i)
      if (i == heads(l)) {
        links(i) = heads(l-1)
      } else {
        val z = i - heads(l) + heads(l - 1)
        val onPrev = lines(z) == l - 1
        if (dk > 0) {
          links(i) = heads(l-1)
          if (onPrev) dk -= 1
        } else {
          if (onPrev) links(i) = z
          else links(i) = heads(l-1)
        }
      }
    }
    assert(dk == 0)

    println(n)
    for (i <- 2 to n) println(links(i) + " " + i)

  }.getOrElse(println(-1))
}

import java.io.PrintWriter
import java.util.StringTokenizer

import scala.util.Try

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

  read()
  val n = int()
  val t = int()
  val k = int()
  read()
  val a = 1 +: Array.fill(t)(int()) :+ 0

  Try {
    val kmin = (0 to t).foldLeft(0)((sum, i) => sum + Math.max(0, a(i)-a(i+1)))
    assert(kmin <= k)
    var dk = k - kmin

    val lines = new Array[Int](n+1)
    val heads = new Array[Int](t+1)
    var j = 1
    for (i <- 0 to t) {
      heads(i) = j
      j += a(i)
    }
    var l = 0
    for (i <- 1 to n) {
      if (heads(l) + a(l) <= i) l += 1
      lines(i) = l
    }

    val links = new Array[Int](n+1)
    for (i <- 2 to n) {
      l = lines(i)
      if (i == heads(l)) {
        links(i) = heads(l-1)
      } else {
        val z = i - heads(l) + heads(l - 1)
        val onPrev = lines(z) == l - 1
        if (dk > 0) {
          links(i) = heads(l-1)
          if (onPrev) dk -= 1
        } else {
          if (onPrev) links(i) = z
          else links(i) = heads(l-1)
        }
      }
    }
    assert(dk == 0)

    val out = new PrintWriter(System.out)
    out.println(n)
    for (i <- 2 to n) out.println(links(i) + " " + i)
    out.close()

  }.getOrElse(println(-1))
}


Alice has a grid with $$$2$$$ rows and $$$n$$$ columns. She fully covers the grid using $$$n$$$ dominoes of size $$$1 \times 2$$$ — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino.Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the width of the grid. The second line of each test case contains a string $$$s$$$ consisting of $$$n$$$ characters, each of which is either L, R, U, or D, representing the left, right, top, or bottom half of a domino, respectively (see notes for better understanding). This string represents one of the rows of the grid.  Additional constraint on the input: each input corresponds to at least one valid tiling.

For each test case, output one string — the other row of the grid, using the same format as the input string. If there are multiple answers, print any.

NoteIn the first test case, Alice shows Bob the top row, the whole grid may look like:   In the second test case, Alice shows Bob the bottom row, the whole grid may look like:   In the third test case, Alice shows Bob the bottom row, the whole grid may look like:   In the fourth test case, Alice shows Bob the top row, the whole grid may look like:

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

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

    def main(args: Array[String]): Unit = {
        val t = readInt()
        var n = 0
        var s = ""
        for (tt <- 1 to t) {
            n = readInt()
            s = readString()
            for (i <- 0 until s.length) {
                if (s(i) == 'U')
                    writer.print('D')
                else if (s(i) == 'D')
                    writer.print('U')
                else if (s(i) == 'L')
                    writer.print('L')
                else writer.print('R')
            }
            writer.flush()
            println()
        }
    }
}

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

object test {
    class FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in))
        var br: BufferedReader = _
        var st: StringTokenizer = _

        def next: String = {
            while ( {
                st == null || !st.hasMoreElements
            }) try st = new StringTokenizer(br.readLine)
            catch {
                case e: IOException =>
                    e.printStackTrace()
            }
            st.nextToken
        }

        def nextInt: Int = next.toInt

        def nextLong: Long = next.toLong

        def nextDouble: Double = next.toDouble

        def nextLine: String = {
            var str = ""
            try str = br.readLine
            catch {
                case e: IOException =>
                    e.printStackTrace()
            }
            str
        }
    }

    def main(args: Array[String]): Unit = {
        val fastReader = new test.FastReader
        val t = fastReader.nextInt
        var n = 0
        var s = ""
        for (tt <- 1 to t) {
            n = fastReader.nextInt
            s = fastReader.nextLine
            for (i <- 0 until s.length) {
                if (s(i) == 'U')
                    print('D')
                else if (s(i) == 'D')
                    print('U')
                else if (s(i) == 'L')
                    print('L')
                else print('R')
            }
            println()
        }
    }
}

import scala.io.StdIn._

object test {
    def main(args: Array[String]): Unit = {
        val t = readInt()
        var n = 0
        var s = ""
        for (tt <- 1 to t) {
            n = readInt()
            s = readLine()
            for (i <- 0 until s.length) {
                if (s(i) == 'U')
                    print('D')
                else if (s(i) == 'D')
                    print('U')
                else if (s(i) == 'L')
                    print('L')
                else print('R')
            }
            println()
        }
    }
}

import scala.io.StdIn._

object test {
    def main(args: Array[String]): Unit = {
        val t = readInt()
        var n = 0
        var s = ""
        for (tt <- 1 to t) {
            n = readInt()
            s = readLine()
            for (x <- s) {
                if (x == 'U')
                    print('D')
                else if (x == 'D')
                    print('U')
                else if (x == 'L')
                    print('L')
                else print('R')
            }
            println()
        }
    }
}

import scala.io.StdIn._

object test {
    def main(args: Array[String]): Unit = {
        val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'L', 'R' -> 'R')
        val t = readInt()
        var n = 0
        var s = ""
        for (tt <- 1 to t) {
            n = readInt()
            s = readLine()
            for (i <- s)
                print(mp(i))
            println()
        }
    }
}

import scala.io.StdIn._

object test {
    def main(args: Array[String]): Unit = {
        val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'L', 'R' -> 'R')
        val t = readInt()
        var n = 0
        var s = ""
        for (tt <- 1 to t) {
            n = readInt()
            s = readLine()
            for (i <- 0 until s.length)
                print(mp(s(i)))
            println()
        }
    }
}

import scala.io.StdIn._

object test {
    def main(args: Array[String]): Unit = {
        val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'L', 'R' -> 'R')
        val t = readInt()
        for (tt <- 1 to t) {
            val n = readInt()
            val s = readLine()
            for (i <- 0 until s.length)
                print(mp(s(i)))
            println()
        }
    }
}

import scala.io.StdIn._

object test {
    def main(args: Array[String]): Unit = {
        val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'L', 'R' -> 'R')
        var t = readInt()
        for (tt <- 1 to t) {
            var n = readInt()
            var s = readLine()
            for (i <- 0 until s.length)
                print(mp(s(i)))
            println()
        }
    }
}

object A extends App {

  def grid(row: String): String =
    row.map {
      case 'U' => 'D'
      case 'D' => 'U'
      case 'L' => 'L'
      case 'R' => 'R'
    }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n = readInt()
    val s = readLine()

    println(grid(s))
  }

}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.Sorting.quickSort
import util.control.Breaks._

object Solution {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {
        while (!st.hasMoreTokens) {
            st = new StringTokenizer(reader.readLine())
        }
        st.nextToken()
    }

    def readInt() = next.toInt
    def readLong() = next.toLong
    def readString() = next()

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

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

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val s = readString()
        for (i <- 0 until n ) {
            if (s(i) == 'U')
                writer.print('D')
            else if (s(i) == 'D')
                writer.print('U')
            else writer.print(s(i))
        }

        writer.println()

    }

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

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

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

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

    def main(args: Array[String]): Unit = {
        val t = readInt()
        var n = 0
        var s = ""
        for (tt <- 1 to t) {
            n = readInt()
            s = readString()
            for (i <- 0 until s.length) {
                if (s(i) == 'U')
                    writer.print('D')
                else if (s(i) == 'D')
                    writer.print('U')
                else if (s(i) == 'L')
                    writer.print('L')
                else writer.print('R')
            }
            println()
        }
    }
}

import scala.io.StdIn._

object test {
    def main(args: Array[String]): Unit = {
        val mp = Map('U' -> 'D', 'D' -> 'U', 'L' -> 'R', 'R' -> 'L')
        var t = readInt()
        for (tt <- 1 to t) {
            var n = readInt()
            var s = readLine()
            for (i <- 0 until s.length)
                print(mp(s(i)))
            println()
        }
    }
}


One day Vasya came up to the blackboard and wrote out n distinct integers from 1 to n in some order in a circle. Then he drew arcs to join the pairs of integers (a, b) (a ≠ b), that are either each other's immediate neighbors in the circle, or there is number c, such that a and с are immediate neighbors, and b and c are immediate neighbors. As you can easily deduce, in the end Vasya drew 2·n arcs.For example, if the numbers are written in the circle in the order 1, 2, 3, 4, 5 (in the clockwise direction), then the arcs will join pairs of integers (1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (1, 3), (2, 4), (3, 5), (4, 1) and (5, 2).Much time has passed ever since, the numbers we wiped off the blackboard long ago, but recently Vasya has found a piece of paper with 2·n written pairs of integers that were joined with the arcs on the board. Vasya asks you to find the order of numbers in the circle by these pairs.

The first line of the input contains a single integer n (5 ≤ n ≤ 105) that shows, how many numbers were written on the board. Next 2·n lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers that were connected by the arcs. It is guaranteed that no pair of integers, connected by a arc, occurs in the input more than once. The pairs of numbers and the numbers in the pairs are given in the arbitrary order.

If Vasya made a mistake somewhere and there isn't any way to place numbers from 1 to n on the circle according to the statement, then print a single number "-1" (without the quotes). Otherwise, print any suitable sequence of n distinct integers from 1 to n.  If there are multiple solutions, you are allowed to print any of them. Specifically, it doesn't matter which number you write first to describe the sequence of the order. It also doesn't matter whether you write out the numbers in the clockwise or counter-clockwise direction.

object C{
  def main(args:Array[String]){

    val n=readLine.toInt
    //arcs
    val arcs=new Array[Set[Int]](n);
    (0 to n-1).foreach(i=> arcs(i)=Set())

    (1 to 2*n).foreach{i=>
      val (a,b)={
        val sp=readLine.split(" ")
        (sp(0).toInt-1 , sp(1).toInt-1)
      }
      arcs(a)+=b
      arcs(b)+=a
    }//arc

    if(arcs.count(_.size!=4)>0){
      //NG
      println(-1)
      return
    }

    //check
    def check(p:List[Int]):Boolean={
      if(p.length!=n){
        false
      }else{
        val ap=p.toArray
        val arcs2=new Array[Set[Int]](n);
        (0 until n).foreach{i=>
          arcs2(ap(i))=Set(-2,-1,1,2).map{ii=>ap((i+ii+n)%n)}
        }
        //ret
        (0 to n-1).forall{i=>
          arcs(i)==arcs2(i)
        }
      }
    }

    //p or null
    val p=
      if(n<=6){
        //全pをcheck
        (0 until n).permutations.map(_.toList).find(check(_)).orNull

      }else{
        val done=new Array[Boolean](n)
        //pp
        val pp={
          def rec(now:Int,l:List[Int]):List[Int]={
            done(now)=true
            def neighbor(a:Int, b:Int):Boolean={
              (arcs(a)&arcs(b)).size==2
            }
            val nbopt=arcs(now).find{a=> !done(a)&&neighbor(a,now)}
            if(nbopt.isEmpty){
              now::l
            }else{
              rec(nbopt.get,now::l)
            }
          }
          rec(0,Nil)
        }//pp

        if(check(pp)) pp else null
      }//p

    println(if(p==null) -1 else p.map(_ +1).mkString(" "))//end
  }
}

object C{
  def main(args:Array[String]){

    val n=readLine.toInt
    //arcs
    val arcs=new Array[Set[Int]](n);
    (0 to n-1).foreach(i=> arcs(i)=Set())

    (1 to 2*n).foreach{i=>
      val (a,b)={
        val sp=readLine.split(" ")
        (sp(0).toInt-1 , sp(1).toInt-1)
      }
      arcs(a)+=b
      arcs(b)+=a
    }//arc

    if(arcs.count(_.size!=4)>0){
      //NG
      println(-1)
      return
    }

    //check
    def check(p:List[Int]):Boolean={
      if(p.length!=n){
        false
      }else{
        val ap=p.toArray
        val arcs2=new Array[Set[Int]](n);
        (0 until n).foreach{i=>
          arcs2(ap(i))=Set(-2,-1,1,2).map{ii=>ap((i+ii+n)%n)}
        }
        //ret
        (0 to n-1).forall{i=>
          arcs(i)==arcs2(i)
        }
      }
    }

    //p or null
    val p=
      if(n<=6){
        //全pをcheck
        (0 until n).permutations.map(_.toList).find(check(_)).orNull

      }else{
        //pp
        val pp:List[Int]={
          val done=new Array[Boolean](n)
          val l=scala.collection.mutable.ListBuffer[Int]()

          def rec(now:Int){
            done(now)=true
            def neighbor(a:Int, b:Int):Boolean={
              (arcs(a)&arcs(b)).size==2
            }
            val nbopt=arcs(now).find{a=> !done(a)&&neighbor(a,now)}
            l+=now
            if(nbopt.isDefined){
              rec(nbopt.get)
            }
          }
          rec(0)
          l.toList
        }//pp

        if(check(pp)) pp else null
      }//p

    println(if(p==null) -1 else p.map(_ +1).mkString(" "))//end
  }
}

object C{
  def main(args:Array[String]){

    val n=readLine.toInt
    //arcs
    val arcs=new Array[Set[Int]](n);
    (0 to n-1).foreach(i=> arcs(i)=Set())

    (1 to 2*n).foreach{i=>
      val (a,b)={
        val sp=readLine.split(" ")
        (sp(0).toInt-1 , sp(1).toInt-1)
      }
      arcs(a)+=b
      arcs(b)+=a
    }//arc

    if(arcs.count(_.size!=4)>0){
      //NG
      println(-1)
      return
    }

    //check
    def check(p:List[Int]):Boolean={
      if(p.length!=n){
        false
      }else{
        val ap=p.toArray
        val arcs2=new Array[Set[Int]](n);
        (0 until n).foreach{i=>
          arcs2(ap(i))=Set(-2,-1,1,2).map{ii=>ap((i+ii+n)%n)}
        }
        //ret
        (0 to n-1).forall{i=>
          arcs(i)==arcs2(i)
        }
      }
    }

    //p or null
    val p=
      if(n<=6){
        //全pをcheck
        (0 until n).permutations.map(_.toList).find(check(_)).orNull

      }else{
        val done=new Array[Boolean](n)
        //pp
        val pp={
          def rec(now:Int,l:List[Int]):List[Int]={
            def neighbor(a:Int, b:Int):Boolean={
              (arcs(a)&arcs(b)).size==2
            }
            val nbopt=arcs(now).find{a=> !done(a)&&neighbor(a,now)}
            if(nbopt.isEmpty){
              now::l
            }else{
              done(nbopt.get)=true
              rec(nbopt.get,now::l)
            }
          }
          rec(0,Nil)
        }//pp

        if(check(pp)) pp else null
      }//p

    println(if(p==null) -1 else p.map(_ +1).mkString(" "))//end
  }
}


There are three cells on an infinite 2-dimensional grid, labeled $$$A$$$, $$$B$$$, and $$$F$$$. Find the length of the shortest path from $$$A$$$ to $$$B$$$ if:   in one move you can go to any of the four adjacent cells sharing a side;  visiting the cell $$$F$$$ is forbidden (it is an obstacle).

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first one contains two integers $$$x_A, y_A$$$ ($$$1 \le x_A, y_A \le 1000$$$) — coordinates of the start cell $$$A$$$. The second one contains two integers $$$x_B, y_B$$$ ($$$1 \le x_B, y_B \le 1000$$$) — coordinates of the finish cell $$$B$$$. The third one contains two integers $$$x_F, y_F$$$ ($$$1 \le x_F, y_F \le 1000$$$) — coordinates of the forbidden cell $$$F$$$. All cells are distinct. Coordinate $$$x$$$ corresponds to the column number and coordinate $$$y$$$ corresponds to the row number (see the pictures below).

Output $$$t$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th test case: the length of the shortest path from the cell $$$A$$$ to the cell $$$B$$$ if the cell $$$F$$$ is not allowed to be visited.

Note    An example of a possible shortest path for the first test case.     An example of a possible shortest path for the second test case.

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    readLine()
    val Array(xa, ya) = readLine().split(" ").map(_.toInt)
    val Array(xb, yb) = readLine().split(" ").map(_.toInt)
    val Array(xf, yf) = readLine().split(" ").map(_.toInt)

    val (x1, x2) = (xa min xb, xa max xb)
    val (y1, y2) = (ya min yb, ya max yb)

    val ans =
      x2 - x1 +
        y2 - y1 +
        (if (x1 == x2 && x1 == xf && y1 < yf && yf < y2 || y1 == y2 && y1 == yf && x1 < xf && xf < x2) 2 else 0)

    println(ans)
  }
}