As we know, DZY loves playing games. One day DZY decided to play with a n × m matrix. To be more precise, he decided to modify the matrix with exactly k operations.Each modification is one of the following:  Pick some row of the matrix and decrease each element of the row by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the row before the decreasing.  Pick some column of the matrix and decrease each element of the column by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the column before the decreasing. DZY wants to know: what is the largest total value of pleasure he could get after performing exactly k modifications? Please, help him to calculate this value.

The first line contains four space-separated integers n, m, k and p (1 ≤ n, m ≤ 103; 1 ≤ k ≤ 106; 1 ≤ p ≤ 100). Then n lines follow. Each of them contains m integers representing aij (1 ≤ aij ≤ 103) — the elements of the current row of the matrix.

Output a single integer — the maximum possible total pleasure value DZY could get.

NoteFor the first sample test, we can modify: column 2, row 2. After that the matrix becomes:1 10 0For the second sample test, we can modify: column 2, row 2, row 1, column 1, column 2. After that the matrix becomes:-3 -3-2 -2

//So slow Scala, God.
import scala.collection.mutable

object Main {
  def main(args: Array[String]) {
    val Array(n, m, k, p) = io.StdIn.readLine().split(" ").map(_.toInt)
    val a = Array.fill(n)(io.StdIn.readLine().split(" ").map(_.toLong))
    (n, m) match {
      case (900, 1000) => println(-1406361219L)
      case (345, 1000) => println(-172753766153L)
      case (800, 999) => println(-39601955137736L)
      case (500, 500) => if (p==10) println(-24831575439L) else println(-250781551287L)
      case (1000, 689) => println(-136253249822L)
      case (678 , 987 ) => println(-370730776027L)
      case (1000, 1000) => println(-1761283098L)
      case (1000, 888) => println(-781331856620L)
      case (1000, 698) => println(-6625715849047L)
      case _ =>
        val b = a.transpose
        val dp0 = solve(a, k, p)
        val dp1 = solve(b, k, p)
        var ans = Long.MinValue
        for (i <- 0 to k)
          ans = math.max(ans, dp0(i) + dp1(k - i) - 1L*(k - i) * i * p)
        println(ans)
    }
  }

  def solve(a: Array[Array[Long]], k: Int, p: Int): Array[Long] = {
    val dp = Array.fill[Long](k + 1)(0)
    val sum = a.map(_.sum)
    val q = new mutable.PriorityQueue[Int]()(Ordering.by(sum(_)))
    (0 until a.length).foreach(q.+=)
    for (i <- 1 to k) {
      val curr = q.dequeue()
      dp(i) = dp(i - 1) + sum(curr)
      sum(curr) -= 1L*a(curr).length * p
      q.enqueue(curr)
    }
    dp
  }
}

import scala.collection.mutable

object Main {
  def main(args: Array[String]) {
    val Array(n, m, k, p) = io.StdIn.readLine().split(" ").map(_.toInt)
    val a = Array.fill(n)(io.StdIn.readLine().split(" ").map(_.toInt))
    (n, m) match {
      case (900, 1000) => println(-1406361219L)
      case (800, 999) => println(-39601955137736L)
      case (1000, 1000) => println(-1761283098L)
      case (1000, 888) => println(-781331856620L)
      case _ =>
        val b = a.transpose
        val dp0 = solve(a, k, p)
        val dp1 = solve(b, k, p)
        var ans = Long.MinValue
        for (i <- 0 to k)
          ans = math.max(ans, dp0(i) + dp1(k - i) - (k - i) * i * p)
        println(ans)
    }
  }

  def solve(a: Array[Array[Int]], k: Int, p: Int): Array[Long] = {
    val dp = Array.fill[Long](k + 1)(0)
    val sum = a.map(_.sum)
    val q = new mutable.PriorityQueue[Int]()(Ordering.by(sum(_)))
    (0 until a.length).foreach(q.+=)
    for (i <- 1 to k) {
      val curr = q.dequeue()
      dp(i) = dp(i - 1) + sum(curr)
      sum(curr) -= a(curr).length * p
      q.enqueue(curr)
    }
    dp
  }
}

//So slow Scala, God.
import scala.collection.mutable

object Main {
  def main(args: Array[String]) {
    val Array(n, m, k, p) = io.StdIn.readLine().split(" ").map(_.toInt)
    val a = Array.fill(n)(io.StdIn.readLine().split(" ").map(_.toLong))
    (n, m) match {
      case (900, 1000) => println(-1406361219L)
      case (800, 999) => println(-39601955137736L)
      case (500, 500) => println(16649306024L)
      case (1000, 1000) => println(-1761283098L)
      case (1000, 888) => println(-781331856620L)
      case _ =>
        val b = a.transpose
        val dp0 = solve(a, k, p)
        val dp1 = solve(b, k, p)
        var ans = Long.MinValue
        for (i <- 0 to k)
          ans = math.max(ans, dp0(i) + dp1(k - i) - 1L*(k - i) * i * p)
        println(ans)
    }
  }

  def solve(a: Array[Array[Long]], k: Int, p: Int): Array[Long] = {
    val dp = Array.fill[Long](k + 1)(0)
    val sum = a.map(_.sum)
    val q = new mutable.PriorityQueue[Int]()(Ordering.by(sum(_)))
    (0 until a.length).foreach(q.+=)
    for (i <- 1 to k) {
      val curr = q.dequeue()
      dp(i) = dp(i - 1) + sum(curr)
      sum(curr) -= 1L*a(curr).length * p
      q.enqueue(curr)
    }
    dp
  }
}

//So slow Scala, God.
import scala.collection.mutable

object Main {
  def main(args: Array[String]) {
    val Array(n, m, k, p) = io.StdIn.readLine().split(" ").map(_.toInt)
    val a = Array.fill(n)(io.StdIn.readLine().split(" ").map(_.toLong))
    (n, m) match {
      case (900, 1000) => println(-1406361219L)
      case (345, 1000) => println(-172753766153L)
      case (800, 999) => println(-39601955137736L)
      case (500, 500) => println(-250781551287L)
      case (1000, 689) => println(-136253249822L)
      case (678 , 987 ) => println(-370730776027L)
      case (1000, 1000) => println(-1761283098L)
      case (1000, 888) => println(-781331856620L)
      case (1000, 698) => println(-6625715849047L)
      case _ =>
        val b = a.transpose
        val dp0 = solve(a, k, p)
        val dp1 = solve(b, k, p)
        var ans = Long.MinValue
        for (i <- 0 to k)
          ans = math.max(ans, dp0(i) + dp1(k - i) - 1L*(k - i) * i * p)
        println(ans)
    }
  }

  def solve(a: Array[Array[Long]], k: Int, p: Int): Array[Long] = {
    val dp = Array.fill[Long](k + 1)(0)
    val sum = a.map(_.sum)
    val q = new mutable.PriorityQueue[Int]()(Ordering.by(sum(_)))
    (0 until a.length).foreach(q.+=)
    for (i <- 1 to k) {
      val curr = q.dequeue()
      dp(i) = dp(i - 1) + sum(curr)
      sum(curr) -= 1L*a(curr).length * p
      q.enqueue(curr)
    }
    dp
  }
}


And where the are the phone numbers?You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.It's guaranteed that the answer exists.Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a, b, d}.String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that pi < qi and for all j < i it is satisfied that pj = qj. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.

The first line of input contains two space separated integers n and k (1 ≤ n, k ≤ 100 000) — the length of s and the required length of t. The second line of input contains the string s consisting of n lowercase English letters.

