Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.

The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109).

Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them.

NoteSample 1. You can reverse the entire array to get [1, 2, 3], which is sorted.Sample 3. No segment can be reversed such that the array will be sorted.DefinitionsA segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r].If you have an array a of size n and you reverse its segment [l, r], the array will become:a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].

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

/**
 * Created by arseny on 24.07.14.
 */
object B extends App {
  val home = true
  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
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    var k = 0
    var f = true
    for (i <- 1 until n if f) {
      if (a(i) >= a(k)) {
        k = i
      } else {
        f = false
      }
    }
    var j = 0
    for (i <- 0 to k if j == 0) {
      if (a(i) == a(k)) {
        j = i
      }
    }
    var t = j
    for (i <- j until n) {
      if (a(i) <= a(j)) {
        t = i
      }
    }
    val b = a.slice(j, t + 1)
    for (i <- j to t) {
      a(i) = b(t - i)
    }

    if (a.toList.sorted == a.toList) {
      out.println(s"yes\n${j + 1} ${t + 1}")
    } else {
      out.println("no")
    }

//    out.println(k)
//    out.println(j)
//    out.println(t)
//    out.println(a.toList)
//    out.println(a.sorted.toList)

  }

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

import java.util.StringTokenizer

object _451B extends App {
  var token = new StringTokenizer("")

  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray

  val first = (0 until n - 1).indexWhere(i => a(i) > a(i + 1))
  if (first == -1) println("yes\n1 1")
  else {
    val cb = Stream.from(first).takeWhile(i => i < n - 1 && a(i) > a(i + 1) && (i == first || a(i - 1) > a(i))).toArray
    def reverse(l: Int, r: Int): Unit = {
      if (l < r) {
        val tmp = a(l)
        a(l) = a(r)
        a(r) = tmp
        reverse(l + 1, r - 1)
      }
    }
    reverse(first, cb.last + 1)
    val ok = (0 until n - 1).forall(i => a(i) <= a(i + 1))
    if (ok) println("yes%n%d %d".format(first + 1, cb.last + 1 + 1))
    else println("no")
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
//    println(index1)
//    println(index2)
//    println(firstUp)
//    println(secondUp)
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    }
    else if (index1 == index2) {
      if (firstUp) {
//        println("gg")
//        println(firstUp)
//        println(data(index1.get))
//        println(data(index1.get + 1))
        if (data(index1.get) > data(index1.get + 1) && data(0) < data(n - 1)) {
          result = Some((index1.get + 1, n))
//          println("lollol")
        }
      } else {
//        println("pp")
//        println(firstUp)
//        println(data(0))
//        println(data(index1.get + 1))
        if (data(0) < data(index1.get + 1)) {
          result = Some(1, index1.get + 1)
        }
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else {
    println("yes")
    println(result.get._1 + " " + result.get._2)
  }

}

object B451 {
  import IO._
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    var start = -1
    var end = -1
    for(i <- 1 until n) {
      if(in(i-1) > in(i)) {
        if(start == -1) {
          start = i-1
          end = i
        } else {
          end = i
        }
      }
    }
    if(start == -1 && end == -1) {
      println("yes")
      println("1 1")
    } else {
      val in2 = in.clone()
      val in3 = in.clone()

      util.Sorting.quickSort(in2)

      val rev = in3.slice(start, end+1).reverse
      var j = 0
      for(i <- start to end){
        in3(i) = rev(j)
        j += 1
      }

      if(in2.sameElements(in3)) {
        println("yes")
        println(s"${start+1} ${end+1}")
      } else {
        println("no")
      }
    }
  }

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

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

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

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

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

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)

