In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.We will consider an extremely simplified subset of Python with only two types of statements.Simple statements are written in a single line, one per line. An example of a simple statement is assignment.For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.

The first line contains a single integer N (1 ≤ N ≤ 5000) — the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.

Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.

NoteIn the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.simple statementfor statement    for statement        simple statementIn the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.for statement    simple statement    for statement        simple statementorfor statement    simple statementfor statement    simple statement

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

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

object Main extends App {

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val n = in.nextInt
  var prev = ""

  var cnt = 0
  var d = new Array[Int](n+1)

  for (i <- 0 to n-1) {

    val s = in.next
    val nd = new Array[Int](n+1)
    prev match {
      case "f" => {
        for (i <- 1 to n) nd(i) = d(i-1)
      }
      case "s" => {
        var sum = 0
        for (i <- n to 0 by -1) {
          sum += d(i)
          sum %= MOD
          nd(i) = sum
        }
      }
      case _ => nd(0) = 1
    }
    //println(nd(0))
    d = nd
    prev = s
  }

  var ans = 0
  for (k <- d) ans = (ans + k)%MOD

  out.println(ans)
  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

object C extends App {

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

  val Array(n) = readInts(1)

  val MOD = 1000000007L

  val dp = Array.fill(n + 1){ 0L }
  var fCount = 0
  var prev = '-'
  dp(0) = 1
  //println(dp.mkString(" "))
  for (_ <- 0 until n) {
    val c = readLine.head
    if (prev != 'f' && c == 's') {
      for (i <- fCount - 1 to 0 by -1) dp(i) = (dp(i) + dp(i + 1)) % MOD
    } else {
      if (prev != 'f') for (i <- fCount - 1 to 0 by -1) dp(i) = (dp(i) + dp(i + 1)) % MOD
      if (c == 'f') {
        fCount += 1
        for (i <- fCount - 1 to 0 by -1) dp(i + 1) = dp(i)
        dp(0) = 0
      }
    }
    //println(dp.mkString(" "))
    prev = c
  }

  var sum = 0L
  for (x <- dp) sum = (sum + x) % MOD

  println(sum)
}

/**
  * @see http://codeforces.com/contest/909/problem/C
  */

object CPythonIndentation extends App {
  val mod = 1000000007

  val n = scala.io.StdIn.readInt()

  val t = (0 until (n - 1)).foldLeft(List(1)) ((l, _) => {
    val c = scala.io.StdIn.readChar()
    if (c == 'f') 0 +: l
    else l.foldRight(List.empty[Int]) ((i, l) => {
      if (l.isEmpty) List(i)
      else ((i + l.head) % mod) +: l
    })
  }).reduce((a, b) => (a + b) % mod)

  println(t)
}

object C extends App {

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

  val Array(n) = readInts(1)

  val MOD = 1000000007L

  val dp = Array.fill(n + 1){ 0L }
  var fCount = 0
  var prev = '-'

  for (_ <- 0 until n) {
    val c = readLine.head
    if (prev != 'f') {
      if (c == 's') for (i <- fCount - 1 to 0 by -1) dp(i) = (dp(i) + dp(i + 1)) % MOD
    } else if (c == 's') {
      dp(fCount) += 1
    }
    if (c == 'f') {
      fCount += 1
    }
    //println(dp.mkString(" "))
    prev = c
  }

  var sum = 0L
  for (x <- dp) sum = (sum + x) % MOD

  if (fCount == 0) sum = 1L

  println(sum)
}

/**
  * @see http://codeforces.com/contest/909/problem/C
  */

object CPythonIndentation extends App {
  val mod = 1000000007

  val N = scala.io.StdIn.readInt()

  def f(l: List[Int], m: List[Int] = List.empty): List[Int] =
    if (l.isEmpty) m
    else f(l.tail, (l.sum % mod) +: m)

  val t = (0 until N).foldLeft((List.empty[Int], 'c')) ((h, i) => {
    val c = scala.io.StdIn.readChar()
    if (i == 0) (List(1), c)
    else if (h._2 == 'f') (0 +: h._1, c)
    else (f(h._1), c)
  })._1

  println(t.sum % mod)
}


There are $$$n$$$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let $$$x$$$ be the number of such pairs of students in a split. Pairs $$$(a, b)$$$ and $$$(b, a)$$$ are the same and counted only once.For example, if there are $$$6$$$ students: "olivia", "jacob", "tanya", "jack", "oliver" and "jessica", then:  splitting into two classrooms ("jack", "jacob", "jessica", "tanya") and ("olivia", "oliver") will give $$$x=4$$$ ($$$3$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom),  splitting into two classrooms ("jack", "tanya", "olivia") and ("jessica", "oliver", "jacob") will give $$$x=1$$$ ($$$0$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom). You are given the list of the $$$n$$$ names. What is the minimum $$$x$$$ we can obtain by splitting the students into classrooms?Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty.

The first line contains a single integer $$$n$$$ ($$$1\leq n \leq 100$$$) — the number of students. After this $$$n$$$ lines follow. The $$$i$$$-th line contains the name of the $$$i$$$-th student. It is guaranteed each name is a string of lowercase English letters of length at most $$$20$$$. Note that multiple students may share the same name.

The output must consist of a single integer $$$x$$$ — the minimum possible number of chatty pairs.

7
kambei
gorobei
shichiroji
kyuzo
heihachi
katsushiro
kikuchiyo

NoteIn the first sample the minimum number of pairs is $$$1$$$. This can be achieved, for example, by putting everyone except jose in one classroom, and jose in the other, so jorge and jerry form the only chatty pair.In the second sample the minimum number of pairs is $$$2$$$. This can be achieved, for example, by putting kambei, gorobei, shichiroji and kyuzo in one room and putting heihachi, katsushiro and kikuchiyo in the other room. In this case the two pairs are kambei and kyuzo, and katsushiro and kikuchiyo.In the third sample the minimum number of pairs is $$$4$$$. This can be achieved by placing three of the students named mike in one classroom and the other two students in another classroom. Thus there will be three chatty pairs in one classroom and one chatty pair in the other classroom.

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val C = Array.ofDim[Int](26)
    REP(N) { _ =>
      val c = ns().head - 'a'
      C(c) += 1
    }

    debug(C)

    def comb(n: Int) = {
      if (n < 2) 0
      else n * (n - 1) / 2
    }

    var ans = 0
    REP(26) { i =>
      if (C(i) >= 2) {
        val f = C(i) / 2
        val s = C(i) - f
        debug(s"f:$f s:$s")
        ans += comb(f) + comb(s)
      }
    }

    out.println(ans)
  }
}

object Main extends App {

	def factorial(n: Int) : Double = {
	    var result : Double = 1

	    for ( i <- 2 to n ) {
	    	result *= i
	    }

	    return result
	}

