Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.

The first line contains integer n (1 ≤ n ≤ 2·105) — the number of throws of the first team. Then follow n integer numbers — the distances of throws ai (1 ≤ ai ≤ 2·109).  Then follows number m (1 ≤ m ≤ 2·105) — the number of the throws of the second team. Then follow m integer numbers — the distances of throws of bi (1 ≤ bi ≤ 2·109).

Print two numbers in the format a:b — the score that is possible considering the problem conditions where the result of subtraction a - b is maximum. If there are several such scores, find the one in which number a is maximum.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).sorted

  def solution(a: Array[Int], b: Array[Int], ai: Int, bi: Int, n: Int, m: Int, maxF: Int, maxS: Int): (Int, Int) = {
    val candidateF = 2 * n + (a.length - ai)
    val candidateS = 2 * m + (b.length - bi)
    val (nMaxF, nMaxS) =
      if (candidateF - candidateS > maxF - maxS)
        (candidateF, candidateS)
      else
        (maxF, maxS)
    if (ai == n && bi == m) (nMaxF, nMaxS)
    else if (ai == n || bi == m) solution(a, b, n, m, n, m, nMaxF, nMaxS)
    else {
      val min = Math.min(a(ai), b(bi))
      solution(a, b, (ai until n).find(i => a(i) > min).getOrElse(a.length),
                     (bi until m).find(i => b(i) > min).getOrElse(b.length), n, m, nMaxF, nMaxS)
    }
  }

  val res = solution(a, b, 0, 0, n, m, 3 * n, 3 * m)

  println(s"${res._1}:${res._2}")
}

import scala.io.StdIn

object VasyaBasketball {

  //0 for a, 1 for b
  def find(a:String, b:String):String = {
    val ai = a.split(" ").map { x => x.toInt }
    val an = ai.length
    val at = ai.map { x => (x,0) }
    val bi = b.split(" ").map { x => x.toInt }
    val bn = bi.length
    val bt = bi.map { x => (x,1) }
    val ct = at ++ bt
    val sct = ct.sortBy(_._1)
    //init max to v(<e)
    var max = 3*(an-bn)
    var maxA = 3*an
    var maxB = 3*bn
    //browsed num for a and b
    var aBnum = 0
    var bBnum = 0
    var score = max
    for (i<-1 to sct.length){
      sct(i-1) match{
        case (e:Int, t:Int) => {
          if (t==0){
            aBnum = aBnum + 1
          }else{
            bBnum = bBnum + 1
          }
          val valA = 3*(an-aBnum)+2*aBnum
          val valB = 3*(bn-bBnum)+2*bBnum
          //println(e + "," + t + "," + valA + "," + valB)
          score = valA - valB
          if (score>max){
            max = score
            maxA = valA
            maxB = valB
          }
        }
      }
    }
    maxA + ":" + maxB
  }

  def main(args:Array[String]){
    val na = StdIn.readLine().toInt
    val as = StdIn.readLine()
    val nb = StdIn.readLine().toInt
    val bs = StdIn.readLine()
    println(find(as, bs))
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_VasyaAndBasketball {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextLong()

    val firstTeam = (for (i <- 1l to n) yield {
      scanner.nextLong()
    }).sorted.toList

    val m = scanner.nextLong()

    val secondTeam = (for (i <- 1l to m) yield {
      scanner.nextLong()
    }).sorted.toList

    val throws = firstTeam.map(x => (x, 1)) ::: secondTeam.map(y => (y, 2))
    val sortedThrows = throws.sortBy(x => x._1)

    val startPoints = (sortedThrows.count(x => x._2 == 1) * 3, sortedThrows.count(x => x._2 == 2) * 3)

    def evalPoints(startPoints : (Int, Int), throws : List[(Long, Int)], acc : List[(Int, Int)] = Nil) : List[(Int, Int)] = {
      throws match {
        case (x, 1) :: tail => evalPoints((startPoints._1 - 1, startPoints._2), tail, (startPoints._1 - 1, startPoints._2) :: acc)
        case (x, 2) :: tail => evalPoints((startPoints._1, startPoints._2 - 1), tail, (startPoints._1, startPoints._2 - 1) :: acc)
        case Nil => acc.reverse
      }
    }

    val points = startPoints :: evalPoints(startPoints, sortedThrows)
    val maxPoint = points.maxBy(x => x._1 - x._2)

    out.println(s"${maxPoint._1}:${maxPoint._2}")
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

import scala.annotation.tailrec

object C_VasyaAndBasketball {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextLong()

    val firstTeam = (for (i <- 1l to n) yield {
      scanner.nextLong()
    }).sorted.toList

    val m = scanner.nextLong()

    val secondTeam = (for (i <- 1l to m) yield {
      scanner.nextLong()
    }).sorted.toList

    val throws = firstTeam.map(x => (x, 1)) ::: secondTeam.map(y => (y, 2))
    val sortedThrows = throws.sortBy(x => x._1)

    val startPoints = (sortedThrows.count(x => x._2 == 1) * 3, sortedThrows.count(x => x._2 == 2) * 3)

    @tailrec def evalPoints(startPoints : (Int, Int), throws : List[(Long, Int)], acc : List[(Int, Int)] = Nil) : List[(Int, Int)] = {
      throws match {
        case (x, 1) :: tail => evalPoints((startPoints._1 - 1, startPoints._2), tail, (startPoints._1 - 1, startPoints._2) :: acc)
        case (x, 2) :: tail => evalPoints((startPoints._1, startPoints._2 - 1), tail, (startPoints._1, startPoints._2 - 1) :: acc)
        case Nil => acc.reverse
      }
    }

    val points = startPoints :: evalPoints(startPoints, sortedThrows)
    val maxPoint = points.maxBy(x => x._1 - x._2)

    out.println(s"${maxPoint._1}:${maxPoint._2}")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).sorted

  def solution(a: Array[Int], b: Array[Int], ai: Int, bi: Int, n: Int, m: Int, maxF: Int, maxS: Int): (Int, Int) = {
    val candidateF = 2 * n + (a.length - ai)
    val candidateS = 2 * m + (b.length - bi)
    val (nMaxF, nMaxS) =
      if (candidateF - candidateS > maxF - maxS)
        (candidateF, candidateS)
      else
        (maxF, maxS)
    if (ai == n || bi == m) (nMaxF, nMaxS)
    else {
      val min = Math.min(a(ai), b(bi))
      solution(a, b, (ai + 1 until n).find(i => a(i) > min).getOrElse(a.length),
                     (bi + 1 until m).find(i => b(i) > min).getOrElse(b.length), n, m, nMaxF, nMaxS)
    }
  }

  val res = solution(a, b, 0, 0, n, m, 0, 0)

  println(s"${res._1}:${res._2}")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).sorted

  val res =  b.foldLeft(b.length * 3l, (a.length * 3l, b.length * 3l), 0) {
    case ((second, (firstM, secondM), index), el) =>
      val newSecond = second - 1
      val newIndex = (index + 1 until a.length).find(i => a(i) > el).map(_ - 1).getOrElse(a.length)
      val newFirst = 3l * a.length - newIndex
      val nDiff = newFirst - newSecond
      val oldDiff = firstM - secondM
      if (nDiff > oldDiff || (nDiff == oldDiff && newFirst >= firstM)) {
        (newSecond, (newFirst, newSecond), newIndex)
      } else {
        (newSecond, (firstM, secondM), newIndex)
      }
  }

  println(s"${res._2._1}:${res._2._2}")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).sorted

  val res =  b.foldLeft(b.length * 3l, (a.length * 3l, b.length * 3l), 0) {
    case ((second, (firstM, secondM), index), el) =>
      val newSecond = second - 1
      val newIndex = (index + 1 until a.length).find(i => a(i) > el).getOrElse(a.length)
      val newFirst = 3 * a.length - newIndex
      val nDiff = newFirst - newSecond
      val oldDiff = firstM - secondM
      if (nDiff > oldDiff || (nDiff == oldDiff && newFirst > firstM)) {
        (newSecond, (newFirst, newSecond), newIndex)
      } else {
        (newSecond, (firstM, secondM), newIndex)
      }
  }

  println(s"${res._2._1}:${res._2._2}")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).sorted

  val res =  b.foldLeft(a.length * 3l, b.length * 3l, (a.length * 3l, b.length * 3l), 0) {
    case ((first, second, (firstM, secondM), index), el) =>
      val newSecond = second - 1
      val newIndex = (index + 1 until a.length).find(i => a(i) > el).map(_ - 1).getOrElse(a.length - 1)
      val newFirst = first - newIndex + index
      val nDiff = newFirst - newSecond
      val oldDiff = firstM - secondM
      if (nDiff > oldDiff || (nDiff == oldDiff && newFirst > firstM)) {
        (newFirst, newSecond, (newFirst, newSecond), newIndex)
      } else {
        (newFirst, newSecond, (firstM, secondM), newIndex)
      }
  }

  println(s"${res._3._1}:${res._3._2}")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).toList.sorted

  val res =  b.foldLeft(a.length * 3l, b.length * 3l, (a.length * 3l, b.length * 3l), a) {
    case ((first, second, (firstM, secondM), left), el) =>
      val newSecond = second - 1
      val newLeft = left.dropWhile(i => i <= el)
      val newFirst = first - left.length + newLeft.length
      if (newFirst - newSecond >= firstM - secondM) {
        (newFirst, newSecond, (newFirst, newSecond), newLeft)
      } else {
        (newFirst, newSecond, (firstM, secondM), newLeft)
      }
  }

  println(s"${res._3._1}:${res._3._2}")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).sorted

  def solution(a: Array[Int], b: Array[Int], ai: Int, bi: Int, n: Int, m: Int, maxF: Int, maxS: Int): (Int, Int) = {
    val candidateF = 2 * n + (a.length - ai)
    val candidateS = 2 * m + (b.length - bi)
    val (nMaxF, nMaxS) =
      if (candidateF - candidateS > maxF - maxS)
        (candidateF, candidateS)
      else
        (maxF, maxS)
    if (ai == n || bi == m) (nMaxF, nMaxS)
    else {
      val min = Math.min(a(ai), b(bi))
      solution(a, b, (ai + 1 until n).find(i => a(i) > min).getOrElse(a.length),
                     (bi + 1 until m).find(i => b(i) > min).getOrElse(b.length), n, m, nMaxF, nMaxS)
    }
  }

  val res = solution(a, b, 0, 0, n, m, 3 * n, 3 * m)

  println(s"${res._1}:${res._2}")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).sorted

  val res =  b.foldLeft(b.length * 3l, (a.length * 3l, b.length * 3l), 0) {
    case ((second, (firstM, secondM), index), el) =>
      val newSecond = second - 1
      val newIndex = (index + 1 until a.length).find(i => a(i) > el).map(_ - 1).getOrElse(a.length)
      val newFirst = 3 * a.length - newIndex
      val nDiff = newFirst - newSecond
      val oldDiff = firstM - secondM
      if (nDiff > oldDiff || (nDiff == oldDiff && newFirst >= firstM)) {
        (newSecond, (newFirst, newSecond), newIndex)
      } else {
        (newSecond, (firstM, secondM), newIndex)
      }
  }

  println(s"${res._2._1}:${res._2._2}")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).sorted

  def solution(a: Array[Int], b: Array[Int], ai: Int, bi: Int, n: Int, m: Int, maxF: Int, maxS: Int): (Int, Int) = {
    val candidateF = 2 * n + (a.length - ai)
    val candidateS = 2 * m + (b.length - bi)
    val (nMaxF, nMaxS) =
      if (candidateF - candidateS > maxF - maxS)
        (candidateF, candidateS)
      else
        (maxF, maxS)
    if (ai == n || bi == m) (nMaxF, nMaxS)
    else {
      val min = Math.min(a(ai), b(bi))
      solution(a, b, (ai until n).find(i => a(i) > min).getOrElse(a.length),
                     (bi until m).find(i => b(i) > min).getOrElse(b.length), n, m, nMaxF, nMaxS)
    }
  }

  val res = solution(a, b, 0, 0, n, m, 3 * n, 3 * m)

  println(s"${res._1}:${res._2}")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt).sorted
  val m = in.next().toInt
  val b = in.next().split(' ').map(_.toInt).sorted

  val res =  b.foldLeft(a.length * 3l, b.length * 3l, (a.length * 3l, b.length * 3l), 0) {
    case ((first, second, (firstM, secondM), index), el) =>
      val newSecond = second - 1
      val newIndex = (index + 1 until a.length).find(_ > el).map(_ - 1).getOrElse(index)
      val newFirst = first - newIndex + index
      val nDiff = newFirst - newSecond
      val oldDiff = firstM - secondM
      if (nDiff > oldDiff || (nDiff == oldDiff && newFirst > firstM)) {
        (newFirst, newSecond, (newFirst, newSecond), newIndex)
      } else {
        (newFirst, newSecond, (firstM, secondM), newIndex)
      }
  }

  println(s"${res._3._1}:${res._3._2}")
}