  if (n == 1) {
    println("yes")
    println("1 1")
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
    if (index1.isEmpty && index2.isEmpty) {
      println("yes")
      println("1 1")
    } else if (!firstUp && !secondUp) {
      println("no")
    } else if (index1 == index2) {
      if (firstUp) {
        if (data(0) > data(n - 1)) {
          println("yes")
          println(index1.get + " " + n)
        } else {
          println("no")
        }
      } else {
        if (data(0) > data(index1.get)) {
          println("yes")
          println(index1.get + " " + n)
        } else {
          println("no")
        }
      }
    } else {
      if (!firstUp || secondUp)
        println("no")
      else {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (!r)
          println("no")
        else {
          println("yes")
          println(index1.get + 1 + " " + (index2.get + 1))
        }
      }
    }
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
//    println(index1)
//    println(index2)
//    println(firstUp)
//    println(secondUp)
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    }
    else if (!firstUp && secondUp) {}
    else if (index1 == index2) {
      if (firstUp) {
//        println("gg")
//        println(firstUp)
//        println(data(index1.get))
//        println(data(index1.get + 1))
        if (data(index1.get) < data(index1.get + 1)) {
          result = Some((index1.get + 1, n))
//          println("lollol")
        }
      } else {
//        println("pp")
//        println(firstUp)
//        println(data(0))
//        println(data(index1.get + 1))
        if (data(0) < data(index1.get + 1)) {
          result = Some(1, index1.get + 1)
        }
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else {
    println("yes")
    println(result.get._1 + " " + result.get._2)
  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
//    println(index1)
//    println(index2)
//    println(firstUp)
//    println(secondUp)
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    } else if (index1 == index2) {
      if (firstUp) {
//        println("gg")
        if (data(0) > data(n - 1)) {
          result = Some((index1.get + 1, n))
//          println("lollol")
        }
      } else {
//        println("pp")
//        println(firstUp)
//        println(data(0))
//        println(data(index1.get + 1))
        if (data(0) < data(index1.get + 1)) {
          result = Some(1, index1.get + 1)
        }
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else {
    println("yes")
    println(result.get._1 + " " + result.get._2)
  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
//    println(index1)
//    println(index2)
//    println(firstUp)
//    println(secondUp)
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    } else if (!firstUp && secondUp) {
    } else if (index1 == index2) {
      if (firstUp) {
        if (data(0) > data(n - 1)) {
          result = Some((index1.get + 1, n))
        }
      } else {
        if (data(0) > data(n - 1)) {
          result = Some(1, index1.get + 1)
        }
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else {
    println("yes")
    println(result.get._1 + " " + result.get._2)
  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
//    println(index1)
//    println(index2)
//    println(firstUp)
//    println(secondUp)
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    } else if (index1 == index2) {
      if (firstUp) {
//        println("gg")
//        println(firstUp)
//        println(data(index1.get + 1))
//        println(data(n - 1))
        if (data(index1.get + 1) > data(n - 1)) {
          result = Some((index1.get + 1, n))
//          println("lollol")
        }
      } else {
//        println("pp")
//        println(firstUp)
//        println(data(0))
//        println(data(index1.get + 1))
        if (data(0) < data(index1.get + 1)) {
          result = Some(1, index1.get + 1)
        }
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else {
    println("yes")
    println(result.get._1 + " " + result.get._2)
  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    } else if (!firstUp && !secondUp) {
    } else if (index1 == index2) {
      if (firstUp) {
        if (data(0) > data(n - 1))
          result = Some((index1.get, n))
      } else {
        if (data(0) > data(index1.get))
          result = Some(index1.get, n)
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else {
    println("yes")
    println(result.get._1 + " " + result.get._2)
  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
//    println(index1)
//    println(index2)
//    println(firstUp)
//    println(secondUp)
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    }
    else if (index1 == index2) {
      if (firstUp) {
//        println("gg")
//        println(firstUp)
//        println(data(index1.get))
//        println(data(index1.get + 1))
        if (data(index1.get) < data(index1.get + 1)) {
          result = Some((index1.get + 1, n))
//          println("lollol")
        }
      } else {
//        println("pp")
//        println(firstUp)
//        println(data(0))
//        println(data(index1.get + 1))
        if (data(0) < data(index1.get + 1)) {
          result = Some(1, index1.get + 1)
        }
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else {
    println("yes")
    println(result.get._1 + " " + result.get._2)
  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    } else if (!firstUp && !secondUp) {
    } else if (index1 == index2) {
      if (firstUp) {
        if (data(0) > data(n - 1))
          result = Some((index1.get, n))
      } else {
        if (data(0) > data(index1.get))
          result = Some(index1.get, n)
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else
    println(result.get._1 + " " + result.get._2)

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
//    println(index1)
//    println(index2)
//    println(firstUp)
//    println(secondUp)
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    } else if (!firstUp && secondUp) {
    } else if (index1 == index2) {
      if (firstUp) {
        if (data(0) > data(n - 1))
          result = Some((index1.get + 1, n))
      } else {
        if (data(0) > data(index1.get))
          result = Some(1, index1.get + 1)
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else {
    println("yes")
    println(result.get._1 + " " + result.get._2)
  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var result: Option[(Int, Int)] = None

  if (n == 1) {
    result = Some((1, 1))
  } else {
    val firstUp = data(1) > data(0)
    val index1 = Range(0, n - 1).find{
      case(i) if firstUp => data(i + 1) < data(i)
      case(i) => data(i + 1) > data(i)
    }
    val secondUp = data(n - 2) > data(n - 1)
    val index2 = Range(n - 1, 0, -1).find {
      case i if secondUp => data(i - 1) < data(i)
      case i => data(i - 1) > data(i)
    }
//    println(index1)
//    println(index2)
//    println(firstUp)
//    println(secondUp)
    if (index1.isEmpty && index2.isEmpty) {
      if (firstUp)
        result = Some((1, 1))
      else
        result = Some((1, n))
    }
    else if (index1 == index2) {
      if (firstUp) {
//        println("gg")
//        println(firstUp)
//        println(data(index1.get))
//        println(data(index1.get + 1))
        if (data(index1.get) > data(index1.get + 1)) {
          result = Some((index1.get + 1, n))
//          println("lollol")
        }
      } else {
//        println("pp")
//        println(firstUp)
//        println(data(0))
//        println(data(index1.get + 1))
        if (data(0) < data(index1.get + 1)) {
          result = Some(1, index1.get + 1)
        }
      }
    } else {
      if (firstUp && !secondUp) {
        var prev = data(index1.get) + 1
        val r = data.slice(index1.get, index2.get + 1).forall{ n =>
          val res = n > data(index1.get - 1) && n < prev && n < data(index2.get + 1)
          prev = n
          res
        }
        if (r)
          result = Some(index1.get + 1, index2.get + 1)
      }
    }
  }

  if (result.isEmpty)
    println("no")
  else {
    println("yes")
    println(result.get._1 + " " + result.get._2)
  }

}


Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station.Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρi, j among all pairs 1 ≤ i < j ≤ n.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of stations. The second line contains n - 1 integer ai (i + 1 ≤ ai ≤ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to ai inclusive.

Print the sum of ρi, j among all pairs of 1 ≤ i < j ≤ n.

NoteIn the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.Consider the second sample:   ρ1, 2 = 1  ρ1, 3 = 2  ρ1, 4 = 3  ρ1, 5 = 3  ρ2, 3 = 1  ρ2, 4 = 2  ρ2, 5 = 2  ρ3, 4 = 1  ρ3, 5 = 1  ρ4, 5 = 1 Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.

import scala.collection.immutable.TreeMap
import scala.io.StdIn
import scala.math.Ordering.Implicits._
import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toInt - 1)
    val rmq = new SegTree(n)(IntTupleMax)
    rmq.set(a.zipWithIndex)
    rmq(n - 1) = (n - 1, n - 1)
    val dp = Array.fill(n)(0L)
    dp(n - 1) = 0
    dp(n - 2) = 1
    for (i <- (0 until n - 2).reverse) {
      val p = rmq.query(i + 1, a(i) + 1)._2
      assert(p != -1)
      dp(i) = (n - 1 - i) + dp(p) - (a(i) - p)
    }
    println(dp.sum)
  }
}

trait Monoid[T] {
  def zero: T
  def mul(a: T, b: T): T
}

class SegTree[T: ClassTag](n0: Int)(m: Monoid[T]) {

  val n = {
    var n1 = 1
    while (n1 < n0) n1 <<= 1
    n1
  }

  val t: Array[T] = Array.fill[T](2 * n - 1)(m.zero)

  def set(a: Array[T]): Unit = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (r - l == 1) {
        if (l < a.length) t(k) = a(l)
        else t(k) = m.zero
        return t(k)
      } else {
        t(k) = m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
        return t(k)
      }
    }
    rec(0, 0, n)
  }

  def update(k0: Int, v: T): Unit = {
    var k = k0 + (n - 1)
    t(k) = v
    while (k > 0) {
      k = (k - 1) / 2
      t(k) = m.mul(t(2 * k + 1), t(2 * k + 2))
    }
  }

  def query(a: Int, b: Int): T = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (b <= l || r <= a) {
        return m.zero
      } else if (a <= l && r <= b) {
        return t(k)
      } else {
        return m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
      }
    }
    return rec(0, 0, n)
  }
}

object IntTupleMax extends Monoid[(Int, Int)] {
  def zero = (Int.MinValue, -1)
  def mul(a: (Int, Int), b: (Int, Int)) = a max b
}

import scala.collection.immutable.TreeMap
import scala.io.StdIn
import scala.math.Ordering.Implicits._
import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toInt - 1)
    val rmq = new SegTree(n)(IntTupleMax)
    rmq.set(a.zipWithIndex)
    rmq(n - 1) = (n - 1, n - 1)
    val dp = Array.fill(n)(0)
    dp(n - 1) = 0
    dp(n - 2) = 1
    for (i <- (0 until n - 2).reverse) {
      val p = rmq.query(i + 1, a(i) + 1)._2
      assert(p != -1)
      dp(i) = (n - 1 - i) + dp(p) - (a(i) - p)
    }
    println(dp.sum)
  }
}

trait Monoid[T] {
  def zero: T
  def mul(a: T, b: T): T
}

class SegTree[T: ClassTag](n0: Int)(m: Monoid[T]) {

  val n = {
    var n1 = 1
    while (n1 < n0) n1 <<= 1
    n1
  }

  val t: Array[T] = Array.fill[T](2 * n - 1)(m.zero)

  def set(a: Array[T]): Unit = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (r - l == 1) {
        if (l < a.length) t(k) = a(l)
        else t(k) = m.zero
        return t(k)
      } else {
        t(k) = m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
        return t(k)
      }
    }
    rec(0, 0, n)
  }

  def update(k0: Int, v: T): Unit = {
    var k = k0 + (n - 1)
    t(k) = v
    while (k > 0) {
      k = (k - 1) / 2
      t(k) = m.mul(t(2 * k + 1), t(2 * k + 2))
    }
  }

  def query(a: Int, b: Int): T = {
    def rec(k: Int, l: Int, r: Int): T = {
      if (b <= l || r <= a) {
        return m.zero
      } else if (a <= l && r <= b) {
        return t(k)
      } else {
        return m.mul(
          rec(2 * k + 1, l, (l + r) / 2),
          rec(2 * k + 2, (l + r) / 2, r)
        )
      }
    }
    return rec(0, 0, n)
  }
}

object IntTupleMax extends Monoid[(Int, Int)] {
  def zero = (Int.MinValue, -1)
  def mul(a: (Int, Int), b: (Int, Int)) = a max b
}


Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.

The first line contains integer n (1 ≤ n ≤ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card.

In a single line print the answer to the problem — the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.

NoteIn the first test you can make only one number that is a multiple of 90 — 0.In the second test you can make number 5555555550, it is a multiple of 90.

import java.util.StringTokenizer

object _352A 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)
  val five = a.filter(i => i == 5).size
  val zero = n - five
  if (zero == 0) println(-1)
  else {
    val ans = if (five < 9) "0" else (1 to five / 9 * 9).map(i => '5').mkString + (1 to zero).map(i => '0').mkString
    println(ans)
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val zeros = data.count(_ == 0)
  val fifths = data.count(_ == 5)

  if (zeros == 0)
    println(-1)
  else if (fifths < 9)
    println(0)
  else
    println("5" * (fifths - fifths % 9) + "0" * zeros)

}

object A352 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val fives = in.count(_ == 5)
    val zeros = in.count(_ == 0)
    if(zeros == 0) {
      println("-1")
    } else if(fives < 9) {
      println("0")
    } else {
      println((Array.fill(9*(fives/9))(5) ++ Array.fill(zeros)(0)).mkString(""))
    }
  }

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

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

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

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

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

}

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

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

  def solve(): String = {
    val c0 = C.filter(_ == 0).size
    val c5 = C.filter(_ == 5).size

    if (c0 < 1) "-1"
    else if (c5 < 9) "0"
    else (List.fill(c5 / 9 * 9)('5') ++ List.fill(c0)('0')).mkString
  }

  out.println(solve)
  out.close
}

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

object A {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def solve = {
    val n = nextInt
    val a = new Array[Int](n)
    val num = new Array[Int](10)
    for (i <- 0 until n) {
      if (nextInt == 5) {
        num(5) = num(5) + 1
      } else {
        num(0) = num(0) + 1
      }
    }
    if (num(0) > 0) {
      if (num(5) < 9) {
        out.println(0)
      } else {
        val r = num(5) / 9
        for (i <- 0 until r) {
          out.print("555555555")
        }
        for (i <- 0 until num(0)) {
          out.print('0')
        }
      }
    } else {
      out.println(-1)
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val n5 = a.count(_ == 5)
    val n0 = a.count(_ == 0)
    if (n0 == 0) println("-1")
    else if (n5 / 9 == 0) println("0")
    else {
      var s = Seq.fill((n5 / 9) * 9)(5) ++ Seq.fill(n0)(0)
      println(s.mkString(""))
    }
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val zeros = data.count(_ == 0)
  val fifths = data.count(_ == 0)

  if (zeros == 0)
    println(-1)
  else if (fifths < 9)
    println(0)
  else
    println("5" * (fifths / 9) + "0" * zeros)

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val zeros = data.count(_ == 0)
  val fifths = data.count(_ == 0)

  if (zeros == 0)
    println(-1)
  else if (fifths < 9)
    println(0)
  else
    println("5" * (fifths % 9) + "0" * zeros)

}

object A352 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val fives = in.count(_ == 5)
    val zeros = in.count(_ == 0)
    if(fives < 9 && zeros == 0) {
      println("-1")
    } else if(fives < 9) {
      println("0")
    } else {
      println((Array.fill(9*(fives/9))(5) ++ Array.fill(zeros)(0)).mkString(""))
    }
  }

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

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

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

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

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

}

object A352 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val fives = in.count(_ == 5)
    val zeros = in.count(_ == 0)
    if(fives < 9) {
      println("0")
    } else {
      println((Array.fill(9*(fives/9))(5) ++ Array.fill(zeros)(0)).mkString(""))
    }
  }

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

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

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

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

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

}

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

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

  def solve(): String = {
    val c0 = C.filter(_ == 0).size
    val c5 = C.filter(_ == 5).size

    if (c0 < 1 && c5 < 9) "-1"
    else if (c0 > 0 && c5 < 9) "0"
    else (List.fill(c5 / 9 * 9)('5') ++ List.fill(c0)('0')).mkString
  }

  out.println(solve)
  out.close
}