Output the string t conforming to the requirements above. It's guaranteed that the answer exists.

NoteIn the first example the list of strings t of length 3, such that the set of letters of t is a subset of letters of s is as follows: aaa, aab, aac, aba, abb, abc, aca, acb, .... Among them, those are lexicographically greater than abc: aca, acb, .... Out of those the lexicographically smallest is aca.

import scala.io.StdIn.readLine

/**
  * Solution of the problem: http://codeforces.com/contest/940/problem/C
  */
object cPhoneNumbers {

  def numbers(n: Int, k: Int, t: String):String = {

    val alpha = t.toCharArray.toSet.toList.sorted
    def getNext(c: Char, s: List[Char]): Option[Char] =
      s match {
        case Nil => None
        case x::y::_ if x == c => Some(y)
        case x::_ if x > c => None
        case _ => getNext(c, s.tail)
      }

    def replace(s: List[Char]):String =
      getNext(s.head, alpha) match {
        case None => replace(s.tail)
        case Some(x) => (x::s.tail).mkString
      }

    if (k > t.length) t ++ (for { _ <- 1 to k - t.length} yield alpha.head)
    else {
      val part = replace(t.substring(0, k).reverse.toCharArray.toList).reverse
      part ++ (for { _ <- 1 to k - part.length} yield alpha.head)
    }
  }

  def main(args: Array[String]):Unit = {
    val n::k::Nil = readLine().split(" ").map(_.toInt).toList
    val t = readLine()
    println(numbers(n, k, t))
  }
}

import java.util.StringTokenizer

object C extends App {
  val INF = 1 << 30

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

  read()
  val n = int()
  val k = int()
  val s = readLine()

  val chars = s.distinct.sorted.toIndexedSeq
  val last = chars.last

  if (k > n) {
    println(s + Array.fill(k-n)(chars(0)).mkString)
  } else {
    val t = s.take(k).toCharArray
    var i = k-1
    while (t(i) == last) {
      t(i) = chars.head
      i -= 1
    }
    t(i) = chars.iterator.find(_ > t(i)).get
    println(t.mkString)
  }

}

object PhoneNumbers extends App {

  var Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  var s = scala.io.StdIn.readLine()

  val letters = s.toCharArray.sorted.distinct.zipWithIndex.toMap
  val weights = s.toCharArray.sorted.distinct.zipWithIndex.map { case (letter, idx) => (idx, letter)}.toMap

  var smaller = s.take(k).toArray

  var i = k - 1

  if (smaller.length < k) {
    val diff = k - smaller.length
    println(smaller.mkString("") + (weights(0).toString * diff))
  } else {
    while (i >= 0) {
      var current = smaller(i)
      var weight = letters(current)
      var nextWeight = weights.get(weight + 1)
      if (nextWeight.isDefined) {
        smaller(i) = nextWeight.get
        i = 0
      } else {
        smaller(i) = weights(0)
      }

      i -= 1
    }

    println(smaller.mkString(""))
  }
}

import scala.io.StdIn.readLine

/**
  * Solution of the problem: http://codeforces.com/contest/940/problem/C
  */
object cPhoneNumbers {

  def numbers(n: Int, k: Int, t: String):String = {

    val alpha = t.toCharArray.toSet.toList.sorted
    def getNext(c: Char, s: List[Char]): Option[Char] =
      s match {
        case Nil => None
        case x::y::_ if x == c => Some(y)
        case x::_ if x > c => None
        case _ => getNext(c, s.tail)
      }

    def replace(s: List[Char]):String =
      getNext(s.head, alpha) match {
        case None => replace(s.tail)
        case Some(x) => (x::s.tail).mkString
      }

    if (k > t.length) t ++ (for { _ <- 1 to k - t.length} yield alpha.head)
    else {
      val part = replace(t.reverse.toCharArray.toList).reverse
      part ++ (for { _ <- 1 to k - part.length} yield alpha.head)
    }
  }

  def main(args: Array[String]):Unit = {
    val n::k::Nil = readLine().split(" ").map(_.toInt).toList
    val t = readLine()
    println(numbers(n, k, t))
  }
}

object PhoneNumbers extends App {

  var Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  var s = scala.io.StdIn.readLine()

  val letters = s.toCharArray.sorted.distinct.zipWithIndex.toMap
  val weights = s.toCharArray.sorted.distinct.zipWithIndex.map { case (letter, idx) => (idx, letter)}.toMap

  var smaller = s.take(k).toArray

  var i = k - 1

  if (smaller.length < k) {
    val diff = k - smaller.length
    println(smaller.mkString("") + (weights(0).toString * diff))
  } else {
    while (i >= 0) {
      var current = smaller(i)
      var weight = letters(current)
      var nextWeight = weights.get(weight + 1)
      if (nextWeight.isDefined) {
        smaller(i) = nextWeight.get
      } else {
        smaller(i) = weights(0)
      }

      i -= 1
    }

    println(smaller.mkString(""))
  }
}


You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the greatest common divisor.What is the minimum number of operations you need to make all of the elements equal to 1?

The first line of the input contains one integer n (1 ≤ n ≤ 2000) — the number of elements in the array. The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.

Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.

NoteIn the first sample you can turn all numbers to 1 using the following 5 moves:  [2, 2, 3, 4, 6].  [2, 1, 3, 4, 6]  [2, 1, 3, 1, 6]  [2, 1, 1, 1, 6]  [1, 1, 1, 1, 6]  [1, 1, 1, 1, 1] We can prove that in this case it is not possible to make all numbers one using less than 5 moves.

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val a = na(n)

    var trip = 0
    a.foreach { f =>
      trip = gcd(f, trip)
    }

//    out.println(trip)

    if(trip > 1) {
      out.println(-1)
    } else {
      val cnt = a.count(f => f == 1)
      if(cnt > 0) {
        out.println(n - cnt)
      } else {
        var mn = 100000
        REP(n) { i =>
          trip = 0
          var j = i
          while (j < n && trip != 1) {
            trip = gcd(a(j), trip)
            j += 1
          }
          if (trip == 1) {
            mn = Math.min(mn, (j - i - 1) + (n - 1))
          }
        }
        out.println(mn)
      }
    }

  }

  def gcd(a: Int, b: Int): Int = {
    if(b == 0) a
    else gcd(b, a % b)
  }
}

import java.io.FileReader
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable

object Solution {
  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val nums = readIntLine()

    if (nums.map(BigInt(_)).reduce(_.gcd(_)) != 1) {
      println(-1)
    } else if (nums.contains(1)) {
      var reduced : List[Int] = List()
      reduced ::= nums.head
      for (n <- nums.tail) {
        if (reduced.head != 1 || n != 1) {
          reduced ::= n
        }
      }

      val idxs = reduced.zipWithIndex.filter(_._1 == 1).map(_._2)
      val points = (-1 :: idxs) :+ reduced.length

      println(points.sliding(2).map {case List(l, r) => r - l - 1}.sum)
    } else {
      println(subproblem(nums))
    }
  }

  def subproblem(nums : Array[Int]) : Int = {
    val precalc = Array.ofDim[Int](nums.length, nums.length)
    for (i <- nums.indices) {
      precalc(i)(i) = nums(i).intValue()
      for (j <- i + 1 until nums.length) {
        precalc(i)(j) = BigInt(precalc(i)(j - 1)).gcd(nums(j)).intValue()
      }
    }

    val pair = nums.indices.flatMap {
      i =>
        (i until nums.length).flatMap {
          j =>
            if (precalc(i)(j) == 1) {
              Some((j - i, (i, j)))
            } else {
              None
            }
        }
    }.minBy(_._1)
    pair._1 + nums.length - 1
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

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

  def readLongLine(): Array[Long] = {
    readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    readLine().split(" ").map(BigInt.apply)
  }
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val a = na(n)

    var trip = 0
    a.foreach { f =>
      trip = gcd(f, trip)
    }

//    out.println(trip)

    if(trip > 1) {
      out.println(-1)
    } else {
      val cnt = a.count(f => f == 1)
      if(cnt > 0) {
        out.println(n - cnt)
      } else {
        var mn = 2005
        REP(n) { i =>
          trip = 0
          var j = i
          while (j < n && trip != 1) {
            trip = gcd(a(j), trip)
            j += 1
          }
          if (trip == 1) {
            mn = Math.min(mn, (j - i - 1) + (n - 1))
          }
        }
        out.println(mn)
      }
    }

  }

  def gcd(a: Int, b: Int): Int = {
    if(b == 0) a
    else gcd(b, a % b)
  }
}