	// your code goes here
	var n = Console.readLine
	var size : Int = n.toInt
	var arrName : Array[String] = new Array[String](size)
	var arrCount : Array[Int] = new Array[Int](30)
	var ans : Double = 0

	for ( i <- 0 to size-1) {
		arrName(i) = Console.readLine
	}

	for (i <- 0 to 29) {
		arrCount(i) = 0
	}

	for ( i <- 0 to size-1) {
		var pos : Int = arrName(i).charAt(0) - 'a'
		arrCount(pos) += 1
	}

	for (i <- 0 to 29) {
		var room1 : Int = arrCount(i)/2
		var room2 : Int = arrCount(i) - room1

		if ( room1 > 1 ) {
			ans += factorial(room1) / 2 / factorial(room1 - 2)
		}

		if ( room2 > 1 ) {
			ans += factorial(room2) / 2 / factorial(room2 - 2)
		}
	}

	println(ans.toLong)
}

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

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

    val ans = students
      .groupBy(_.head)
      .mapValues(grps => pairs(grps.size))
      .values
      .sum

    io.write(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

object Main extends App {

	def factorial(n: Int): Int = n match {
	    case 0 => 1
	    case _ => n * factorial(n-1)
	}

	// your code goes here
	var n = Console.readLine
	var size : Int = n.toInt
	var arrName : Array[String] = new Array[String](size)
	var arrCount : Array[Int] = new Array[Int](30)
	var ans : Long = 0

	for ( i <- 0 to size-1) {
		arrName(i) = Console.readLine
	}

	for (i <- 0 to 29) {
		arrCount(i) = 0
	}

	for ( i <- 0 to size-1) {
		var pos : Int = arrName(i).charAt(0) - 'a'
		arrCount(pos) += 1
	}

	for (i <- 0 to 29) {
		var room1 : Int = arrCount(i)/2
		var room2 : Int = arrCount(i) - room1

		if ( room1 > 1 ) {
			ans += factorial(room1) / 2 / factorial(room1 - 2)
		}

		if ( room2 > 1 ) {
			ans += factorial(room2) / 2 / factorial(room2 - 2)
		}
	}

	println(ans)
}


Nick had received an awesome array of integers $$$a=[a_1, a_2, \dots, a_n]$$$ as a gift for his $$$5$$$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $$$a_1 \cdot a_2 \cdot \dots a_n$$$ of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := -a_i - 1$$$.For example, he can change array $$$[3, -1, -4, 1]$$$ to an array $$$[-4, -1, 3, 1]$$$ after applying this operation to elements with indices $$$i=1$$$ and $$$i=3$$$. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements $$$a_1 \cdot a_2 \cdot \dots a_n$$$ which can be received using only this operation in some order.If there are multiple answers, print any of them.

The first line contains integer $$$n$$$ ($$$1 \leq n \leq 10^{5}$$$) — number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^{6} \leq a_i \leq 10^{6}$$$) — elements of the array

Print $$$n$$$ numbers — elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array. If there are multiple answers, print any of them.

//package round569

import scala.io.StdIn._

object TaskB extends App {
  val n = readInt
  val arr = readLine.split(" ").map(_.toInt).map(x => if(x == 0) -1 else if (x > 0) -x - 1 else x)
  if (arr.length % 2 == 0)
    println(arr.mkString(" "))
  else {
    val max = arr.min
    var flag = false
    println(arr.map {
      x =>
        if(x == max && !flag) {
          flag = true
          -x - 1
        } else {
          x
        }
    }.mkString(" "))
  }
}

import scala.io.StdIn._

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

  A = A.map { v =>
    if (v >= 0) -v - 1 else v
  }

  if (A.count(_ < 0) % 2 == 1) {
    val (_, minId) = A.zipWithIndex.minBy(_._1)
    A(minId) = -A(minId) - 1
  }

  println(A.mkString(" "))

}

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
  //val out: PrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt).map(x => if (x >= 0) -x - 1 else x )
  if (a.foldLeft(0)((acc, x) => if (x < 0) acc + 1 else acc) % 2 == 1) {
    var min = a.min
    for (i <- 0 until n)
      if (a(i) == min) {
        a(i) = -min - 1
        min = 0
      }
  }
  out.print(a.mkString(" "))
  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    def nextDouble: Double = next.toDouble

    def nextLine: String = br.readLine
  }

}

import scala.io.StdIn._

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

  var B = A.sorted

  B = B.map { v =>
    if (v >= 0) -v - 1 else v
  }

  var answer = B.product
  if (answer <= 0) {
    val (min, minId) = B.zipWithIndex.minBy(_._1)
    B(minId) = -B(minId) - 1
  }

  println(B.mkString(" "))

}

import scala.io.StdIn._

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

  val B = A.zipWithIndex.sortBy(_._1)

  var left  = 0
  var right = n - 1

  val negatives = B.count(_._1 < 0)
  val positives = B.count(_._1 > 0)

  if (negatives % 2 == 0) {
    var right = B.length - 2
    while (right >= 0 && B(right)._1 >= 0) {
      B(right + 1) = (-B(right + 1)._1 - 1, B(right + 1)._2)
      B(right) = (-B(right)._1 - 1, B(right)._2)
      right -= 2
    }
  } else {
    var right = B.length - 1
    while (right > 0 && B(right)._1 > 0) {
      B(right) = (-B(right)._1 - 1, B(right)._2)
      right -= 1
    }
  }

  var zeros = B.count(_._1 == 0)

  val newNegatives = B.count(_._1 < 0)
  if (newNegatives % 2 == 1) {
    zeros = if (zeros % 2 == 1) zeros else zeros - 1
  } else {
    zeros = if (zeros % 2 == 0) zeros else zeros - 1
  }
  if (zeros < 0) zeros = 0

  var i = 0
  while (zeros > 0) {
    if (B(i)._1 == 0) {
      B(i) = (-1, B(i)._2)
      zeros -= 1
    }
    i += 1
  }

  println(B.sortBy(_._2).map(_._1).mkString(" "))
}

import scala.io.StdIn._

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

  A = A.map { v =>
    if (v >= 0) -v - 1 else v
  }

  var answer = A.product
  if (answer <= 0) {
    val (min, minId) = A.zipWithIndex.minBy(_._1)
    A(minId) = -A(minId) - 1
  }

  println(A.mkString(" "))

}