This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computersPolycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture.    (1) — bus, (2) — ring, (3) — star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown.

The first line contains two space-separated integers n and m (4 ≤ n ≤ 105; 3 ≤ m ≤ 105) — the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≤ xi, yi ≤ n) — the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself.

In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes).

bus topology
ring topology
star topology
unknown topology

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val graph = Array.fill(n){Set.empty[Int]}
  (1 to m).foreach { _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
    graph(a) += b
    graph(b) += a
  }
  val oneCount = graph.groupBy(_.size).map(t => (t._1, t._2.length))
  if (oneCount.getOrElse(1, 0) == 2 && oneCount.getOrElse(2, 0) == n - 2 && m == n - 1)
    println("bus topology")
  else if (oneCount.getOrElse(2, 0) == n && m == n)
    println("ring topology")
  else if (oneCount.getOrElse(1, 0) == (n - 1) && oneCount.getOrElse(n - 1, 0) == 1 && m == n - 1)
    println("star topology")
  else
    println("unknown topology")
}

/*
B. Топология сети
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

В задаче используется упрощенная модель топологий сетей, внимательно прочтите условие задачи и используйте его как формальный документ при разработке решения.

Поликарп продолжает работать системным администратором в некоторой большой корпорации. Компьютерная сеть этой корпорации состоит из n компьютеров, некоторые из которых соединены кабелем. Компьютеры пронумеруем целыми числами от 1 до n. Известно, что любые два компьютера соединены кабелем непосредственно или через другие компьютеры.

Поликарп решил узнать топологию этой сети. Сетевая топология — это способ описания конфигурации сети, схема расположения и соединения сетевых устройств.

Поликарп знает три основные топологии сети: шина, кольцо и звезда. Шина — это топология, которая представляет собой общий кабель, к которому подсоединены все компьютеры. Кольцо — топология, в которой каждый компьютер соединен кабелем только с двумя другими. Звезда — это топология, в которой все компьютеры сети присоединены к единому центральному узлу.

Представим каждую из этих топологий сети в виде связного неориентированного графа. Под шиной будем понимать связный граф, являющийся единственным путем, то есть граф, в котором все вершины соединены с двумя другими, за исключением двух вершин, которые являются началом и концом пути. Под кольцом будем понимать связный граф, в котором все вершины соединены с двумя другими. Под звездой будем понимать связный граф, в котором выделена единственная центральная вершина, которая соединена со всеми остальными вершинами. Для лучшего понимания ознакомьтесь с рисунком.

1) o -- o -- o -- o -- o

2) o -- o -- o
   |         |
   o -- o -- o

3)   o o
      \|
       o -- o
      /|\
     o o o

(1) — шина, (2) — кольцо, (3) — звезда

Вам задан связный неориентированный граф, характеризующий компьютерную сеть корпорации, в которой работает Поликарп. Помогите ему узнать, к какой из данных топологий относится заданная компьютерная сеть. Если это невозможно определить, сообщите, что топология этой сети неизвестна.
Входные данные

В первой строке через пробел заданы два целых числа n и m (4 ≤ n ≤ 105; 3 ≤ m ≤ 105) — количество вершин и ребер в графе соответственно. Далее в m строках задано описание ребер графа. В i-той строке через пробел задана пара целых чисел xi, yi (1 ≤ xi, yi ≤ n) — номера вершин, которые соединяет i-ое ребро.

Гарантируется, что заданный граф является связным. Между любыми двумя вершинами существует не более одного ребра. Ни одно ребро не соединяет вершину саму с собой.
Выходные данные

В единственную строку выведите название топологии сети, к которой относится заданный граф. Если ответом является шина, выведите «bus topology» (без кавычек), если ответом является кольцо, выведите «ring topology» (без кавычек), если ответом является звезда, выведите «star topology» (без кавычек). Если ни один из этих типов не подходит, выведите «unknown topology» (без кавычек).
Примеры тестов
Входные данные

4 3
1 2
2 3
3 4

Выходные данные

bus topology

Входные данные

4 4
1 2
2 3
3 4
4 1

Выходные данные

ring topology

Входные данные

4 3
1 2
1 3
1 4

Выходные данные

star topology

Входные данные

4 4
1 2
2 3
3 1
1 4

Выходные данные

unknown topology
*/
object CrocRound1Task2 extends App {
  def bus = "bus topology"
  def ring = "ring topology"
  def star = "star topology"
  def unknown = "unknown topology"

