Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $$$1$$$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $$$3$$$ steps, and the second contains $$$4$$$ steps, she will pronounce the numbers $$$1, 2, 3, 1, 2, 3, 4$$$.You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

The first line contains $$$n$$$ ($$$1 \le n \le 1000$$$) — the total number of numbers pronounced by Tanya. The second line contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with $$$x$$$ steps, she will pronounce the numbers $$$1, 2, \dots, x$$$ in that order. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

In the first line, output $$$t$$$ — the number of stairways that Tanya climbed. In the second line, output $$$t$$$ numbers — the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)

    val cnts = ArrayBuffer[Int]()
    var cnt = 0
    var prev = 0
    REP(N) { i =>
      if (A(i) == prev + 1) {
        cnt += 1
      } else {
        cnts += cnt
        cnt = 1
      }
      prev = A(i)
    }
    if (cnt > 0) cnts += cnt
    out.println(cnts.length)
    out.println(cnts.mkString(" "))
  }

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

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

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

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

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

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

object CF496A extends App {

  import java.io.PrintWriter
  import java.util.Scanner

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

  def solve = {
    val numbers = (new Array[Int](in.nextInt)).map(_ => in.nextInt)

    def count(numbers: Array[Int], stairs: List[Int], current: Int): List[Int] = {
      if (numbers.isEmpty)
        return stairs :+ current
      if (numbers.head == 1)
        return count(numbers.tail, stairs :+ current, 1)
      else
        return count(numbers.tail, stairs, current + 1)
    }

    val stairs = count(numbers, List[Int](), 0).tail

    out.println(stairs.length)
    out.println(stairs.mkString(" "))
  }

  solve
  out.flush
  out.close
}

import scala.collection.mutable._

object Solution {
  def main(args: Array[String]) {
    val n = io.StdIn.readLine.toInt
    val stairs = io.StdIn.readLine.split(" ").map(_.toInt)

    var count = 0
    var lastStep = new ListBuffer[Int]()
    for (i <- 0 until stairs.length) {
      if (stairs(i) == 1) {
        count += 1
        if (i != 0) {
          lastStep += stairs(i-1)
        }
      }
    }
    lastStep += stairs(n-1)
    println(count)
    println(lastStep.toList.mkString(" "))

  }
}

/**
  * @author ShankarShastri
  *         Algorithm: ProblemA
  */
import scala.io.StdIn._
import scala.annotation.tailrec

object ProblemA {

  def getAllIndicesOfElement[T](element: T, l: List[T]): List[Int] = {
    @tailrec
    def getAllIndicesHelper(l: List[T], accumList: List[Int] = List[Int](), index: Int=0): List[Int] = {
      if(l.length == 0) {
        (index :: accumList).reverse
      }  else {
        l match {
          case head :: tail if head == element => getAllIndicesHelper(tail, index :: accumList, index+1)
          case _ :: tail => getAllIndicesHelper(tail, accumList, index+1)
        }
      }
    }
    getAllIndicesHelper(l)
  }

  def tanyaStairwayStr(list: List[Int]): String = {
    getAllIndicesOfElement(1, list).sliding(2).toList.map(_.reduce((a,b) => b - a)).mkString(" ")
  }

  def main(args: Array[String]): Unit = {
    val _ = readInt
    val arr = readLine().split(" ").map(_.toInt).toList
    println(arr.count(_ == 1))
    println(tanyaStairwayStr(arr))
  }
}

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

object Codeforces1005A {

  def parseStairs(sounds: Array[Int]): Seq[Int] = {
    val stairs = new ListBuffer[Int]
    for (sound <- sounds) {
      if (sound == 1) {
        stairs.append(1)
      } else {
        stairs(stairs.length - 1) += 1
      }
    }
    stairs
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val sounds = StdIn.readLine.split(" ").map(_.trim.toInt)

    val stairs = parseStairs(sounds)
    println(stairs.length)
    println(stairs.mkString(" "))
  }
}


There are $$$n$$$ block towers in a row, where tower $$$i$$$ has a height of $$$a_i$$$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation:  Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \leq i, j \leq n$$$; $$$i \neq j$$$), and move a block from tower $$$i$$$ to tower $$$j$$$. This essentially decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_j$$$ by $$$1$$$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $$$\max(a)-\min(a)$$$. What's the minimum possible ugliness you can achieve, after any number of days?

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of buildings. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the heights of the buildings.

For each test case, output a single integer — the minimum possible ugliness of the buildings.

NoteIn the first test case, the ugliness is already $$$0$$$.In the second test case, you should do one operation, with $$$i = 1$$$ and $$$j = 3$$$. The new heights will now be $$$[2, 2, 2, 2]$$$, with an ugliness of $$$0$$$.In the third test case, you may do three operations:   with $$$i = 3$$$ and $$$j = 1$$$. The new array will now be $$$[2, 2, 2, 1, 5]$$$,  with $$$i = 5$$$ and $$$j = 4$$$. The new array will now be $$$[2, 2, 2, 2, 4]$$$,  with $$$i = 5$$$ and $$$j = 3$$$. The new array will now be $$$[2, 2, 3, 2, 3]$$$.  The resulting ugliness is $$$1$$$. It can be proven that this is the minimum possible ugliness for this test.

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

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("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615A(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 CF1615A (fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val T = ni()
    (1 to T).foreach { i =>
      val n = ni()
      val sum =
        (1 to n).map(_ => ni()).sum
      out.println{
        if (sum % n == 0) 0
        else 1
      }
    }
  }

}


You are given $$$n$$$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $$$0$$$ in case the intersection is an empty set.For example, the intersection of segments $$$[1;5]$$$ and $$$[3;10]$$$ is $$$[3;5]$$$ (length $$$2$$$), the intersection of segments $$$[1;5]$$$ and $$$[5;7]$$$ is $$$[5;5]$$$ (length $$$0$$$) and the intersection of segments $$$[1;5]$$$ and $$$[6;6]$$$ is an empty set (length $$$0$$$).Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $$$(n - 1)$$$ segments has the maximal possible length.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of segments in the sequence. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 10^9$$$) — the description of the $$$i$$$-th segment.

Print a single integer — the maximal possible length of the intersection of $$$(n - 1)$$$ remaining segments after you remove exactly one segment from the sequence.

