object CF506B extends App {
  import scala.io.StdIn
  StdIn.readLine
  val problems = StdIn.readLine.split(' ').map(_.toInt)

  var i = 0
  var max = 0
  var count = 0
  var difficulty = -1
  while (i < problems.length) {
    if (difficulty == -1 || problems(i) <= difficulty * 2) {
      count += 1
      if (count > max)
        max = count
      difficulty = problems(i)
      i += 1
    } else {
      count = 0
      difficulty = -1
    }
  }

  println(max)
}

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val A = map(N)(_ => sc.nextInt())

    var mx = 0
    var cnt = 0
    rep(N - 1) { i =>
      if (A(i + 1) <= A(i) * 2) {
        cnt += 1
        mx = max(mx, cnt)
      }
      else cnt = 0
    }

    out.println(mx + 1)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt

    var maxLen = 1
    var curLen = 1
    var left = in.nextInt

    for (_ <- 1 until n) {
      val right = in.nextInt
      if (left * 2 >= right) {
        curLen = curLen + 1
      } else {
        maxLen = Math.max(maxLen, curLen)
        curLen = 1
      }
      left = right
    }

    maxLen = Math.max(maxLen, curLen)
    println(maxLen)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextLong: Long = {
      next.toLong
    }

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

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

}

//package com.test.tasks

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

  readInt()
  print(maxContext(readLine().split(" ").map(_.toInt).toList))

  def maxContext(diffs: List[Int]): Int = {
    def loop(diffs: List[Int], last: Int,  max: Int, cur: Int): Int = diffs match {
      case Nil => Math.max(max, cur)
      case x :: xs =>
        if (x <= last * 2) loop(xs, x, max, cur+1)
        else loop(xs, x, if (cur > max) cur else max, 1)
    }
    loop(diffs.tail, diffs.head, 1, 1)
  }

}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val a: Array[Int] = Array.fill(n)(in.nextInt)
    var ans = 1
    var maxAns = 1
    (1 until n).foreach { i =>
      if (a(i) <= a(i - 1) * 2) {
        ans += 1
        maxAns = math.max(maxAns, ans)
      } else
        ans = 1
    }
    println(maxAns)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

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

}

//package com.test.tasks

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

  readInt()
  print(maxContext(readLine().split(" ").map(_.toInt).toList))

  def maxContext(diffs: List[Int]): Int = {
    def loop(diffs: List[Int], last: Int,  max: Int, cur: Int): Int = diffs match {
      case Nil => Math.max(max, cur)
      case x :: xs =>
        if (x <= last * 2) loop(xs, x, max, cur+1)
        else loop(xs, x, if (cur > max) cur else max, 1)
    }
    loop(diffs.tail, diffs.head, 1, 1)
  }

}

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

  readInt()
  print(maxContext(readLine().split(" ").map(_.toInt).toList))

  def maxContext(diffs: List[Int]): Int = {
    def loop(diffs: List[Int], last: Int,  max: Int, cur: Int): Int = diffs match {
      case Nil => Math.max(max, cur)
      case x :: xs =>
        if (x <= last * 2) loop(xs, x, max, cur+1)
        else loop(xs, x, if (cur > max) cur else max, 1)
    }
    loop(diffs.tail, diffs.head, 1, 1)
  }

}

//package com.test.tasks

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

  readInt()
  print(maxContext(readLine().split(" ").map(_.toInt).toList))

  def maxContext(diffs: List[Int]): Int = {
    def loop(diffs: List[Int], last: Int,  max: Int, cur: Int): Int = diffs match {
      case Nil => Math.max(max, cur)
      case x :: xs =>
        if (x <= last * 2) loop(xs, x, max, cur+1)
        else loop(xs, x, if (cur > max) cur else max, 1)
    }
    loop(diffs.tail, diffs.head, 1, 1)
  }

}

//package com.test.tasks

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

  readInt()
  print(1)

  def maxContext(diffs: List[Int]): Int = {
    def loop(diffs: List[Int], last: Int,  max: Int, cur: Int): Int = diffs match {
      case Nil => Math.max(max, cur)
      case x :: xs =>
        if (x <= last * 2) loop(xs, x, max, cur+1)
        else loop(xs, x, if (cur > max) cur else max, 1)
    }
    loop(diffs.tail, diffs.head, 1, 1)
  }

}

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

  readInt()
  print(2)

  def maxContext(diffs: List[Int]): Int = {
    def loop(diffs: List[Int], last: Int,  max: Int, cur: Int): Int = diffs match {
      case Nil => Math.max(max, cur)
      case x :: xs =>
        if (x <= last * 2) loop(xs, x, max, cur+1)
        else loop(xs, x, if (cur > max) cur else max, 1)
    }
    loop(diffs.tail, diffs.head, 1, 1)
  }

}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val arr = new Array[Int](n)

    for (i <- 0 until n) {
      arr(i) = in.nextInt
    }

    var maxLen = 1
    var curLen = 1
    var left = arr(0)

    for (i <- 1 until n) {
      if (left * 2 >= arr(i)) {
        curLen = curLen + 1
      } else {
        maxLen = Math.max(maxLen, curLen)
        curLen = 1
        left = arr(i)
      }
    }

    maxLen = Math.max(maxLen, curLen)
    println(maxLen)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextLong: Long = {
      next.toLong
    }

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

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

}