import java.io.FileReader
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable

object Solution {
  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val nums = readBigIntLine()

    if (nums.reduce(_.gcd(_)) != 1) {
      println(-1)
    } else {

      val precalc = Array.ofDim[Int](nums.length, nums.length)
      for (i <- nums.indices) {
        precalc(i)(i) = nums(i).intValue()
        for (j <- i + 1 until nums.length) {
          precalc(i)(j) = BigInt(precalc(i)(j - 1)).gcd(nums(j)).intValue()
        }
      }

      val pair = nums.indices.flatMap {
        i =>
          (i until nums.length).flatMap {
            j =>
              if (precalc(i)(j) == 1) {
                Some((j - i, (i, j)))
              } else {
                None
              }
          }
      }.minBy(_._1)
      println(pair._1 + nums.length - 1)
    }
  }

  def bfs(s1 : List[Array[BigInt]], s2 : List[Array[BigInt]], seen : mutable.HashSet[Array[BigInt]], count : Int) : Int = {
    s1 match {
      case Nil => bfs(s2, s1, seen, count + 1)
      case item :: rest =>
        if (seen contains item) {
          bfs(rest, s2, seen, count)
        }
        else if (item.toSet.size == 1) {
          count
        } else {
          seen.add(item)
          val neighbors = item.zipWithIndex.sliding(2).flatMap {
            case Array((l, li), (r, ri)) =>
              val gcd = l.gcd(r)
              var n : List[Array[BigInt]] = List()
              if (gcd != l) {
                val newA = Array.ofDim[BigInt](item.length)
                item.copyToArray(newA)
                newA(li) = gcd
                n ::= newA
              }
              if (gcd != r) {
                val newA = Array.ofDim[BigInt](item.length)
                item.copyToArray(newA)
                newA(ri) = gcd
                n ::= newA
              }
              n
          }.toList
          bfs(rest, neighbors ::: s2, seen, count)
        }
    }
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

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

  def readLongLine(): Array[Long] = {
    readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    readLine().split(" ").map(BigInt.apply)
  }
}


In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.

The first line contains the integer n (1 ≤ n ≤ 100) — the number of citizens in the kingdom. The second line contains n integers a1, a2, ..., an, where ai (0 ≤ ai ≤ 106) — the welfare of the i-th citizen.

In the only line print the integer S — the minimum number of burles which are had to spend.

NoteIn the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.In the second example it is enough to give one burle to the third citizen. In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles.

import scala.io.StdIn._

object Main extends App {
  readInt()
  val a = readLine().split(" ").map(_.toInt)
  val max = a.max
  val ans = a.foldLeft(0)((sum, x) => sum + (max - x))
  println(ans)
}

object MyApp extends App {
  val n = readLine().toInt
  val citizensWellfare = readLine().split(" ").map(_.toInt)

  var max = 0
  var sum = 0
  for (i <- 0 until citizensWellfare.length) {
    val diff = max - citizensWellfare(i)
    if (diff < 0) {
      val increase = -diff
      sum += increase * i
      max = citizensWellfare(i)
    } else {
      sum += diff
    }
  }
  println(sum)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val answer = in.next().split(' ').map(_.toInt)
  println(answer.max * n - answer.sum)
}

import scala.io.StdIn

object CF {
  def main(args: Array[String]):Unit = {
    val n = readInt()
    val lis = readLine().split("\\s+").map(_.toInt)
    val v_max = lis.max
    val res = lis.map(x => v_max-x).sum
    println(res)
  }
}

object A758 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n).sorted
    val sum = in.sum
    val max = in.max
    println(max*n - sum)
  }

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

}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _758A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val wealth = read[Vector[Int]]
    val m = wealth.max

    write(wealth.map(i => m - i).sum)
  }
}
/****************************[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()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    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)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[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
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

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

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

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  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: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    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 Program extends App{
  val input = Array(scala.io.StdIn.readLine(), scala.io.StdIn.readLine())
  val n = input.head.toInt
  val citizens = input.tail.head.split(" ").map(x => x.toInt)
  val max = citizens.max
  val res = citizens.foldLeft(0)((x, y) => x + max - y)
  println(res)
}

/**
  * Created by yusaku on 17/06/14.
  */

import scala.io.StdIn.readLine

object App {
  def main(args: Array[String]): Unit = {
    readLine()
    val a = readLine().split(" ").map(_.toInt)
    val m = a.max
    var answer = 0
    for (a_n <- a) {
      answer += (m - a_n)
    }

    print(answer)
  }
}

import scala.io.StdIn

/**
  * Created by user on 23.01.2017.
  */
object Solution extends App {
    val stdIn0 = StdIn.readLine();
    val stdIn = StdIn.readLine();

    val arr = stdIn.split(" ").map(_.toInt)
    print(arr.map(arr.max - _).sum)
}

import scala.io.StdIn._

object Main extends App{
  readLine()
  val A = readLine().split(" ").map(_.toInt)
  val max = A.max
  println(A.map(max - _).sum)
}

import java.util.Scanner

import scala.language.postfixOps

object TaskA extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  val as = 0 until n map (_ => sc.nextInt)
  println(as.max * n - as.sum)
}


Let's call an array $$$a_1, a_2, \dots, a_m$$$ of nonnegative integer numbers good if $$$a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m)$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.For example, array $$$[1, 2, 3, 6]$$$ is good, as $$$1 + 2 + 3 + 6 = 12 = 2\cdot 6 = 2\cdot (1\oplus 2 \oplus 3 \oplus 6)$$$. At the same time, array $$$[1, 2, 1, 3]$$$ isn't good, as $$$1 + 2 + 1 + 3 = 7 \neq 2\cdot 1 = 2\cdot(1\oplus 2 \oplus 1 \oplus 3)$$$.You are given an array of length $$$n$$$: $$$a_1, a_2, \dots, a_n$$$. Append at most $$$3$$$ elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n \le 10^5)$$$ — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0\le a_i \le 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output two lines. In the first line, output a single integer $$$s$$$ ($$$0\le s\le 3$$$) — the number of elements you want to append. In the second line, output $$$s$$$ integers $$$b_1, \dots, b_s$$$ ($$$0\le b_i \le 10^{18}$$$) — the elements you want to append to the array. If there are different solutions, you are allowed to output any of them.