NoteIn the first example you should remove the segment $$$[3;3]$$$, the intersection will become $$$[2;3]$$$ (length $$$1$$$). Removing any other segment will result in the intersection $$$[3;3]$$$ (length $$$0$$$).In the second example you should remove the segment $$$[1;3]$$$ or segment $$$[2;6]$$$, the intersection will become $$$[2;4]$$$ (length $$$2$$$) or $$$[1;3]$$$ (length $$$2$$$), respectively. Removing any other segment will result in the intersection $$$[2;3]$$$ (length $$$1$$$).In the third example the intersection will become an empty set no matter the segment you remove.In the fourth example you will get the intersection $$$[3;10]$$$ (length $$$7$$$) if you remove the segment $$$[1;5]$$$ or the intersection $$$[1;5]$$$ (length $$$4$$$) if you remove the segment $$$[3;10]$$$.

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    case class Seg(l: Int, r: Int) {
      def len = max(0, r - l)
    }
    val S = map(N) { _ =>
      val l, r = sc.nextInt()
      Seg(l, r)
    }

    var msR = 0
    var mxL = 0
    rep(N) { i =>
      val s = S(i)
      if (s.r < S(msR).r || (s.r == S(msR).r && s.len < S(msR).len)) {
        msR = i
      }
      if (S(mxL).l < s.l || (s.l == S(mxL).l && s.len < S(mxL).len)) {
        mxL = i
      }
    }

    def intersect(ignore: Int): Int = {
      var msR = Integer.MAX_VALUE
      var mxL = 0
      rep(N) { i =>
        if (i != ignore) {
          val s = S(i)
          if (s.r < msR) {
            msR = s.r
          }
          if (mxL < s.l) {
            mxL = s.l
          }
        }
      }
      max(0, msR - mxL)
    }

    out.println(max(intersect(msR), intersect(mxL)))
  }

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

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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

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

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

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

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

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

import scala.collection.mutable.ListBuffer

object CF506C extends App {
  import scala.io.StdIn
  val n = StdIn.readLine.toInt
  val segments = new Array[Int](n).map(_ => StdIn.readLine.split(' ').map(_.toInt))

  val shrink = ListBuffer[Int]()

  var min = Int.MinValue
  var max = Int.MaxValue

  for (i <- 0 until n) {
    val segment = segments(i)
    if (segment(0) > min || segment(1) < max) {
      shrink += i
    }
    if (segment(0) > min)
      min = segment(0)
    if (segment(1) < max)
      max = segment(1)
  }

  var maxLength = 0
  for (drop <- shrink) {
    min = Int.MinValue
    max = Int.MaxValue
    for (i <- (0 until n).filter(_ != drop)) {
      if (segments(i)(0) > min)
        min = segments(i)(0)
      if (segments(i)(1) < max)
        max = segments(i)(1)
    }
    maxLength = maxLength.max(max-min)
  }

  println(maxLength)
}

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

import collection.Searching._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

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

  case class Interval(l: Int, r: Int) {
    def intersect(o: Option[Interval]): Option[Interval] = {
      o match {
        case Some(Interval(ol, or)) =>
          if (ol < r && l < or) {
            Some(Interval(Math.max(ol, l), Math.min(or, r)))
          } else {
            None
          }
        case None => None
      }
    }

    def contains(o: Option[Interval]): Boolean = {
      intersect(o).exists(this.equals(_))
    }

    def len(): Int = {
      r - l
    }
  }

  def doCase(): Unit ={
    val N = readInt()
    val ints: Array[Interval] = Array.fill(N)(null)
    var i = 0
    while (i < N) {
      ints(i) = readIntLine() match {case Array(a, b) => Interval(a, b)}
      i += 1
    }

    var full = Some(Interval(Integer.MIN_VALUE, Integer.MAX_VALUE)): Option[Interval]
    var other = List[Option[Interval]]()
    for (int <- ints) {
      var n = full
      full = full.flatMap(_.intersect(Some(int)))
      val intersected = other.map(int.intersect)
      other = n :: intersected.distinct
    }

    print(other.map(_.map(_.len()).getOrElse(0)).max)
  }

  def main(args: Array[String]): Unit = {
    val noCases = 1
    for (i <- 0 until noCases) {
      doCase()
    }
  }

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

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

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

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

object C extends App {

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

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val points = Array.ofDim[Point](n * 2)
    (0 until n).foreach { i =>
      points(i * 2) = Point(in.nextInt, i, isBegin = true)
      points(i * 2 + 1) = Point(in.nextInt, i, isBegin = false)
    }
    util.Sorting.quickSort(points)((x: Point, y: Point) => Ordering[Int].compare(x.x, y.x))
    //points.sortBy(_.x)
    //points.foreach(println)
    var k = 0
    var ans = 0
    (0 until n * 2 - 1).foreach { i =>
      if (points(i).isBegin)
        k += 1
      else
        k -= 1
      if (k == n - 1) {
        ans = math.max(ans, points(i + 1).x - points(i).x)
      }
      if (k == n) {
        if (points(i).segId == points(i + 1).segId) {
          ans = math.max(ans, points(i + 2).x - points(i - 1).x)
        }
        ans = math.max(ans, points(i + 1).x - points(i - 1).x)
        ans = math.max(ans, points(i + 2).x - points(i).x)
      }
    }
    print(ans)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

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

}


Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times.

The first line contains three integers: a, b, n (1 ≤ a, b, n ≤ 105).

In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(a, b, n) = in.next().split(' ').map(_.toInt)
  val r = (0 to 9).find(i => (a * 10 + i) % b == 0)
  if (r.isEmpty)
    println(-1)
  else
    println(s"$a${r.get}" + "0" * (n - 1))
}

object Main{

    def main(args: Array[String]){
         val Array(a, b, n) = readLine().split(" ").map(_.toInt)
         val d = (b - (a*10)%b) % b
         if (d >= 10) println("-1") else{
            print(a)
            print(d)
            for (i <- 1 to n-1)
                print(0)
            println()
         }
    }                                         //> main: (args: Array[String])Unit
}

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

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

  val A, B, N = sc.nextInt

  def solve(): String = {
    val sb = new StringBuilder(A.toString)

    @inline
    def extend(x: Int): Int = {
      val rem = x * 10 % B
      if (rem == 0) 0
      else {
        val d = B - rem
        if (d > 9) -1
        else d
      }
    }

    val d = extend(A)
    if (d < 0) "-1"
    else {
      sb += ('0' + d).toChar
      for (_ <- 1 until N)
        sb += '0'
      sb.toString
    }
  }

  out.println(solve)
  out.close
}

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

  val Array(a, b, n) = readLine().split(" ").map(_.toInt)

  val k        = math.floor(a * 10.0 / b).toInt
  val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)
  val (a1, a2) = (a * 10 + x1, a * 10 + x2)

  val ans =
    if (x1 >= 0 && x1 < 10 && a1 % b == 0)
      a1.toString + "0" * (n - 1)
    else if (x2 >= 0 && x2 < 10 && a2 % b == 0)
      a2.toString + "0" * (n - 1)
    else
      "-1"

  println(ans)
}

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

  val Array(a, b, n) = readLine().split(" ").map(_.toInt)
  val d              = (b - (a * 10) % b) % b

  if (d > 9)
    println("-1")
  else
    println(s"$a$d${"0" * (n - 1)}")
}