  /** Analyzez the graph to find out topology */
  def solve(n: Int, edges: Seq[(Int, Int)]): String = {
    val arr = Array.fill[Int](n)(0)
    val edgesCleaned = (edges map (p => if (p._2 > p._1) p.swap else p)).distinct
    edgesCleaned map {
      case (x, y) => {
        arr(x - 1) += 1
        arr(y - 1) += 1
      }
    }
    val seq = IndexedSeq(arr: _*).sorted
    if (seq.head == 2 && seq.last == 2) {
      ring
    } else if (seq(0) == 1 && seq(1) == 1 && seq(2) == 2 && seq.last == 2) {
      bus
    } else if (seq(0) == 1 && seq(n - 2) == 1 && seq(n - 1) == (n - 1)) {
      star
    } else {
      unknown
    }
  }

  val (n, m) = {
    val l = readLine split ' ' map (_.toInt)
    (l(0), l(1))
  }
  val edges = (0 until m) map (_ => readLine split ' ' map (_.toInt)) map (l => (l(0), l(1)))

  val res = solve(n, edges)
  println(res)
}

/*
B. Топология сети
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

В задаче используется упрощенная модель топологий сетей, внимательно прочтите условие задачи и используйте его как формальный документ при разработке решения.

Поликарп продолжает работать системным администратором в некоторой большой корпорации. Компьютерная сеть этой корпорации состоит из n компьютеров, некоторые из которых соединены кабелем. Компьютеры пронумеруем целыми числами от 1 до n. Известно, что любые два компьютера соединены кабелем непосредственно или через другие компьютеры.

Поликарп решил узнать топологию этой сети. Сетевая топология — это способ описания конфигурации сети, схема расположения и соединения сетевых устройств.

Поликарп знает три основные топологии сети: шина, кольцо и звезда. Шина — это топология, которая представляет собой общий кабель, к которому подсоединены все компьютеры. Кольцо — топология, в которой каждый компьютер соединен кабелем только с двумя другими. Звезда — это топология, в которой все компьютеры сети присоединены к единому центральному узлу.

Представим каждую из этих топологий сети в виде связного неориентированного графа. Под шиной будем понимать связный граф, являющийся единственным путем, то есть граф, в котором все вершины соединены с двумя другими, за исключением двух вершин, которые являются началом и концом пути. Под кольцом будем понимать связный граф, в котором все вершины соединены с двумя другими. Под звездой будем понимать связный граф, в котором выделена единственная центральная вершина, которая соединена со всеми остальными вершинами. Для лучшего понимания ознакомьтесь с рисунком.

1) o -- o -- o -- o -- o

2) o -- o -- o
   |         |
   o -- o -- o

3)   o o
      \|
       o -- o
      /|\
     o o o

(1) — шина, (2) — кольцо, (3) — звезда

Вам задан связный неориентированный граф, характеризующий компьютерную сеть корпорации, в которой работает Поликарп. Помогите ему узнать, к какой из данных топологий относится заданная компьютерная сеть. Если это невозможно определить, сообщите, что топология этой сети неизвестна.
Входные данные

В первой строке через пробел заданы два целых числа n и m (4 ≤ n ≤ 105; 3 ≤ m ≤ 105) — количество вершин и ребер в графе соответственно. Далее в m строках задано описание ребер графа. В i-той строке через пробел задана пара целых чисел xi, yi (1 ≤ xi, yi ≤ n) — номера вершин, которые соединяет i-ое ребро.

Гарантируется, что заданный граф является связным. Между любыми двумя вершинами существует не более одного ребра. Ни одно ребро не соединяет вершину саму с собой.
Выходные данные

В единственную строку выведите название топологии сети, к которой относится заданный граф. Если ответом является шина, выведите «bus topology» (без кавычек), если ответом является кольцо, выведите «ring topology» (без кавычек), если ответом является звезда, выведите «star topology» (без кавычек). Если ни один из этих типов не подходит, выведите «unknown topology» (без кавычек).
Примеры тестов
Входные данные

4 3
1 2
2 3
3 4

Выходные данные

bus topology

Входные данные

4 4
1 2
2 3
3 4
4 1

Выходные данные

ring topology

Входные данные

4 3
1 2
1 3
1 4

Выходные данные

star topology

Входные данные

4 4
1 2
2 3
3 1
1 4

Выходные данные

unknown topology
*/
import java.util.Arrays