At the Byteland State University marks are strings of the same length. Mark x is considered better than y if string y is lexicographically smaller than x.Recently at the BSU was an important test work on which Vasya recived the mark a. It is very hard for the teacher to remember the exact mark of every student, but he knows the mark b, such that every student recieved mark strictly smaller than b.Vasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.More formally: you are given two strings a, b of the same length and you need to figure out the number of different strings c such that:1) c can be obtained from a by swapping some characters, in other words c is a permutation of a.2) String a is lexicographically smaller than c.3) String c is lexicographically smaller than b.For two strings x and y of the same length it is true that x is lexicographically smaller than y if there exists such i, that x1 = y1, x2 = y2, ..., xi - 1 = yi - 1, xi < yi.Since the answer can be very large, you need to find answer modulo 109 + 7.

First line contains string a, second line contains string b. Strings a, b consist of lowercase English letters. Their lengths are equal and don't exceed 106. It is guaranteed that a is lexicographically smaller than b.

Print one integer  — the number of different strings satisfying the condition of the problem modulo 109 + 7.

NoteIn first sample from string abc can be obtained strings acb, bac, bca, cab, cba, all of them are larger than abc, but smaller than ddd. So the answer is 5.In second sample any string obtained from abcdef is larger than abcdeg. So the answer is 0.

object Main extends App {

  import io.StdIn.readLine

  val MOD = 1000000007

  val a = readLine().map(_ - 'a')
  val d = readLine().map(_ - 'a')
  val n = a length

  val fact = new Array[Integer](n+10)
  val rfact = new Array[Integer](n+10)

  fact(0) = 1
  for (i <- 1 to n) fact(i) = (1l*fact(i-1)*i%MOD).toInt
  rfact(n) = pow(fact(n), MOD - 2)
  for (i <- n-1 to 0 by -1) rfact(i) = 1l * rfact(i+1) * (i+1) % MOD toInt

  println(((f(d) - f(a) - 1)%MOD + MOD)%MOD)

  def f(s: IndexedSeq[Int]): Integer = {

    val cnt = new Array[Int](26)
    for (k <- a) cnt(k) += 1

    var ans = 0
    val n = s.length
    var mul = fact(n)
    for (i <- 0 until 26)
      mul = 1l * mul * rfact(cnt(i)) % MOD toInt

    //System.err.println(mul)

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

      mul = (1l * mul * rfact(n - i) % MOD).toInt
      mul = (1l * mul * fact(n - i - 1) % MOD).toInt

      //mul = (1l * mul * pow(n - i, MOD - 2) % MOD).toInt

      for (ch <- 0 until s(i)) {
        //System.err.println(mul)
        if (cnt(ch) > 0) {
          mul = (1l * mul * fact(cnt(ch)) % MOD).toInt
          mul = (1l * mul * rfact(cnt(ch)-1) % MOD).toInt
          ans = (ans + mul) % MOD
          mul = (1l * mul * fact(cnt(ch)-1) % MOD).toInt
          mul = (1l * mul * rfact(cnt(ch)) % MOD).toInt
        }
      }

      if (cnt(s(i)) == 0) return ans

      mul = (1l * mul * fact(cnt(s(i))) % MOD).toInt
      mul = (1l * mul * rfact(cnt(s(i))-1) % MOD).toInt
      cnt(s(i)) -= 1

    }

    ans
  }

  def pow(x: Int, n: Int): Int = n%2 match {
    case 0 if n == 0 => 1
    case 0 if n > 0 => {
      val res = pow(x, n/2)
      1l * res * res % MOD toInt
    }
    case 1 => {
      (1l * pow(x, n-1) * x) % MOD toInt
    }
  }

}


Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of $$$n$$$ distinct integers. An array $$$b = [b_1, b_2, \ldots, b_k]$$$ is called nice if for any two distinct elements $$$b_i, b_j$$$ of $$$b$$$, $$$|b_i-b_j|$$$ appears in $$$b$$$ at least once. In addition, all elements in $$$b$$$ must be distinct. Can you add several (maybe, $$$0$$$) integers to $$$a$$$ to create a nice array $$$b$$$ of size at most $$$300$$$? If $$$a$$$ is already nice, you don't have to add any elements.For example, array $$$[3, 6, 9]$$$ is nice, as $$$|6-3|=|9-6| = 3$$$, which appears in the array, and $$$|9-3| = 6$$$, which appears in the array, while array $$$[4, 2, 0, 6, 9]$$$ is not nice, as $$$|9-4| = 5$$$ is not present in the array.For integers $$$x$$$ and $$$y$$$, $$$|x-y| = x-y$$$ if $$$x > y$$$ and $$$|x-y| = y-x$$$ otherwise.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \leq t \leq 50$$$), the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \cdots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$) — the elements of the array $$$a$$$.

For each test case, output one line containing YES if Omkar can create a nice array $$$b$$$ by adding elements to $$$a$$$ and NO otherwise. The case of each letter does not matter, so yEs and nO will also be accepted. If the first line is YES, output a second line containing a single integer $$$k$$$ ($$$n \leq k \leq 300$$$).  Then output one line containing $$$k$$$ distinct integers $$$b_1, b_2, \cdots, b_k$$$ ($$$-10^9 \leq b_i \leq 10^9$$$), the elements of the nice array $$$b$$$. $$$b_1, b_2, \cdots, b_k$$$ can be in any order. For each $$$a_i$$$ in $$$a$$$, $$$a_i$$$ must appear at least once in $$$b$$$. It can be proved that if Omkar can create such an array $$$b$$$, then he can also do so in a way that satisfies the above constraints. If multiple solutions exist, you can print any.

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

  val t = readInt()

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

    val (h, l) = (an.min, an.max)

    val bn =
      if (h.signum >= 0) Some(0 to l)
      else None

    bn match {
      case Some(value) =>
        println("YES")
        println(value.length)
        println(value.mkString(" "))
      case _           =>
        println("NO")
    }
  }
}

import scala.io.StdIn._
import scala.collection.immutable._
import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer
object test {
    def main(args: Array[String]): Unit = {
        var t = readInt

        while(t > 0) {
            var n = readInt
            val arr = readLine.split(" ").map(_.toInt).toList
            var cur = arr.length - 1
            var flag = 1
            try {
            for(x <- arr) {
                if(x < 0) {
                    print("NO")
                    flag = 0
                    object break extends Exception { }
                    throw break
                }
            }
            }
            catch {
                case break =>
            }
            if(flag == 1) {
                println("YES")
                println(arr.max + 1)
                for(x <- 0 to arr.max)
                    print(x + " ")
            }
            println()
            t -= 1
        }
    }
}

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

  val t = readInt()

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

    val (h, l) = (an.head, an.last)

    val bn =
      if (h.signum >= 0) Some(0 to l)
      else if (an.length == 1) Some(h to l)
      else if (an.length == 2 && (l == 0 || l == -h)) Some(h to (-h, -h))
      else if (an.length == 3 && l == -h && an.sum == 0) Some(h to (l, l))
      else None

    bn match {
      case Some(value) =>
        println("YES")
        println(value.length)
        println(value.mkString(" "))
      case _           =>
        println("NO")
    }
  }
}

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

  val t = readInt()

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

    val (h, l) = (an.head, an.last)

    val bn =
      if (h.signum >= 0) Some(0 to l)
      else if (an.length == 1) Some(h to l)
      else if (an.length == 2 && l.signum == 0) Some(h to (-h, -h))
      else if (an.length == 3 && -h == l && an(1) == 0) Some(h to (l, l))
      else None

    bn match {
      case Some(value) =>
        println("YES")
        println(value.length)
        println(value.mkString(" "))
      case _           =>
        println("NO")
    }
  }
}

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

  val t = readInt()

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

    val (h, l) = (an.head, an.last)

    val bn =
      if (h.signum == l.signum || h.signum * l.signum == 0) Some(0 to l)
      else if (an.length == 3 && h.signum * h == l.signum * l) Some(h to l)
      else None

    bn match {
      case Some(value) =>
        println("YES")
        println(value.length)
        println(value.mkString(" "))
      case _           =>
        println("NO")
    }
  }
}

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

  val t = readInt()

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

    val (h, l) = (an.head, an.last)

    val bn =
      if (h.signum == l.signum || h.signum * l.signum == 0) Some(h to l)
      else if (an.length == 3 && h.signum * h == l.signum * l) Some(h to l)
      else None

    bn match {
      case Some(value) =>
        println("YES")
        println(value.length)
        println(value.mkString(" "))
      case _           =>
        println("NO")
    }
  }
}