object Main {
  def main(args: Array[String]) {
    val abn =  readLine().split(" ").map(_.toInt)
    val a = abn(0)
    val b = abn(1)
    val n = abn(2)

    val max = (a * 10 + 9).toFloat / b.toFloat
    val min = (a * 10).toFloat / b.toFloat

    val dec = if (max.floor >= min.ceil) (min.ceil.toInt * b - a * 10)
    else -1

    if (dec == -1) println("-1")
    else {
      val s = Seq(a, dec) ++ (1 until n).map(_ => 0)
      println(s.mkString)
    }
  }
}

import scala.Math.pow;

object App {
  def f1(n: Long, m: Int) = {
    val k = n * 10
    for {
        i <- (0 to 9).toList
        if ((k + i) % m == 0)
    } yield k + i
  }                                               //> f1: (n: Int, m: Int)List[Int]

  def f1_io() = {
    val Array(a, b, n) = (readLine split " ") map (_.toInt)
    val l = f1(a, b)
    if (l.isEmpty) print(-1)
    else {
        print(l(0))
        for (i <- (1 to n - 1)) print(0)
    }
  }                                 //> f: (input: String)Double

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

}

object Main{

    def main(args: Array[String]){
         val Array(a, b, n) = readLine().split(" ").map(_.toInt)
         val d = b - (a*10)%b
         if (d >= 10) println("-1") else{
            print(a)
            print(d)
            for (i <- 1 to n-1)
                print(0)
            println()
         }
    }                                         //> main: (args: Array[String])Unit
}

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

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

  val A, B, N = sc.nextInt

  def solve(): String = {
    val sb = new StringBuilder(A.toString)

    @inline
    def extend(x: Int): Int = {
      val rem = x * 10 % B
      if (rem == 0) 0
      else {
        val d = B - rem
        if (d > 9) -1
        else d
      }
    }

    @tailrec
    def loop(acc: Int, n: Int): String = {
      if (n == 0) sb.toString
      else {
        val d: Int = extend(acc)
        sb += (d + '0').toChar
        if (d < 0) "-1"
        else loop(d, n - 1)
      }
    }

    loop(A % B, N)
  }

  out.println(solve)
  out.close
}

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

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

  val A, B, N = sc.nextInt

  def solve(): BigInt = {

    def lengthen(x: BigInt): BigInt = {
      val x10: BigInt = x * 10
      val a: BigInt = B - x10 % B
      if (a < 10) x10 + a
      else -1
    }

    @tailrec
    def loop(acc: BigInt, n: Int): BigInt = {
      if (n == 0 || acc < 0) acc
      else loop(lengthen(acc), n - 1)
    }

    loop(BigInt(A), N)
  }

  out.println(solve)
  out.close
}

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

  val Array(a, b, n) = readLine().split(" ").map(_.toInt)
  val d              = (b - (a * 10) % b) % b

  if (d > 0)
    println("-1")
  else
    println(s"$a$d${"0" * (n - 1)}")
}

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

  val Array(a, b, n) = readLine().split(" ").map(_.toLong)

  @annotation.tailrec
  def go(a: Long, n: Long): Long =
    if (n == 0) a
    else {
      val k        = math.floor(a * 10 / b).toLong
      val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)

      if (x1 >= 0 && x1 < 10) go(a * 10 + x1, n - 1)
      else if (x2 >= 0 && x2 < 10) go(a * 10 + x2, n - 1)
      else -1L
    }

  val ans = go(a, n)

  println(ans)
}

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

  val Array(a, b, n) = readLine().split(" ").map(_.toInt)

  val k        = math.floor(a * 10 / b).toInt
  val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)

  val ans =
    if (x1 >= 0 && x1 < 10)
      (a * 10 + x1).toString + "0" * (n - 1)
    else if (x2 >= 0 && x2 < 10)
      (a * 10 + x2).toString + "0" * (n - 1)
    else
      "-1"

  println(ans)
}

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

  val Array(a, b, n) = readLine().split(" ").map(_.toInt)

  val k        = math.floor(a * 10.0 / b).toInt
  val (x1, x2) = (a * 10 - k * b, (k + 1) * b - a * 10)

  val ans =
    if (x1 >= 0 && x1 < 10)
      (a * 10 + x1).toString + "0" * (n - 1)
    else if (x2 >= 0 && x2 < 10)
      (a * 10 + x2).toString + "0" * (n - 1)
    else
      "-1"

  println(ans)
}

object Main {
  def main(args: Array[String]) {
    val abn =  readLine().split(" ").map(_.toInt)
    val a = abn(0)
    val b = abn(1)
    val n = abn(2)

    val max = (a * 10 + 9).toFloat / b.toFloat
    val min = (a * 10).toFloat / b.toFloat

    val dec = if (max.floor >= min.ceil) (min.ceil.toInt - a * 10)
    else -1

    if (dec == -1) println("-1")
    else {
      val s = Seq(a, n) ++ (1 until n).map(_ => 0)
      println(s.mkString)
    }
  }
}

import scala.Math.pow;

object App {
  def f1(n: Long, m: Int) = {
    val k = n * 10
    for {
        i <- (0 to 9).toList
        if ((k + i) % m == 0)
    } yield k + i
  }                                               //> f1: (n: Int, m: Int)List[Int]

  def f1_io() = {
    val Array(a, b, n) = (readLine split " ") map (_.toInt)
    val l = f1(a, b)
    if (l.isEmpty) print(-1)
    else {
        print(l(0))
        for (i <- (1 to n + 1 - l(0).toString.length)) print(0)
    }
  }                                 //> f: (input: String)Double

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

}

import scala.Math.pow;

object App {
  def f1(n: Int, m: Int) = {
    val k = n * 10
    for {
        i <- (0 to 9).toList
        if ((k + i) % m == 0)
    } yield k + i
  }                                               //> f1: (n: Int, m: Int)List[Int]

  def f1_io() = {
    val Array(a, b, n) = (readLine split " ") map (_.toInt)
    val l = f1(a, b)
    if (l.isEmpty) print(-1)
    else {
        print(l(0))
        for (i <- (1 to n + 1 - l(0).toString.length)) print(0)
    }
  }                                 //> f: (input: String)Double

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

}