object CrocRound1Task2 extends App {
  def bus = "bus topology"
  def ring = "ring topology"
  def star = "star topology"
  def unknown = "unknown topology"

  /** Analyzez the graph to find out topology */
  def solve(n: Int, edges: Seq[(Int, Int)]): String = {
    val arr = Array.fill[Int](n)(0)
    val edgesCleaned = (edges map (p => if (p._2 > p._1) p.swap else p)).distinct
    edgesCleaned map {
      case (x, y) => {
        arr(x - 1) += 1
        arr(y - 1) += 1
      }
    }
    Arrays.sort(arr)
    if (arr.head == 2 && arr.last == 2) {
      ring
    } else if (arr(0) == 1 && arr(1) == 1 && arr(2) == 2 && arr.last == 2) {
      bus
    } else if (arr(0) == 1 && arr(n - 2) == 1 && arr(n - 1) == (n - 1)) {
      star
    } else {
      unknown
    }
  }

  val (n, m) = {
    val l = readLine split ' ' map (_.toInt)
    (l(0), l(1))
  }
  val edges = (0 until m) map (_ => readLine split ' ' map (_.toInt)) map (l => (l(0), l(1)))

  val res = solve(n, edges)
  println(res)
}

import io.Source
import java.io.PrintWriter
import scala.collection.mutable.ArrayBuffer

object CF292B {

  def solve(in: In, out: PrintWriter) {
    val n, m = in().toInt
    val ls = Array.fill(n)(0)
    for (it <- 0 until m) {
      val u, v = in().toInt - 1
      ls(u) += 1
      ls(v) += 1
    }
    out.println {
      if (ls.forall(_ == 2)) {
        "ring topology"
      } else if (ls.count(_ == 2) == n - 2 && ls.count(_ == 1) == 2) {
        "bus topology"
      } else if (ls.count(_ == 1) == n - 1 && ls.count(_ == n - 1) == 1) {
        "star topology"
      } else {
        "unknown topology"
      }
    }
  }

  def main(args: Array[String]) {
      val in: In = new In(Source.fromInputStream(System.in))
      val out: PrintWriter = new PrintWriter(System.out)
      solve(in, out)
      out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

object NetworkTopology292B extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val m = scanner.nextInt()
    val nodes = (1 to n).map(Node)
    val edges = (1 to m).map(_ => UndirectedEdge(nodes(scanner.nextInt()-1),nodes(scanner.nextInt()-1)))
    val g = new Graph(nodes,edges)
    val result: String = g match {
      case g: Graph if g.isBusTopological => "bus topology"
      case g: Graph if g.isRingTopological => "ring topology"
      case g: Graph if g.isStarTopological => "star topology"
      case _ => "unknown topology"
    }
    out.println(result)
  }

  class Graph(val nodes: Seq[Node],val edges: Seq[UndirectedEdge]){

    nodes.foreach(_.clearNeighbours())
    edges.foreach{case UndirectedEdge(a,b) => {
      a.addNeighbour(b)
      b.addNeighbour(a)
    }}

    val isBusTopological: Boolean = {
      if(edges.length == nodes.length-1){
        nodes.count(_.neighbours.length == 1) == 2
      }else{
        false
      }
    }
    val isStarTopological: Boolean = {
      if(edges.length == nodes.length-1){
        nodes.count(_.neighbours.length == nodes.length-1) == 1
      }else{
        false
      }
    }
    val isRingTopological: Boolean = {
      if(edges.length == nodes.length){
        nodes.count(_.neighbours.length == 2) == nodes.length
      }else{
        false
      }
    }

  }
  case class Node(node: Int){
    val neighbours: ListBuffer[Node] = ListBuffer[Node]()
    def clearNeighbours(): Unit = neighbours.clear()
    def addNeighbour(n: Node): Unit = neighbours.append(n)
  }
  case class UndirectedEdge(a: Node, b: Node)
}

object NetworkTopology292B  extends App {
  import java.io.{BufferedReader, IOException, InputStreamReader}
  import java.util.StringTokenizer
  import java.io.{InputStream, PrintStream}
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val m = in.nextInt()
    val nodes = (1 to n).map(Node)
    val edges = (1 to m).map(_ => UndirectedEdge(nodes(in.nextInt()-1),nodes(in.nextInt()-1)))
    val myGraph = new Graph(nodes,edges)
    val result: String = myGraph match {
      case g: Graph if g.isBusTopological => "bus topology"
      case g: Graph if g.isRingTopological => "ring topology"
      case g: Graph if g.isStarTopological => "star topology"
      case _ => "unknown topology"
    }
    out.println(result)
  }

  class Graph(val nodes: Seq[Node],val edges: Seq[UndirectedEdge]){

    nodes.foreach(_.clearNeighbours())
    edges.foreach{case UndirectedEdge(a,b) => {
      a.addNeighbour(b)
      b.addNeighbour(a)
    }}

    val isBusTopological: Boolean = {
      if(edges.length == nodes.length-1){
        nodes.count(_.neighbours.length == 1) == 2
      }else{
        false
      }
    }
    val isStarTopological: Boolean = {
      if(edges.length == nodes.length-1){
        nodes.count(_.neighbours.length == nodes.length-1) == 1
      }else{
        false
      }
    }
    val isRingTopological: Boolean = {
      if(edges.length == nodes.length){
        nodes.count(_.neighbours.length == 2) == nodes.length
      }else{
        false
      }
    }

  }
  case class Node(node: Int){
    val neighbours: ListBuffer[Node] = ListBuffer[Node]()
    def clearNeighbours(): Unit = neighbours.clear()
    def addNeighbour(n: Node): Unit = neighbours.append(n)
  }
  case class UndirectedEdge(a: Node, b: Node)

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


Your favorite shop sells $$$n$$$ Kinder Surprise chocolate eggs. You know that exactly $$$s$$$ stickers and exactly $$$t$$$ toys are placed in $$$n$$$ eggs in total.Each Kinder Surprise can be one of three types:  it can contain a single sticker and no toy;  it can contain a single toy and no sticker;  it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$T$$$ lines contain three integers $$$n$$$, $$$s$$$ and $$$t$$$ each ($$$1 \le n \le 10^9$$$, $$$1 \le s, t \le n$$$, $$$s + t \ge n$$$) — the number of eggs, stickers and toys. All queries are independent.

Print $$$T$$$ integers (one number per query) — the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toy

