import scala.collection.mutable

object C extends App {

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

  val Array(a0, b0) = readInts(2)

  def can(maxK: Int): Boolean = {
    var k = maxK
    var a = a0
    var b = b0
    while (k > 0 && a >= 0 && b >= 0) {
      if (a >= b) a -= k else b -= k
      k -= 1
    }
    a >= 0 && b >= 0
  }

  @annotation.tailrec
  def binSearch(low: Int, hi: Int): Int = {
    if (hi < low) hi
    else {
      val mid = (low + hi) / 2
      if (can(mid)) binSearch(mid + 1, hi)
      else binSearch(low, mid - 1)
    }
  }

  val res = binSearch(0, 1000000)

  val asBuilder, bsBuilder = new mutable.ArrayBuilder.ofInt
  var k = res
  var a = a0
  var b = b0
  while (k > 0 && a >= 0 && b >= 0) {
    if (a >= b) {
      asBuilder += k
      a -= k
    } else {
      bsBuilder += k
      b -= k
    }
    k -= 1
  }

  val as = asBuilder.result().reverse
  val bs = bsBuilder.result().reverse

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

  println(as.length)
  println(as.mkString(" "))
  println(bs.length)
  println(bs.mkString(" "))

  Console.flush
}

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

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

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

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

  def solve(): Unit = {
    var a, b = ni()
    def calcN(sum: Long) = {
      var i = 0
      while(i.toLong * i  + i <= 2 * sum) {i += 1}
      i - 1
    }
    val n = calcN(a + b)
    val selected = mutable.Set[Int]()
    var last = n
    while(a > 0 && last > 0) {
      if (a > last) {
        selected += last
        a -= last
        last -= 1
      } else {
        selected += a
        a = 0
      }
    }

    out.println(selected.size)
    out.println(selected.mkString(" "))
    out.println(n - selected.size)
    val bs = ArrayBuffer[Int]()
    rep(n, 1) { i =>
      if (!selected.contains(i)) bs += i
    }
    out.println(bs.mkString(" "))
  }

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    var a, b = ni()
    def calcN(sum: Int) = {
      var i = 0
      while(i * i  + i< 2 * sum) {i += 1}
      i
    }
    val n = calcN(a + b)
    val selected = mutable.Set[Int]()
    var last = n
    while(a > 0) {
      if (a > last) {
        selected += last
        a -= last
        last -= 1
      } else {
        selected += a
        a = 0
      }
    }

    out.println(selected.size)
    out.println(selected.mkString(" "))
    out.println(n - selected.size)
    val bs = ArrayBuffer[Int]()
    rep(n, 1) { i =>
      if (!selected.contains(i)) bs += i
    }
    out.println(bs.mkString(" "))
  }

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    var a, b = ni()
    def calcN(sum: Long) = {
      var i = 0
      while(i.toLong * i  + i< 2 * sum) {i += 1}
      i
    }
    val n = calcN(a + b)
    val selected = mutable.Set[Int]()
    var last = n
    while(a > 0) {
      if (a > last) {
        selected += last
        a -= last
        last -= 1
      } else {
        selected += a
        a = 0
      }
    }

    out.println(selected.size)
    out.println(selected.mkString(" "))
    out.println(n - selected.size)
    val bs = ArrayBuffer[Int]()
    rep(n, 1) { i =>
      if (!selected.contains(i)) bs += i
    }
    out.println(bs.mkString(" "))
  }

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    var a, b = ni()
    def calcN(sum: Long) = {
      var i = 0
      while(i.toLong * i  + i<= 2 * sum) {i += 1}
      i - 1
    }
    val n = calcN(a + b)
    val selected = mutable.Set[Int]()
    var last = n
    while(a > 0) {
      if (a > last) {
        selected += last
        a -= last
        last -= 1
      } else {
        selected += a
        a = 0
      }
    }

    out.println(selected.size)
    out.println(selected.mkString(" "))
    out.println(n - selected.size)
    val bs = ArrayBuffer[Int]()
    rep(n, 1) { i =>
      if (!selected.contains(i)) bs += i
    }
    out.println(bs.mkString(" "))
  }

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

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

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

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

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


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

object test6 extends App {
    val s=readLine
    val n=s.length
    val dp=new Array[Int](n)

    for(i<-1 until n){
        var j=i
        while(j>0 && s(i)!=s(dp(j-1))) j=dp(j-1)
        dp(i)=if(j>0) dp(j-1)+1 else 0
    }