import scala.io.StdIn._
import scala.collection.immutable._
import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer
object test {
    def main(args: Array[String]): Unit = {
        var t = readInt

        while(t > 0) {
            var n = readInt
            val arr = readLine.split(" ").map(_.toInt).toList
            var cur = arr.length - 1
            var flag = 1
            try {
            for(x <- arr) {
                if(x < 0) {
                    print("NO")
                    flag = 0
                    object break extends Exception { }
                    throw break
                }
            }
            }
            catch {
                case break =>
            }
            if(flag == 1) {
                println("YES")
                println(arr.max - arr.min + 1)
                for(x <- 0 to arr.max)
                    print(x + " ")
            }
            println()
            t -= 1
        }
    }
}


You have a string of decimal digits s. Let's define bij = si·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j) such that x ≤ i ≤ y, z ≤ j ≤ t.

The first line contains integer a (0 ≤ a ≤ 109), the second line contains a string of decimal integers s (1 ≤ |s| ≤ 4000).

Print a single integer — the answer to a problem. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

import scala.collection.mutable.HashMap

object Matrix extends App {
    val a = readInt
    val s = readLine.map(_.toInt - 0x30).toArray
    val n = s.size
    val sum = new Array[Int](n + 1)

    for(i <- 1 to n) sum(i) = sum(i-1) + s(i-1)

    val cnt = new Array[Long](n * 10)
    for(i <- 0 to n; j <- i+1 to n) {
        val x = sum(j) - sum(i)
        cnt(x) = cnt(x) + 1
    }

    if (a == 0) {
        val ret = cnt(0) * n * (n + 1) - cnt(0) * cnt(0)
        println(ret)
        exit(0)
    }

    val mapAll = HashMap[Int, Long]()
    for(i <- 1 until cnt.size if cnt(i) != 0) mapAll.put(i, cnt(i))

    def mapFunc(kv: (Int, Long)): Long = {
        val key = kv._1
        if (a % key == 0 && mapAll.contains(a/key))
            kv._2 * mapAll(a/key)
        else 0
    }

    println(mapAll.map(mapFunc).toList.foldLeft(0.toLong)((x:Long, y:Long) => x + y))
}

/**
 * Contest 213, Div 2, problem C
 *
 *
You have a string of decimal digits s. Let's define bij = si·sj. Find
 * in matrix b the number of such rectangles that the sum bij for all
 * cells (i, j) that are the elements of the rectangle equals a in each
 * rectangle.
 *
 * A rectangle in a matrix is a group of four integers (x, y, z, t)
 * (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j)
 * such that x ≤ i ≤ y, z ≤ j ≤ t.
 *
 * Input The first line contains integer a (0 ≤ a ≤ 109), the second line
 * contains a string of decimal integers s (1 ≤ |s| ≤ 4000).
 *
 * Output Print a single integer — the answer to a problem.
 *
 * Please, do not write the %lld specifier to read or write 64-bit
 * integers in С++. It is preferred to use the cin, cout streams or the
 * %I64d specifier.

 */
object Round213_Div2_Task3 {
  val inputStreamReader = {
    import java.net.InetAddress
    import java.security.MessageDigest
    import java.io.{ FileInputStream, InputStreamReader, BufferedReader }

    val md = MessageDigest.getInstance("SHA-1")
    val userName = System.getProperty("user.name")
    val hostName = InetAddress.getLocalHost.getHostName

    val bytes = md.digest((userName + hostName).getBytes)
    val sb = new StringBuilder
    for (i ← 0 until bytes.length)
      sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))

    val inputStream =
      if (sb.result == "51a302f8ba1abe181e33fe86c0ab4c7bedfb6c9") new FileInputStream("tmp/0.txt")
      else System.in
    new BufferedReader(new InputStreamReader(inputStream))
  }

  def main(args: Array[String]): Unit = {
    val a = inputStreamReader.readLine.toInt
    val str = inputStreamReader.readLine
    val prefix = Array.fill(str.length + 1)(0)
    for (i ← 1 to str.length)
      prefix(i) = prefix(i - 1) + str.charAt(i - 1) - '0'
    val count = Array.fill(40000)(0L)
    for {
      i ← 0 until prefix.length
      j ← i + 1 until prefix.length
    } count(prefix(j) - prefix(i)) += 1
    val res = if (a == 0) {
      count(0) * (str.length * (str.length + 1) - count(0))
    } else {
      (1 until count.length)
        .withFilter(i ⇒ a % i == 0 && a / i < count.length)
        .map(i ⇒ count(i) * count(a / i))
        .sum
    }
    println(res)
  }
}

/**
 * Contest 213, Div 2, problem C
 *
 *
You have a string of decimal digits s. Let's define bij = si·sj. Find
 * in matrix b the number of such rectangles that the sum bij for all
 * cells (i, j) that are the elements of the rectangle equals a in each
 * rectangle.
 *
 * A rectangle in a matrix is a group of four integers (x, y, z, t)
 * (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j)
 * such that x ≤ i ≤ y, z ≤ j ≤ t.
 *
 * Input The first line contains integer a (0 ≤ a ≤ 109), the second line
 * contains a string of decimal integers s (1 ≤ |s| ≤ 4000).
 *
 * Output Print a single integer — the answer to a problem.
 *
 * Please, do not write the %lld specifier to read or write 64-bit
 * integers in С++. It is preferred to use the cin, cout streams or the
 * %I64d specifier.

 */
object Round213_Div2_Task3 {
  val inputStreamReader = {
    import java.net.InetAddress
    import java.security.MessageDigest
    import java.io.{ FileInputStream, InputStreamReader, BufferedReader }

    val md = MessageDigest.getInstance("SHA-1")
    val userName = System.getProperty("user.name")
    val hostName = InetAddress.getLocalHost.getHostName

    val bytes = md.digest((userName + hostName).getBytes)
    val sb = new StringBuilder
    for (i ← 0 until bytes.length)
      sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))

    val inputStream =
      if (sb.result == "51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91") new FileInputStream("tmp/0.txt")
      else System.in
    new BufferedReader(new InputStreamReader(inputStream))
  }

  def main(args: Array[String]): Unit = {
    val a = inputStreamReader.readLine.toInt
    val str = inputStreamReader.readLine
    val prefix = str.foldLeft(Vector(0))((acc, ch) => acc :+ (ch - '0' + acc.last))
    val count = Array.fill(40000)(0L)
    for {
      i ← 0 until prefix.length
      j ← i + 1 until prefix.length
    } count(prefix(j) - prefix(i)) += 1
    val res =
      if (a == 0) count(0) * (str.length * (str.length + 1) - count(0))
      else
        (1 until count.length)
          .withFilter(i ⇒ a % i == 0 && a / i < count.length)
          .map(i ⇒ count(i) * count(a / i))
          .sum
    println(res)
  }
}

import scala.collection.mutable.HashMap

object Matrix extends App {
    val a = readInt
    val s = readLine.map(_.toInt - 0x30).toArray
    val n = s.size
    val sum = new Array[Int](n + 1)

    for(i <- 1 to n) sum(i) = sum(i-1) + s(i-1)

    val cnt = new Array[Int](n * 10)
    for(i <- 0 to n; j <- i+1 to n) {
        val x = sum(j) - sum(i)
        cnt(x) = cnt(x) + 1
    }

    if (a == 0) {
        val ret = cnt(0) * n * (n + 1) - cnt(0) * cnt(0)
        println(ret)
        exit(0)
    }

    val mapAll = HashMap[Int, Long]()
    for(i <- 1 until cnt.size if cnt(i) != 0) mapAll.put(i, cnt(i))

    def mapFunc(kv: (Int, Long)): Long = {
        val key = kv._1
        if (a % key == 0 && mapAll.contains(a/key))
            kv._2 * mapAll(a/key)
        else 0
    }

    println(mapAll.map(mapFunc).reduce(_ + _))
}

import scala.collection.mutable.HashMap

object Matrix extends App {
    val a = readInt
    val s = readLine.map(_.toInt - 0x30).toArray
    val n = s.size
    val sum = new Array[Int](n + 1)

    for(i <- 1 to n) sum(i) = sum(i-1) + s(i-1)

    val cnt = new Array[Int](n * 10)
    for(i <- 0 to n; j <- i+1 to n) {
        val x = sum(j) - sum(i)
        cnt(x) = cnt(x) + 1
    }

    val mapAll = HashMap[Int, Long]()
    for(i <- 1 until cnt.size if cnt(i) != 0) mapAll.put(i, cnt(i))

    def mapFunc(kv: (Int, Long)): Long = {
        val key = kv._1
        if (a % key == 0 && mapAll.contains(a/key))
            kv._2 * mapAll(a/key)
        else 0
    }

    println(mapAll.map(mapFunc).reduce(_ + _))
}

/**
 * Contest 213, Div 2, problem C
 *
 *
You have a string of decimal digits s. Let's define bij = si·sj. Find
 * in matrix b the number of such rectangles that the sum bij for all
 * cells (i, j) that are the elements of the rectangle equals a in each
 * rectangle.
 *
 * A rectangle in a matrix is a group of four integers (x, y, z, t)
 * (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j)
 * such that x ≤ i ≤ y, z ≤ j ≤ t.
 *
 * Input The first line contains integer a (0 ≤ a ≤ 109), the second line
 * contains a string of decimal integers s (1 ≤ |s| ≤ 4000).
 *
 * Output Print a single integer — the answer to a problem.
 *
 * Please, do not write the %lld specifier to read or write 64-bit
 * integers in С++. It is preferred to use the cin, cout streams or the
 * %I64d specifier.

 */
object Round213_Div2_Task3 {
  import java.net.InetAddress
  import java.security.MessageDigest
  import java.io.{ FileInputStream, InputStreamReader, BufferedReader }

  val inputStreamReader = {
    val md = MessageDigest.getInstance("SHA-1")
    val userName = System.getProperty("user.name")
    val hostName = InetAddress.getLocalHost.getHostName

    val bytes = md.digest((userName + hostName).getBytes)
    val sb = new StringBuilder
    for (i ← 0 until bytes.length)
      sb.append(Integer.toString((bytes(i) & 0xff) + 0x100, 16).substring(1))

    val inputStream =
      if (sb.result == "51a302f8ba1abe181e33fe86c0ab4c7bedfb6c91") new FileInputStream("tmp/0.txt")
      else System.in
    new BufferedReader(new InputStreamReader(inputStream))
  }

  def main(args: Array[String]): Unit = {
    val a = inputStreamReader.readLine.toInt
    val str = inputStreamReader.readLine
    val prefix = Array.fill(str.length + 1)(0)
    for (i ← 1 to str.length)
      prefix(i) = prefix(i - 1) + str.charAt(i - 1) - '0'
    val count = Array.fill(40000)(0L)
    for {
      i ← 0 until prefix.length
      j ← i + 1 until prefix.length
    } count(prefix(j) - prefix(i)) += 1
    val res = (1 until count.length)
      .withFilter(i ⇒ a % i == 0 && a / i < count.length)
      .map(i ⇒ count(i) * count(a / i))
      .sum
    println(res)
  }
}


Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value v = |sa - sb|.In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5, 1, 3, 2, 4] and the array b is [3, 3, 2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2, 1, 3, 2, 4] and the new array b [3, 3, 5].Professor doesn't want to make more than two swaps. Find the minimal value v and some sequence of no more than two swaps that will lead to the such value v. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.