NoteIn the first query, we have to take at least $$$6$$$ eggs because there are $$$5$$$ eggs with only toy inside and, in the worst case, we'll buy all of them.In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg.In the third query, we have to buy both eggs: one with a sticker and one with a toy.

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { i =>
      val n, s, t = ni()
      out.println(n - min(s, t) + 1)
    }
  }
}

import scala.io.StdIn._

object A_1187 extends App {
  val q = readInt()

  1 to q foreach { _ =>
    val Array(n, a, b) = readLine().split(" ").map(_.toInt)
    val answer = if (a + b == n) {
      Math.max(a, b) + 1
    } else {
      if (n == Math.max(a, b)) {
        Math.max(a, b) - Math.min(a, b) + 1
      } else {
        n - Math.min(a, b) + 1
      }
    }

    println(answer)
  }

}


Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type). If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of friends.  Then follow n data blocks that describe each friend's phone books. Each block is presented in the following form: first goes the line that contains integer si and string namei (0 ≤ si ≤ 100) — the number of phone numbers in the phone book of the i-th friend and the name of the i-th friend. The name is a non-empty sequence of uppercase and lowercase Latin letters, containing no more than 20 characters. Next si lines contain numbers as "XX-XX-XX", where X is arbitrary digits from 0 to 9.

In the first line print the phrase "If you want to call a taxi, you should call: ". Then print names of all friends whose phone books contain maximal number of taxi phone numbers.  In the second line print the phrase "If you want to order a pizza, you should call: ". Then print names of all friends who have maximal number of pizza phone numbers.  In the third line print the phrase "If you want to go to a cafe with a wonderful girl, you should call: ". Then print names of all friends who have maximal number of girls' phone numbers.  Print the names in the order in which they are given in the input data. Separate two consecutive names with a comma and a space. Each line should end with exactly one point. For clarifications concerning the output form, see sample tests. It is necessary that you follow the output form strictly. Extra spaces are not allowed.

If you want to call a taxi, you should call: Rogulenko.
If you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.
If you want to go to a cafe with a wonderful girl, you should call: Melnikov.

If you want to call a taxi, you should call: Gleb.
If you want to order a pizza, you should call: Gleb, Serega.
If you want to go to a cafe with a wonderful girl, you should call: Melnik.

If you want to call a taxi, you should call: Pachocki.
If you want to order a pizza, you should call: Kulczynski, Pachocki.
If you want to go to a cafe with a wonderful girl, you should call: Kulczynski.

NoteIn the first sample you are given four friends. Fedorov's phone book contains one taxi number and one pizza delivery number, Melnikov's phone book only has 3 numbers of girls, Rogulenko's one has 6 taxi numbers and one pizza delivery number, Kaluzhin's one contains 2 taxi numbers and one pizza delivery number.Thus, if you need to order a taxi, you should obviously call Rogulenko, if you need to order a pizza you should call anybody of the following: Rogulenko, Fedorov, Kaluzhin (each of them has one number). Melnikov has maximal number of phone numbers of girls.

import scala.util.DynamicVariable
object Main {
  private val inVar = new DynamicVariable[java.io.BufferedReader](new java.io.BufferedReader(new java.io.InputStreamReader(java.lang.System.in)))
  def in = inVar.value
  var MyFriends =new  Array[MyFriend](0)
  def MMM(): String = {
     var NamberType1:Int =0
     var NamberType2:Int =0
     var NamberType3:Int =0
     var FriendNamberType1:String = ""
     var FriendNamberType2:String = ""
     var FriendNamberType3:String = ""

     for(i<- 0 until MyFriends.length){
    	 if(MyFriends(i).NamberType1>NamberType1){
    	   NamberType1=MyFriends(i).NamberType1
    	 }
    	 if(MyFriends(i).NamberType2>NamberType2){
    	   NamberType2=MyFriends(i).NamberType2
    	 }
    	 if(MyFriends(i).NamberType3>NamberType3){
    	   NamberType3=MyFriends(i).NamberType3
    	 }
     }
    for(i<- 0 until MyFriends.length){
       if(MyFriends(i).NamberType1==NamberType1){
    	   if(FriendNamberType1==""){
    	     FriendNamberType1=MyFriends(i).Name
    	   }else{
    	     FriendNamberType1+=", "+MyFriends(i).Name
    	   }
    	 }
    	 if(MyFriends(i).NamberType2==NamberType2){
    	   if(FriendNamberType2==""){
    	     FriendNamberType2=MyFriends(i).Name
    	   }else{
    	     FriendNamberType2+=", "+MyFriends(i).Name
    	   }
    	 }
    	 if(MyFriends(i).NamberType3==NamberType3){
    	   if(FriendNamberType3==""){
    	     FriendNamberType3=MyFriends(i).Name
    	   }else{
    	     FriendNamberType3+=", "+MyFriends(i).Name
    	   }
    	 }
    }

    return "If you want to call a taxi, you should call: " + FriendNamberType1 + ".\n" + "If you want to order a pizza, you should call: " + FriendNamberType2+".\n" + "If you want to go to a cafe with a wonderful girl, you should call: " + FriendNamberType3+ ".\n"
  }

  def Read():String ={
    var result: String = ""
    try{
      result = in.readLine()
    }
    catch {
     case e: Exception => result=""
   }
    result
  }

  def main(args: Array[String]) {
    var CountFriends: Int = Read().toInt
    MyFriends= new  Array[MyFriend](CountFriends)
    for(i<- 0 until CountFriends){
      var line = Read()
      if(line !=""){
    	  var CountName = line.split(" ")
    			  var CountNambers: Int = CountName(0).toInt
    			  MyFriends(i)=new MyFriend(CountName(1),CountNambers)
    	  for(j<- 0 until CountNambers){
    		  MyFriends(i).Nambers(j)= new PhoneNumber(Read())
    	  }
    	  MyFriends(i).TypesOfNamber()
      }
    }
    println(MMM())
  }
}

class PhoneNumber(number: String) {
  var Number: String = number
  var TypeNumber: Int = GetTypeNumber(number)
  private def  GetTypeNumber(n:String): Int =  {
	if(number != null){
	  var number=n.replace("-","")
	if(number == new String (""+number(0)+number(0)+number(0)+number(0)+number(0)+number(0))){
	  return 1
	}else{
		for(i<- 0 until number.length-1){
			if(number(i).toInt <= number(i+1).toInt)
				return 3
		}
		return 2
	  }
	}
	return 3
  }
}

class MyFriend(name: String, countNumbers: Int){
  var Name:String = name
  var Nambers: Array[PhoneNumber] =new Array[PhoneNumber](countNumbers)
  var NamberType1:Int =0
  var NamberType2:Int =0
  var NamberType3:Int =0
  def TypesOfNamber(){
    for(j<- 0 until Nambers.length){
        if(Nambers(j).TypeNumber==1){
          NamberType1+=1
        }
        if(Nambers(j).TypeNumber==2){
          NamberType2+=1
        }
        if(Nambers(j).TypeNumber==3){
          NamberType3+=1
        }
    }

  }
}