    val max=if(n>2) dp.slice(1,n-1).max else 0
    var j=dp(n-1)
    while(j>max) j=dp(j-1)
    println(if(j==0) "Just a legend" else s.substring(0,j))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last - 1) == 0)
    println("Just a legend")
  else
    println(line.take(p(p.last - 1)))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last) == 0)
    println("Just a legend")
  else
    println(line.take(p(p.last) - 1))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val first = line.head
  val last = line.last
  val lettersInit = Array.ofDim[Int](26)
  val lettersTail = Array.ofDim[Int](26)

  def isEqual(len: Int) = {
    (0 until len).forall(i => line(i) == line(line.length - 1 - len + i))
  }

  val candidates = (0 until line.length - 2).filter { i =>
      val j = line.length - 1 - i
      lettersInit(line(i) - 'a') += 1
      lettersTail(line(j) - 'a') += 1
//      println(line(i))
//      println(line(j))
      line(i) == last && line(j) == first && (lettersInit sameElements lettersTail)
  }

  candidates.find(i =>  isEqual(i) && line.indexOf(line.take(i + 1), 1) != line.length - 1 - i) match {
    case None => println("Just a legend")
    case Some(i) => println(line.take(i + 1))
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last) == 0)
    println("Just a legend")
  else
    println(line.take(p(p.last)))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)
  println(p.mkString(" "))

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last - 1) == 0)
    println("Just a legend")
  else
    println(line.take(p(p.last - 1)))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val first = line.head
  val last = line.last
  val lettersInit = Array.ofDim[Int](26)
  val lettersTail = Array.ofDim[Int](26)

  def isEqual(len: Int) = {
    (0 until len).forall(i => line(i) == line(line.length - 1 - len + i))
  }

  val candidates = (0 until line.length - 2).filter { i =>
      val j = line.length - 1 - i
      lettersInit(line(i) - 'a') += 1
      lettersTail(line(j) - 'a') += 1
//      println(line(i))
//      println(line(j))
      line(i) == last && line(j) == first && (lettersInit sameElements lettersTail) && isEqual(i)
  }

  candidates.find(i => line.indexOf(line.take(i + 1), 1) != line.length - 1 - i) match {
    case None => println("Just a legend")
    case Some(i) => println(line.take(i + 1))
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()

  def prefixFunction(str: String) = {
    val answer = Array.ofDim[Int](str.length)
    var k = 0
    (1 until str.length).foreach {
      case i =>
        while ((k > 0) && str(k) != str(i))
          k = answer(k - 1)
        if (str(k) == str(i))
          k += 1
        answer(i) = k
    }
    answer
  }

  val p = prefixFunction(line)

  if (p.last == 0)
    println("Just a legend")
  else if (p.init.contains(p.last))
    println(line.take(p.last))
  else if (p(p.last) < 2)
    println("Just a legend")
  else
    println(line.take(p(p.last) - 1))
}


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

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


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