The first line contains integer n (1 ≤ n ≤ 2000) — the number of elements in the array a. The second line contains n integers ai ( - 109 ≤ ai ≤ 109) — the elements of the array a. The third line contains integer m (1 ≤ m ≤ 2000) — the number of elements in the array b. The fourth line contains m integers bj ( - 109 ≤ bj ≤ 109) — the elements of the array b.

In the first line print the minimal value v = |sa - sb| that can be got with no more than two swaps. The second line should contain the number of swaps k (0 ≤ k ≤ 2). Each of the next k lines should contain two integers xp, yp (1 ≤ xp ≤ n, 1 ≤ yp ≤ m) — the index of the element in the array a and the index of the element in the array b in the p-th swap. If there are several optimal solutions print any of them. Print the swaps in order the professor did them.

import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  final case class Pair(d: Int, a: Int, b: Int)

  def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {
    var l = start
    var r = end
    while (l <= r) {
      val mid = (l + r) / 2
      if (2L * a(mid).d > v) r = mid - 1
      else l = mid + 1
    }
    if (r >= start) r
    else -1
  }

  def main(args: Array[String]) {
    val n = readLine().toInt
    val a = readInts(n)
    val m = readLine().toInt
    val b = readInts(m)
    val nb = ArrayBuilder.make[Pair]()
    val mb = ArrayBuilder.make[Pair]()
    val diff: Long = a.foldLeft(0L)(_+_) - b.foldLeft(0L)(_+_)
    var v: Long = Math.abs(diff)
    var k = 0
    val npb = ArrayBuilder.make[Int]()
    val mpb = ArrayBuilder.make[Int]()

    for (i <- 1 to n) {
      for (j <- 1 to m) {
        val cur = a(i-1) - b(j-1)
        if (Math.abs(diff - 2L * cur) < v) {
          v = Math.abs(diff - 2L * cur)
          npb.clear()
          npb += i
          mpb.clear()
          mpb += j
          k = 1
        }
      }
    }

    for (i <- 1 to n) {
      for (j <- i+1 to n) {
        nb += Pair(a(i-1) + a(j-1), i, j)
      }
    }

    for (i <- 1 to m) {
      for (j <- i+1 to m) {
        mb += Pair(b(i-1) + b(j-1), i, j)
      }
    }

    val na = nb.result()
    val ma = mb.result().sortWith(_.d < _.d)

    for (i <- na.indices) {
      var idx = find(ma, 0, ma.length-1, 2L*na(i).d-diff)
      if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) > Math.abs(diff+2L*ma(idx+1).d-2L*na(i).d)))) {
        idx += 1
      }
      if (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) < v) {
        v = Math.abs(diff+2L*ma(idx).d-2L*na(i).d)
        npb.clear()
        npb += (na(i).a, na(i).b)
        mpb.clear()
        mpb += (ma(idx).a, ma(idx).b)
        k = 2
      }
    }

    val np = npb.result()
    val mp = mpb.result()

    if (v == 14520) {
      println(diff)
      println(a(37) + " " + a(1627))
      println(b(0) + " " + b(2))
    }

    println(v)
    println(k)
    for (i <- np.indices) {
      println(np(i) + " " + mp(i))
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  final case class Pair(d: Int, a: Int, b: Int)

  def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {
    var l = start
    var r = end
    while (l <= r ) {
      val mid = (l + r) / 2
      if (2 * a(mid).d > v) r = mid - 1
      else l = mid + 1
    }
    if (r >= start && a(r).d <= v) r
    else -1
  }

  def main(args: Array[String]) {
    val n = readLine().toInt
    val a = readInts(n)
    val m = readLine().toInt
    val b = readInts(m)
    val nb = ArrayBuilder.make[Pair]()
    val mb = ArrayBuilder.make[Pair]()

    val diff: Long = a.sum - b.sum
    var v: Long = Math.abs(diff)
    var k = 0
    val npb = ArrayBuilder.make[Int]()
    val mpb = ArrayBuilder.make[Int]()

    for (i <- 1 to n) {
      for (j <- 1 to m) {
        val cur: Long = a(i-1) - b(j-1)
        if (Math.abs(diff - 2 * cur) < v) {
          v = Math.abs(diff - 2 * cur)
          npb.clear()
          npb += i
          mpb.clear()
          mpb += j
          k = 1
        }
      }
    }

    for (i <- 1 to n) {
      for (j <- 1 to n) {
        if (i != j) {
          nb += Pair(a(i-1) + a(j-1), i, j)
        }
      }
    }

    for (i <- 1 to m) {
      for (j <- 1 to m) {
        if (i != j) {
          mb += Pair(b(i-1) + b(j-1), i, j)
        }
      }
    }

    val na = nb.result().sortWith(_.d < _.d)
    val ma = mb.result().sortWith(_.d < _.d)

    for (i <- na.indices) {
      var idx = find(ma, 0, ma.length-1, 2*na(i).d-diff)
      if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) > Math.abs(diff+2*ma(idx+1).d-2*na(i).d)))) {
        idx += 1
      }
      if (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) < v) {
        v = Math.abs(diff+2*ma(idx).d-2*na(i).d)
        npb.clear()
        npb += (na(i).a, na(i).b)
        mpb.clear()
        mpb += (ma(idx).a, ma(idx).b)
        mpb += (ma(idx).a, ma(idx).b)
        k = 2
      }
    }

    val np = npb.result()
    val mp = mpb.result()
    println(v)
    println(k)
    for (i <- np.indices) {
      println(np(i) + " " + mp(i))
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  final case class Pair(d: Long, a: Int, b: Int)

  def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {
    var l = start
    var r = end
    while (l <= r ) {
      val mid = (l + r) / 2
      if (2 * a(mid).d > v) r = mid - 1
      else l = mid + 1
    }
    if (r >= start && a(r).d <= v) r
    else -1
  }

  def main(args: Array[String]) {
    val n = readLine().toInt
    val a = readLongs(n)
    val m = readLine().toInt
    val b = readLongs(m)
    val nb = ArrayBuilder.make[Pair]()
    val mb = ArrayBuilder.make[Pair]()

    val diff = a.sum - b.sum
    var v = Math.abs(diff)
    var k = 0
    val npb = ArrayBuilder.make[Int]()
    val mpb = ArrayBuilder.make[Int]()

    for (i <- 1 to n) {
      for (j <- 1 to m) {
        val cur = a(i-1) - b(j-1)
        if (Math.abs(diff - 2 * cur) < v) {
          v = diff - 2 * cur
          npb.clear()
          npb += i
          mpb.clear()
          mpb += j
          k = 1
        }
      }
    }

    for (i <- 1 to n) {
      for (j <- 1 to n) {
        if (i != j) {
          nb += Pair(a(i-1) + a(j-1), i, j)
        }
      }
    }

    for (i <- 1 to m) {
      for (j <- 1 to m) {
        if (i != j) {
          mb += Pair(b(i-1) + b(j-1), i, j)
        }
      }
    }

    val na = nb.result().sortWith(_.d < _.d)
    val ma = mb.result().sortWith(_.d < _.d)

    for (i <- na.indices) {
      var idx = find(ma, 0, ma.length-1, 2*na(i).d-diff)
      if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) > Math.abs(diff+2*ma(idx+1).d-2*na(i).d)))) {
        idx += 1
      }
      if (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) < v) {
        v = Math.abs(diff+2*ma(idx).d-2*na(i).d)
        npb.clear()
        npb += (na(i).a, na(i).b)
        mpb.clear()
        mpb += (ma(idx).a, ma(idx).b)
        k = 2
      }
    }

    val np = npb.result()
    val mp = mpb.result()
    println(v)
    println(k)
    for (i <- np.indices) {
      println(np(i) + " " + mp(i))
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  final case class Pair(d: Int, a: Int, b: Int)

  def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {
    var l = start
    var r = end
    while (l <= r) {
      val mid = (l + r) / 2
      if (2L * a(mid).d > v) r = mid - 1
      else l = mid + 1
    }
    if (r >= start && a(r).d <= v) r
    else -1
  }

  def main(args: Array[String]) {
    val n = readLine().toInt
    val a = readInts(n)
    val m = readLine().toInt
    val b = readInts(m)
    val nb = ArrayBuilder.make[Pair]()
    val mb = ArrayBuilder.make[Pair]()
    val diff: Long = a.foldLeft(0L)(_+_) - b.foldLeft(0L)(_+_)
    var v: Long = Math.abs(diff)
    var k = 0
    val npb = ArrayBuilder.make[Int]()
    val mpb = ArrayBuilder.make[Int]()

    for (i <- 1 to n) {
      for (j <- 1 to m) {
        val cur = a(i-1) - b(j-1)
        if (Math.abs(diff - 2L * cur) < v) {
          v = Math.abs(diff - 2L * cur)
          npb.clear()
          npb += i
          mpb.clear()
          mpb += j
          k = 1
        }
      }
    }

    for (i <- 1 to n) {
      for (j <- i+1 to n) {
        nb += Pair(a(i-1) + a(j-1), i, j)
      }
    }

    for (i <- 1 to m) {
      for (j <- i+1 to m) {
        mb += Pair(b(i-1) + b(j-1), i, j)
      }
    }

    val na = nb.result()
    val ma = mb.result().sortWith(_.d < _.d)

    for (i <- na.indices) {
      var idx = find(ma, 0, ma.length-1, 2L*na(i).d-diff)
      if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) > Math.abs(diff+2L*ma(idx+1).d-2L*na(i).d)))) {
        idx += 1
      }
      if (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) < v) {
        v = Math.abs(diff+2L*ma(idx).d-2L*na(i).d)
        npb.clear()
        npb += (na(i).a, na(i).b)
        mpb.clear()
        mpb += (ma(idx).a, ma(idx).b)
        k = 2
      }
    }

    val np = npb.result()
    val mp = mpb.result()

    if (v == 14520) {
      println(diff)
      println(a(37) + " " + a(1627))
      println(b(0) + " " + b(2))
    }

    println(v)
    println(k)
    for (i <- np.indices) {
      println(np(i) + " " + mp(i))
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  final case class Pair(d: Int, a: Int, b: Int)

  def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {
    var l = start
    var r = end
    while (l <= r ) {
      val mid = (l + r) / 2
      if (2 * a(mid).d > v) r = mid - 1
      else l = mid + 1
    }
    if (r >= start && a(r).d <= v) r
    else -1
  }

  def main(args: Array[String]) {
    val n = readLine().toInt
    val a = readInts(n)
    val m = readLine().toInt
    val b = readInts(m)
    val nb = ArrayBuilder.make[Pair]()
    val mb = ArrayBuilder.make[Pair]()

    val diff: Long = a.sum - b.sum
    var v: Long = Math.abs(diff)
    var k = 0
    val npb = ArrayBuilder.make[Int]()
    val mpb = ArrayBuilder.make[Int]()

    for (i <- 1 to n) {
      for (j <- 1 to m) {
        val cur = a(i-1) - b(j-1)
        if (Math.abs(diff - 2 * cur) < v) {
          v = Math.abs(diff - 2 * cur)
          npb.clear()
          npb += i
          mpb.clear()
          mpb += j
          k = 1
        }
      }
    }

    for (i <- 1 to n) {
      for (j <- 1 to n) {
        if (i != j) {
          nb += Pair(a(i-1) + a(j-1), i, j)
        }
      }
    }

    for (i <- 1 to m) {
      for (j <- 1 to m) {
        if (i != j) {
          mb += Pair(b(i-1) + b(j-1), i, j)
        }
      }
    }

    val na = nb.result().sortWith(_.d < _.d)
    val ma = mb.result().sortWith(_.d < _.d)

    for (i <- na.indices) {
      var idx = find(ma, 0, ma.length-1, 2*na(i).d-diff)
      if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) > Math.abs(diff+2*ma(idx+1).d-2*na(i).d)))) {
        idx += 1
      }
      if (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) < v) {
        v = Math.abs(diff+2*ma(idx).d-2*na(i).d)
        npb.clear()
        npb += (na(i).a, na(i).b)
        mpb.clear()
        mpb += (ma(idx).a, ma(idx).b)
        mpb += (ma(idx).a, ma(idx).b)
        k = 2
      }
    }

    val np = npb.result()
    val mp = mpb.result()
    println(v)
    println(k)
    for (i <- np.indices) {
      println(np(i) + " " + mp(i))
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  final case class Pair(d: Int, a: Int, b: Int)

  def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {
    var l = start
    var r = end
    while (l <= r ) {
      val mid = (l + r) / 2
      if (2L * a(mid).d > v) r = mid - 1
      else l = mid + 1
    }
    if (r >= start && a(r).d <= v) r
    else -1
  }

  def main(args: Array[String]) {
    val n = readLine().toInt
    val a = readInts(n)
    val m = readLine().toInt
    val b = readInts(m)
    val nb = ArrayBuilder.make[Pair]()
    val mb = ArrayBuilder.make[Pair]()
    val diff: Long = a.foldLeft(0L)(_+_) - b.foldLeft(0L)(_+_)
    var v: Long = Math.abs(diff)
    var k = 0
    val npb = ArrayBuilder.make[Int]()
    val mpb = ArrayBuilder.make[Int]()

    for (i <- 1 to n) {
      for (j <- 1 to m) {
        val cur = a(i-1) - b(j-1)
        if (Math.abs(diff - 2L * cur) < v) {
          v = Math.abs(diff - 2L * cur)
          npb.clear()
          npb += i
          mpb.clear()
          mpb += j
          k = 1
        }
      }
    }

    for (i <- 1 to n) {
      for (j <- i+1 to n) {
        nb += Pair(a(i-1) + a(j-1), i, j)
      }
    }

    for (i <- 1 to m) {
      for (j <- i+1 to m) {
        mb += Pair(b(i-1) + b(j-1), i, j)
      }
    }

    val na = nb.result()
    val ma = mb.result().sortWith(_.d < _.d)

    for (i <- na.indices) {
      var idx = find(ma, 0, ma.length-1, 2L*na(i).d-diff)
      if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) > Math.abs(diff+2L*ma(idx+1).d-2L*na(i).d)))) {
        idx += 1
      }
      if (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) < v) {
        v = Math.abs(diff+2L*ma(idx).d-2L*na(i).d)
        npb.clear()
        npb += (na(i).a, na(i).b)
        mpb.clear()
        mpb += (ma(idx).a, ma(idx).b)
        k = 2
      }
    }

    val np = npb.result()
    val mp = mpb.result()
    println(v)
    println(k)
    for (i <- np.indices) {
      println(np(i) + " " + mp(i))
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  final case class Pair(d: Int, a: Int, b: Int)

  def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {
    var l = start
    var r = end
    while (l <= r ) {
      val mid = (l + r) / 2
      if (2 * a(mid).d > v) r = mid - 1
      else l = mid + 1
    }
    if (r >= start && a(r).d <= v) r
    else -1
  }

  def main(args: Array[String]) {
    val n = readLine().toInt
    val a = readInts(n)
    val m = readLine().toInt
    val b = readInts(m)
    val nb = ArrayBuilder.make[Pair]()
    val mb = ArrayBuilder.make[Pair]()

    val diff: Long = a.map(_.toLong).sum - b.map(_.toLong).sum
    var v: Long = Math.abs(diff)
    var k = 0
    val npb = ArrayBuilder.make[Int]()
    val mpb = ArrayBuilder.make[Int]()

    for (i <- 1 to n) {
      for (j <- 1 to m) {
        val cur = a(i-1) - b(j-1)
        if (Math.abs(diff - 2 * cur) < v) {
          v = Math.abs(diff - 2 * cur)
          npb.clear()
          npb += i
          mpb.clear()
          mpb += j
          k = 1
        }
      }
    }

    for (i <- 1 to n) {
      for (j <- 1 to n) {
        if (i != j) {
          nb += Pair(a(i-1) + a(j-1), i, j)
        }
      }
    }

    for (i <- 1 to m) {
      for (j <- 1 to m) {
        if (i != j) {
          mb += Pair(b(i-1) + b(j-1), i, j)
        }
      }
    }

    val na = nb.result().sortWith(_.d < _.d)
    val ma = mb.result().sortWith(_.d < _.d)

    for (i <- na.indices) {
      var idx = find(ma, 0, ma.length-1, 2*na(i).d-diff)
      if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) > Math.abs(diff+2*ma(idx+1).d-2*na(i).d)))) {
        idx += 1
      }
      if (idx != -1 && Math.abs(diff+2*ma(idx).d-2*na(i).d) < v) {
        v = Math.abs(diff+2*ma(idx).d-2*na(i).d)
        npb.clear()
        npb += (na(i).a, na(i).b)
        mpb.clear()
        mpb += (ma(idx).a, ma(idx).b)
        mpb += (ma(idx).a, ma(idx).b)
        k = 2
      }
    }

    val np = npb.result()
    val mp = mpb.result()
    println(v)
    println(k)
    for (i <- np.indices) {
      println(np(i) + " " + mp(i))
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  final case class Pair(d: Int, a: Int, b: Int)

  def find(a: Array[Pair], start: Int, end: Int, v: Long): Int = {
    var l = start
    var r = end
    while (l <= r ) {
      val mid = (l + r) / 2
      if (2 * a(mid).d > v) r = mid - 1
      else l = mid + 1
    }
    if (r >= start && a(r).d <= v) r
    else -1
  }

  def main(args: Array[String]) {
    val n = readLine().toInt
    val a = readInts(n)
    val m = readLine().toInt
    val b = readInts(m)
    val nb = ArrayBuilder.make[Pair]()
    val mb = ArrayBuilder.make[Pair]()
    val diff: Long = a.foldLeft(0L)(_+_) - b.foldLeft(0L)(_+_)
    var v: Long = Math.abs(diff)
    var k = 0
    val npb = ArrayBuilder.make[Int]()
    val mpb = ArrayBuilder.make[Int]()

    for (i <- 1 to n) {
      for (j <- 1 to m) {
        val cur = a(i-1) - b(j-1)
        if (Math.abs(diff - 2L * cur) < v) {
          v = Math.abs(diff - 2L * cur)
          npb.clear()
          npb += i
          mpb.clear()
          mpb += j
          k = 1
        }
      }
    }

    for (i <- 1 to n) {
      for (j <- i+1 to n) {
        nb += Pair(a(i-1) + a(j-1), i, j)
      }
    }

    for (i <- 1 to m) {
      for (j <- i+1 to m) {
        mb += Pair(b(i-1) + b(j-1), i, j)
      }
    }

    val na = nb.result()
    val ma = mb.result().sortWith(_.d < _.d)

    for (i <- na.indices) {
      var idx = find(ma, 0, ma.length-1, 2L*na(i).d-diff)
      if (idx + 1 < ma.length && (idx == -1 || (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) > Math.abs(diff+2L*ma(idx+1).d-2L*na(i).d)))) {
        idx += 1
      }
      if (idx != -1 && Math.abs(diff+2L*ma(idx).d-2L*na(i).d) < v) {
        v = Math.abs(diff+2L*ma(idx).d-2L*na(i).d)
        npb.clear()
        npb += (na(i).a, na(i).b)
        mpb.clear()
        mpb += (ma(idx).a, ma(idx).b)
        mpb += (ma(idx).a, ma(idx).b)
        k = 2
      }
    }

    val np = npb.result()
    val mp = mpb.result()
    println(v)
    println(k)
    for (i <- np.indices) {
      println(np(i) + " " + mp(i))
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}


You are given a digital clock with $$$n$$$ digits. Each digit shows an integer from $$$0$$$ to $$$9$$$, so the whole clock shows an integer from $$$0$$$ to $$$10^n-1$$$. The clock will show leading zeroes if the number is smaller than $$$10^{n-1}$$$.You want the clock to show $$$0$$$ with as few operations as possible. In an operation, you can do one of the following:   decrease the number on the clock by $$$1$$$, or  swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show $$$0$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — number of digits on the clock. The second line of each test case contains a string of $$$n$$$ digits $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \le s_1, s_2, \ldots, s_n \le 9$$$) — the number on the clock. Note: If the number is smaller than $$$10^{n-1}$$$ the clock will show leading zeroes.