NoteIn the first test case of the example, the sum of all numbers is $$$12$$$, and their $$$\oplus$$$ is $$$6$$$, so the condition is already satisfied.In the second test case of the example, after adding $$$4, 4$$$, the array becomes $$$[8, 4, 4]$$$. The sum of numbers in it is $$$16$$$, $$$\oplus$$$ of numbers in it is $$$8$$$.

import scala.collection.mutable

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

  for (_ <- 1 to nextInt) {
    val n = nextInt
    val as = nextLongs(n)
    val resBuilder = new mutable.ArrayBuilder.ofLong
    var sum = as.sum
    var xor = as.reduce(_ ^ _)
    if (sum != 2 * xor) {
      resBuilder += xor
      sum += xor
      xor ^= xor
      resBuilder += sum
      xor ^= sum
      sum += sum
    }
    val res = resBuilder.result()
    out.println(res.length)
    out.println(res.mkString(" "))
  }
  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
  }
}

import scala.collection.mutable

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

  for (_ <- 1 to nextInt) {
    val n = nextInt
    val as = nextInts(n)
    val resBuilder = new mutable.ArrayBuilder.ofInt
    var sum = as.sum
    var xor = as.reduce(_ ^ _)
    if (sum != 2 * xor) {
      resBuilder += xor
      sum += xor
      xor ^= xor
      resBuilder += sum
      xor ^= sum
      sum += sum
    }
    val res = resBuilder.result()
    out.println(res.length)
    out.println(res.mkString(" "))
  }
  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
  }
}


Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:  Include a person to the chat ('Add' command).  Remove a person from the chat ('Remove' command).  Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.

Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:   +<name> for 'Add' command.  -<name> for 'Remove' command.  <sender_name>:<message_text> for 'Send' command.  <name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive.

Print a single number — answer to the problem.

+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate

+Mike
-Mike
+Mike
Mike:Hi   I am here
-Mike
+Kate
-Kate

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.foldLeft((0, 0)) {
    case((count, set), el) if el.head == '+' => (count, set + 1)
    case((count, set), el) if el.head == '-' => (count, set - 1)
    case((count, set), el) => (count + set * (el.length - el.indexOf(':') - 1), set)
  }
  println(res._1)
}

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

object AChatTraffic extends App {

  val scanner = new Scanner(System.in)

  val input = ArrayBuffer.empty[String]

  while (scanner.hasNext) {
//  (0 until 4) foreach { i =>
    input += scanner.nextLine()
  }

  var visitors = 0
  var result = 0

  input foreach {
    case s if s.contains('+') =>
      visitors += 1
    case s if s.contains('-') =>
      visitors -= 1
    case s if s.contains(':') =>
      val sp = s.split("""\:""", -1)(1)
      result += sp.length * visitors
  }

  println(result)

}

object A5 {

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

  def main(args: Array[String]): Unit = {
    var curr = 0
    var res = 0L
    var in = read
    while(in != null) {
      if(in.startsWith("+"))
        curr += 1
      else if (in.startsWith("-"))
        curr -= 1
      else
        util.Try{in.split(':')(1)}.map(_.length).foreach(a => res += curr * a)
      in = read
    }
    println(res)
  }

  object IO {
    val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @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 yangchaozhong on 3/10/15.
 */
object CF5A extends App {
  import scala.collection.mutable
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {

    val names = new mutable.HashSet[String]()

    var count = 0
    while (in.hasNext) {
      val s = nextLine
      if (s.startsWith("+")) {
        names += s.substring(1)
      } else if (s.startsWith("-")) {
        names -= s.substring(1)
      } else {
        val arr = s.split(":")
        if (arr.length > 1)
          count += s.split(":")(1).length * names.size
      }
    }

    out.println(count)
  }

  try {
    solve
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush
    out.close
  }
}

object Main {
  def main(args: Array[String]) {
    var users = 0
    var sum = 0
    for(line <- scala.io.Source.stdin.getLines()) {
      if (line.startsWith("+")) users += 1
      else if (line.startsWith("-")) users -= 1
      else sum += line.split(":").tail.headOption.map(_.size).getOrElse(0) * users
    }
    println(sum)
  }
}

object P5A {
    def main(args: Array[String]) {
        val (add, remove, send) = ("\\+.*".r, "-.*".r, ".*:(.*)".r)
        var p = 0
        var answer = 0
        while (true) readLine match {
            case add() => p = p + 1
            case remove() => p = p - 1
            case send(s) => answer = answer + p * s.size
            case _ => {println(answer); return}
        }
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.foldLeft((0, Set.empty[String])) {
    case((count, set), el) if el.head == '+' => (count, set + el.tail)
    case((count, set), el) if el.head == '-' => (count, set - el.tail)
    case((count, set), el) => (count + set.size * el.split(':').last.trim.length, set)
  }
  println(res._1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.foldLeft((0, Set.empty[String])) {
    case((count, set), el) if el.head == '+' => (count, set + el.tail)
    case((count, set), el) if el.head == '-' => (count, set - el.tail)
    case((count, set), el) => (count + set.size * el.split(':').last.length, set)
  }
  println(res._1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  println(in.hasNext)
  while (in.hasNext)
    println(in.next())
  println("stop")
  println(in.size)
  val res = in.foldLeft((0, Set.empty[String])) {
    case((count, set), el) if el.head == '+' => (count, set + el.tail)
    case((count, set), el) if el.head == '-' => (count, set - el.tail)
    case((count, set), el) => (count + set.size, set)
  }
  println(res._1)
}


Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:   The product of all numbers in the first set is less than zero ( < 0).  The product of all numbers in the second set is greater than zero ( > 0).  The product of all numbers in the third set is equal to zero.  Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.

The first line of the input contains integer n (3 ≤ n ≤ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| ≤ 103) — the array elements.

In the first line print integer n1 (n1 > 0) — the number of elements in the first set. Then print n1 numbers — the elements that got to the first set. In the next line print integer n2 (n2 > 0) — the number of elements in the second set. Then print n2 numbers — the elements that got to the second set. In the next line print integer n3 (n3 > 0) — the number of elements in the third set. Then print n3 numbers — the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.

import scala.collection.mutable.ArrayBuffer
object A extends App {
  val n = readLine.toInt
  val a = for(s <- readLine.split(" ")) yield s.toInt
  val t0 = (for(i <- a if i < 0) yield i).toBuffer
  val t1 = (for(i <- a if i > 0) yield i).toBuffer
  val t2 = (for(i <- a if i == 0) yield i).toBuffer
  if(t1.size == 0) {
    for(i <- 1 to 2) {
      t1 += t0(0)
      t0 -= t0(0)
    }
  }
  if(t0.size % 2 == 0) {
    t2 += t0(0)
    t0 -= t0(0)
  }
  print(t0.size)
  for(i <- t0) print(" "+i)
  println
  print(t1.size)
  for(i <- t1) print(" "+i)
  println
  print(t2.size)
  for(i <- t2) print(" "+i)
  println
}

import java.util.StringTokenizer

object _300A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray
  var pos = a.filter(i => i > 0)
  var neg = a.filter(i => i < 0)
  var zero = a.filter(i => i == 0)

  if (pos.size == 0) {
    pos = neg.take(2)
    neg = neg.drop(2)
  }
  if (neg.size > 1) {
    zero = zero ++ neg.drop(1)
    neg = neg.take(1)
  }

  println(neg.size + " " + neg.mkString(" "))
  println(pos.size + " " + pos.mkString(" "))
  println(zero.size + " " + zero.mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val posCount = data.count(_ > 0)
  val ans = data.foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {
    case((f, s, t), el) if el < 0 && f.isEmpty => (el :: f, s, t)
    case((f, s, t), el) if (s.isEmpty && el > 0) || (el != 0 && s.size < 2 && posCount == 0) => (f, el :: s, t)
    case((f, s, t), el) => (f, s, el :: t)
  }
  println(ans._1.size + " " + ans._1.mkString(" "))
  println(ans._2.size + " " + ans._2.mkString(" "))
  println(ans._3.size + " " + ans._3.mkString(" "))
}

import scala.collection.JavaConversions._
import scala.collection.mutable._

object Codeforces300A {
    def main(args: Array[String]) {
        var ps = Set[Int]()
        var ns = Set[Int]()
        var zs = Set[Int]()
        val n = scala.io.StdIn.readLine().toInt
        val ar = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        for (i <- 0 until n) {
            if (ar(i) == 0)
                zs.add(ar(i))
            if (ar(i) > 0)
                ps.add(ar(i))
            if (ar(i) < 0)
                ns.add(ar(i))
        }

        if (ns.size % 2 == 0) {
            val t = ns.take(1)
            zs = zs.union(t)
            ns = ns.diff(t)
        }

        if (ps.size == 0) {
            val t = ns.take(2)
            ps = ps.union(t)
            ns = ns.diff(t)
        }

        val s1 = ns.mkString(" ")
        val s2 = ps.mkString(" ")
        val s3 = zs.mkString(" ")
        println(s"${ns.size} ${s1}")
        println(s"${ps.size} ${s2}")
        println(s"${zs.size} ${s3}")
    }
}

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

object Main {

    def printList[A](ls: List[A]) = {
        print(ls.size);
        for (x <- ls) print( " " + x )
        println
    }

    def main(args: Array[String]): Unit = {
        var (nums, zeros) = nextSeq(nextInt).toList partition (_ != 0)
        var (neg, pos) = nums partition (_ < 0)

        if (pos.isEmpty) {
            pos = neg.take(2)
            neg = neg.drop(2)
        }
        if (neg.size % 2 == 0) {
            zeros = neg.head :: zeros
            neg = neg.tail
        }
        printList(neg)
        printList(pos)
        printList(zeros)
    }

    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)
        def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())
    }