/**
 * 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)
  }
}

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


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


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


object Main{
  def main(args:Array[String])={
    val sc = new java.util.Scanner(System.in)
    val n, x = sc.nextInt
    val a = Array.fill(1000001)(0)
    var ans:BigInt = 0
    for(i <- 1 to n)
    {
      var xx = sc.nextInt
      ans += a(xx^x)
      a(xx) += 1
    }
    println(ans)
  }
}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).groupBy(identity).mapValues(_.length.toLong).toArray.sortBy(_._1)
//    println(nums.mkString(" "))
    var ex = 0.toLong
    val ns = nums.map(_._1)
//    println(ns.mkString(" "))
    val vs = nums.map(_._2)
    if (x > 0) {
      nums.foreach(y => ns.search(x ^ y._1) match {
        case Found(cc) =>
        {
          ex += vs(cc) * y._2
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex = (ex + 1) / 2
    } else {
      ex = vs.map(nn => nn * (nn - 1) / 2).sum
    }
    println(ex)
  }
}

object B742 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, x) = readInts(2)
    val in = readInts(n)
    val map = cu.Map.empty[Int, Int].withDefaultValue(0)
    var res = 0L
    for(a <- in) {
      val c = x ^ a
      if(map(c) > 0)
        res += map(c)
      map(a) += 1
    }
    println(res)
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).groupBy(identity).mapValues(_.length).toArray.sortBy(_._1)
//    println(nums.mkString(" "))
    var ex = 0.toLong
    val ns = nums.map(_._1)
//    println(ns.mkString(" "))
    val vs = nums.map(_._2)
    if (x > 0) {
      nums.foreach(y => ns.search(x ^ y._1) match {
        case Found(cc) =>
        {
          ex += vs(cc) * y._2
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex = (ex + 1) / 2
    } else {
      ex = vs.map(nn => nn * (nn - 1) / 2).sum
    }
    println(ex)
  }
}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).groupBy(identity).mapValues(_.length).toArray.sortBy(_._1)
//    println(nums.mkString(" "))
    var ex = 0
    val ns = nums.map(_._1)
//    println(ns.mkString(" "))
    val vs = nums.map(_._2)
    if (x > 0) {
      nums.foreach(y => ns.search(x ^ y._1) match {
        case Found(cc) =>
        {
          ex += vs(cc) * y._2
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex = (ex + 1) / 2
    } else {
      ex = vs.map(nn => nn * (nn - 1) / 2).sum
    }
    println(ex)
  }
}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).sorted.groupBy(identity).mapValues(_.size)
//    println(nums.mkString(" "))
    var ex = 0
    val ns = nums.keys.toArray
    val vs = nums.values.toArray
    if (x > 0) {
      ns.zipWithIndex.foreach(y => ns.search(x ^ y._1) match {
        case Found(cc) =>
        {
          ex += vs(cc)
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex = (ex + 1) / 2
    } else {
      ex = vs.map(nn => nn * (nn - 1) / 2).sum
    }
    println(ex)
  }
}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).sorted.groupBy(identity).mapValues(_.length)
    println(nums.mkString(" "))
    var ex = 0
    val ns = nums.keys.toArray
    println(ns.mkString(" "))
    val vs = nums.values.toArray
    if (x > 0) {
      ns.foreach(y => ns.search(x ^ y) match {
        case Found(cc) =>
        {
          ex += vs(cc)
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex = (ex + 1) / 2
    } else {
      ex = vs.map(nn => nn * (nn - 1) / 2).sum
    }
    println(ex)
  }
}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).sorted
    var ex = 0
    if (x > 0) {
      nums.foreach(y => nums.search(x ^ y) match {
        case Found(cc) =>
        {
          ex += 1
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex = (ex + 1) / 2
    } else {
      ex = nums.groupBy(identity).mapValues(nn => nn.size * (nn.size - 1) / 2).values.sum
    }
    println(ex)
  }
}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).groupBy(identity).mapValues(_.length).toArray.sortBy(_._1)
//    println(nums.mkString(" "))
    var ex = 0
    val ns = nums.map(_._1)
//    println(ns.mkString(" "))
    val vs = nums.map(_._2)
    if (x > 0) {
      ns.foreach(y => ns.search(x ^ y) match {
        case Found(cc) =>
        {
          ex += vs(cc)
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex = (ex + 1) / 2
    } else {
      ex = vs.map(nn => nn * (nn - 1) / 2).sum
    }
    println(ex)
  }
}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).groupBy(identity).mapValues(_.length).toArray.sortBy(_._1)
    println(nums.mkString(" "))
    var ex = 0
    val ns = nums.map(_._1)
    println(ns.mkString(" "))
    val vs = nums.map(_._2)
    if (x > 0) {
      ns.foreach(y => ns.search(x ^ y) match {
        case Found(cc) =>
        {
          ex += vs(cc)
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex = (ex + 1) / 2
    } else {
      ex = vs.map(nn => nn * (nn - 1) / 2).sum
    }
    println(ex)
  }
}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).sorted.groupBy(identity).mapValues(_.length)
//    println(nums.mkString(" "))
    var ex = 0
    val ns = nums.keys.toArray
//    println(ns.mkString(" "))
    val vs = nums.values.toArray
    if (x > 0) {
      ns.foreach(y => ns.search(x ^ y) match {
        case Found(cc) =>
        {
          ex += vs(cc)
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex = (ex + 1) / 2
    } else {
      ex = vs.map(nn => nn * (nn - 1) / 2).sum
    }
    println(ex)
  }
}

object B {
  import scala.collection.Searching._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val nums = scala.io.StdIn.readLine.split(" ").map(_.toInt).sorted
    var ex = 0
    if (x > 0) {
      nums.foreach(y => nums.search(x ^ y) match {
        case Found(cc) =>
        {
          ex += 1
//          println(Array(x, y, nums(cc)).mkString(" "))
        }
        case InsertionPoint(cc) =>
        {
//          println(Array(-1, x, y, cc).mkString(" "))
          0
        }
      })
      ex /= 2
    } else {
      ex = nums.groupBy(identity).mapValues(nn => nn.size * (nn.size - 1) / 2).values.sum
    }
    println(ex)
  }
}

object Main{
  def main(args:Array[String])={
    val sc = new java.util.Scanner(System.in)
    val n, x = sc.nextInt
    val a = Array.fill(1000001)(0)
    var ans = 0
    for(i <- 1 to n)
    {
      var xx = sc.nextInt
      ans += a(xx^x)
      a(xx) += 1
    }
    println(ans)
  }
}

object B742 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, x) = readInts(2)
    val in = readInts(n)
    val set = cu.Set.empty[Int]
    var res = 0L
    for(a <- in) {
      val c = x ^ a
      if(set.contains(c))
        res += 1
      set.add(a)
    }
    println(res)
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


import scala.math._
import scala.Console
object Object {

  def main(args : Array[String]){

    var n = readInt
    var ar = readLine split " "
    var m = scala.collection.mutable.Map("25" -> 0, "50" -> 0, "100" -> 0)
    var yesOrNo = "YES"

    for(i <- 0 until n){
      ar(i) match {
         case "25" => {m("25") += 1}
         case "50" => {m("50") += 1;if(m("25") > 0)m("25") -= 1 else yesOrNo = "NO"}
         case "100"=> {if(m("25") > 0 && m("50") > 0){m("25") -= 1; m("50") -= 1}  else if(m("25") > 2){m("25") -= 3} else yesOrNo = "NO"}
         case _ =>    {yesOrNo = "NO"}
      }
    }
    println(yesOrNo)
  }
}

object Main {
  class Cash {
    private var n25, n50 = 0

    def add(n: Int) = n match {
      case 25 => n25 += 1; true
      case 50 =>
        n50 += 1
        n25 -= 1
        n25 != -1
      case 100 =>
        if (n50 == 0) {
          n25 -= 3
          n25 >= 0
        } else {
          n50 -= 1
          n25 -=  1
          n25 != -1
        }
    }
  }

  def main(args: Array[String]) {
    val c = new Cash
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val r = a.foldLeft(true){ (r, n) => r & c.add(n) }
    if (r) println("YES")
    else println("NO")
  }
}

import scala.io.StdIn

/**
 * @author unit7
 */