import scala.Math.pow;

object App {
  def f1(n: Int, m: Int) = {
    val k = n * 10
    for {
        i <- (0 to 9).toList
        if ((k + i) % m == 0)
    } yield k + i
  }                                               //> f1: (n: Int, m: Int)List[Int]

  def f1_io() = {
    val Array(a, b, n) = (readLine split " ") map (_.toInt)
    val l = f1(a, b)
    if (l.isEmpty) print(-1)
    else {
        print(l(1))
        for (i <- (1 to n - l(1).toString.length)) print(0)
    }
  }                                 //> f: (input: String)Double

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

}


A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.

The first input line contains integer k (1 ≤ k ≤ 1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1 ≤ |s| ≤ 1000, where |s| is the length of string s.

Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them. If the solution doesn't exist, print "-1" (without quotes).

import java.util.Scanner

/**
  * Created by MZKL7315 on 4/12/2016.
  */

object Main {

  def main(args: Array[String]) = {
    val in: Scanner = new Scanner(System.in)
    val k = in.nextInt()
    val s = in.next()

    val m = s.map(x => (x, s.count(y => y == x))).toMap
    if (m.exists(_._2 % k != 0)) println(-1)
    else {
      val res = m.map({ case (x, y) => (1 to y / k).map(_ => x).mkString }).mkString
      println((1 to k).map(_ => res).mkString)
    }

  }
}

import java.util.Scanner

/**
  * Created by MZKL7315 on 4/12/2016.
  */

object Main {

  def calc(s: String, k: Int): String = s match {
    case "" => ""
    case s => {
      val c = s.count(_ == s.head)
      if (c % k != 0) throw new Error("-1") else (1 to c / k).map(_ => s.head).mkString + calc(s filter (_ != s.head), k)
    }
  }

  def gen(s: String, k: Int): String = (s, k) match {
    case (s, 0) => ""
    case _ => s + gen(s, k - 1)
  }

  def main(args: Array[String]) = {
    val in: Scanner = new Scanner(System.in)
    val k = in.nextInt()
    val s = in.next()
    try {
      val res = calc(s, k)
      println(gen(res, k))
    } catch {
      case e: Error => println(e.getMessage)
    }
  }
}

import java.util.Scanner

/**
  * Created by MZKL7315 on 4/12/2016.
  */

object Main {

  def charCounts(s: String): Map[Char, Int] = s match {
    case "" => Map()
    case s => charCounts(s filter (_ != s.head)) + (s.head -> s.count(_ == s.head))
  }

  def main(args: Array[String]) = {
    val in: Scanner = new Scanner(System.in)
    val k = in.nextInt()
    val s = in.next()

    val m = charCounts(s)
    if (m.exists(_._2 % k != 0)) println(-1)
    else {
      println((1 to k).map(_ => m.map({ case (x, y) => (1 to y / k).map(_ => x).mkString }).mkString).mkString)
    }

  }
}

import java.util.StringTokenizer

object _219A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val k = next.toInt
  val s = next
  val grouped = s.groupBy(ch => ch)
  if (grouped.exists(pair => pair._2.length % k != 0)) println(-1)
  else {
    val map = grouped.map(pair => (pair._1, pair._2.length / k))
    val one = map.map(i => (0 until i._2).map(j => i._1).mkString).mkString
    val ans = (0 until k).map(i => one).mkString
    println(ans)
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val k = in.next().toInt
  val str = in.next().foldLeft(Map.empty[Char, Int]) {
    case (acc, el) if acc.contains(el) => acc + (el -> (acc(el) + 1))
    case (acc, el) => acc + (el -> 1)
  }
  if (str.values.exists(_ % k > 0))
    println("-1")
  else {
    val s = str.map{
      case(key, v) => List.fill(v / k){key}.mkString
    }.mkString
    println(List.fill(k){s}.mkString)
  }
}

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

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

  val N = sc.nextLine.toInt
  val S = sc.nextLine.sorted
  val len = S.length

  val base: String = {
    @tailrec
    def loop(acc: List[Char], i: Int): String =
      if (i >= len) acc.mkString
      else loop(acc :+ S(i), i + N)
    loop(Nil, 0)
  }

  val answer: String = {
    val res = base * N
    if (S == res.sorted) res
    else "-1"
  }

  out.println(answer)
  out.close
}

import annotation.tailrec
import java.io._

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

  val k = readInt
  val s = reader.readLine().groupBy(x => x)
  val ans = Map(false -> (() => "-1"), true -> (() => s.values.map(str => str.take(str.length / k)).mkString * k)) apply {
    s.values.forall(_.length % k == 0)
  }

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

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val s = readLine
    val map = scala.collection.mutable.Map[Char, Int]()
    s.foreach(c => map(c) = map.getOrElse(c, 0) + 1)
    var r = Seq[Char]()
    var cor = true
    map.foreach { case (c, i) =>
      if (i % n == 0) r ++= Seq.fill(i / n)(c)
      else cor = false
    }
    if(cor) println(Seq.fill(n)(r.mkString).mkString)
    else println("-1")
  }
}

import Console._

object Main extends App {

  def getCountMap(str: String): Map[Char, Int] = {
    str.groupBy(_.toChar).map(p => (p._1, p._2.length))
  }

  val k = readInt
  val str = readLine

  // check if str.length % k == 0
  if (str.length % k != 0) {
    print(-1)
    exit
  }

  // fill map(letter, count) sorted by count
  val freqMap = getCountMap(str).toSeq.sortBy(_._2).toMap

  // Precondition check - every map count % k must be == 0
  freqMap.keys.map(chr => {
    if (freqMap(chr) % k != 0) {
      print(-1)
      exit
    }
  })

  // form initial sequence
  val chrSeq = freqMap.flatMap(chr => {
    List.fill(chr._2 / k)(chr._1)
  }).toList
  for(i <- 0 until k) {
      print(chrSeq.mkString)
  }

  // print all ? - generate not repeating sequences
  // chrSeq.permutations.toList.map(x => println(List.fill(k)(x.mkString).mkString))

}

import java.util.Scanner

/**
  * Created by MZKL7315 on 4/12/2016.
  */

object Main {

  def calc(s: String): String = s match {
    case "" => ""
    case s => {
      val c = s.count(_ == s.head)
      if (c % 2 == 1) throw new Error("-1") else (1 to c / 2).map(_ => s.head).mkString + calc(s filter (_ != s.head))
    }
  }