import scala.io.Source

object Solution extends App {

  def classify(str: String) = {
    if (str.distinct.length == 1) 1
    else if (str.distinct.length == str.length && str.sorted.reverse == str) 2
    else 3
  }

  val in = Source.stdin.getLines()
  var n = in.next().toInt
  val data = (1 to n).map { _ =>
    val Array(countStr, name) = in.next().split(' ')
    val groups = (1 to countStr.toInt).map(_ => in.next().replaceAll("\\-", "")).map(classify)
      .groupBy(i => i).map(i => i._1 -> i._2.length)
    (groups.getOrElse(1, 0), groups.getOrElse(2, 0), groups.getOrElse(3, 0), name)
  }
  val maxTaxi = data.maxBy(_._1)._1
  val maxPizza = data.maxBy(_._2)._2
  val maxGirl = data.maxBy(_._3)._3
  println(data.filter(_._1 == maxTaxi)
    .map(_._4).mkString("If you want to call a taxi, you should call: ", ", ", "."))
  println(data.filter(_._2 == maxPizza)
    .map(_._4).mkString("If you want to order a pizza, you should call: ", ", ", "."))
  println(data.filter(_._3 == maxGirl)
    .map(_._4).mkString("If you want to go to a cafe with a wonderful girl, you should call: ", ", ", "."))
}

object Main {
  def isTaxi(str: String) = str forall (_ == str(0))
  def isPizza(str: String) = str sliding(2) forall(t => t(0) > t(1))

  def main(args: Array[String]) {
    val n = readInt()
    val map = scala.collection.mutable.LinkedHashMap[String, (Int, Int, Int)]()
    for(_ <- 1 to n) {
      val Array(k, name) = readLine().split(" ")
      var taxies = 0
      var pizzaes = 0
      var girls = 0
      for(_ <- 1 to k.toInt) {
        val str = readLine().replaceAll("\\-", "")
        if (isTaxi(str)) taxies += 1
        else if(isPizza(str)) pizzaes += 1
        else girls += 1
      }
      map(name.toString) = (taxies, pizzaes, girls)
    }
    val max1 = map.values.map(_._1).max
    println("If you want to call a taxi, you should call: " +
      map.filter(_._2._1 == max1).keys.mkString(", ") + ".")

    val max2 = map.values.map(_._2).max
    println("If you want to order a pizza, you should call: " +
      map.filter(_._2._2 == max2).keys.mkString(", ") + ".")

    val max3 = map.values.map(_._3).max
    println("If you want to go to a cafe with a wonderful girl, you should call: " +
      map.filter(_._2._3 == max3).keys.mkString(", ") + ".")
  }
}

import scala.util.DynamicVariable
object Main {
  private val inVar = new DynamicVariable[java.io.BufferedReader](new java.io.BufferedReader(new java.io.InputStreamReader(java.lang.System.in)))
  def in = inVar.value
  var MyFriends =new  Array[MyFriend](0)
  def MMM(): String = {
     var NamberType1:Int =0
     var NamberType2:Int =0
     var NamberType3:Int =0
     var FriendNamberType1:String = ""
     var FriendNamberType2:String = ""
     var FriendNamberType3:String = ""

     for(i<- 0 until MyFriends.length){
    	 if(MyFriends(i).NamberType1>NamberType1){
    	   NamberType1=MyFriends(i).NamberType1
    	 }
    	 if(MyFriends(i).NamberType2>NamberType2){
    	   NamberType2=MyFriends(i).NamberType2
    	 }
    	 if(MyFriends(i).NamberType3>NamberType3){
    	   NamberType3=MyFriends(i).NamberType3
    	 }
     }
    for(i<- 0 until MyFriends.length){
       if(MyFriends(i).NamberType1==NamberType1){
    	   if(FriendNamberType1==""){
    	     FriendNamberType1=MyFriends(i).Name
    	   }else{
    	     FriendNamberType1+=", "+MyFriends(i).Name
    	   }
    	 }
    	 if(MyFriends(i).NamberType2==NamberType2){
    	   if(FriendNamberType2==""){
    	     FriendNamberType2=MyFriends(i).Name
    	   }else{
    	     FriendNamberType2+=", "+MyFriends(i).Name
    	   }
    	 }
    	 if(MyFriends(i).NamberType3==NamberType3){
    	   if(FriendNamberType3==""){
    	     FriendNamberType3=MyFriends(i).Name
    	   }else{
    	     FriendNamberType3+=", "+MyFriends(i).Name
    	   }
    	 }
    }

    return "If you want to call a taxi, you should call: " + FriendNamberType1 + ".\n" + "If you want to order a pizza, you should call: " + FriendNamberType2+".\n" + "If you want to go to a cafe with a wonderful girl, you should call: " + FriendNamberType3+ ".\n"
  }

  def Read():String ={
    var result: String = ""
    try{
      result = in.readLine()
    }
    catch {
     case e: Exception => result=""
   }
    result
  }

  def main(args: Array[String]) {
    var CountFriends: Int = Read().toInt
    MyFriends= new  Array[MyFriend](CountFriends)
    for(i<- 0 until CountFriends){
      var line = Read()
      if(line !=""){
    	  var CountName = line.split(" ")
    			  var CountNambers: Int = CountName(0).toInt
    			  MyFriends(i)=new MyFriend(CountName(1),CountNambers)
    	  for(j<- 0 until CountNambers){
    		  MyFriends(i).Nambers(j)= new PhoneNumber(Read())
    	  }
    	  MyFriends(i).TypesOfNamber()
      }
    }
    println(MMM())
  }
}

class PhoneNumber(number: String) {
  var Number: String = number
  var TypeNumber: Int = GetTypeNumber(number)
  private def  GetTypeNumber(n:String): Int =  {
	if(number != null){
	  var number=n.replace("-","")
	if(number == new String (""+number(0)+number(0)+number(0)+number(0)+number(0)+number(0))){
	  return 1
	}else{
		for(i<- 0 until number.length-1){
			if(number(i) < number(i+1))
				return 3
		}
		return 2
	  }
	}
	return 3
  }
}

class MyFriend(name: String, countNumbers: Int){
  var Name:String = name
  var Nambers: Array[PhoneNumber] =new Array[PhoneNumber](countNumbers)
  var NamberType1:Int =0
  var NamberType2:Int =0
  var NamberType3:Int =0
  def TypesOfNamber(){
    for(j<- 0 until Nambers.length){
        if(Nambers(j).TypeNumber==1){
          NamberType1+=1
        }
        if(Nambers(j).TypeNumber==2){
          NamberType2+=1
        }
        if(Nambers(j).TypeNumber==3){
          NamberType3+=1
        }
    }

  }
}