object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val denominations = StdIn.readLine().split("\\s").map(_.toInt)

    var can = true

    val cashBox = scala.collection.mutable.HashMap[Int, Int](25 -> 0, 50 -> 0)

    for (i <- 0 until n) {
      val denomination = denominations(i)

      if (denomination == 25) {
        cashBox.update(25, cashBox(25) + 1)
      } else if (denomination == 50) {
        val curTwentyFive = cashBox(25)

        if (curTwentyFive > 0) {
          cashBox.update(25, curTwentyFive - 1)
          cashBox.update(50, cashBox(50) + 1)
        } else {
          can = false
        }
      } else {
        var need = 3
        val curFifty = cashBox(50)

        if (curFifty > 0) {
          need -= 2
          cashBox.update(50, curFifty - 1)
        }

        val curTwentyFive = cashBox(25)

        if (curTwentyFive >= need) {
          cashBox.update(25, curTwentyFive - need)
        } else {
          can = false
        }
      }
    }

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

object Main {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    var b25 = 0
    var b50 = 0
    var b100 = 0
    for (i <- 0 until n) {
      val b = sc.nextInt
      if (b == 25)
        b25 += 1
      else if (b == 50) {
        b50 += 1
        b25 -= 1
      }
      else if (b == 100) {
        b100 += 1
        b50 -= 1
        b25 -= 1
      }
      while (b50 < 0) {
        b25 -= 2
        b50 += 1
      }
      if (b25 < 0) {
        println("NO")
        return
      }
    }
    println("YES")
  }
}

import java.util.StringTokenizer

object _349A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt)
  def f(a: List[Int], cb: Int, wb: Int): Boolean =
    if (cb < 0 || wb < 0) false
    else if (a == Nil) true
    else if (a.head == 25) f(a.tail, cb + 1, wb)
    else if (a.head == 50) f(a.tail, cb - 1, wb + 1)
    else {
      if (wb > 0) f(a.tail, cb - 1, wb - 1)
      else f(a.tail, cb - 3, wb)
    }

  if (f(a.toList, 0, 0)) println("YES")
  else println("NO")
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  in.next()
  val data = in.next().split(" ").map(_.toInt).foldLeft((0, 0, true)) {
    case((s, m, false), el) => (s, m, false)
    case((s, m, true), 25) => (s + 1, m, true)
    case((s, m, true), 50) => (s - 1, m + 1, s >= 1)
    case((s, m, true), 100) if m >= 1 => (s - 1, m - 1, s >= 1)
    case((s, m, true), 100) => (s - 3, m, s >= 3)
  }
  if (data._3)
    println("YES")
  else
    println("NO")
}

object A349 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

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

    var curr25 = 0
    var curr50 = 0
    var break = false

    for(i <- 0 until n if !break) {
      if(input(i) == 25) {
        curr25 += 1
      } else if(input(i) == 50) {
        if(curr25 >= 1) {
          curr25 -= 1
          curr50 += 1
        } else {
          println("NO")
          break = true
        }
      } else {
        if(curr50 >= 1 && curr25 >= 1) {
          curr50 -= 1
          curr25 -= 1
        } else if(curr25 >= 3) {
          curr25 -= 3
        } else {
          println("NO")
          break = true
        }
      }
    }
    if(!break) {
      println("YES")
    }
  }
}

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