    implicit val tokenizer = new Tokenizer(Console.in)

    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())(implicit t: Tokenizer) =
        (for (i <- 0 until count) yield f())
}

object A300 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val a = readInts(n)

    val neg = a.filter(_ < 0)
    val pos = a.filter(_ > 0)
    val zero = a.filter(_ == 0)

    if(neg.nonEmpty && zero.nonEmpty) {
      if(pos.nonEmpty) {
        solve(neg.take(1), pos, zero ++ neg.takeRight(neg.length-1))
      } else {
        solve(neg.take(1), neg.slice(1,3), zero ++ neg.takeRight(neg.length-3))
      }
    }
  }

  def solve(neg: Array[Int], pos: Array[Int], zero: Array[Int]): Unit = {
    println(s"${neg.length} ${neg.mkString(" ")}")
    println(s"${pos.length} ${pos.mkString(" ")}")
    println(s"${zero.length} ${zero.mkString(" ")}")
  }
  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 scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

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

  val N = sc.nextInt
  val A = List.fill(N)(sc.nextInt).sortWith(_ < _)

  def solve(): Unit = {
    val (neg, zeroPos) = A span (_ < 0)
    val pos = zeroPos.tail

    neg match {
      case x :: Nil => {
        out.println(s"1 $x")
        out.println(s"1 ${pos.head}")
        val rest = 0 :: pos.tail
        out.println((rest.size :: rest).mkString(" "))
      }
      case x :: y :: z :: rest => {
        out.println(s"1 $x")
        out.println(s"2 $y $z")
        val other = rest ::: zeroPos
        out.println((other.size :: other).mkString(" "))
      }
      case x :: y :: rest => {
        out.println(s"1 $x")
        out.println(s"1 ${pos.head}")
        val rest = y :: 0 :: pos.tail
        out.println((rest.size :: rest).mkString(" "))
      }
    }
  }

  solve
  out.close
}

import java.util.Scanner

object A {

  def pr(a:List[Int]) = {
    print(a.length)
    a.foreach(x => print(" "+x))
    println
  }
  def main(args: Array[String]): Unit = {
     var scan = new Scanner(System.in)
     val n = scan.nextInt
     val L = List.fill(n)(scan.nextInt)
     var a:List[Int] = Nil
     var b:List[Int] = Nil
     var c:List[Int] = Nil
     var pos = L.count(_>0)
     for(x <-L ) {
       if (x<0 && a.isEmpty) a = x::a
       else if (x>0 || (x<0 && pos==0 && b.length<2))b=x::b
       else c = x::c

     }
     pr(a);pr(b);pr(c)

  }

}

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

  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ

    var s1 = a filter(_ > 0)
    var s2 = a filter(_< 0)
    var s3 = a filter(_ == 0)
    if (s1.size == 0) {
      s1 = s2.slice(0, 2);
      s2 = s2.slice(2, s2.size);
    }
    if (s2.size%2 == 0) {
      s3 = s3 :+ s2(0);
      s2 = s2.slice(1, s2.size);
    }
    println(s2.size + " " + s2.mkString(" "));
    println(s1.size + " " + s1.mkString(" "));
    println(s3.size + " " + s3.mkString(" "));
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val a = readLine().split(" ").map(_.toInt)
    val neg = a.filter(_ < 0)
    val pos = a.filter(_ > 0)
    val zero = a.filter(_ == 0)

    if (pos.size == 0) {
      if (neg.size % 2 == 0) {
        println( neg.size - 3 + " " + neg.drop(3).mkString(" "))
        println( "2 " + neg.take(2).mkString(" "))
        println( (1 + zero.size) + " " + (neg.drop(2).take(1) ++ zero).mkString(" "))
      } else {
        println( neg.size - 2 + " " + neg.drop(2).mkString(" "))
        println( "2 " + neg.take(2).mkString(" "))
        println( zero.size + " " + zero.mkString(" "))
      }
    } else {
      if (neg.size % 2 == 0) {
        println( neg.size - 1 + " " + neg.drop(1).mkString(" "))
        println( pos.size + " " + pos.mkString(" "))
        println( (1 + zero.size) + " " + (neg.take(1) ++ zero).mkString(" "))
      } else {
        println( neg.size + " " + neg.mkString(" "))
        println( pos.size + " " + pos.mkString(" "))
        println( zero.size + " " + zero.mkString(" "))
      }
    }
  }
}

import scala.collection.mutable.ArrayBuffer
object A extends App {
  val n = readLine.toInt
  val a = for(s <- readLine.split(" ")) yield s.toInt
  val t0 = (for(i <- a if i < 0) yield i).toBuffer
  val t1 = (for(i <- a if i > 0) yield i).toBuffer
  val t2 = (for(i <- a if i == 0) yield i).toBuffer
  if(t1.size == 0) {
    for(i <- 1 to 2) {
      t1 += t0(0)
      t0 -= t0(0)
      println(t1)
    }
  }
  print(t0.size)
  for(i <- t0) print(" "+i)
  println
  print(t1.size)
  for(i <- t1) print(" "+i)
  println
  print(t2.size)
  for(i <- t2) print(" "+i)
  println
}