import scala.util.DynamicVariable
object Main {
  private val inVar = new DynamicVariable[java.io.BufferedReader](new java.io.BufferedReader(new java.io.InputStreamReader(java.lang.System.in)))
  def in = inVar.value
  var MyFriends =new  Array[MyFriend](0)
  def MMM(): String = {
     var NamberType1:Int =0
     var NamberType2:Int =0
     var NamberType3:Int =0
     var FriendNamberType1:String = ""
     var FriendNamberType2:String = ""
     var FriendNamberType3:String = ""

     for(i<- 0 until MyFriends.length){
    	 if(MyFriends(i).NamberType1>NamberType1){
    	   NamberType1=MyFriends(i).NamberType1
    	 }
    	 if(MyFriends(i).NamberType2>NamberType2){
    	   NamberType2=MyFriends(i).NamberType2
    	 }
    	 if(MyFriends(i).NamberType3>NamberType3){
    	   NamberType3=MyFriends(i).NamberType3
    	 }
     }
    for(i<- 0 until MyFriends.length){
       if(MyFriends(i).NamberType1==NamberType1){
    	   if(FriendNamberType1==""){
    	     FriendNamberType1=MyFriends(i).Name
    	   }else{
    	     FriendNamberType1+=", "+MyFriends(i).Name
    	   }
    	 }
    	 if(MyFriends(i).NamberType2==NamberType2){
    	   if(FriendNamberType2==""){
    	     FriendNamberType2=MyFriends(i).Name
    	   }else{
    	     FriendNamberType2+=", "+MyFriends(i).Name
    	   }
    	 }
    	 if(MyFriends(i).NamberType3==NamberType3){
    	   if(FriendNamberType3==""){
    	     FriendNamberType3=MyFriends(i).Name
    	   }else{
    	     FriendNamberType3+=", "+MyFriends(i).Name
    	   }
    	 }
    }

    return "If you want to call a taxi, you should call: " + FriendNamberType1 + ".\n" + "If you want to order a pizza, you should call: " + FriendNamberType2+".\n" + "If you want to go to a cafe with a wonderful girl, you should call: " + FriendNamberType3+ ".\n"
  }

  def Read():String ={
    var result: String = ""
    try{
      result = in.readLine()
    }
    catch {
     case e: Exception => result=""
   }
    result
  }

  def main(args: Array[String]) {
    var CountFriends: Int = Read().toInt
    MyFriends= new  Array[MyFriend](CountFriends)
    for(i<- 0 until CountFriends){
      var line = Read()
      if(line !=""){
    	  var CountName = line.split(" ")
    			  var CountNambers: Int = CountName(0).toInt
    			  MyFriends(i)=new MyFriend(CountName(1),CountNambers)
    	  for(j<- 0 until CountNambers){
    		  MyFriends(i).Nambers(j)= new PhoneNumber(Read())
    	  }
    	  MyFriends(i).TypesOfNamber()
      }
    }
    println(MMM())
  }
}

class PhoneNumber(number: String) {
  var Number: String = number
  var TypeNumber: Int = GetTypeNumber(number)
  private def  GetTypeNumber(number:String): Int =  {
	if(number != null){
	  number.replace("-","")
	if(number == number(0)+number(0)+number(0)+number(0)+number(0)+number(0)){
	  return 1
	}else{
		for(i<- 0 until number.length-1){
			if(number(i) < number(i+1))
				return 3
		}
		return 2
	  }
	}
	return 3
  }
}

class MyFriend(name: String, countNumbers: Int){
  var Name:String = name
  var Nambers: Array[PhoneNumber] =new Array[PhoneNumber](countNumbers)
  var NamberType1:Int =0
  var NamberType2:Int =0
  var NamberType3:Int =0
  def TypesOfNamber(){
    for(j<- 0 until Nambers.length){
        if(Nambers(j).TypeNumber==1){
          NamberType1+=1
        }
        if(Nambers(j).TypeNumber==2){
          NamberType2+=1
        }
        if(Nambers(j).TypeNumber==3){
          NamberType3+=1
        }
    }

  }
}


A number $$$a_2$$$ is said to be the arithmetic mean of two numbers $$$a_1$$$ and $$$a_3$$$, if the following condition holds: $$$a_1 + a_3 = 2\cdot a_2$$$. We define an arithmetic mean deviation of three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ as follows: $$$d(a_1, a_2, a_3) = |a_1 + a_3 - 2 \cdot a_2|$$$.Arithmetic means a lot to Jeevan. He has three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ and he wants to minimize the arithmetic mean deviation $$$d(a_1, a_2, a_3)$$$. To do so, he can perform the following operation any number of times (possibly zero):  Choose $$$i, j$$$ from $$$\{1, 2, 3\}$$$ such that $$$i \ne j$$$ and increment $$$a_i$$$ by $$$1$$$ and decrement $$$a_j$$$ by $$$1$$$ Help Jeevan find out the minimum value of $$$d(a_1, a_2, a_3)$$$ that can be obtained after applying the operation any number of times.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 5000)$$$  — the number of test cases. The first and only line of each test case contains three integers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ $$$(1 \le a_1, a_2, a_3 \le 10^{8})$$$.

For each test case, output the minimum value of $$$d(a_1, a_2, a_3)$$$ that can be obtained after applying the operation any number of times.

NoteNote that after applying a few operations, the values of $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ may become negative.In the first test case, $$$4$$$ is already the Arithmetic Mean of $$$3$$$ and $$$5$$$.$$$d(3, 4, 5) = |3 + 5 - 2 \cdot 4| = 0$$$In the second test case, we can apply the following operation:$$$(2, 2, 6)$$$ $$$\xrightarrow[\text{increment $$$a_2$$$}]{\text{decrement $$$a_1$$$}}$$$ $$$(1, 3, 6)$$$$$$d(1, 3, 6) = |1 + 6 - 2 \cdot 3| = 1$$$It can be proven that answer can not be improved any further.In the third test case, we can apply the following operations:$$$(1, 6, 5)$$$ $$$\xrightarrow[\text{increment $$$a_3$$$}]{\text{decrement $$$a_2$$$}}$$$ $$$(1, 5, 6)$$$ $$$\xrightarrow[\text{increment $$$a_1$$$}]{\text{decrement $$$a_2$$$}}$$$ $$$(2, 4, 6)$$$$$$d(2, 4, 6) = |2 + 6 - 2 \cdot 4| = 0$$$

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

  override def solve(io: IO) = io.repeat {
    val a1, a2, a3 = io.read[Int]
    val ans = (a1 + a3 - 2*a2) % 3
    io.write(if (ans == 0) 0 else 1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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

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

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

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

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

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

    val t = readInt()
    for (tt <- 1 to t) {
        val a = readInt()
        val b = readInt()
        val c = readInt()
        val k = a + c - 2 * b
        if (k % 3 == 0)
            writer.println(0)
        else
            writer.println(1)
    }
    writer.flush()
}

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

  override def solve(io: IO) = io.repeat {
    val a1, a2, a3 = io.read[Int]
    val ans = (a1 + a3 - 2*a2) mod 3
    io.write(ans)
  }

  implicit class IntegralExtensions[A](x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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