import scala.io.StdIn._

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

  val B = A.sorted

  var left  = 0
  var right = n - 1

  val negatives = B.count(_ < 0)
  val positives = B.count(_ > 0)

  if (negatives % 2 == 0) {
    var right = B.length - 2
    while (right >= 0 && B(right) >= 0) {
      B(right + 1) = -B(right + 1) - 1
      B(right) = -B(right) - 1
      right -= 2
    }
  } else {
    var right = B.length - 1
    while (right > 0 && B(right) > 0) {
      B(right) = -B(right) - 1
      right -= 1
    }
  }

  var zeros = B.count(_ == 0)

  val newNegatives = B.count(_ < 0)
  if (newNegatives % 2 == 1) {
    zeros = if (zeros % 2 == 1) zeros else zeros - 1
  } else {
    zeros = if (zeros % 2 == 0) zeros else zeros - 1
  }
  if (zeros < 0) zeros = 0

  var i = 0
  while (zeros > 0) {
    if (B(i) == 0) {
      B(i) = -1
      zeros -= 1
    }
    i += 1
  }

  println(B.mkString(" "))
}

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
  //val out: PrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))

  val n = in.nextInt
  val a = in.nextLine.split(' ').map(_.toInt).map(x => if (x >= 0) -x - 1 else x )
  if (a.foldLeft(0)((acc, x) => if (x < 0) acc + 1 else acc) % 2 == 1)
    a(0) = -a(0) - 1
  out.print(a.mkString(" "))
  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    def nextDouble: Double = next.toDouble

    def nextLine: String = br.readLine
  }

}


Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.

The first line contains two integer n and m (1 ≤ n, m ≤ 100). The second line contains integer b (0 ≤ b ≤ n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≤ xi < n), denoting the list of indices of happy boys. The third line conatins integer g (0 ≤ g ≤ m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≤ yj < m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.

If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".

NoteBy  we define the remainder of integer division of i by k.In first sample case:   On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day.  On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day.  On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day.  On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy.  On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.

object B515F extends App {

    def readNextLine : Array[Int] = {
      readLine.split(" ").map(_.toInt)
    }

    def becomeHappy (pair : (Int, Int), hg : Array[Int], hl: Array[Int], isHappy: Int) : Boolean = {
      def exist(arr : Array[Int], value : Int) : Int =
        arr.contains(value) match { case true => 1; case false => 0}
      (exist(hg, pair._1) + exist(hl, pair._2)) == isHappy
    }

    def isStuck(tg : List[(Int, Int)], hg : Array[Int], hl : Array[Int]) : Boolean = {
      tg.filter(pair =>
       becomeHappy(pair, hg, hl, 1) || becomeHappy(pair, hg, hl, 2) ).isEmpty
    }

    def B515F = {
      val l : Array[Int] = readNextLine
      val n = l(0)
      val m = l(1)
      val t = n * m
      var guys : List[Int] = Nil
      var gals : List[Int] = Nil

      for(i <- 0 until t) {
         guys ::= i % n
         gals ::= i % m
      }

      var together = guys.zip(gals).distinct

      var happyGuys : Array[Int] = (readNextLine) drop 1
      var happyGals : Array[Int] = (readNextLine) drop 1
      var willBeHappy : List[(Int, Int)] = Nil

      do {

        willBeHappy = together.filter(pair => becomeHappy(pair, happyGuys, happyGals, 1) || becomeHappy(pair, happyGuys, happyGals, 2))
        together = together.filter(pair => ! (becomeHappy(pair, happyGuys, happyGals, 1) || becomeHappy(pair, happyGuys, happyGals, 2)))
        happyGuys ++= willBeHappy.map(pair => pair._1)
        happyGals ++= willBeHappy.map(pair => pair._2)
      } while(!isStuck(together, happyGuys, happyGals) && !together.isEmpty)

       println(together.isEmpty match {case true => "Yes"; case false => "No"})
    }

 B515F

}

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

  def checkAllHappy(boys: Array[Boolean], girls: Array[Boolean]): Boolean = {
    boys.foreach((b) => {
      if (!b) {
        return false
      }
    })
    girls.foreach((b) => {
      if (!b) {
        return false
      }
    })
    true
  }

  def solve() = {
    val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val b: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val g: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val boys: Array[Boolean] = Array.ofDim[Boolean](n)
    val girls: Array[Boolean] = Array.ofDim[Boolean](m)
    for (i <- 0 until b.head) {
      boys(b(i+1)) = true
    }
    for (i <- 0 until g.head) {
      girls(g(i+1)) = true
    }

    for (i <- 0 until 100 * 100) {
      val boyId = i % n
      val girlId = i % m
      if (boys(boyId) || girls(girlId)) {
        boys(boyId) = true
        girls(girlId) = true
      }
    }

    if (checkAllHappy(boys, girls)) {
      println("Yes")
    } else {
      println("No")
    }
  }

  solve()

}

import java.util.Scanner

/**
 * Created by root on 2/21/15.
 */
object Drazil2 {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val m = sc.nextInt()

    val boys = Array.tabulate[Int](n)(_ => 0)
    val girls = Array.tabulate[Int](m)(_ => 0)

    (0 until sc.nextInt()) foreach { _ =>
      boys(sc.nextInt()) = 1
    }

    (0 until sc.nextInt()) foreach { _ =>
      girls(sc.nextInt()) = 1
    }

    val max = n*m

    for (i<- 0 to 2*max) {
      val b = i%n
      val g = i%m
      if (boys(b) == 1) {
        girls(g) = 1
      }
      if (girls(g) == 1){
        boys(b) = 1
      }
    }

    val ans = boys.filter(bf => bf ==0).size + girls.filter(gf => gf == 0).size
    if (ans == 0)
      println("Yes")
    else
      println("No")

  }

}

import java.util.Scanner

/**
 * Created by root on 2/21/15.
 */
object Drazil2 {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val m = sc.nextInt()

    val boys = Array.tabulate[Int](n)(_ => 0)
    val girls = Array.tabulate[Int](m)(_ => 0)

    (0 until sc.nextInt()) foreach { _ =>
      boys(sc.nextInt()) = 1
    }

    (0 until sc.nextInt()) foreach { _ =>
      girls(sc.nextInt()) = 1
    }

    val max = n*m

    for (i<- 0 until max) {
      val b = i%n
      val g = i%m
      if (boys(b) == 1) {
        girls(g) = 1
      }
      if (girls(g) == 1){
        boys(b) = 1
      }
    }

    val ans = boys.filter(bf => bf ==0).size + girls.filter(gf => gf == 0).size
    if (ans == 0)
      println("Yes")
    else
      println("No")

  }

}