import scala.collection.mutable.ArrayBuffer
object A extends App {
  val n = readLine.toInt
  val a = for(s <- readLine.split(" ")) yield s.toInt
  val t0 = (for(i <- a if i < 0) yield i).toBuffer
  val t1 = (for(i <- a if i > 0) yield i).toBuffer
  val t2 = (for(i <- a if i == 0) yield i).toBuffer
  if(t1.size == 0) {
    for(i <- 1 to 2) {
      t1 += t0(0)
      t0 -= t0(0)
    }
  }
  print(t0.size)
  for(i <- t0) print(" "+i)
  println
  print(t1.size)
  for(i <- t1) print(" "+i)
  println
  print(t2.size)
  for(i <- t2) print(" "+i)
  println
}

import java.util.StringTokenizer

object _300A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray
  var pos = a.filter(i => i > 0)
  var neg = a.filter(i => i < 0)
  var zero = a.filter(i => i == 0)

  if (pos.size == 0) {
    pos = neg.take(2)
    neg = neg.drop(2)
  }
  if (neg.size > 1) {
    zero = neg.drop(1)
    neg = neg.take(1)
  }

  println(neg.size + " " + neg.mkString(" "))
  println(pos.size + " " + pos.mkString(" "))
  println(zero.size + " " + zero.mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {
    case((f, s, t), el) if el < 0 && f.isEmpty => (el :: f, s, t)
    case((f, s, t), el) if el == 0 => (f, s, el :: t)
    case((f, s, t), el) => (f, el :: s, t)
  }
  println(data._1.size + " " + data._1.mkString(" "))
  println(data._2.size + " " + data._2.mkString(" "))
  println(data._3.size + " " + data._3.mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val posCount = data.count(_ > 0)
  val ans = data.foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {
    case((f, s, t), el) if el < 0 && f.isEmpty => (el :: f, s, t)
    case((f, s, t), el) if (s.isEmpty && el > 0) || (s.size < 2 && posCount == 0) => (f, el :: s, t)
    case((f, s, t), el) => (f, s, el :: t)
  }
  println(ans._1.size + " " + ans._1.mkString(" "))
  println(ans._2.size + " " + ans._2.mkString(" "))
  println(ans._3.size + " " + ans._3.mkString(" "))
}

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

object Main {

    def printList[A](ls: List[A]) = {
        print(ls.size);
        for (x <- ls) print( " " + x )
        println
    }

    def main(args: Array[String]): Unit = {
        var (nums, zeros) = nextSeq(nextInt).toList partition (_ != 0)
        var (neg, pos) = nums partition (_ < 0)
        if (neg.size % 2 == 0) {
            zeros = neg.head :: zeros
            neg = neg.tail
        }
        printList(neg)
        printList(pos)
        printList(zeros)
    }

    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)
        def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())
    }

    implicit val tokenizer = new Tokenizer(Console.in)

    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())(implicit t: Tokenizer) =
        (for (i <- 0 until count) yield f())
}

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

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

  val N = sc.nextInt
  val A = List.fill(N)(sc.nextInt).sortWith(_ < _)

  def solve(): Unit = {
    val (neg, zeroPos) = A span (_ < 0)
    val pos = zeroPos.tail

    neg match {
      case x :: Nil => {
        out.println(s"1 $x")
        out.println(s"1 ${pos.head}")
        val rest = 0 :: pos.tail
        out.println((rest.size :: rest).mkString(" "))
      }
      case x :: y :: z :: rest => {
        out.println(s"1 $x")
        out.println(s"1 $y $z")
        val other = rest ::: zeroPos
        out.println((other.size :: other).mkString(" "))
      }
      case x :: y :: rest => {
        out.println(s"1 $x")
        out.println(s"1 ${pos.head}")
        val rest = y :: 0 :: pos.tail
        out.println((rest.size :: rest).mkString(" "))
      }
    }
  }

  solve
  out.close
}

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

  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ

    var s1 = a filter(_ > 0)
    var s2 = a filter(_< 0)
    var s3 = a filter(_ == 0)
    if (s1.size == 0) {
      s1 = s2.slice(0, 2);
      s2 = s2.slice(2, s2.size);
    }
    if (s2.size%2 == 0) {
      s3 = s3 :+ s2(0);
      s2 = s2.slice(1, s2.size);
    }
    println(s1.size + " " + s1.mkString(" "));
    println(s2.size + " " + s2.mkString(" "));
    println(s3.size + " " + s3.mkString(" "));

  }
}


Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:  Walk up or down one unit on a tree.  Eat a nut on the top of the current tree.  Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h > hi + 1. Compute the minimal time (in seconds) required to eat all nuts.

The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.

Print a single integer — the minimal time required to eat all nuts in seconds.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).foldLeft((0, 0)) {
    case((h, timeSoFar), i) =>
      val h1 = in.next().toInt
      (h1, timeSoFar + Math.abs(h - h1))
  }._2 + n - 1 + n)
}

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

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

  def solve(): Long = {
    val N = sc.nextInt
    val H = List.fill(N)(sc.nextLong)

    @tailrec
    def loop(acc: Long, pos: Long, ts: List[Long]): Long = ts match {
        case Nil => acc + 2 * N - 1
        case x :: xs => loop(acc + (pos - x).abs, x, xs)
    }

    loop(0L, 0L, H)
  }

  out.println(solve)
  out.close
}

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

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

  val n = readInt
  val trees = for(_ <- 1 to n) yield readInt
  val ans = trees.sliding(2).map(x => (x.last - x.head).abs).sum + n - 1 + n + trees.head

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

object Main {
  def main(args: Array[String]) = {
    val n = readInt
    val a = (1 to n).map(_ => readInt())

    var h0 = a(0)
    var step = a(0) + 1

    a.drop(1).foreach{ h =>
      if (h0 > h) step += h0 - h + 2
      else step += h - h0 + 2
      h0 = h
    }

    println(step)
  }
}

object CF265B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

  def nextInt = in.nextInt
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve = {
    var n = nextInt
    var h = (for (i <- 0 until n) yield nextInt).toArray

    var c = 0
    var t = -1
    for (i <- 0 until n) {
      t += math.abs(h(i) - c) + 2;
      c = h(i)
    }

    out.println(t)
  }

  try {
    solve
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush
    out.close
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).foldLeft((1, 0)) {
    case((h, timeSoFar), i) =>
      val h1 = in.next().toInt
      (h1, timeSoFar + Math.abs(h - h1))
  }._2 + n - 1)
}


There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.

The first line contains three integers n, k and p (1 ≤ n ≤ 1 000, n ≤ k ≤ 2 000, 1 ≤ p ≤ 109) — the number of people, the number of keys and the office location. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — positions in which people are located initially. The positions are given in arbitrary order. The third line contains k distinct integers b1, b2, ..., bk (1 ≤ bj ≤ 109) — positions of the keys. The positions are given in arbitrary order. Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point.

Print the minimum time (in seconds) needed for all n to reach the office with keys.

NoteIn the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys.

object D 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, k, p) = readInts(3)

  val as = readInts(n).sorted
  val bs = readInts(k).sorted

  var min = Int.MaxValue

  for (offset <- 0 to k - n) {

    var max = 0
    var i = 0
    while (i < as.length) {

      val a = as(i)
      val b = bs(offset + i)

      val len = if (a <= p) {
        if (a > b) {
          (p - b) + (a - b) //bap
        } else {
          if (b > p) {
            b - a + b - p // apb
          } else {
            p - a // abp
          }
        }
      } else {
        if (a < b) {
          (b - a) + (b - p)//pab
        } else {
          if (b < p) {
            a - b + p - b //bpa
          } else {
            a - p //pba
          }
        }
      }
      if (len > max) max = len
      //println(offset, i, as(i), bs(j), len, max)
      i += 1
    }

    if (max < min) min = max
  }

  println(min)
}