object P349A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val P = List.fill(N)(sc.nextInt)

  def solve(): String = {

    @tailrec
    def loop(r50: Int, r25: Int, line: List[Int]): String =
      line match {
        case Nil       => "YES"
        case 25 :: xs  => loop(r50, r25 + 1, xs)
        case 50 :: xs  => if (r25 < 1) "NO"
                          else loop(r50 + 1, r25 - 1, xs)
        case 100 :: xs => if (r50 < 1) {
          if (r25 < 3) "NO"
          else loop(r50, r25 - 3, xs)
        }
        else {
          if (r25 < 1) "NO"
          else loop(r50 - 1, r25 - 1, xs)
        }
      }

    loop(0, 0, P)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner

object Codeforces extends App {
  val in = new Scanner(System.in)
  var a = 0
  var b = 0
  var res = "YES"
  val n = in.nextInt()
  for (i <- 0 until n) {
    val k = in.nextInt()
    if (k == 25) {
      a += 1
    }
    if (k == 50) {
      a -= 1
      b += 1
    }
    if (k == 100) {
      if (b != 0) {
        a -= 1
        b -= 1
      } else {
        a -= 3
      }
    }
    if (a < 0 || b < 0) {
      res = "NO"
    }
  }
  println(res)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  in.next()
  val data = in.next().split(" ").map(_.toInt).foldLeft((0, 0, true)) {
    case((s, m, false), el) => (s, m, false)
    case((s, m, true), 25) => (s + 1, m, true)
    case((s, m, true), 50) => (s - 1, m + 1, s >= 1)
    case((s, m, true), 100) if m > 1 => (s - 1, m - 1, s >= 1)
    case((s, m, true), 100) => (s - 3, m, s >= 3)
  }
  if (data._3)
    println("YES")
  else
    println("NO")
}

object A349 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

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

    var curr = 0
    var break = false
    for(i <- 0 until n if !break) {
      if(input(i) == 25) {
        curr += 1
      } else if(input(i) == 50) {
        if(curr >= 1) {
          curr -= 1
        } else {
          println("NO")
          break = true
        }
      } else {
        if(curr >= 2) {
          curr -= 2
        } else {
          println("NO")
          break = true
        }
      }
    }
    if(!break) {
      println("YES")
    }
  }
}

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

object P349A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val P = List.fill(N)(sc.nextInt)

  def solve(): String = {

    @tailrec
    def loop(r50: Int, r25: Int, line: List[Int]): String =
      line match {
        case Nil     => "YES"
        case 25 :: xs => loop(r50, r25 + 1, xs)
        case 50 :: xs => if (r25 < 1) "NO"
                         else loop(r50 + 1, r25 - 1, xs)
        case 100 :: xs => if (r50 > 0) loop(r50 - 1, r25, 50 :: xs)
                          else if (r25 < 3) "NO"
                          else loop(r50, r25 -3, xs)
      }

    loop(0, 0, P)
  }

  out.println(solve)
  out.close
}

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