There are $$$n$$$ dormitories in Berland State University, they are numbered with integers from $$$1$$$ to $$$n$$$. Each dormitory consists of rooms, there are $$$a_i$$$ rooms in $$$i$$$-th dormitory. The rooms in $$$i$$$-th dormitory are numbered from $$$1$$$ to $$$a_i$$$.A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $$$n$$$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $$$1$$$ to $$$a_1 + a_2 + \dots + a_n$$$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.For example, in case $$$n=2$$$, $$$a_1=3$$$ and $$$a_2=5$$$ an envelope can have any integer from $$$1$$$ to $$$8$$$ written on it. If the number $$$7$$$ is written on an envelope, it means that the letter should be delivered to the room number $$$4$$$ of the second dormitory.For each of $$$m$$$ letters by the room number among all $$$n$$$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \le n, m \le 2 \cdot 10^{5})$$$ — the number of dormitories and the number of letters. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{10})$$$, where $$$a_i$$$ equals to the number of rooms in the $$$i$$$-th dormitory. The third line contains a sequence $$$b_1, b_2, \dots, b_m$$$ $$$(1 \le b_j \le a_1 + a_2 + \dots + a_n)$$$, where $$$b_j$$$ equals to the room number (among all rooms of all dormitories) for the $$$j$$$-th letter. All $$$b_j$$$ are given in increasing order.

Print $$$m$$$ lines. For each letter print two integers $$$f$$$ and $$$k$$$ — the dormitory number $$$f$$$ $$$(1 \le f \le n)$$$ and the room number $$$k$$$ in this dormitory $$$(1 \le k \le a_f)$$$ to deliver the letter.

NoteIn the first example letters should be delivered in the following order:  the first letter in room $$$1$$$ of the first dormitory  the second letter in room $$$9$$$ of the first dormitory  the third letter in room $$$2$$$ of the second dormitory  the fourth letter in room $$$13$$$ of the second dormitory  the fifth letter in room $$$1$$$ of the third dormitory  the sixth letter in room $$$12$$$ of the third dormitory

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = nal(N)
    val cum = cumSum(A)
    val L = nal(M)
    REP(M) { i =>
      val dorm = lowerBound(cum, L(i)) - 1
      out.println(s"${dorm + 1} ${L(i) - cum(dorm)}")
    }
  }

  // a >= x  [x-2, x-1, x, x, x, x+1] の 2
  def lowerBound(a: Array[Long], x: Long): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

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

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

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

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

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

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

object CF_978C {
	def main(args: Array[String]) {
		val temp_nm = readLine().split(" ")
		val n = temp_nm(0).toInt
		val m = temp_nm(1).toInt

		val temp_a = readLine().split(" ")
		val a = for(x <- temp_a) yield(x.toLong)

		val temp_b = readLine().split(" ")
		var prefix_sum = 0l
		var p = 0

		for(x_str <- temp_b)
		{
			val x = x_str.toLong
			while(x - prefix_sum > a(p))
			{
				prefix_sum += a(p)
				p+=1
			}
			printf("%d %d\n",p+1,x-prefix_sum)
		}

	}
}

object problemA {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable
    import scala.util.control.Breaks._
    import scala.collection.JavaConverters._

    val source = System.in
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val Array(n, m) = readArray().map(_.toInt)
        val a = readArray().map(_.toLong)
        val f = new Array[Long](n)
        f(0) = a(0)
        for (i <- 1 until n) f(i) = f(i - 1) + a(i)

        def find(k: Long): Int = {
            var (l, r) = (0, n - 1)
            var rs = 0
            while (l <= r) {
                val mid = (l + r) / 2
                if (f(mid) < k)
                    l = mid + 1
                else {
                    r = mid - 1
                    rs = mid
                }
            }
            rs
        }

        readArray().map(_.toLong).foreach(i => {
            val k = find(i)
            val t = if (k > 0) f(k - 1) else 0
            println(s"${k + 1} ${i - t}")
        })
    }
}


Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.Everybody knows that the World history encompasses exactly n events: the i-th event had continued from the year ai to the year bi inclusive (ai < bi). Polycarpus easily learned the dates when each of n events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event j includes an event i if aj < ai and bi < bj. Your task is simpler: find the number of events that are included in some other event.

The first input line contains integer n (1 ≤ n ≤ 105) which represents the number of events. Next n lines contain descriptions of the historical events, one event per line. The i + 1 line contains two integers ai and bi (1 ≤ ai < bi ≤ 109) — the beginning and the end of the i-th event. No two events start or finish in the same year, that is, ai ≠ aj, ai ≠ bj, bi ≠ aj, bi ≠ bj for all i, j (where i ≠ j). Events are given in arbitrary order.

Print the only integer — the answer to the problem.

NoteIn the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third — in the second and the second — in the first.In the second example all events except the first one are contained in the first.In the third example only one event, so the answer is 0.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map { _ =>
    val l = in.next().split(' ').map(_.toInt)
    (l.head, l.last)
  }.sorted
  println(data.foldLeft((0, 0)) {
    case((maxEnd, sum), (_, end)) =>
      if (end < maxEnd)
        (maxEnd, sum + 1)
      else
        (end, sum)
  }._2)
}


Let's denote the Manhattan distance between two points $$$p_1$$$ (with coordinates $$$(x_1, y_1)$$$) and $$$p_2$$$ (with coordinates $$$(x_2, y_2)$$$) as $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|$$$. For example, the distance between two points with coordinates $$$(1, 3)$$$ and $$$(4, 2)$$$ is $$$|1 - 4| + |3 - 2| = 4$$$.You are given two points, $$$A$$$ and $$$B$$$. The point $$$A$$$ has coordinates $$$(0, 0)$$$, the point $$$B$$$ has coordinates $$$(x, y)$$$.Your goal is to find a point $$$C$$$ such that:  both coordinates of $$$C$$$ are non-negative integers;  $$$d(A, C) = \dfrac{d(A, B)}{2}$$$ (without any rounding);  $$$d(B, C) = \dfrac{d(A, B)}{2}$$$ (without any rounding). Find any point $$$C$$$ that meets these constraints, or report that no such point exists.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 3000$$$) — the number of test cases. Each test case consists of one line containing two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 50$$$) — the coordinates of the point $$$B$$$.

For each test case, print the answer on a separate line as follows:   if it is impossible to find a point $$$C$$$ meeting the constraints, print "-1 -1" (without quotes);  otherwise, print two non-negative integers not exceeding $$$10^6$$$ — the coordinates of point $$$C$$$ meeting the constraints. If there are multiple answers, print any of them. It can be shown that if any such point exists, it's possible to find a point with coordinates not exceeding $$$10^6$$$ that meets the constraints.