  def main(args: Array[String]) = {
    val in: Scanner = new Scanner(System.in)
    val n = in.nextInt()
    val s = in.next()
    try {
      val res = calc(s)
      println(res + res)
    } catch {
      case e: Error => println(e.getMessage)
    }
  }
}

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

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

  val N = sc.nextLine.toInt
  val S = sc.nextLine.sorted
  val len = S.length

  val base: String = {
    @tailrec
    def loop(acc: List[Char], i: Int): String =
      if (i >= len) acc.mkString
      else loop(acc :+ S(i), i + N)
    loop(Nil, 0)
  }

  val answer: String =
    if (S == (base * N).sorted) base
    else "-1"

  out.println(answer)
  out.close
}

import Console._

object Main extends App {

  def getCountMap(str: String): Map[Char, Int] = {
    str.groupBy(_.toChar).map(p => (p._1, p._2.length))
  }

  val k = readInt
  val str = readLine

  // check if str.length % k == 0
  if (str.length % k != 0) {
    print(-1)
    exit
  }

  // fill map(letter, count) sorted by count
  val freqMap = getCountMap(str).toSeq.sortBy(_._2).toMap

  // Precondition check - every map count % k must be == 0
  freqMap.keys.map(chr => {
    if (freqMap(chr) % k != 0) {
      print(-1)
      exit
    }
  })

  // form initial sequence
  val chrSeq = freqMap.flatMap(chr => {
    List.fill(chr._2 / k)(chr._1)
  }).toList

  // generate not repeating sequences
  chrSeq.permutations.toList.map(x => println(List.fill(k)(x.mkString).mkString))

}


Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?

First line of input data contains single integer n (1 ≤ n ≤ 106) — length of the array. Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).

Output answer in single line. "First", if first player wins, and "Second" otherwise (without quotes).

NoteIn first sample first player remove whole array in one move and win.In second sample first player can't make a move and lose.

/**
  * Created by mettu.r on 20/08/17.
  */
object Demo extends App {
  override def main(args: Array[String]): Unit = {
    var n = readInt();
    var a = readLine().split(" ").map( x => x.toInt)
    var sum = 0;
    a.foreach(x =>{
      sum += x;
      sum %= 2;
    });
    var ans = false;
    if( sum % 2 == 1 )
      ans = true;
    a.foreach(x => if( x % 2 == 1 ) ans = true);
    if( ans )
      println("First\n");
    else
      println("Second\n");
  }
}


Let's call an array $$$t$$$ dominated by value $$$v$$$ in the next situation.At first, array $$$t$$$ should have at least $$$2$$$ elements. Now, let's calculate number of occurrences of each number $$$num$$$ in $$$t$$$ and define it as $$$occ(num)$$$. Then $$$t$$$ is dominated (by $$$v$$$) if (and only if) $$$occ(v) > occ(v')$$$ for any other number $$$v'$$$. For example, arrays $$$[1, 2, 3, 4, 5, 2]$$$, $$$[11, 11]$$$ and $$$[3, 2, 3, 2, 3]$$$ are dominated (by $$$2$$$, $$$11$$$ and $$$3$$$ respectevitely) but arrays $$$[3]$$$, $$$[1, 2]$$$ and $$$[3, 3, 2, 2, 1]$$$ are not.Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.You are given array $$$a_1, a_2, \dots, a_n$$$. Calculate its shortest dominated subarray or say that there are no such subarrays.The subarray of $$$a$$$ is a contiguous part of the array $$$a$$$, i. e. the array $$$a_i, a_{i + 1}, \dots, a_j$$$ for some $$$1 \le i \le j \le n$$$.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the corresponding values of the array $$$a$$$. It's guaranteed that the total length of all arrays in one test doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or $$$-1$$$ if there are no such subarrays.

NoteIn the first test case, there are no subarrays of length at least $$$2$$$, so the answer is $$$-1$$$.In the second test case, the whole array is dominated (by $$$1$$$) and it's the only dominated subarray.In the third test case, the subarray $$$a_4, a_5, a_6$$$ is the shortest dominated subarray.In the fourth test case, all subarrays of length more than one are dominated.

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

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

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

  class InputReader(val stream: InputStream) {
    private[this] val reader = new BufferedReader(new InputStreamReader(stream), 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
  }
}

object Workspace {
  import Main._
}

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val A = na(N)
      if (N == 1) {
        out.println(-1)
      } else {
        val inf = 1e9.toInt
        var d = inf
        val lst = mutable.Map[Int, Int]().withDefaultValue(-1)
        REP(N) { i =>
          val a = A(i)
          if (lst(a) != -1) {
            d = min(d, i - lst(a))
          }
          lst(a) = i
        }
        if (d == inf) out.println(-1)
        else out.println(d + 1)
      }
    }
  }
}

object C1257 {

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

  def main(args: Array[String]): Unit = {
    var t = readInt
    while (t > 0) {
      val n = readInt
      val arr = readInts(n)
      var res = Integer.MAX_VALUE
      val lastPos = cu.Map.empty[Int, Int]
      var i = 0
      while (i < n) {
        if (lastPos.contains(arr(i)) && i - lastPos(arr(i)) >= 1) {
          res = math.min(res, i - lastPos(arr(i)) + 1)
        }
        lastPos(arr(i)) = i
        i += 1
      }
      if (res == Integer.MAX_VALUE)
        res = -1
      out.println(res)
      t -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.

If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output. If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print "Friendship" (without quotes).

NoteIn the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".

object _734 extends App {
  implicit class Pipe[T](val v: T) extends AnyVal {
    def |>[U](f: T => U): U = f(v)
  }

  val std = scala.io.StdIn
  val _ = std.readLine()
  val line = std.readLine()
  val aCount = line.filter(c => c == 'A').size
  val dCount = line.size - aCount
  (if (aCount > dCount) "Anton"
   else if (dCount > aCount) "Danik"
   else "Friendship") |> print
}

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

object _734A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val s = read[String].toSeq.toMultiSet

    val ans = if (s('A') > s('D')) {
      "Anton"
    } else if (s('A') < s('D')) {
      "Danik"
    } else {
      "Friendship"
    }

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
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 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 = "\n"): 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
      }
    }
  }
}

import scala.io.StdIn._
object Solution {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val ds = readLine.count(_ == 'D')
    val as = n - ds
    println(if (as == ds) "Friendship" else if (as > ds) "Anton" else "Danik")
  }
}

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

import scala.io.StdIn

object App {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val s = StdIn.readLine()
    var a, d = 0
    for (c <- s) {
      if (c == 'A') {
        a += 1
      } else {
        d += 1
      }
    }