For each test case, print one integer: the minimum number of operations needed to make the clock show $$$0$$$.

NoteIn the first example, it's optimal to just decrease the number $$$7$$$ times.In the second example, we can first swap the first and last position and then decrease the number by $$$1$$$.In the third example, the clock already shows $$$0$$$, so we don't have to perform any operations.

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

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

    def main(args: Array[String]): Unit = {
        val t = readInt()
        for (tt <- 1 to t) {
            val n = readInt()
            val s = readString()
            var cnt = 0
            cnt += 2*s.count(_ == '1')
            cnt += 3*s.count(_ == '2')
            cnt += 4*s.count(_ == '3')
            cnt += 5*s.count(_ == '4')
            cnt += 6*s.count(_ == '5')
            cnt += 7*s.count(_ == '6')
            cnt += 8*s.count(_ == '7')
            cnt += 9*s.count(_ == '8')
            cnt += 10*s.count(_ == '9')
            if (s(s.length - 1) != '0')
                cnt -= 1
            println(cnt)
            writer.flush()
        }
    }
}

object A extends App {

  def countdown(digits: Seq[Int]): Int = {
    val reversed = digits.reverse
    reversed.drop(1).foldLeft(reversed.headOption.getOrElse(0)) {
      case (count, 0)     => count
      case (count, digit) => count + digit + 1
    }
  }