NoteExplanations for some of the test cases from the example:  In the first test case, the point $$$B$$$ has coordinates $$$(49, 3)$$$. If the point $$$C$$$ has coordinates $$$(23, 3)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|49 - 0| + |3 - 0| = 52$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|23 - 0| + |3 - 0| = 26$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|23 - 49| + |3 - 3| = 26$$$.  In the second test case, the point $$$B$$$ has coordinates $$$(2, 50)$$$. If the point $$$C$$$ has coordinates $$$(1, 25)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|2 - 0| + |50 - 0| = 52$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|1 - 0| + |25 - 0| = 26$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|1 - 2| + |25 - 50| = 26$$$.  In the third and the fourth test cases, it can be shown that no point with integer coordinates meets the constraints.  In the fifth test case, the point $$$B$$$ has coordinates $$$(42, 0)$$$. If the point $$$C$$$ has coordinates $$$(21, 0)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|42 - 0| + |0 - 0| = 42$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|21 - 0| + |0 - 0| = 21$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|21 - 42| + |0 - 0| = 21$$$.

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

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

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

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

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

    val t = 1//readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        for (i <- 1 to n) {
            val x = readInt()
            val y = readInt()
            if ((x + y)%2 == 1) {
                writer.println("-1 -1")
            } else  {
                writer.println(((x+1)/2).toInt + " " + ((y)/2).toInt)
            }
        }
    }
    writer.flush()
}


William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.

NoteIn the first test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements:   swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$  swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$  swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$  swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$

object B extends App {

  def swaps(an: IndexedSeq[Int]): Option[Int] = {
    val odds = an.indices.collect { case i if an(i) % 2 == 1 => i }

    def count(startIndex: Int): Int =
      (odds zip (startIndex to (an.length, 2))).foldLeft(0) { case (c, (j, i)) => c + math.abs(i - j) }

    (odds.length, an.length - odds.length) match {
      case (ol, el) if ol == el     => Some(count(0) min count(1))
      case (ol, el) if ol == el + 1 => Some(count(0))
      case (ol, el) if el == ol + 1 => Some(count(1))
      case _                        => None
    }
  }

  import scala.io.StdIn._

  val t = readInt()

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

    swaps(an) match {
      case Some(count) => println(count)
      case None        => println(-1)
    }
  }

}

object B1556 {

  import scala.collection.mutable.ArrayBuffer

  /** TODO: Check! */
  private val multipleTests: Boolean = true

  def run(testNum: Int): Unit = {
    val n = int()
    val a = new ArrayBuffer[Int]()
    var even = 0
    var odd = 0
    for (_ <- 0 until n) {
      val x = int() % 2
      a += x
      if (x % 2 == 0)
        even += 1
      else
        odd += 1
    }
    if ((even - odd).abs > 1) {
      println(-1)
    } else {
      if (even > odd) {
        for (i <- 0 until n)
          a(i) = 1 - a(i)
      }
      var last = 0
      var ans: Long = 0
      for (i <- 0 until n) {
        if (a(i) == 1) {
          ans += (last - i).abs
          last += 2
        }
      }
      if (n % 2 == 0) {
        for (i <- 0 until n)
          a(i) = 1 - a(i)
        var secondAns: Long = 0
        var secondLast = 0
        for (i <- 0 until n) {
          if (a(i) == 1) {
            secondAns += (secondLast - i).abs
            secondLast += 2
          }
        }
        if (ans > secondAns) {
          println(secondAns)
        } else {
          println(ans)
        }
      } else {
        println(ans)
      }
    }
  }

  /** Template. */

  private val onlineJudge = System.getProperty("ONLINE_JUDGE") != null

  def main(args: Array[String]): Unit = {
    val t = if (multipleTests) reader.int() else 1
    (1 to t).foreach(run)
  }

  /** I/O. */

  import java.io._
  import java.nio.file._

  private val inputFileName = "input.txt"
  private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)

  private def string(): String = reader.string()
  private def int(): Int = reader.int()
  private def long(): Long = reader.long()
  private def double(): Double = reader.double()

  /** TODO: implement faster reader with buffer */
  /** TODO: implement writer */
  final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {
    import java.util.StringTokenizer

    def string(): String = next()
    def line(): String = tokenizer().get.nextToken("\n\r")
    def boolean(): Boolean = next().toBoolean
    def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
    def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
    def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
    def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
    def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
    def float(): Float = next().toFloat
    def double(): Double = next().toDouble
    def bigDecimal(): BigDecimal = BigDecimal(next())
    def lineNumber(): Int = linedDelegate.getLineNumber

    @inline def nextLine(): String = {
      current = None // reset the rest of current line
      delegate.readLine()
    }

    override def hasNext: Boolean = tokenizer().nonEmpty
    override def next(): String = tokenizer().getOrElse(throw new RuntimeException("End of input")).nextToken()
    override def close(): Unit = delegate.close()

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

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

  object FastReader {
    import scala.io.Codec

    def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)
    def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {
      Files.newBufferedReader(Paths.get(fileName), codec.charSet)
    }
    def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))
    def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {
      new BufferedReader(new InputStreamReader(inputStream, codec.charSet))
    }
  }
}


Today Pari and Arya are playing a game called Remainders.Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value . There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya  if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value  for any positive integer x?Note, that  means the remainder of x after dividing it by y.

The first line of the input contains two integers n and k (1 ≤ n,  k ≤ 1 000 000) — the number of ancient integers and value k that is chosen by Pari. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 1 000 000).

Print "Yes" (without quotes) if Arya has a winning strategy independent of value of x, or "No" (without quotes) otherwise.

NoteIn the first sample, Arya can understand  because 5 is one of the ancient numbers.In the second sample, Arya can't be sure what  is. For example 1 and 7 have the same remainders after dividing by 2 and 3, but they differ in remainders after dividing by 7.