    if (a > d) {
      print("Anton")
    } else if (d > a) {
      print("Danik")
    } else {
      print("Friendship")
    }
  }
}

import java.util.Scanner

object Main2 extends App {
    val scanner = new Scanner(System.in)
    val gameNumber = scanner.nextInt()
    val gameResults = scanner.next()
    val res = (gameResults.count(_ == 'A'), gameResults.count(_ == 'D')) match {
      case (a, d) if a > d => "Anton"
      case (a, d) if a < d => "Danik"
      case (a, d) if a == d => "Friendship"
    }
    println(res)
}

object Solution extends App {
  val n = readInt
  val gs = readLine

  val a = gs.count(_ == 'A')
  val d = gs.count(_ == 'D')

  if(a == d) {
    println("Friendship")
  } else if(a < d ) {
    println("Danik")
  } else {
    println("Anton")
  }

}

import scala.io.StdIn._

object TaskA extends App {
  readInt()
  val (a, d) = readLine().toSeq.partition(_ == 'A')
  println(if (a.size > d.size) "Anton" else if (a.size < d.size) "Danik" else "Friendship")
}

object ScannerTest {

  def getWinner(games: String): String = {
    val occ = games.groupBy(c => c) mapValues (s => s.length) withDefaultValue 0
    val danikWins = occ('D')
    val antonWins = occ('A')

    if (danikWins > antonWins) "Danik"
    else if (antonWins > danikWins) "Anton"
    else "Friendship"
  }

  def main(args: Array[String]) {
    readLine()
    println(getWinner(readLine()))
  }
}

import scala.io.StdIn._

object M734A {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val an = readLine.count(_ == 'A')
    val dn = n - an
    val winner = if(an == dn) {"Friendship" } else if(an > dn){"Anton"} else {"Danik"}
    println(winner)
  }
}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    val anton = results.count(_ == 'A')
    //val danik = results.length() - anton
    val danik = results.count(_ == 'D')

    if (anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    val anton = results.filter(_ == 'A').length()
    val danik = results.filter(_ == 'D').length()

    if (anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    val anton = results.count(_ == 'A')
    val danik = results.length() - anton

    if (anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    val anton = results.filter(_ == 'A').size
    val danik = results.length() - anton

    if (anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object AntonAndDanik extends App{
    val matches: Int = scala.io.StdIn.readInt()
    val results: String = scala.io.StdIn.readLine()

    var anton = 0
    var danik = 0

    results.foreach(c =>
        if(c == 'A') anton+=1
        else danik+=1
    )

    if( anton > danik) println("Anton")
    else if (danik > anton) println("Danik")
    else println("Friendship")

}

object CF0734A extends App {
  val n = readInt()
  val str = readLine().split("").toList

  val A = str.filter(_ == "A").size
  val D = str.filter(_ == "D").size

  if(A > D) {
    println("Anton")
  } else if (A < D) {
    println("Danik")
  } else {
    println("Friendship")
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  in.next()
  val pair = in.next().foldLeft(0, 0) {
    case ((a, d), 'A') => (a + 1, d)
    case ((a, d), 'D') => (a, d + 1)
    case (acc, _) => acc
  }
  if (pair._1 == pair._2)
    println("Friendship")
  else if (pair._1 > pair._2)
    println("Anton")
  else
    println("Danik")
}

import scala.io.StdIn

object AntonAndDanik extends App {

  val games = StdIn.readLine().toInt
  val results = StdIn.readLine()
  print(impl(results))

  def impl(results: String): String = {
    var antonWins = 0
    var danikWins = 0
    for (result <- results) {
      if (result == 'A') {
        antonWins += 1
      } else {
        danikWins += 1
      }
    }

    if (antonWins > danikWins) {
      "Anton"
    } else if (danikWins > antonWins) {
      "Danik"
    } else {
      "Friendship"
    }
  }
}

import java.util.Scanner

object Ex extends App {
  val scanner = new Scanner(System.in)
  val n: Int = scanner.nextInt()
  val games: String = scanner.next()
  var a = 0
  var b = 0
  games.foreach(ch => if (ch == 'A') a += 1 else b += 1)
  println(if (a > b) "Anton" else if (a == b) "Friendship" else "Danik")
}

// package codeforces.problemset.p734A

object Main {
  def main(args: Array[String]): Unit = {
    val a = scala.io.Source.stdin.getLines()
    val n = a.next().toInt
    //    println(n)
    val s = a.next()
    //    println(s)
    val x = s.count(_ == 'A')
    val y = s.count(_ == 'D')
    println(if (x > y) "Anton" else if (x < y) "Danik" else "Friendship")

  }
}

import scala.io.StdIn
object AntonDanik extends App
{
    val numOfGames = StdIn.readInt()
    val input = StdIn.readLine()

    val anton = input.filter(_ == 'A').length
    val danik = numOfGames - anton

    if(anton > danik)
    {
        println("Anton")
    }
    else if(anton < danik)
    {
        println("Danik")
    } else println("Friendship")
}

object A734 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = scala.io.StdIn.readLine
    val A = input.count(_=='A')
    val D = input.size - A
    val ans = if(A > D) {
      "Anton"
    }  else if(A < D) {
      "Danik"
    } else {
      "Friendship"
    }
    println(ans)
  }
}

import scala.io.StdIn._
object Solution {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val ds = readLine.count(_ == 'd')
    val as = n - ds
    println(if (as == ds) "Friendship" else if (as > ds) "Anton" else "Danik")
  }
}

object ScannerTest {

  def getWinner(games: String): String = {
    val occ = "AADDA".groupBy(c => c) mapValues (s => s.length) withDefaultValue 0
    val danikWins = occ('D')
    val antonWins = occ('A')

    if (danikWins > antonWins) "Danik"
    else if (antonWins > danikWins) "Anton"
    else "Friendship"
  }

  def main(args: Array[String]) {
    readLine()
    println(getWinner(readLine()))
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val pair = in.next().foldLeft(0, 0) {
    case ((a, d), 'A') => (a + 1, d)
    case ((a, d), 'D') => (a, d + 1)
    case (acc, _) => acc
  }
  if (pair._1 == pair._2)
    println("Friendship")
  else if (pair._1 > pair._2)
    println("Anton")
  else
    println("Danik")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val pair = in.next().foldLeft(0, 0) {
    case ((a, d), 'A') => (a + 1, d)
    case ((a, d), 'B') => (a, d + 1)
    case (acc, _) => acc
  }
  if (pair._1 == pair._2)
    println("Friendship")
  else if (pair._1 > pair._2)
    println("Anton")
  else
    println("Danik")
}


This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.

NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.

import scala.io.StdIn._
import scala.math._

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach { _ =>
       val nq = readLine.split(" ").map(_.toInt)
       val n = nq.head
       val a = readLine.split(" ").map(_.toLong)
       val d1 = new Array[Long](n + 1)
       val d2 = new Array[Long](n + 1)
       d1(0) = -(300000 + 1)
       d2(0) = 0
       var i = 0
       for (k <- a) {
         d1(i + 1) = max(d1(i), d2(i) + k)
         d2(i + 1) = max(d2(i), d1(i) - k)
         i = i + 1
       }
       println(max(d1(n), d2(n)))
    }
  }
}

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

  val t = readInt()

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

    val (ans1, ans2) = an.foldLeft((0L, 0L)) {
      case ((dp1, dp2), a) => (dp1 max (dp2 - a), dp2 max (dp1 + a))
    }

    val ans = ans1 max ans2

    println(ans)
  }
}

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

  val t = readInt()

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

    val (ans1, ans2) = an.foldLeft((0L, 0L)) {
      case ((dp1, dp2), a) => (dp1 max (dp2 - a), dp2 max (dp1 + a))
    }

    val ans = ans1 max ans2
  }
}