object P349A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  val P = List.fill(N)(sc.nextInt)

  def solve(): String = {

    @tailrec
    def loop(r50: Int, r25: Int, line: List[Int]): String =
      line match {
        case Nil     => "YES"
        case 25 :: xs => loop(r50, r25 + 1, xs)
        case 50 :: xs => if (r25 < 1) "NO"
                         else loop(r50 + 1, r25 - 1, xs)
        case 100 :: xs => if (r50 > 0) loop(r50 - 1, r25, 50 :: xs)
                          else if (r25 < 3) "NO"
                          else loop(r50, r25 - 3, xs)
      }

    loop(0, 0, P)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner

object Codeforces extends App {
  val in = new Scanner(System.in)
  var a = 0
  var b = 0
  var res = "YES"
  val n = in.nextInt()
  for (i <- 1 until n) {
    var k = in.nextInt()
    if (k == 25) {
      a += 1
    }
    if (k == 50) {
      a -= 1
      b += 1
    }
    if (k == 100) {
      if (b != 0) {
        a -= 1
        b -= 1
      } else {
        a -= 3
      }
    }
    if (a < 0 || b < 0) {
      res = "NO"
    }
  }
  println(res)
}

object Main {
  class Cash {
    private var n25, n50 = 0

    def add(n: Int) = n match {
      case 25 => n25 += 1; true
      case 50 =>
        n50 += 1
        n25 -= 1
        n25 != -1
      case 100 =>
        if (n50 == 0) {
          n25 -= 3
          n25 >= 0
        } else {
          n50 -= 1
          n25 -=  1
          n25 != 1
        }
    }
  }

  def main(args: Array[String]) {
    val c = new Cash
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val r = a.foldLeft(true){ (r, n) => r & c.add(n) }
    if (r) println("YES")
    else println("NO")
  }
}

import scala.math._
import scala.Console
object Object {

  def main(args : Array[String]){

    var n = readInt
    var ar = readLine split " "
    var m = scala.collection.mutable.Map("25" -> 0, "50" -> 0, "100" -> 0)
    var yesOrNo = "YES"

    for(i <- 0 until n){
      ar(i) match {
         case "25" => {m("25") += 1}
         case "50" => {m("50") += 1;if(m("25") > 0)m("25") -= 1 else yesOrNo = "NO"}
         case "100"=> {if(m("25") > 0 && m("50") > 0){m("25") -= 1; m("50") -= 1}  else if(m("25") > 1){m("25") -= 2} else yesOrNo = "NO"}
         case _ =>    {}
      }
    }
    println(yesOrNo)
  }
}

import scala.math._
import scala.Console
object Object {

  def main(args : Array[String]){

    var n = readInt
    var ar = readLine split " "
    var m = scala.collection.mutable.Map("25" -> 0, "50" -> 0, "100" -> 0)
    var yesOrNo = "YES"

    for(i <- 0 until n){
      ar(i) match {
         case "25" => {m("25") += 1}
         case "50" => {m("50") += 1;if(m("25") > 0)m("25") -= 1 else yesOrNo = "NO"}
         case "100"=> {if(m("25") > 0 && m("50") > 0){m("25") -= 1; m("50") -= 1}  else if(m("25") > 1){m("25") -= 2} else yesOrNo = "NO"}
         case _ =>    {yesOrNo = "NO"}
      }
    }
    println(yesOrNo)
  }
}

import scala.math._
import scala.Console
object Object {

  def main(args : Array[String]){

    var n = readInt
    var ar = readLine split " "
    var m = scala.collection.mutable.Map("25" -> 0, "50" -> 0, "100" -> 0)
    var yesOrNo = "YES"

    for(i <- 0 until n){
      ar(i) match {
         case "25" => {m("25") += 1}
         case "50" => {m("50") += 1;if(m("25") > 0)m("25") -= 1 else yesOrNo = "NO"}
         case "100"=> {if(m("25") > 0 && m("50") > 0){m("25") -= 1; m("50") -= 1}  else if(m("25") > 1){m("25") -= 2} else yesOrNo = "NO"}
         case _ =>    {}
      }
    }
    println(m("25")  + " " + m("50") + " " + m("100"))
    println(yesOrNo)
  }
}

import scala.math._
import scala.Console
object Object {

  def main(args : Array[String]){

    var n = readInt
    var ar = readLine split " "
    var m = scala.collection.mutable.Map("25" -> 0, "50" -> 0, "100" -> 0)
    var yesOrNo = "YES"

    for(i <- 0 until n){
      ar(i) match {
         case "25" => {m("25") += 1}
         case "50" => {m("50") += 1;if(m("25") > 0)m("25") -= 1 else yesOrNo = "NO"}
         case "100"=> {if(m("25") > 0 && m("50") > 0){m("25") -= 1; m("50") -= 1}  else if(m("25") > 2){m("25") -= 1} else yesOrNo = "NO"}
         case _ =>    {}
      }
    }
    println(yesOrNo)
  }
}

import scala.math._
import scala.Console
object Object {

  def main(args : Array[String]){

    var n = readInt
    var ar = readLine split " "
    var m = scala.collection.mutable.Map("25" -> 0, "50" -> 0, "100" -> 0)
    var yesOrNo = "YES"

    for(i <- 0 until n){
      ar(i) match {
         case "25" => {m("25") += 1}
         case "50" => {m("50") += 1;if(m("25") > 0)m("25") -= 1 else yesOrNo = "NO"}
         case "100"=> {if(m("25") > 0 && m("50") > 0){m("25") -= 1; m("50") -= 1}  else if(m("25") > 2){m("25") -= 2} else yesOrNo = "NO"}
         case _ =>    {}
      }
    }
    println(yesOrNo)
  }
}

import scala.math._
import scala.Console
object Object {

  def main(args : Array[String]){

    var n = readInt
    var ar = readLine split " "
    var m = scala.collection.mutable.Map("25" -> 0, "50" -> 0, "100" -> 0)
    var yesOrNo = "YES"

    for(i <- 0 until n){
      ar(i) match {
         case "25" => {m("25") += 1}
         case "50" => {m("50") += 1;if(m("25") > 0)m("25") -= 1 else yesOrNo = "NO"}
         case "100"=> {if(m("25") > 0 && m("50") > 0){m("25") -= 1; m("50") -= 1}  else yesOrNo = "NO"}
         case _ =>    {}
      }
    }
    println(yesOrNo)
  }
}


object Main extends App{

	val sc = new java.util.Scanner(System.in)
	val n = sc.nextInt

	case class room(living: Int, accommodate: Int){
		val vacancy = accommodate - living
		val canMoveIn: Boolean = vacancy >= 2
	}

	val rooms = Array.fill(n)(room(sc.nextInt, sc.nextInt))
	val res = rooms.filter(_.canMoveIn == true)
	println(res.length)
}

import scala.io.StdIn._

object Accommodation {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    val nums =
      for {
        _ <- 0 until n
        a :: b :: _ = readLine().split(" ").map(_.toInt).toList
      } yield (a, b)
    val space = nums.map { case (a, b) => b - a }
    val ans = space.count(_ >= 2)
    println(ans)
  }
}