import annotation.tailrec

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    var r = k
    for (x <- c) {
      r = gcd(r, k / gcd(k, x))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  @tailrec def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.specialized

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.specialized

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    var r = k
    for (x <- c) {
      r = gcd(r, k / gcd(k, x))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd[@specialized T](x: T, y: T)(implicit integral: Integral[T]): T = {
    import integral._
    if (y == 0)
      x
    else
      gcd(y, x % y)
  }

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import java.io.IOException
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object D {
  def main(args: Array[String]) = {
    val sc = new MyScanner()
    val n = sc.nextInt()
    val k = sc.nextInt()
    var r = k
    for (_i <- 1 to n) {
      val x = sc.nextInt()
      r = gcd(r, k / gcd(k, x))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)

  class MyScanner {
    val br = new BufferedReader(new InputStreamReader(System.in))

    var st = new StringTokenizer(br.readLine())

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

    def nextInt() = next().toInt
  }
}

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    var r = k
    for (x <- c) {
      r = gcd(r, k / gcd(k, x))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.specialized

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd[@specialized T](x: T, y: T)(implicit integral: Integral[T]): T =
    if (y == 0)
      x
    else
      gcd(y, integral.rem(x, y))

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import annotation.tailrec

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)
      println("Yes")
    else
      println("No")
  }

  @tailrec def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.specialized

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    var r = k
    for (x <- c) {
      r = gcd(r, k / gcd(k, r))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd[@specialized T](x: T, y: T)(implicit integral: Integral[T]): T = {
    import integral._
    if (y == 0)
      x
    else
      gcd(y, x % y)
  }

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}


Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not.A permutation triple of permutations of length n (a, b, c) is called a Lucky Permutation Triple if and only if . The sign ai denotes the i-th element of permutation a. The modular equality described above denotes that the remainders after dividing ai + bi by n and dividing ci by n are equal.Now, he has an integer n and wants to find a Lucky Permutation Triple. Could you please help him?

The first line contains a single integer n (1 ≤ n ≤ 105).

If no Lucky Permutation Triple of length n exists print -1. Otherwise, you need to print three lines. Each line contains n space-seperated integers. The first line must contain permutation a, the second line — permutation b, the third — permutation c. If there are multiple solutions, print any of them.

NoteIn Sample 1, the permutation triple ([1, 4, 3, 2, 0], [1, 0, 2, 4, 3], [2, 4, 0, 1, 3]) is Lucky Permutation Triple, as following holds:  ;  ;  ;  ;  . In Sample 2, you can easily notice that no lucky permutation triple exists.

object Main {
  def main(args: Array[String]) {
    val n = readInt()

    if (n % 2 == 0)
      println("-1")
    else {
      val a = 0 until n
      val b = a.map(k => (k + 1) % n)
      val c = a.zip(b).map { case (i, j) => (i + j) % n }

      println(a.mkString(" "))
      println(b.mkString(" "))
      println(c.mkString(" "))
    }
  }
}

import scala.io._
import java.util.StringTokenizer
import java.io.BufferedReader

object Main {

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

		if (n % 2 == 0)
			println(-1)
		else
		{
			val a = (0 until n)
			val b = for (i <- 0 until n) yield ((3 + i) % n)
			val c = a zip b map {case (a, b) => ((a+b) % n)}

			if (c.sorted != (0 until n))
				println("-1")
			else
			{
				println(a mkString(" "))
				println(b mkString(" "))
				println(c mkString(" "))
			}
		}
	}

	class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
	{
		private var tokenizer = new StringTokenizer("")
		def readLine() = in.readLine()
		def nextToken(): String = {
			while (!tokenizer.hasMoreTokens) {
				val line = readLine
				if (line == null) return null
				tokenizer = new StringTokenizer(line, splitOn)
			}
			tokenizer.nextToken
		}
		def next[A](f: String => A) = f(nextToken)
	}

	implicit val tokenizer = new Tokenizer(Console.in)

	def nextString()(implicit t: Tokenizer) = t.nextToken()
	def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
	def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
	def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
	def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
	def nextSeq[A](f : () => A, count: Int = nextInt()) = for (i <- 0 until count) yield f()
}

import scala.io._
import java.util.StringTokenizer
import java.io.BufferedReader

object Main {

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

		//if (n % 2 == 0)
//			println(-1)
		//else
		{
			for (i <- 0 until n) print(i + " ")
			println

			for (i <- 0 until n) print((3 * i % n) + " ")
			println

			for (i <- 0 until n) print(((4 * i) % n) + " ")
			println
		}
	}

	class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
	{
		private var tokenizer = new StringTokenizer("")
		def readLine() = in.readLine()
		def nextToken(): String = {
			while (!tokenizer.hasMoreTokens) {
				val line = readLine
				if (line == null) return null
				tokenizer = new StringTokenizer(line, splitOn)
			}
			tokenizer.nextToken
		}
		def next[A](f: String => A) = f(nextToken)
	}

	implicit val tokenizer = new Tokenizer(Console.in)

	def nextString()(implicit t: Tokenizer) = t.nextToken()
	def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
	def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
	def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
	def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
	def nextSeq[A](f : () => A, count: Int = nextInt()) = for (i <- 0 until count) yield f()
}

import scala.io._
import java.util.StringTokenizer
import java.io.BufferedReader

object Main {

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

		if (n % 2 == 0)
			println(-1)
		else
		{
			for (i <- 0 until n) print(i + " ")
			println

			for (i <- 0 until n) print((3 * i % n) + " ")
			println

			for (i <- 0 until n) print(((4 * i) % n) + " ")
			println
		}
	}

	class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
	{
		private var tokenizer = new StringTokenizer("")
		def readLine() = in.readLine()
		def nextToken(): String = {
			while (!tokenizer.hasMoreTokens) {
				val line = readLine
				if (line == null) return null
				tokenizer = new StringTokenizer(line, splitOn)
			}
			tokenizer.nextToken
		}
		def next[A](f: String => A) = f(nextToken)
	}

	implicit val tokenizer = new Tokenizer(Console.in)

	def nextString()(implicit t: Tokenizer) = t.nextToken()
	def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
	def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
	def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
	def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
	def nextSeq[A](f : () => A, count: Int = nextInt()) = for (i <- 0 until count) yield f()
}


You are given an array $$$a$$$ of length $$$n$$$. The array is called 3SUM-closed if for all distinct indices $$$i$$$, $$$j$$$, $$$k$$$, the sum $$$a_i + a_j + a_k$$$ is an element of the array. More formally, $$$a$$$ is 3SUM-closed if for all integers $$$1 \leq i < j < k \leq n$$$, there exists some integer $$$1 \leq l \leq n$$$ such that $$$a_i + a_j + a_k = a_l$$$.Determine if $$$a$$$ is 3SUM-closed.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output "YES" (without quotes) if $$$a$$$ is 3SUM-closed and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, there is only one triple where $$$i=1$$$, $$$j=2$$$, $$$k=3$$$. In this case, $$$a_1 + a_2 + a_3 = 0$$$, which is an element of the array ($$$a_2 = 0$$$), so the array is 3SUM-closed.In the second test case, $$$a_1 + a_4 + a_5 = -1$$$, which is not an element of the array. Therefore, the array is not 3SUM-closed.In the third test case, $$$a_i + a_j + a_k = 0$$$ for all distinct $$$i$$$, $$$j$$$, $$$k$$$, and $$$0$$$ is an element of the array, so the array is 3SUM-closed.

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

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

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

  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      tokenizer = new StringTokenizer(input.readLine())
      val A = ListBuffer.empty[Int]
      for (i <- 1 to n) A+= tokenizer.nextToken().toInt
      val B = A.toArray
      val C = A.toList
      var CC = C.filter(x => x != 0)
      if (CC.length >= 5) {
        output.println("NO")
      }
      else {
        var c1 = true
        if (CC.length != n) {
           CC = 0 :: CC
        }
        for {j <- CC.indices; k <- CC.indices; l <- CC.indices
             if ((j<k) && (k < l))} {
          if (!CC.contains(CC(j) + CC(l) + CC(k))) c1 = false
        }
        if (c1) {
          output.println("Yes")
        }
        else {
          output.println("NO")
        }
      }
    }
  }

}


Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.

The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space.