Moamen has an array of $$$n$$$ distinct integers. He wants to sort that array in non-decreasing order by doing the following operations in order exactly once:  Split the array into exactly $$$k$$$ non-empty subarrays such that each element belongs to exactly one subarray.  Reorder these subarrays arbitrary.  Merge the subarrays in their new order. A sequence $$$a$$$ is a subarray of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Can you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le |a_i| \le 10^9$$$). It is guaranteed that all numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test case, you should output a single string. If Moamen can sort the array in non-decreasing order, output "YES" (without quotes). Otherwise, output "NO" (without quotes). You can print each letter of "YES" and "NO" in any case (upper or lower).

NoteIn the first test case, $$$a = [6, 3, 4, 2, 1]$$$, and $$$k = 4$$$, so we can do the operations as follows:   Split $$$a$$$ into $$$\{ [6], [3, 4], [2], [1] \}$$$.  Reorder them: $$$\{ [1], [2], [3,4], [6] \}$$$.  Merge them: $$$[1, 2, 3, 4, 6]$$$, so now the array is sorted. In the second test case, there is no way to sort the array by splitting it into only $$$2$$$ subarrays.As an example, if we split it into $$$\{ [1, -4], [0, -2] \}$$$, we can reorder them into $$$\{ [1, -4], [0, -2] \}$$$ or $$$\{ [0, -2], [1, -4] \}$$$. However, after merging the subarrays, it is impossible to get a sorted array.

import scala.io.StdIn._

object _1557B {

  def main(args: Array[String]): Unit = {
    var t = readInt()
    while (t > 0) {
      t -= 1
      val Array(n, k) = ni();
      val ar = ni()
      val br = ar.zipWithIndex.sorted
//      println(br.mkString(", "));
      var count = 0;
      for(i <- 0 until n - 1)
        if(br(i)._2 + 1 != br(i + 1)._2)count += 1;

      if(count < k)println("Yes");
      else println("No")
    }
  }
  def ni(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }
}

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

  val t = readInt()

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

    val r = bn.tail.foldLeft((1, bn.head._2)) {
      case ((count, i), (_, j)) if j == i + 1 => (count, j)
      case ((count, _), (_, j))               => (count + 1, j)
    }._1

    if (r <= k) println("YES") else println("NO")
  }
}

import scala.io.StdIn._

object _1557B {

  def main(args: Array[String]): Unit = {
    var t = readInt()
    while (t > 0) {
      t -= 1
      val Array(n, k) = ni();
      val ar = ni()
      var count = 0;
      for(i <- 0 until n - 1)
        if(ar(i) >= ar(i + 1))count += 1;

      if(count < k)println("Yes");
      else println("No")
    }
  }
  def ni(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }
}

import scala.io.StdIn._

object _1557B {

  def main(args: Array[String]): Unit = {
    var t = readInt()
    while (t > 0) {
      t -= 1
      val Array(n, k) = ni();
      val ar = ni()
      var count = 0;
      for(i <- 0 until n - 1)
        if(ar(i) > ar(i + 1))count += 1;

      if(count < k)println("Yes");
      else println("No")
    }
  }
  def ni(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }
}

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

  val t = readInt()

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

    val r = bn.tail.foldLeft((0, bn.head._2)) {
      case ((count, i), (_, j)) if j == i + 1 => (count, j)
      case ((count, _), (_, j))               => (count + 1, j)
    }._1

    if (r <= k) println("YES") else println("NO")
  }
}

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

  val t = readInt()

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

    val bm = an.foldLeft(List.empty[List[Int]]) {
      case ((l @ (ap :: _)) :: ls, ac) if ac >= ap => (ac :: l) :: ls
      case (ls, ac)                                => List(ac) :: ls
    }

    val ans = bm.length == k && bm.reverse.flatten.sameElements(an.sorted(Ordering[Int].reverse))

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


Bash likes playing with arrays. He has an array a1, a2, ... an of n integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.Suppose he guesses that the gcd of the elements in the range [l, r] of a is x. He considers the guess to be almost correct if he can change at most one element in the segment such that the gcd of the segment is x after making the change. Note that when he guesses, he doesn't actually change the array — he just wonders if the gcd of the segment can be made x. Apart from this, he also sometimes makes changes to the array itself.Since he can't figure it out himself, Bash wants you to tell him which of his guesses are almost correct. Formally, you have to process q queries of one of the following forms:  1 l r x — Bash guesses that the gcd of the range [l, r] is x. Report if this guess is almost correct.  2 i y — Bash sets ai to y. Note: The array is 1-indexed.

The first line contains an integer n (1 ≤ n ≤ 5·105)  — the size of the array. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109)  — the elements of the array. The third line contains an integer q (1 ≤ q ≤ 4·105)  — the number of queries. The next q lines describe the queries and may have one of the following forms:   1 l r x (1 ≤ l ≤ r ≤ n, 1 ≤ x ≤ 109).  2 i y (1 ≤ i ≤ n, 1 ≤ y ≤ 109).  Guaranteed, that there is at least one query of first type.

For each query of first type, output "YES" (without quotes) if Bash's guess is almost correct and "NO" (without quotes) otherwise.