object CF0467A extends App {

  var n = readInt()
  var result = 0
  (1 to n ).foreach(n => {
    val Array(p, q) = readLine().split(" ").map(_.toInt)
    if (q >= (p + 2)) {
      result += 1
    }
  })

  println(result)

}

object GandAcc {
    def main(args: Array[String]) {
        // println("Hello, world!")
        val n = readLine().toInt
        var ctr = 0
        for (i <- 1 to n){
            var Array(p,q) = readLine().split(" ").map(_.toLong)
            if (q - p >= 2)
                ctr+=1;
        }
        printf("%d\n", ctr)
        ctr = 0
    }
}

import scala.io.StdIn

object Task467A {
	def main(args: Array[String]): Unit ={
		var r = 0
		for (_ <- 0 until StdIn.readInt()) {
			val in = StdIn.readf2("{0} {1}")
			if (in._1.asInstanceOf[String].toInt + 1 < in._2.asInstanceOf[String].toInt)
				r += 1
		}
		println(r)
	}
}

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

/**
 * Created by arseny on 18.09.14.
 */
object A extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextInt
    var ans = 0
    for(i <- 0 until n) {
      val p = nextInt
      val q = nextInt
      if(q - p >= 2) {
        ans += 1
      }
    }
    out.print(ans)
  }

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

object Main {

  def main(args: Array[String]) {
    val std = scala.io.StdIn

    val n = std.readLine().toInt
    var result = 0
    for (_ <- 0 until n) {
      val str = std.readLine().split(" ").map(_.toInt)
      val p = str(0)
      val q = str(1)
      result += (if (q - p >= 2) 1 else 0)
    }
    print(result)
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._

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

    val n = readLine.toInt

    var counter = 0
    for (i <- 0 until n) {
      val line = readLine.split(" ")
      val p = line(0).toInt
      val q = line(1).toInt

      if (p + 2 <= q) counter+=1
    }

    println(counter)
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._

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

    val n = readLine.toInt

    var counter = 0
    for (i <- 0 until n) {
      val pq = readLine.split(" ").map(value => value.toInt)

      if (pq(0) + 2 <= pq(1)) counter+=1
    }

    println(counter)
  }
}

import scala.io.StdIn

/**
 * Created by richard on 2015/6/10.
 */
object cf467a {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    var c = 0
    for (i <- 0 until n) {
      val in = StdIn.readf2("{0} {1}")
      if ( in._2.asInstanceOf[String].toInt - in._1.asInstanceOf[String].toInt > 1 ) {
        c+=1
      }
    }
    println(c)
  }
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = Array.fill(n)(readInts(2))

    println(input.map{arr => arr(1) - arr(0)}.count(_ > 1))
  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/467/A"/>
 *
 * @author pvasilyev
 * @since 08 Apr 2016
 */
object Problem145 extends App {

  private val numberOfLines: Int = scala.io.StdIn.readInt()
  private var answer = 0
  for (i <- 0 until numberOfLines) {
    val Array(p, q) = scala.io.StdIn.readLine().split(" ").map(_.toLong)
    if (q - p >= 2) {
      answer += 1
    }
  }

  println(answer)
}

/**
 * @author pvasilyev
 * @since 08 Apr 2016
 */
object Problem145 extends App {
  private val lines: Iterator[String] = scala.io.Source.stdin.getLines().takeWhile(s => s nonEmpty)
  val firstLine = lines.next()
  var answer = 0
  lines.foreach(line => {
    val strings: Array[String] = line.split(" ")
    val first = strings(0).toInt
    val second = strings(1).toInt
    if (second - first >= 2) {
      answer += 1
    }
  })