//package com.test.tasks

import scala.annotation.tailrec

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

  readInt()
  val diffs = readLine().split(" ").map(_.toInt).toList

  print(maxContext(diffs.tail, 1, 1, diffs.head))

  @tailrec
  def maxContext(diffs: List[Int], max: Int, cur: Int, y: Int): Int = diffs match {
    case Nil => max
    case x :: xs =>
      if (y * 2 < x) maxContext(xs, if (max < cur) cur else max, 1, x)
      else maxContext(xs, max, cur+1, x)
  }

}


import java.util.Scanner

import scala.collection.immutable

object A extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val a: Array[Array[Int]] = Array.ofDim(n, n)
  for(i <- 0 until n; j <- 0 until n) {
    a(i)(j) = sc.nextInt()
  }

  val isValid = for {
    i <- 0 until n
    j <- 0 until n
    if a(i)(j) != 1
  } yield genPairs(i, j, n).exists {
    case ((x1, y1), (x2, y2)) =>
      a(x1)(y1) + a(x2)(y2) == a(i)(j)
  }

  if (isValid.forall(_ == true)) {
    println("Yes")
  } else {
    println("No")
  }

  def genPairs(i: Int, j: Int, n: Int): Seq[((Int, Int), (Int, Int))] = {
    val col = (0 until n).map(x => (x,j)).filterNot(p => p._1 == i && p._2 == j)
    val row = (0 until n).map(y => (i,y)).filterNot(p => p._1 == i && p._2 == j)
    for {
      c <- col
      r <- row
    } yield (c, r)
  }
}

object zero extends App {

  val n: Int = scala.io.StdIn.readInt()

  val square: Array[Array[Int]] = Array.ofDim(n, n)

  for (i <- 0 until square.length)
    square(i) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  var result = true

  for {i <- 0 until square.length
       j <- 0 until square(i).length
       if result && square(i)(j) != 1} {

    def answer(arr: Array[Array[Int]], row: Int, col: Int): Boolean = {
      val rows =
        for (j <- 0 until arr(row).length if j != col)
          yield square(row)(j)

      val columns =
        for (i <- 0 until arr.length if i != row)
          yield square(i)(col)

      rows.flatMap(r => columns.map(c => c + r))
        .exists(_ == square(row)(col))
    }

    if (!answer(square, i, j))
      result = false
  }

  println(if (result) "Yes" else "No")
}

// 821/A - Okabe and Future Gadget Laboratory
object Problem821A extends App {

  val n: Int = scala.io.StdIn.readInt()

  val square: Array[Array[Int]] = Array.ofDim(n, n)

  for (i <- square.indices)
    square(i) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  var result = true

  for {i <- square.indices
       j <- square(i).indices
       if result && square(i)(j) != 1} {

    val columns =
      for (c <- square(i).indices if c != j)
        yield square(i)(c)

    val rows =
      for (r <- square.indices if r != i)
        yield square(r)(j)

    result = columns.flatMap(c => rows.map(r => c + r))
      .contains(square(i)(j))
  }

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

}

// 821/A - Okabe and Future Gadget Laboratory
object Problem821A extends App {

  // Getting the integer `n` representing the size of the lab
  val n: Byte = scala.io.StdIn.readByte()

  // Creating the `n` by `n` square grid of integers
  val square: Array[Array[Int]] = Array.ofDim(n, n)

  // Filling the grid with integers
  for (i <- square.indices)
    square(i) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  var result = true

  for {i <- square.indices
       j <- square(i).indices
       if result && square(i)(j) != 1} {

    def answer(arr: Array[Array[Int]], row: Int, col: Int): Boolean = {
      val columns =
        for (j <- arr(row).indices if j != col)
          yield square(row)(j)

      val rows =
        for (i <- arr.indices if i != row)
          yield square(i)(col)

      columns.flatMap(c => rows.map(r => r + c))
        .contains(square(row)(col))
    }

    if (!answer(square, i, j))
      result = false
  }

  // Printing the answer
  println(if (result) "Yes" else "No")

}

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

import scala.collection.mutable

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val arr = new Array[Array[Int]](n)
    for (i <- 0 until n) {
      arr(i) = new Array[Int](n)
      for (j <- 0 until n) {
        arr(i)(j) = nextInt
      }
    }
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        var flag = false
        if (arr(i)(j) != 1) {
          for (k <- 0 until n) {
            for (l <- 0 until n) {
              if (k != j && l != i && arr(i)(k) + arr(l)(j) == arr(i)(j)) {
                flag = true
              }
            }
          }
          if (!flag) {
            out.println("No")
            return 0
          }
        }

      }
    }
    out.println("Yes")
    return 0
  }
}

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

  override def apply(io: IO) = {import io.{read, write}
    val n = read[Int]
    val lab = IndexedSeq.fill(n, n)(read[Int])
    def indices = (0 until n) X (0 until n)

    def isOkay(r: Int, c: Int) = {
      lab(r)(c) == 1 || indices.exists({case (i, j) => lab(i)(c) + lab(r)(j) == lab(r)(c)})
    }

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

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

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

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

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

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

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


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

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

}


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

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


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


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

}


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

  }
}