NoteIn the first sample, the array initially is {2, 6, 3}. For query 1, the first two numbers already have their gcd as 2.For query 2, we can achieve a gcd of 3 by changing the first element of the array to 3. Note that the changes made during queries of type 1 are temporary and do not get reflected in the array. After query 3, the array is now {9, 6, 3}. For query 4, no matter which element you change, you cannot get the gcd of the range to be 2.

import java.util

import scala.collection.mutable

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) = readInts(1)
  val as = readInts(n)
  val Array(q) = readInts(1)

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

  case class SegTree(as: Array[Int]) {

    //val NEUTRAL = Array.empty[Int]

    private val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = gcd(t(v2), t(v2 + 1))
      }
    }

    private def merge(left: Array[Int], right: Array[Int]): Array[Int] = {
      val resBuilder = new mutable.ArrayBuilder.ofInt
      var l = 0
      var r = 0
      while (l < left.length && r < right.length) {
        if (left(l) == right(r)) {
          resBuilder += left(l)
          l += 1
          r += 1
        } else if (left(l) < right(r)) l += 1
        else r += 1
      }
      val res = resBuilder.result()
      println("Merge " + left.mkString(" ") + "; " + right.mkString(" ") + "; " + res.mkString(" ") + "; ")
      res
    }

    def query(l: Int, r: Int, goal: Int, canChange: Boolean, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Boolean = {
      if (l > r) true
      else if (l == tl && r == tr && l == r) {
        canChange || t(v) % goal == 0
      } else if (l == tl && r == tr && t(v) % goal == 0) {
        true
      } else if (l == tl && r == tr && !canChange) {
        t(v) % goal == 0
      } else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        val q1 = query(l, Math.min(r, tm), goal, false, v2, tl, tm)
        val q2 = query(Math.max(l, tm + 1), r, goal, false, v2 + 1, tm + 1, tr)
        if (q1 && q2) true
        else if ((q1 || q2) && canChange) {
          (q1 && query(Math.max(l, tm + 1), r, goal, true, v2 + 1, tm + 1, tr)) ||
            (q2 && query(l, Math.min(r, tm), goal, true, v2, tl, tm))
        } else false
      }
    }

    def update(pos: Int, value: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (tl == tr) t(v) = value
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        if (pos <= tm) update(pos, value, v2, tl, tm)
        else update(pos, value, v2 + 1, tm + 1, tr)
        t(v) = gcd(t(v2), t(v2 + 1))
      }
    }

  }

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

  val segTree = SegTree(as)

  for (_ <- 1 to q) {
    val s = readLine
    if (s.head == '1') {
      val Array(_, _l, _r, x) = s.split(" ").map(_.toInt)
      val l = _l - 1
      val r = _r - 1
      val ok = segTree.query(l, r, x, true)
      println(if (ok) "YES" else "NO")
    } else {
      val Array(_, i, y) = s.split(" ").map(_.toInt)
      as(i - 1) = y
      segTree.update(i - 1, y)
    }
  }

  Console.flush
}


Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.

The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj).

In a single line print a single integer — the answer to the problem.

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

object Segments extends App {

	// scan input
	val scanner = new Scanner( System.in )
	val n = scanner.nextInt
	val k = scanner.nextInt
	val input: ArrayBuffer[(Int,Int)] = ArrayBuffer.empty
	for( i <- 1 to n)
		input += (( scanner.nextInt, scanner.nextInt ))
	val segments = input.sortBy( _._1 ).toIndexedSeq	// sort the segments

	val value = (0 /: segments)( (l,e) => l + e._2 - e._1 + 1 ) 	// check value (total length) of segments

	val moves = ( k - value % k ) % k	// check required moves

	/* not required by test
	// check if there is a place for those moves - check distances between segments and absolute margins
	// minimal and maximal value
	final val MIN_MAX = 10000
	val left = segments.head._1 + MIN_MAX
	val right = MIN_MAX - segments.last._2
	val distance = (left /: segments.sliding( 2 )) ( (d, pair) => d + pair.last._1 - pair.head._2 - 1 ) + right
	// if( distance < moves ) then there is no solution
	*/

	println( moves )
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = (1 to n).map{_ =>
    val r = in.next().split(' ').map(_.toInt)
    r.last - r.head + 1
  }.sum
  val left = data % k
  if (left == 0)
    println(0)
  else
    println(k - left)
}

object A177 {

  def R = readLine().split(" ").toList map(_.toInt)

  def main(args: Array[String]): Unit = {
        var N = R
        var n = N.head
        var k = N.tail.head

        def helper(acc: Int, sum: Int): Int = {

        if(acc > n)
        {
          sum
        }
        else
        {
            var foo = R
            var a = foo.head
            var b = foo.tail.head
            helper(acc+1, sum+b-a+1)
        }
      }

        var sumX = helper(1,0)
        if(sumX%k == 0)
        {
          println(0)

        }
        else
        {
            println(k-sumX%k)
        }

      }

  }

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

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

  val N, K = sc.nextInt

  val sum = Stream.fill(N)(- sc.nextInt + sc.nextInt + 1).sum
  val res = (K - sum % K) % K

  out.println(res)
  out.close
}

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

  def main(args: Array[String]) {
    var Array(n, k) = READ;
    var s = 0;
      for (i <- 1 to n){
      var Array(a,b) = READ;
      s += b-a+1;
    };
    println(if (s%k == 0) 0 else k-s%k);
  }
}

object Main {
  def main(args: Array[String]) {
    val nk = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(1)

    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val sum = a.map(a0 => a0(1) - a0(0) + 1).sum
    println((k - (sum % k)) % k)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = (1 to n).map{_ =>
    val r = in.next().split(' ').map(_.toInt)
    r.last - r.head + 1
  }.sum
  val left = data % k
  println(k - left)
}


n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and ai = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.You have to write a program which prints the number of the child to be eliminated on every step.

The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1). The next line contains k integer numbers a1, a2, ..., ak (1 ≤ ai ≤ 109).

Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.

NoteLet's consider first example:   In the first step child 4 is eliminated, child 5 becomes the leader.  In the second step child 2 is eliminated, child 3 becomes the leader.  In the third step child 5 is eliminated, child 6 becomes the leader.  In the fourth step child 6 is eliminated, child 7 becomes the leader.  In the final step child 1 is eliminated, child 3 becomes the leader.

import io.StdIn.readLine
object B extends App{
  val Array(n, k) = readLine().split(' ').map(_.toInt)

  val game = readLine().split(' ').map(_.toInt).scanLeft((Vector.range[Int](1, n + 1), -1)) {
    case ((children, _), num) ⇒
      val i = num % children.size
      (children.drop(i + 1) ++ children.take(i), children(i))
  }.map(_._2).tail

  println(game.mkString(" "))
}