  println(answer)
}

object GeorgeAndAccommodation {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt()
		var counter = 0
		for (i <- 1 to n) {
		  val p = scanner.nextInt
		  val q = scanner.nextInt
		  counter += (if (q - p >= 2) 1 else 0)
		}
		println(counter)
	}
}

object Main extends App{
        val n = readLine().toInt
        var ctr = 0
        for (i <- 1 to n){
        	var Array(p,q) = readLine().split(" ").map(_.toLong)
        	if (q - p >= 2)
        		ctr+=1;
        }
        println(ctr)
        ctr = 0
    }

object Codeforces467A extends App{

  def FindRoom(totalroom:Int):Int={
    var ans:Int=0
    for (i <- 0 until totalroom){
      var tempa=scala.io.StdIn.readLine.split(" ").map(_.toInt)
      if (tempa(0)+2 <= tempa(1)) ans+=1
    }
    return ans
  }
  val totalroom=scala.io.StdIn.readInt
  println(FindRoom(totalroom))

}

import scala.io.StdIn._

object A_467 extends App {
  val n = readInt()
  println(
    1 to n count { _ =>
      val Array(a, b) = readLine().split(" ").map(_.toInt)
      b - a >= 2
    }
  )
}

/**
 * @author unit7
 */
object Codeforces {
  def main(args: Array[String]) {
    val input = scala.io.Source.fromInputStream(System.in)
    val lines = input.getLines()
    val n = lines.next().toInt

    var answer = 0

    for (i <- 0 until n) {
      val pq = lines.next().split(' ')
      val p = pq(0).toInt
      val q = pq(1).toInt

      answer += (if (q - p >= 2) 1 else 0)
    }

    println(answer)
  }
}

import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
  val n = readLine.toInt
    var cnt = 0
    for(i<-0 until n){
      val Array(a,b) = readLine.split(" ").map(_.toInt)
      if( b - a >= 2) cnt += 1
    }
    println(cnt)
  }
}

import java.io.BufferedReader

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

    import java.util.Scanner
    import java.io.InputStreamReader

    val streamReader: InputStreamReader = new InputStreamReader(System.in)
    val scanner: Scanner = new Scanner(new BufferedReader(streamReader))

    val n: Int = Integer.parseInt(scanner.next())
    var capacity: Int = 0
    var people: Int = 0
    var count: Int = 0

    for (i <- 0 until n){
      people = Integer.parseInt(scanner.next())
      capacity = Integer.parseInt(scanner.next())
      if (capacity - people >= 2){
        count = count + 1
      }
    }

    println(count)
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-19.
 */
object A467 extends App{
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  var i = 0
  var res = 0

  while (i < n) {
    val p, q = sc.nextInt()

    if (q - p >= 2) {
      res += 1
    }

    i += 1
  }

  println(res)
}

import java.util.Scanner

object HelloWorldMain {

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

    val n = sc.nextInt()
    var q : Int = 0
    var p : Int = 0

    var numberOfRooms : Int = 0
    for(i <- 1 to n ){
            p = sc.nextInt()
            q = sc.nextInt()
            if(q - p > 1) numberOfRooms +=1
    }
    println(numberOfRooms)
  }
}

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object George {
   def main(args: Array[String]) {
     val n = readInt
     val rooms = for {
       i <- 1 to n
       line = readLine.split(' ').map(_.toInt)
     } yield(line(0),line(1))
     println(rooms.count(x => x._2 - x._1 >= 2))
   }
}

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

object App {

  def main(args: Array[String]) {

    val n = StdIn.readLine().toInt
    var ans = 0
    var cur = 0
    for(i<-0 to n-1) {
      val Array(a,b) = StdIn.readLine().split(" ").map(_.toInt)
      if(b - a >= 2)
        ans += 1
    }
    println(ans)
  }

}

import java.util.Scanner

object TEST extends App{
    val sc = new Scanner(System.in)
    val n = sc.nextInt
    val d = List.fill(n)(-sc.nextInt+sc.nextInt())
    print(d.count(_>=2))
}

import scala.io.StdIn._

object Task extends App{
  val N = readLine.split(" ") map {_.toInt} head
  val rooms = for(i <- 1 to N) yield {
    val Array(a,b) = readLine.split(" ") map {_.toLong}
    (a,b)
  }

  val ans = rooms filter { case(a,b) => (a-b).abs > 1}

  println(ans.size)
}

object Main extends App{
val n = readLine().toInt
        var ctr = 0
        for (i <- 1 to n){
        	var Array(p,q) = readLine().split(" ").map(_.toLong)
        	if (q - p >= 2)
        		ctr+=1;
        }
        println("%d\n", ctr)
        ctr = 0
}