In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.

NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".

import scala.math._
import scala.collection.mutable
import scala.util.control.Breaks
import scala.annotation.tailrec

object Problem extends App {
  import Scanner._

  val n = readInt
  val degrees, sums = Array.ofDim[Int](n)
  val queue = mutable.Queue[Int]()
  for(i <- 0 until n) {
    degrees(i) = readInt
    sums(i) = readInt
    if(degrees(i) == 1)
      queue += i
  }

  val pairs = mutable.Set[(Int, Int)]()
  while(!queue.isEmpty) queue.dequeue match {
    case v if degrees(v) != 1 =>
    case v =>
      val t = sums(v)

      degrees(t) -= 1
      sums(t) ^= v
      if(degrees(t) == 1)
        queue.enqueue(t)

      if(v <= t)
        pairs += ((v, t))
      else
        pairs += ((t, v))
  }

  println(pairs.size)
  for(pair <- pairs)
    println(s"${pair._1} ${pair._2}")
}

case class Memo[A, B](f: A => B) extends (A => B) {
  private val cache = mutable.Map[A, B]()
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string.toString
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}


Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.

The first line contains two space-separated integers n and m (1 ≤ m ≤ n ≤ 100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 ≤ ai ≤ 1000) — prices of the TV sets.

Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.util.StringTokenizer;
import java.util.Arrays

object Solver {

    var st : StringTokenizer = null;
    var in : BufferedReader = null;
    var out : PrintWriter = null;

    def main(args: Array[String]){
        open();
        solve();
        close();
    }

    def open() {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
    }

    def nextToken() : String = {
        while (st == null || !st.hasMoreTokens()) {
            val line : String = in.readLine();
            if(line==null) return null;
            st = new StringTokenizer(line);
        }
        st.nextToken();
    }

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

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

    def nextDouble() : Double = {
        nextToken().toDouble;
    }

    def solve(){
        val n:Int = nextInt;
        val m:Int = nextInt;
        val ar:Array[Int] = new Array[Int](n);

        for(i <- 0 to n-1){
            ar(i) = nextInt;
        }

        Arrays.sort(ar);

        var sum : Int = 0;
        var i : Int = 0;
        while (i<m && ar(i)<0){
            sum -= ar(i);
            i+=1;
        }
        out println sum;
    }

    def close() {
        out.flush();
        out.close();
    }

}

object P34B extends App {
  val Array(n,m) = readLine.split(" ").map(_.toInt)
  val prices = readLine.split(" ").map(_.toInt).sorted
  print(prices.take(m).takeWhile(_<0).sum * -1)
}

object P34B extends App {
  val in = (readLine + " " + readLine).split(" ").map(_.toInt)
  print(in.slice(2,in.size).sorted.take(in(1)).takeWhile(_<0).sum * -1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val res = in.next().split(" ").map(_.toInt).filter(_ < 0).sorted.take(m).sum
  println(-res)
}

object B34 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    println(a.take(m).foldLeft(0){case (sum, i) => if(i < 0) sum - i else sum})
  }

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

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

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

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

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

}

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

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

  def solve(): Int = {
    val N, M = sc.nextInt
    List.fill(N)(sc.nextInt).sorted.takeWhile(_ < 0).take(M).sum.abs
  }

  out.println(solve)
  out.close
}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, m) = readLine.split(" ").map(_.toInt);
    var a = readLine.split(" ").toList.map(_.toInt).sorted;
    if (a(0) > 0) {
      println(0);
      return;
    }
    var result = 0;
    for (i <- 0 until n if a(i) < 0 && i < m) {
      result -= a(i);
    }
    println(result);
  }
}

object Main {
  def main(args: Array[String]) {
    val op = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt).sorted
    val m = op(1)
    println(-a.filter(_ < 0).take(m).sum)
  }
}

  object Sales extends App {
  	val lines = io.Source.stdin.getLines.toList
  	val m = {
  		val tokens = lines.head.split(" ")
  		tokens(1).toInt
  	}

  	println(-1 * (lines.last.split(" ").toList.map(_.toInt).sorted.filter(_ <= 0).take(m).sum))
  }

object P34B extends App {
  val in = (readLine + " " + readLine).split(" ").map(_.toInt)
  print(in.slice(2,in.size-1).sorted.take(in(1)).takeWhile(_<0).sum * -1)
}

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

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

  def solve(): Int = {
    val N, M = sc.nextInt
    List.fill(N)(sc.nextInt).sorted.takeWhile(_ < 0).take(M).sum
  }

  out.println(solve)
  out.close
}

  object Sales extends App {
  	val lines = io.Source.stdin.getLines.toList
  	val m = {
  		val tokens = lines.head.split(" ")
  		tokens(1).toInt
  	}

  	println(-1 * (lines.last.split(" ").toList.map(_.toInt).sorted.take(m).sum))
  }


You have a large electronic screen which can display up to $$$998244353$$$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $$$7$$$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $$$10$$$ decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display $$$1$$$, you have to turn on $$$2$$$ segments of the screen, and if you want to display $$$8$$$, all $$$7$$$ segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $$$n$$$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $$$n$$$ segments.Your program should be able to process $$$t$$$ different test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow, each of them is represented by a separate line containing one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the maximum number of segments that can be turned on in the corresponding testcase. It is guaranteed that the sum of $$$n$$$ over all test cases in the input does not exceed $$$10^5$$$.

For each test case, print the greatest integer that can be displayed by turning on no more than $$$n$$$ segments of the screen. Note that the answer may not fit in the standard $$$32$$$-bit or $$$64$$$-bit integral data type.

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val cases = in.nextInt()
    val sb = new mutable.StringBuilder()
    (1 to cases).foreach{ _ =>
      val n = in.nextInt()
      val numOnes = n/2-1
      val first = if(n%2==1) '7' else '1'
      sb.append(first)
      (1 to numOnes).foreach(_ => sb.append('1'))
      sb.append(System.lineSeparator())

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

import scala.io.StdIn._

object A extends App {
  /*
  0 - 6 x
  1 - 2
  2 - 5 x
  3 - 5 x
  4 - 4 x
  5 - 5 x
  6 - 6 x
  7 - 3
  8 - x
  9 - x

   */
  val t = readInt()
  1 to t foreach { _ =>
    val n = readInt()
    var sevens = n / 3
    var ones = (n % 3)

    if (ones % 2 == 0) {
      ones = ones / 2
    } else {
      ones = ones / 2 + 2
      sevens -= 1
    }

    println(("7" * sevens) + ("1" * ones))
  }
}


You are given an integer $$$n$$$. You have to change the minimum number of digits in it in such a way that the resulting number does not have any leading zeroes and is divisible by $$$7$$$.If there are multiple ways to do it, print any of them. If the given number is already divisible by $$$7$$$, leave it unchanged.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 990$$$) — the number of test cases. Then the test cases follow, each test case consists of one line containing one integer $$$n$$$ ($$$10 \le n \le 999$$$).