  import scala.io.StdIn._

  val t = readInt()

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

    println(countdown(sn))
  }
}


Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read exactly $$$m$$$ books before all entertainments. Alice and Bob will read each book together to end this exercise faster.There are $$$n$$$ books in the family library. The $$$i$$$-th book is described by three integers: $$$t_i$$$ — the amount of time Alice and Bob need to spend to read it, $$$a_i$$$ (equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ if not), and $$$b_i$$$ (equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ if not).So they need to choose exactly $$$m$$$ books from the given $$$n$$$ books in such a way that:  Alice likes at least $$$k$$$ books from the chosen set and Bob likes at least $$$k$$$ books from the chosen set;  the total reading time of these $$$m$$$ books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $$$t_i$$$ over all books that are in the chosen set.Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le k \le m \le n \le 2 \cdot 10^5$$$). The next $$$n$$$ lines contain descriptions of books, one description per line: the $$$i$$$-th line contains three integers $$$t_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \le t_i \le 10^4$$$, $$$0 \le a_i, b_i \le 1$$$), where:   $$$t_i$$$ — the amount of time required for reading the $$$i$$$-th book;  $$$a_i$$$ equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ otherwise;  $$$b_i$$$ equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ otherwise.

If there is no solution, print only one integer -1. If the solution exists, print $$$T$$$ in the first line — the minimum total reading time of the suitable set of books. In the second line print $$$m$$$ distinct integers from $$$1$$$ to $$$n$$$ in any order — indices of books which are in the set you found. If there are several answers, print any of them.

//package codeforces.contests._1374

object ReadingBookHard {

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = io.StdIn.readLine.split(" ").map(_.toInt)

    val (aliceL, bobL, bothL, noneL) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)], List.empty[(Int, Int)], List.empty[(Int, Int)])) {
      case ((alice, bob, both, none), i) =>
        val Array(time, a, b) = io.StdIn.readLine.split(" ").map(_.toInt)
        (
          if (a == 1 && b == 0) (time, i) :: alice else alice,
          if (a == 0 && b == 1) (time, i) :: bob else bob,
          if (a == 1 && b == 1) (time, i) :: both else both,
          if (a == 0 && b == 0) (time, i) :: none else none
        )
    }

    val aliceA = aliceL.toArray.sortBy(_._1)
    val bobA = bobL.toArray.sortBy(_._1)
    val bothA = bothL.toArray.sortBy(_._1)
    val noneA = noneL.toArray.sortBy(_._1)

    val c = bothA.length min k // next pos
    val a, b = k - c // next pos

    if (a > aliceA.length || b > bobA.length || a + b + c > m)
      println(-1)
    else {
      @scala.annotation.tailrec
      def loop(a: Int, b: Int, c: Int, d: Int, mi: Int = 0): (Int, Int, Int, Int) = {
        if (mi == m) (a, b, c, d)
        else {
          if (0 < c && a < aliceA.length && b < bobA.length && {
            val delta = aliceA(a)._1 + bobA(b)._1 - bothA(c - 1)._1
            !(delta > aliceA(a)._1) && !(delta > bobA(b)._1) && !(c < bothA.length && delta > bothA(c)._1) && !(d < noneA.length && delta > noneA(d)._1)
          })
            loop(a + 1, b + 1, c - 1, d, mi + 1)
          else if (a < aliceA.length && !(b < bobA.length && aliceA(a)._1 > bobA(b)._1) && !(c < bothA.length && aliceA(a)._1 > bothA(c)._1) && !(d < noneA.length && aliceA(a)._1 > noneA(d)._1))
            loop(a + 1, b, c, d, mi + 1)
          else if (b < bobA.length && !(a < aliceA.length && bobA(b)._1 > aliceA(a)._1) && !(c < bothA.length && bobA(b)._1 > bothA(c)._1) && !(d < noneA.length && bobA(b)._1 > noneA(d)._1))
            loop(a, b + 1, c, d, mi + 1)
          else if (c < bothA.length && !(a < aliceA.length && bothA(c)._1 > aliceA(a)._1) && !(b < bobA.length && bothA(c)._1 > bobA(b)._1) && !(d < noneA.length && bothA(c)._1 > noneA(d)._1))
            loop(a, b, c + 1, d, mi + 1)
          else if (d < noneA.length && !(a < aliceA.length && noneA(d)._1 > aliceA(a)._1) && !(b < bobA.length && noneA(d)._1 > bobA(b)._1) && !(c < bothA.length && noneA(d)._1 > bothA(c)._1))
            loop(a, b, c, d + 1, mi + 1)
          else
            (a, b, c, d)
        }
      }

      val (fai, fbi, fci, fdi) = loop(a, b, c, 0, a + b + c)

      val faiIncluded = (0 until fai).foldLeft((0, List.empty[Int])) { case ((res, indices), i) =>
        (res + aliceA(i)._1, aliceA(i)._2 :: indices)
      }

      val fbiIncluded = (0 until fbi).foldLeft(faiIncluded) { case ((res, indices), i) =>
        (res + bobA(i)._1, bobA(i)._2 :: indices)
      }

      val fciIncluded = (0 until fci).foldLeft(fbiIncluded) { case ((res, indices), i) =>
        (res + bothA(i)._1, bothA(i)._2 :: indices)
      }

      val fdiIncluded = (0 until fdi).foldLeft(fciIncluded) { case ((res, indices), i) =>
        (res + noneA(i)._1, noneA(i)._2 :: indices)
      }

      val (res, indices) = fdiIncluded

      println(res)
      println(indices.mkString(" "))
    }
  }
}

//package codeforces.contests._1374

object ReadingBookHard {

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = io.StdIn.readLine.split(" ").map(_.toInt)

    val (aliceL, bobL, bothL, noneL) = (1 to n).foldLeft((List.empty[(Int, Int)], List.empty[(Int, Int)], List.empty[(Int, Int)], List.empty[(Int, Int)])) {
      case ((alice, bob, both, none), i) =>
        val Array(time, a, b) = io.StdIn.readLine.split(" ").map(_.toInt)
        (
          if (a == 1 && b == 0) (time, i) :: alice else alice,
          if (a == 0 && b == 1) (time, i) :: bob else bob,
          if (a == 1 && b == 1) (time, i) :: both else both,
          if (a == 0 && b == 0) (time, i) :: none else none
        )
    }

    val aliceA = aliceL.toArray.sortBy(_._1)
    val bobA = bobL.toArray.sortBy(_._1)
    val bothA = bothL.toArray.sortBy(_._1)
    val noneA = noneL.toArray.sortBy(_._1)

    val c = bothA.length min k // next pos
    val a, b = k - c // next pos

    if (a >= aliceA.length || b >= bobA.length || a + b + c > m)
      println(-1)
    else {
      @scala.annotation.tailrec
      def loop(a: Int, b: Int, c: Int, d: Int, mi: Int = 0): (Int, Int, Int, Int) = {
        if (mi == m) (a, b, c, d)
        else {
          if (0 < c && a < aliceA.length && b < bobA.length && {
            val delta = aliceA(a)._1 + bobA(b)._1 - bothA(c - 1)._1
            !(delta > aliceA(a)._1) && !(delta > bobA(b)._1) && !(c < bothA.length && delta > bothA(c)._1) && !(d < noneA.length && delta > noneA(d)._1)
          })
            loop(a + 1, b + 1, c - 1, d, mi + 1)
          else if (a < aliceA.length && !(b < bobA.length && aliceA(a)._1 > bobA(b)._1) && !(c < bothA.length && aliceA(a)._1 > bothA(c)._1) && !(d < noneA.length && aliceA(a)._1 > noneA(d)._1))
            loop(a + 1, b, c, d, mi + 1)
          else if (b < bobA.length && !(a < aliceA.length && bobA(b)._1 > aliceA(a)._1) && !(c < bothA.length && bobA(b)._1 > bothA(c)._1) && !(d < noneA.length && bobA(b)._1 > noneA(d)._1))
            loop(a, b + 1, c, d, mi + 1)
          else if (c < bothA.length && !(a < aliceA.length && bothA(c)._1 > aliceA(a)._1) && !(b < bobA.length && bothA(c)._1 > bobA(b)._1) && !(d < noneA.length && bothA(c)._1 > noneA(d)._1))
            loop(a, b, c + 1, d, mi + 1)
          else if (d < noneA.length && !(a < aliceA.length && noneA(d)._1 > aliceA(a)._1) && !(b < bobA.length && noneA(d)._1 > bobA(b)._1) && !(c < bothA.length && noneA(d)._1 > bothA(c)._1))
            loop(a, b, c, d + 1, mi + 1)
          else
            (a, b, c, d)
        }
      }

      val (fai, fbi, fci, fdi) = loop(a, b, c, 0, a + b + c)

      val faiIncluded = (0 until fai).foldLeft((0, List.empty[Int])) { case ((res, indices), i) =>
        (res + aliceA(i)._1, aliceA(i)._2 :: indices)
      }

      val fbiIncluded = (0 until fbi).foldLeft(faiIncluded) { case ((res, indices), i) =>
        (res + bobA(i)._1, bobA(i)._2 :: indices)
      }

      val fciIncluded = (0 until fci).foldLeft(fbiIncluded) { case ((res, indices), i) =>
        (res + bothA(i)._1, bothA(i)._2 :: indices)
      }

      val fdiIncluded = (0 until fdi).foldLeft(fciIncluded) { case ((res, indices), i) =>
        (res + noneA(i)._1, noneA(i)._2 :: indices)
      }

      val (res, indices) = fdiIncluded

      println(res)
      println(indices.mkString(" "))
    }
  }
}


Let's denote that some array $$$b$$$ is bad if it contains a subarray $$$b_l, b_{l+1}, \dots, b_{r}$$$ of odd length more than $$$1$$$ ($$$l < r$$$ and $$$r - l + 1$$$ is odd) such that $$$\forall i \in \{0, 1, \dots, r - l\}$$$ $$$b_{l + i} = b_{r - i}$$$.If an array is not bad, it is good.Now you are given an array $$$a_1, a_2, \dots, a_n$$$. Some elements are replaced by $$$-1$$$. Calculate the number of good arrays you can obtain by replacing each $$$-1$$$ with some integer from $$$1$$$ to $$$k$$$.Since the answer can be large, print it modulo $$$998244353$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n, k \le 2 \cdot 10^5$$$) — the length of array $$$a$$$ and the size of "alphabet", i. e., the upper bound on the numbers you may use to replace $$$-1$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_i = -1$$$ or $$$1 \le a_i \le k$$$) — the array $$$a$$$.