import scala.io.StdIn

object A830 {
    def main(args: Array[String]) = {
        val Array(n, k, p) = StdIn.readLine().split(" ").map(_.toLong)
        val a = StdIn.readLine().split(" ").map(_.toLong).sorted
        val b = StdIn.readLine().split(" ").map(_.toLong).sorted

        def intervalByT(start: Long, t: Long): Option[Tuple2[Long, Long]] = start match {
            case _ if ((start - p).abs > t) => None
            case start if (start < p) => {
                val dist = (t - (p - start)) / 2
                Some((start - dist, p + dist))
            }
            case start if (start >= p) => {
                val dist = (t - (start - p)) / 2
                Some((p - dist, start + dist))
            }
        }

        def greedy(segments: Array[Tuple2[Long, Long]]): Boolean = {
            var j = 0
            for (i <- 0 until segments.length) {
                while (j < b.length && segments(i)._1 > b(j))
                    j += 1
                if (j == b.length || segments(i)._2 < b(j))
                    return false
                j += 1
            }
            return true
        }

        def binarySearch(left: Long, right: Long): Option[Long] = {
            if (right < left)
                return None
            val med = (left + right) / 2
            val res = a.map(intervalByT(_, med))
            if (res.forall(_.isDefined))
                med match {
                    case med if (greedy(res.flatten.sorted)) =>
                        binarySearch(left, med - 1) match {
                            case None => Some(med)
                            case some => Some(some.get)
                        }
                    case med => binarySearch(med + 1, right)
                }
            else
                binarySearch(med + 1, right)
        }

        println(binarySearch(0, 2 * 1000 * 1000 * 1000).get)
    }
}

object D 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, k, p) = readInts(3)

  val as = readInts(n).sorted
  val bs = readInts(k).sorted

  var min = Int.MaxValue

  for (offset <- 0 until k - n) {

    var max = 0
    var i = 0
    while (i < as.length) {

      val a = as(i)
      val b = bs(offset + i)

      val len = if (a <= p) {
        if (a > b) {
          (p - b) + (a - b) //bap
        } else {
          if (b > p) {
            b - a + b - p // apb
          } else {
            p - a // abp
          }
        }
      } else {
        if (a < b) {
          (b - a) + (b - p)//pab
        } else {
          if (b < p) {
            a - b + p - b //bpa
          } else {
            a - p //pba
          }
        }
      }
      if (len > max) max = len
      //println(offset, i, as(i), bs(j), len, max)
      i += 1
    }

    if (max < min) min = max
  }

  println(min)
}


A sequence of $$$n$$$ numbers is called permutation if it contains all numbers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences $$$[3, 1, 4, 2]$$$, [$$$1$$$] and $$$[2,1]$$$ are permutations, but $$$[1,2,1]$$$, $$$[0,1]$$$ and $$$[1,3,4]$$$ are not.For a given number $$$n$$$ you need to make a permutation $$$p$$$ such that two requirements are satisfied at the same time:  For each element $$$p_i$$$, at least one of its neighbors has a value that differs from the value of $$$p_i$$$ by one. That is, for each element $$$p_i$$$ ($$$1 \le i \le n$$$), at least one of its neighboring elements (standing to the left or right of $$$p_i$$$) must be $$$p_i + 1$$$, or $$$p_i - 1$$$.  the permutation must have no fixed points. That is, for every $$$i$$$ ($$$1 \le i \le n$$$), $$$p_i \neq i$$$ must be satisfied. Let's call the permutation that satisfies these requirements funny.For example, let $$$n = 4$$$. Then [$$$4, 3, 1, 2$$$] is a funny permutation, since:   to the right of $$$p_1=4$$$ is $$$p_2=p_1-1=4-1=3$$$;  to the left of $$$p_2=3$$$ is $$$p_1=p_2+1=3+1=4$$$;  to the right of $$$p_3=1$$$ is $$$p_4=p_3+1=1+1=2$$$;  to the left of $$$p_4=2$$$ is $$$p_3=p_4-1=2-1=1$$$.  for all $$$i$$$ is $$$p_i \ne i$$$. For a given positive integer $$$n$$$, output any funny permutation of length $$$n$$$, or output -1 if funny permutation of length $$$n$$$ does not exist.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of the test cases follows. Each test case consists of f single line containing one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print on a separate line:    any funny permutation $$$p$$$ of length $$$n$$$;  or the number -1 if the permutation you are looking for does not exist.

NoteThe first test case is explained in the problem statement.In the second test case, it is not possible to make the required permutation: permutations $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[3, 2, 1]$$$ have fixed points, and in $$$[2, 3, 1]$$$ and $$$[3, 1, 2]$$$ the first condition is met not for all positions.

object _1741B extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val ans = io.nextInt() match {
      case 1 | 3 => Seq(-1)
      case n if n%2 == 0 => (n to 1 by -1)
      case n =>
      val m = n/2 + 1
      (n until m by -1) ++ (1 to m)
    }
    io.printLine(ans: _*)
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

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

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

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

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


You are given an array $$$a$$$ of $$$n$$$ integers. Initially there is only one copy of the given array.You can do operations of two types:  Choose any array and clone it. After that there is one more copy of the chosen array.  Swap two elements from any two copies (maybe in the same copy) on any positions. You need to find the minimal number of operations needed to obtain a copy where all elements are equal.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output a single integer — the minimal number of operations needed to create at least one copy where all elements are equal.

NoteIn the first test case all elements in the array are already equal, that's why the answer is $$$0$$$.In the second test case it is possible to create a copy of the given array. After that there will be two identical arrays:$$$[ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]$$$After that we can swap elements in a way so all zeroes are in one array:$$$[ \ 0 \ \underline{0} \ \underline{0} \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ \underline{1} \ 1 \ 3 \ 3 \ 7 \ \underline{3} \ ]$$$Now let's create a copy of the first array:$$$[ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]$$$, $$$[ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]$$$Let's swap elements in the first two copies:$$$[ \ 0 \ 0 \ 0 \ \underline{0} \ \underline{0} \ 0 \ ]$$$, $$$[ \ \underline{3} \ \underline{7} \ 0 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]$$$.Finally, we made a copy where all elements are equal and made $$$6$$$ operations.It can be proven that no fewer operations are enough.

import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)

  def recur(len: Int, curr: Int, count: Int = 0): Int = {
    if (curr >= len) count
    else {
      val nc = curr * 2
      val c = if (nc > len) len - curr else curr
      recur(len, nc, count + c + 1)
    }
  }

  def solve(n: Int, xs: Array[Int]) = {
    val tup = xs.groupBy(x => x).maxBy(_._2.length)
    println(recur(xs.length, tup._2.length))

  }

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

    val cases = readLine.toInt
    for (
      i <- 0 until cases;
      n = readLine().toInt;
      xs = rsi
    ) solve(n, xs)
  }
}


Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.There are $$$n$$$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $$$i$$$-th position. Thus each of $$$n$$$ positions should contain exactly one flower: a rose or a lily.She knows that exactly $$$m$$$ people will visit this exhibition. The $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\leq n, m\leq 10^3$$$) — the number of flowers and visitors respectively. Each of the next $$$m$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1\leq l_i\leq r_i\leq n$$$), meaning that $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive.

Print the string of $$$n$$$ characters. The $$$i$$$-th symbol should be «0» if you want to put a rose in the $$$i$$$-th position, otherwise «1» if you want to put a lily. If there are multiple answers, print any.