For each test case, print one integer without any leading zeroes — the result of your changes (i. e. the integer that is divisible by $$$7$$$ and can be obtained by changing the minimum possible number of digits in $$$n$$$). If there are multiple ways to apply changes, print any resulting number. If the given number is already divisible by $$$7$$$, just print it.

NoteIn the first test case of the example, $$$42$$$ is already divisible by $$$7$$$, so there's no need to change it.In the second test case of the example, there are multiple answers — $$$28$$$, $$$21$$$ or $$$63$$$.In the third test case of the example, other possible answers are $$$357$$$, $$$371$$$ and $$$378$$$. Note that you cannot print $$$077$$$ or $$$77$$$.

object Div7 extends App {
  def changeToDiv7(i: Int): Int = {
    val rest7 = i % 7
    if (rest7 == 0) i
    else i - rest7 + (if (i % 10 - rest7 >= 0) 0 else 7)
  }

  val lines = io.Source.stdin.getLines
  val t = lines.next.toInt
  (1 to t).foreach(_ => println(changeToDiv7(lines.next.toInt)))
}

import scala.io.StdIn.readInt

object cf1633a {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var n = readInt()
      if(n % 7 == 0) println(n)
      else {
        var found = false
        for(i <- ((n / 10) * 10) to (n + 10)) {
          if(i % 7 == 0 && !found) {
            println(i)
            found = true
          }
        }
      }
    }
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val number = readInt()
    val minNumber = number/7 * 7
    val maxNumber = minNumber + 7
    val answer = if (minNumber / 10 == number / 10) minNumber else maxNumber
    println(answer)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import scala.io.StdIn.readInt
object _1633A{
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0){
      t-=1
      var n = readInt();
      if(n % 7 == 0)println(n)
      else {
        n = (n / 10) * 10
        loop10(n)
        }
      }
    }
  def loop10 (n : Int): Any ={
    for (i <- n to n + 10) {
      if (i % 7 == 0) {
        println(i)
        return
      }
    }
  }
}

import scala.io.StdIn.readInt

object cf1633a {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var n = readInt()
      if(n % 7 == 0) println(n)
      else {
        var found = false
        for(i <- (n - 10) to (n + 10)) {
          if(i % 7 == 0 && !found) {
            println(i)
            found = true
          }
        }
      }
    }
  }
}

import scala.io.StdIn.readInt

object cf1633a {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var n = readInt()
      if(n % 7 == 0) println(n)
      else {
        var found = false
        for(i <- (n - 10) to (n + 10)) {
          if(i % 7 == 0 && !found) {
            println(i)
            found = false
          }
        }
      }
    }
  }
}


You are given an array $$$a$$$ of $$$n$$$ integers. Find the number of pairs $$$(i, j)$$$ ($$$1 \le i < j \le n$$$) where the sum of $$$a_i + a_j$$$ is greater than or equal to $$$l$$$ and less than or equal to $$$r$$$ (that is, $$$l \le a_i + a_j \le r$$$).For example, if $$$n = 3$$$, $$$a = [5, 1, 2]$$$, $$$l = 4$$$ and $$$r = 7$$$, then two pairs are suitable:   $$$i=1$$$ and $$$j=2$$$ ($$$4 \le 5 + 1 \le 7$$$);  $$$i=1$$$ and $$$j=3$$$ ($$$4 \le 5 + 2 \le 7$$$).

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n, l, r$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le l \le r \le 10^9$$$) — the length of the array and the limits on the sum in the pair. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ overall test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of index pairs $$$(i, j)$$$ ($$$i < j$$$), such that $$$l \le a_i + a_j \le r$$$.

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

  @annotation.tailrec
  private def binary(p: Int, q: Int, f: Int => Boolean): Int =
    if (p + 1 >= q) q
    else {
      val o = (p + q) / 2

      f(o) match {
        case true  => binary(o, q, f)
        case false => binary(p, o, f)
      }
    }

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, l, r) = readLine().split(" ").map(_.toInt)
    val an             = readLine().split(" ").map(_.toInt).sorted

    val ans = (0 until n).foldLeft(0L) { case (count, i) =>
      val ai = an(i)

      val p = binary(i, n, an(_) + ai <= r)
      val q = binary(i, n, an(_) + ai <= l - 1)

      count + p - q
    }

    println(ans)
  }
}

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

  @annotation.tailrec
  private def binary(p: Int, q: Int, f: Int => Boolean): Int =
    if (p + 1 >= q) q
    else {
      val o = (p + q) / 2

      f(o) match {
        case true  => binary(o, q, f)
        case false => binary(p, o, f)
      }
    }

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, l, r) = readLine().split(" ").map(_.toInt)
    val an             = readLine().split(" ").map(_.toInt).sorted

    val ans = (0 until n).foldLeft(0) { case (count, i) =>
      val ai = an(i)

      val p = binary(i, n, an(_) + ai <= r)
      val q = binary(i, n, an(_) + ai <= l - 1)

      count + p - q
    }

    println(ans)
  }
}

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

  val t = readInt()

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

    def go(i: Int, count: Long): Long =
      if (i == n) count
      else {
        val ai = an(i)

        if (ai >= r) go(i + 1, count)
        else {
          val p = an.indexWhere(_ + ai <= r, i + 1)

          if (p == -1) go(i + 1, count)
          else {
            val q = an.lastIndexWhere(_ + ai >= l)

            if (q < p) count
            else go(i + 1, count + q - p + 1L)
          }
        }
      }

    val ans = go(0, 0L)

    println(ans)
  }
}

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

  val t = readInt()

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

    def go(i: Int, count: Int): Int =
      if (i == n) count
      else {
        val ai = an(i)

        if (ai >= r) go(i + 1, count)
        else {
          val p = an.indexWhere(_ + ai <= r, i + 1)

          if (p == -1) go(i + 1, count)
          else {
            val q = an.lastIndexWhere(_ + ai >= l)

            if (q == -1 || q < p) count
            else go(i + 1, count + q - p + 1)
          }
        }
      }

    val ans = go(0, 0)

    println(ans)
  }
}

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

  val t = readInt()

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

    def go(i: Int, count: Int): Int =
      if (i == n) count
      else {
        val ai = an(i)

        if (ai >= r) go(i + 1, count)
        else {
          val p = an.indexWhere(_ + ai <= r, i + 1)

          if (p == -1) count
          else {
            val q = an.lastIndexWhere(_ + ai >= l)

            if (q == -1 || q < p) count
            else go(i + 1, count + q - p + 1)
          }
        }
      }

    val ans = go(0, 0)

    println(ans)
  }
}