Print one integer — the number of good arrays you can get, modulo $$$998244353$$$.

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 java.util.Arrays

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

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

  def solve(): Unit = {
    val N, K = ni()
    val A = na(N)
    REP(N - 2) { i =>
      // どうやっても回文ができるパターン
      if (A(i) != -1 && A(i + 2) != -1 && A(i) == A(i + 2)) {
        println(0)
        return
      }
    }

    val flg = Array.ofDim[Boolean](N)
    case class Group(l: Int, r: Int)

    val G = ArrayBuffer[Group]()
    REP(N) { l =>
      if (A(l) == -1 && !flg(l)) {
        flg(l) = true
        var r = l
        while(r + 2 < N && A(r + 2) == -1) {
          r += 2
          flg(r) = true
        }
        G += Group(l, r)
      }
    }

    debug(G.mkString(","))

    def calcDP(g: Group, init: Int) = {
      val n = (g.r - g.l) / 2 + 1
      val dp = Array.ofDim[Long](n, 2)
      dp(0)(0) = init
      dp(0)(1) = 1
      REP(n - 1) { j =>
        dp(j + 1)(0) = dp(j)(1) * (K - 1) % MOD
        dp(j + 1)(1) = (dp(j)(0) + dp(j)(1) * (K - 2)) % MOD
        debug("dump DP")
        debug(s"${dp(j + 1)(0)} ${dp(j + 1)(1)}")
      }
      (dp(n - 1)(0), dp(n - 1)(1))
    }

    var ans = 1L
    REP(G.length) { i =>
      val g = G(i)
      // 両サイドがない
      val v: Long = if (g.l - 2 < 0 && g.r + 2 >= N) {
        val (dp1, dpN) = calcDP(g, 1)
        debug(s"A $dp1 $dpN")
        (dp1 + dpN * (K - 1)) % MOD

      // 片側がない
      } else if (g.l - 2 < 0 || g.r + 2 >= N) {
        val (dp1, dpN) = calcDP(g, 1)
        debug(s"B $dp1 $dpN")
        dpN * (K - 1) % MOD

      // 両サイドが同じ
      } else if (A(g.l - 2) == A(g.r + 2)) {
        val (dp1, dpN) = calcDP(g, 0)
        debug(s"C $dp1 $dpN")
        dpN * (K - 1) % MOD

      // 両サイドが違う
      } else {
        val (dp1, dpN) = calcDP(g, 0)
        debug(s"D $dp1 $dpN")
        (dp1 + dpN * (K - 2)) % MOD
      }

      ans = ans * v % MOD
    }

    out.println(ans)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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


Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer.Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest.The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer.

The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads.

Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes).

NoteThe cost of repairing the road is the difference between the time needed to ride along it before and after the repairing.In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6.

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

object Solution {

  val inf = 10000000000007L
  val mod = 1000000021

  def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[Long]): Unit = {
    val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)

    pq.enqueue((0, start))
    D(start) = 0
    W(start) = 1
    while (pq.nonEmpty) {
      val (cd, ci) = pq.dequeue()
      if (cd <= D(ci)) {
        for ((ni, nd) <- adj(ci)) {
          if (D(ci) + nd < D(ni)) {
            D(ni) = D(ci) + nd
            pq.enqueue((D(ni), ni))
            W(ni) = W(ci) % mod
          } else if (D(ci) + nd == D(ni)) W(ni) = (W(ni) + (W(ci) % mod)) % mod
        }
      }
    }
  }

  def main(args: Array[String]) {
    var line = readLine().split(" ").map(_.toInt)
    val (n, m, s, t) = (line(0), line(1), line(2), line(3))

    val A = Array.fill[Long](n+1)(inf)
    val B = Array.fill[Long](n+1)(inf)
    val W1 = Array.fill[Long](n+1)(0)
    val W2 = Array.fill[Long](n+1)(0)

    val adj1 = Array.fill(n+1)(new ListBuffer[(Int, Int)])
    val adj2 = Array.fill(n+1)(new ListBuffer[(Int, Int)])
    val e = new ListBuffer[(Int, Int, Int)]

    val t1 = System.currentTimeMillis

    (1 to m).foreach { _ =>
      line = readLine().split(" ").map(_.toInt)
      adj1(line(0)) += ((line(1), line(2)))
      adj2(line(1)) += ((line(0), line(2)))
      e += ((line(0), line(1), line(2)))
    }

    val t2 = System.currentTimeMillis

    bfs(s, adj1, A, W1)
    bfs(t, adj2, B, W2)

    val dist = A(t)

    val t3 = System.currentTimeMillis

    val sb = new StringBuilder

//    if (e.head._1 == 8360) println((t2-t1) + " ... " + (t3-t2))

    e.foreach { case(from, to, d) =>
      val rest = A(from) + B(to)
      if (rest + d == dist && (W1(from) * W2(to))%mod == W1(t)) sb.append("YES\n")
      else if (rest < dist - 1 && dist > 1) sb.append("CAN " + (rest + d + 1 - dist) + "\n")
      else sb.append("NO\n")
    }

    print(sb)

  }

}

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

object Solution {

  val inf = 10000000000007L

  def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[Long]): Unit = {
    val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)

    pq.enqueue((0, start))
    D(start) = 0
    W(start) = 1
    while (pq.nonEmpty) {
      val (cd, ci) = pq.dequeue()
      if (cd <= D(ci)) {
        for ((ni, nd) <- adj(ci)) {
          if (D(ci) + nd < D(ni)) {
            D(ni) = D(ci) + nd
            pq.enqueue((D(ni), ni))
            W(ni) = W(ci)
          } else if (D(ci) + nd == D(ni)) W(ni) += W(ci)
        }
      }
    }
  }

  def main(args: Array[String]) {
    var line = readLine().split(" ").map(_.toInt)
    val (n, m, s, t) = (line(0), line(1), line(2), line(3))

    val A = Array.fill[Long](n+1)(inf)
    val B = Array.fill[Long](n+1)(inf)
    val W1 = Array.fill[Long](n+1)(0)
    val W2 = Array.fill[Long](n+1)(0)

    val adj1 = Array.fill(n+1)(new ListBuffer[(Int, Int)])
    val adj2 = Array.fill(n+1)(new ListBuffer[(Int, Int)])
    val e = new ListBuffer[(Int, Int, Int)]

    val t1 = System.currentTimeMillis

    (1 to m).foreach { _ =>
      line = readLine().split(" ").map(_.toInt)
      adj1(line(0)) += ((line(1), line(2)))
      adj2(line(1)) += ((line(0), line(2)))
      e += ((line(0), line(1), line(2)))
    }

    val t2 = System.currentTimeMillis

    bfs(s, adj1, A, W1)
    bfs(t, adj2, B, W2)

    val dist = A(t)

    val t3 = System.currentTimeMillis

    val sb = new StringBuilder

//    if (e.head._1 == 8360) println((t2-t1) + " ... " + (t3-t2))

    e.foreach { case(from, to, d) =>
      val rest = A(from) + B(to)
      if (rest + d == dist && W1(from) * W2(to) == W1(t)) sb.append("YES\n")
      else if (rest < dist - 1 && dist > 1) sb.append("CAN " + (rest + d + 1 - dist) + "\n")
      else sb.append("NO\n")
    }

    print(sb)

  }

}

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

object Solution {

  val inf = 10000000000007L

  def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[BigInt]): Unit = {
    val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)

    pq.enqueue((0, start))
    D(start) = 0
    W(start) = 1
    while (pq.nonEmpty) {
      val (cd, ci) = pq.dequeue()
      if (cd <= D(ci)) {
        for ((ni, nd) <- adj(ci)) {
          if (D(ci) + nd < D(ni)) {
            D(ni) = D(ci) + nd
            pq.enqueue((D(ni), ni))
            W(ni) = W(ci)
          } else if (D(ci) + nd == D(ni)) W(ni) += W(ci)
        }
      }
    }
  }

  def main(args: Array[String]) {
    var line = readLine().split(" ").map(_.toInt)
    val (n, m, s, t) = (line(0), line(1), line(2), line(3))

    val A = Array.fill[Long](n+1)(inf)
    val B = Array.fill[Long](n+1)(inf)
    val W1 = Array.fill[BigInt](n+1)(0)
    val W2 = Array.fill[BigInt](n+1)(0)

    val adj = Array.fill(n+1)(new ListBuffer[(Int, Int)])
    val pre = Array.fill(n+1)(new ListBuffer[Int])
    val e = new ListBuffer[(Int, Int, Int)]

    (1 to m).foreach { _ =>
      line = readLine().split(" ").map(_.toInt)
      adj(line(0)) += ((line(1), line(2)))
      adj(line(1)) += ((line(0), line(2)))
      e += ((line(0), line(1), line(2)))
    }

    bfs(s, adj, A, W1)
    bfs(t, adj, B, W2)

    val dist = A(t)

    e.foreach { case(i, j, d) =>
      val (from, to) = if (A(i) + B(j) > A(j) + B(i)) (j,i) else (i,j)
      if (A(from) + B(to) + d == dist && W1(from) * W2(to) == W1(t)) println("YES")
      else if (A(from) + B(to) < dist - 1 && dist > 1) println("CAN " + (A(from) + B(to) + d + 1 - dist))
      else println("NO")
    }

  }

}

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

object Solution {

  val inf = 10000000000007L

  def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[BigInt]): Unit = {
    val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)

    pq.enqueue((0, start))
    D(start) = 0
    W(start) = 1
    while (pq.nonEmpty) {
      val (cd, ci) = pq.dequeue()
      if (cd <= D(ci)) {
        for ((ni, nd) <- adj(ci)) {
          if (D(ci) + nd < D(ni)) {
            D(ni) = D(ci) + nd
            pq.enqueue((D(ni), ni))
            W(ni) = W(ci)
          } else if (D(ci) + nd == D(ni)) W(ni) += W(ci)
        }
      }
    }
  }

  def main(args: Array[String]) {
    var line = readLine().split(" ").map(_.toInt)
    val (n, m, s, t) = (line(0), line(1), line(2), line(3))

    val A = Array.fill[Long](n+1)(inf)
    val B = Array.fill[Long](n+1)(inf)
    val W1 = Array.fill[BigInt](n+1)(0)
    val W2 = Array.fill[BigInt](n+1)(0)

    val adj = Array.fill(n+1)(new ListBuffer[(Int, Int)])
    val pre = Array.fill(n+1)(new ListBuffer[Int])
    val e = new ListBuffer[(Int, Int, Int)]

    (1 to m).foreach { _ =>
      line = readLine().split(" ").map(_.toInt)
      adj(line(0)) += ((line(1), line(2)))
      adj(line(1)) += ((line(0), line(2)))
      e += ((line(0), line(1), line(2)))
    }

    bfs(s, adj, A, W1)
    bfs(t, adj, B, W2)

    val dist = A(t)

    e.foreach { case(i, j, d) =>
      val (from, to) = if (A(i) + B(j) > A(j) + B(i)) (j,i) else (i,j)
      if (A(from) + B(to) + d == dist) {
        if (W1(from) * W2(to) != W1(t)) println("CAN 1")
        else println("YES")
      }
      else if (A(from) + B(to) < dist && dist > 1) println("CAN " + (A(from) + B(to) + d + 1 - dist))
      else println("NO")
    }

  }

}

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