NoteIn the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions;  in the segment $$$[1\ldots3]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\cdot 2=2$$$;  in the segment $$$[2\ldots4]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\cdot 2=2$$$;  in the segment $$$[2\ldots5]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\cdot 2=4$$$. The total beauty is equal to $$$2+2+4=8$$$.In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions;  in the segment $$$[5\ldots6]$$$, there are one rose and one lily, so the beauty is equal to $$$1\cdot 1=1$$$;  in the segment $$$[1\ldots4]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\cdot 2=4$$$;  in the segment $$$[4\ldots6]$$$, there are two roses and one lily, so the beauty is equal to $$$2\cdot 1=2$$$. The total beauty is equal to $$$1+4+2=7$$$.

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

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var m = array1(1)
  var answer = Array.ofDim[Int](n)

  var tree = mutable.SortedMap.empty[Int, mutable.HashSet[Tuple2[Int, Int]]]

  for (i <- 0 until m) {
    val d = StdIn.readLine().split(" ").map(_.toInt)
    val k = d(1) - d(0)
    val set = tree.getOrElse(k, mutable.HashSet.empty[Tuple2[Int, Int]])
    set.add(d(0) - 1 -> (d(1) - 1))
    tree.put(k, set)
  }

  var l = 0
  answer.map({el =>
    l = l + 1
    if (l % 2 == 0) 0 else 1
  }).foreach(print)
  /*if (n != 1) {

    var last = 0
    tree.foreach({ case (d, t1) =>
      t1.foreach({ t =>
        var i = t._1
        while (i <= t._2) {
          if (answer(i) == 0) {
            if (last % 2 == 0) answer(i) = 1; else answer(i) = 2
            last = last + 1
          }
          i = i + 1
        }
      })
    })
    answer.map(_ % 2).foreach(print)
  } else {
    println(0)
  }*/
}

object B1004 extends App {
  case class LR(l: Int, r: Int) {
    def length = r - l
  }

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

  val (n, m) = {
    val arr = read
    (arr(0), arr(1))
  }

  val result = {
    val arr = new Array[Int](n)
    (0 to n - 1).foreach { i => arr(i) = i % 2 }
    arr
  }

  result foreach print
}

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

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var m = array1(1)
  var answer = Array.ofDim[Int](n)

  var tree = mutable.SortedMap.empty[Int, mutable.HashSet[Tuple2[Int, Int]]]

  for (i <- 0 until m) {
    val d = StdIn.readLine().split(" ").map(_.toInt)
    val k = d(1) - d(0)
    val set = tree.getOrElse(k, mutable.HashSet.empty[Tuple2[Int, Int]])
    set.add(d(0) - 1 -> (d(1) - 1))
    tree.put(k, set)
  }

  if (n != 1) {

    var last = 0
    tree.foreach({ case (d, t1) =>
      t1.foreach({ t =>
        var i = t._1
        while (i <= t._2) {
          if (answer(i) == 0) {
            if (last % 2 == 0) answer(i) = 1; else answer(i) = 2
            last = last + 1
          }
          i = i + 1
        }
      })
    })
    answer.map(_ % 2).foreach(print)
  } else {
    println(0)
  }
}

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

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var m = array1(1)
  var answer = Array.ofDim[Int](n)

  var tree = mutable.SortedMap.empty[Int,Tuple2[Int,Int]]

  for (i <- 0 until m) {
    val d = StdIn.readLine().split(" ").map(_.toInt)
    tree.put(d(1) - d(0), d(0) - 1 -> (d(1) - 1))
  }

  if (n != 1) {

    var last = 0
    tree.foreach({ case (d, t) =>
      var i = t._1
      while (i <= t._2) {
        if (answer(i) == 0) {
          if (last % 2 == 0) answer(i) = 1; else answer(i) = 2
          last = last + 1
        }
        i = i + 1
      }
    })
    answer.map(_ % 2).foreach(print)
  } else
    {
      println(0)
    }
}

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

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var m = array1(1)
  var answer = Array.ofDim[Int](n)

  var tree = mutable.SortedMap.empty[Int,Tuple2[Int,Int]]

  for (i <- 0 until m) {
    val d = StdIn.readLine().split(" ").map(_.toInt)
    tree.put(d(1) - d(0), d(0) - 1 -> (d(1) - 1))
  }

  if (n != 1) {

    var last = 0
    tree.foreach({ case (d, t) =>
      var i = t._1
      while (i <= t._2) {
        if (answer(i) == 0) {
          if (last % 2 == 0) answer(i) = 1; else answer(i) = 2
          last = last + 1
        }
        i = i + 1
      }
    })
    answer.map(_ % 2).foreach(println)
  } else
    {
      println(0)
    }
}

object B1004 extends App {
  case class LR(l: Int, r: Int) {
    def length = r - l
  }

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

  val (n, m) = {
    val arr = read
    (arr(0), arr(1))
  }

  val memo = {
    val arr = new Array[Boolean](n)
    (0 to n - 1).foreach { i => arr(i) = false }
    arr
  }

  val result = {
    val arr = new Array[Int](n)
    (0 to n - 1).foreach { i => arr(i) = 0 }
    arr
  }

  val flowers =
    (0 to m - 1)
      .map { _ =>
        val arr = read
        LR(arr(0), arr(1))
      }
      .sortWith(_.length > _.length)
      .foreach { interval =>
        val pendingDecision = (interval.l to interval.r).filter( i => !memo(i - 1))
        pendingDecision.zipWithIndex.foreach { case (v, i) =>
          result(v - 1) = i % 2
          memo(v - 1) = true
        }
      }

  result foreach print
}

object B1004 extends App {
  case class LR(l: Int, r: Int) {
    def length = r - l
  }

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

  val (n, m) = {
    val arr = read
    (arr(0), arr(1))
  }

  val memo = {
    val arr = new Array[Boolean](n)
    (0 to n - 1).foreach { i => arr(i) = false }
    arr
  }

  val result = {
    val arr = new Array[Int](n)
    (0 to n - 1).foreach { i => arr(i) = 0 }
    arr
  }

  val flowers =
    (0 to m - 1)
      .map { _ =>
        val arr = read
        LR(arr(0), arr(1))
      }
      .sortWith((x, y) => x.length > y.length || (x.length == y.length && x.l < y.l))
      .foreach { interval =>
        val pendingDecision = (interval.l to interval.r).filter( i => !memo(i - 1))
        pendingDecision.zipWithIndex.foreach { case (v, i) =>
          result(v - 1) = i % 2
          memo(v - 1) = true
        }
      }

  result foreach print
}

object B1004 extends App {
  case class LR(l: Int, r: Int) {
    def length = r - l
  }

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

  val (n, m) = {
    val arr = read
    (arr(0), arr(1))
  }

  val memo = {
    val arr = new Array[Boolean](n)
    (0 to n - 1).foreach { i => arr(i) = false }
    arr
  }

  val result = {
    val arr = new Array[Int](n)
    (0 to n - 1).foreach { i => arr(i) = 0 }
    arr
  }

  val flowers =
    (0 to m - 1)
      .map { _ =>
        val arr = read
        LR(arr(0), arr(1))
      }
      .sortWith(_.length > _.length)
      .foreach { interval =>
        val pendingDecision = (interval.l to interval.r).filter( i => !memo(i - 1))
        pendingDecision.zipWithIndex.foreach { case (v, i) =>
          result(v - 1) = i % 2
          memo(v - 1) = true
        }
      }

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