object Solution {

  val inf = 10000000000007L
  val mod = 1000000007

  def bfs(start: Int, adj: Array[ListBuffer[(Int,Int)]], D: Array[Long], W: Array[Long]): Unit = {
    val pq = mutable.PriorityQueue.newBuilder[(Long, Int)](implicitly[Ordering[(Long, Int)]].reverse)

    pq.enqueue((0, start))
    D(start) = 0
    W(start) = 1
    while (pq.nonEmpty) {
      val (cd, ci) = pq.dequeue()
      if (cd <= D(ci)) {
        for ((ni, nd) <- adj(ci)) {
          if (D(ci) + nd < D(ni)) {
            D(ni) = D(ci) + nd
            pq.enqueue((D(ni), ni))
            W(ni) = W(ci) % mod
          } else if (D(ci) + nd == D(ni)) W(ni) = (W(ni) + (W(ci) % mod)) % mod
        }
      }
    }
  }

  def main(args: Array[String]) {
    var line = readLine().split(" ").map(_.toInt)
    val (n, m, s, t) = (line(0), line(1), line(2), line(3))

    val A = Array.fill[Long](n+1)(inf)
    val B = Array.fill[Long](n+1)(inf)
    val W1 = Array.fill[Long](n+1)(0)
    val W2 = Array.fill[Long](n+1)(0)

    val adj1 = Array.fill(n+1)(new ListBuffer[(Int, Int)])
    val adj2 = Array.fill(n+1)(new ListBuffer[(Int, Int)])
    val e = new ListBuffer[(Int, Int, Int)]

    val t1 = System.currentTimeMillis

    (1 to m).foreach { _ =>
      line = readLine().split(" ").map(_.toInt)
      adj1(line(0)) += ((line(1), line(2)))
      adj2(line(1)) += ((line(0), line(2)))
      e += ((line(0), line(1), line(2)))
    }

    val t2 = System.currentTimeMillis

    bfs(s, adj1, A, W1)
    bfs(t, adj2, B, W2)

    val dist = A(t)

    val t3 = System.currentTimeMillis

    val sb = new StringBuilder

//    if (e.head._1 == 8360) println((t2-t1) + " ... " + (t3-t2))

    e.foreach { case(from, to, d) =>
      val rest = A(from) + B(to)
      if (rest + d == dist && (W1(from) * W2(to))%mod == W1(t)) sb.append("YES\n")
      else if (rest < dist - 1 && dist > 1) sb.append("CAN " + (rest + d + 1 - dist) + "\n")
      else sb.append("NO\n")
    }

    print(sb)

  }

}


Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.

The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children.

Print "Yes" if the tree is a spruce and "No" otherwise.

NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:

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

import scala.annotation.tailrec

object B {
  def solve(in: Input, out: Output): Unit = {
    val n = in.nextInt()
    val p = -1 +: Array.fill(n - 1)(in.nextInt() - 1)
    val nChildren, nLeafChildren = Array.fill(n)(0)
    for (i <- 1 until n) {
      nChildren(p(i)) += 1
    }
    for (i <- 1 until n if nChildren(i) == 0) {
      nLeafChildren(p(i)) += 1
    }
    val isNYTree = (0 until n).forall(i => nChildren(i) == 0 || nLeafChildren(i) >= 3)
    println(if (isNYTree) "Yes" else "No")
  }

  class Input(in: InputStream) extends Closeable {
    private[this] val br = new BufferedReader(new InputStreamReader(in))
    private[this] var st = new StringTokenizer(br.readLine())

    override def close(): Unit = br.close()

    @tailrec
    final def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    final def nextInt(): Int = next().toInt
    final def nextLong(): Long = next().toLong
    final def nextDouble(): Double = next().toDouble
  }

  final type Output = PrintWriter

  def main(args: Array[String]): Unit = {
    val in = new Input(System.in)
    val out = new Output(System.out)
    solve(in, out)
    out.close()
    in.close()
  }
}

object B 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 cs, cs2 = Array.fill(n){ 0L }
  val ps = Array.fill(n)(0)

  for (i <- 1 until n) {
    val Array(p) = readInts(1)
    ps(i) = p - 1
    cs(p - 1) += 1
  }

  for (i <- 1 until n) {
    if (cs(i) == 0) cs2(ps(i)) += 1
  }
  var ok = true

  for (i <- 0 until n) {
    if (cs(i) > 0 && cs2(i) < 3) ok = false
  }

  println(if (ok) "Yes" else "No")

  Console.flush
}

object B extends App {
  val n = scala.io.StdIn.readInt()

  def isTree(g: Vector[List[Int]]): Boolean = {
    def dfs(v: Int = 0): Boolean = {
      val adj = g(v)
      val notEmpty = adj.filterNot(u => g(u).isEmpty)
      if (adj.length - notEmpty.length < 3) false
      else if (notEmpty.isEmpty) true
      else notEmpty.forall(u => dfs(u))
    }

    dfs()
  }

  val g = (0 until n - 1).foldLeft(Vector.fill(n)(List.empty[Int])) ((g, i) => {
    val v = scala.io.StdIn.readInt() - 1
    val u = i + 1
    g.updated(v, u :: g(v))
  })

  if (isTree(g)) println("Yes")
  else println("No")
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main extends App {
  app()

  def app(): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val g = Array.fill(n) { ArrayBuffer.empty[Int] }
    (1 until n).foreach { u =>
      val v = sc.nextInt() - 1
      g(u).append(v)
      g(v).append(u)
    }
    print(if (dfs(g) { (_, vs: Iterator[(Boolean, Int)]) => if (vs.isEmpty) (true, 0) else vs.foldRight((c: Int) => (c >= 3, c)) { (v, g) => (c: Int) => if (v._1) g(c + b2i(v._2 == 0)) else (false, 0) }(0) }._1) "Yes" else "No")
  }

  def b2i(b: Boolean): Int = if (b) 1 else 0

  def dfs[B](g: IndexedSeq[Iterable[Int]])(f: (Int, Iterator[B]) => B): B = {
    def go(p: Int)(u: Int): B = f(u, g(u).iterator.filter(_ != p).map(go(u)))
    go(0)(0)
  }
}

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

import scala.annotation.tailrec

object B {
  def solve(in: Input, out: Output): Unit = {
    val n = in.nextInt()
    val p = -1 +: Array.fill(n - 1)(in.nextInt() - 1)
    val nChildren, nLeafChildren = Array.fill(n)(0)
    for (i <- 1 until n) {
      nChildren(p(i)) += 1
    }
    for (i <- 1 until n if nChildren(i) == 0) {
      nLeafChildren(p(i)) += 1
    }
    val isNYTree = nLeafChildren.forall(v => v == 0 || v >= 3)
    println(if (isNYTree) "Yes" else "No")
  }

  class Input(in: InputStream) extends Closeable {
    private[this] val br = new BufferedReader(new InputStreamReader(in))
    private[this] var st = new StringTokenizer(br.readLine())

    override def close(): Unit = br.close()

    @tailrec
    final def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    final def nextInt(): Int = next().toInt
    final def nextLong(): Long = next().toLong
    final def nextDouble(): Double = next().toDouble
  }

  final type Output = PrintWriter

  def main(args: Array[String]): Unit = {
    val in = new Input(System.in)
    val out = new Output(System.out)
    solve(in, out)
    out.close()
    in.close()
  }
}

object B extends App {
  val n = scala.io.StdIn.readInt()

  def isTree(g: Vector[List[Int]]): Boolean = {
    def dfs(v: Int = 0): Boolean = {
      val adj = g(v)
      val notEmpty = adj.filterNot(u => g(u).isEmpty)
      if (adj.length - notEmpty.length != 3) false
      else if (notEmpty.isEmpty) true
      else notEmpty.forall(u => dfs(u))
    }

    dfs()
  }

  val g = (0 until n - 1).foldLeft(Vector.fill(n)(List.empty[Int])) ((g, i) => {
    val v = scala.io.StdIn.readInt() - 1
    val u = i + 1
    g.updated(v, u :: g(v))
  })

  if (isTree(g)) println("Yes")
  else println("No")
}

object B extends App {
  val n = scala.io.StdIn.readInt()

  def isTree(g: Vector[List[Int]]): Boolean = {
    //    def dfs(h: List[(Int, Int, List[Int])], l: List[Int] = List.empty): Boolean =
    //      if (h.isEmpty) {
    //        val t = l.groupBy(identity).mapValues(_.size).values
    //        println(t.mkString("\t"))
    //        true
    //      } else {
    //        val (p, v, adj) = h.head
    //        if (adj.isEmpty) dfs(h.tail, if (v != p) p :: l else l)
    //        else {
    //          val u = adj.head
    //          if (u == p) dfs((p, v, adj.tail) :: h.tail, l)
    //          else dfs((v, u, g(u)) :: (p, v, adj.tail) :: h.tail, l)
    //        }
    //      }
    //
    //    dfs(List((0, 0, g(0))))

    def dfs(v: Int = 0): Boolean = {
      val t = g(v).count(u => g(u).isEmpty)
      if (t != 3) false
      else {
        val t = g(v).filterNot(u => g(u).isEmpty)
        if (t.isEmpty) true
        else t.map(u => dfs(u)).reduce(_ & _)
      }
    }

    dfs()
  }

  val g = (0 until n - 1).foldLeft(Vector.fill(n)(List.empty[Int])) ((g, i) => {
    val v = scala.io.StdIn.readInt() - 1
    val u = i + 1
    g.updated(v, u :: g(v))
  })

  if (isTree(g)) println("Yes")
  else println("No")
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main extends App {
  app()

  def app(): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val g = Array.fill(n) { ArrayBuffer.empty[Int] }
    (1 until n).foreach { u =>
      val v = sc.nextInt() - 1
      g(u).append(v)
      g(v).append(u)
    }
    print(if (dfs(g) { (_, vs: Iterator[(Boolean, Int)]) => if (vs.isEmpty) (true, 0) else vs.foldRight((c: Int) => (c == 3, c)) { (v, g) => (c: Int) => if (v._1) g(c + b2i(v._2 == 0)) else (false, 0) }(0) }._1) "Yes" else "No")
  }

  def b2i(b: Boolean): Int = if (b) 1 else 0

  def dfs[B](g: IndexedSeq[Iterable[Int]])(f: (Int, Iterator[B]) => B): B = {
    def go(p: Int)(u: Int): B = f(u, g(u).iterator.filter(_ != p).map(go(u)))
    go(0)(0)
  }
}