import scala.io.StdIn._

object _361A extends App {
  readInt
  val s = readLine.toCharArray.map(_.asDigit).toSet
  val unique =
    List(
      Set(1, 4, 7, 0),
      Set(1, 2, 3),
      Set(3, 6, 9, 0),
      Set(7, 0, 9))
  val ans = unique.forall(x => x.intersect(s).nonEmpty)
  println(if (ans) "YES" else "NO")
}

import scala.io.StdIn._
import scala.util.control._

object cf689A {
    def main (args: Array[String]) {
        val n = readInt();
        val s = readLine();

        if (judge(s, up) || judge(s, down) || judge(s, left) || judge(s, right)) {
            println("NO");
        } else {
            println("YES");
        }
    }

    def judge (s:String, f: Char => Boolean) : Boolean = {
        var res:Boolean = true;
        for (i <- 0 until s.length()) {
            if (f(s(i)) == false) {
                res = false
            }
        }
        return res;
    }

    def up (c:Char) : Boolean = {
        if (c == '0' || c > '3') return true;
        else return false;
    }

    def down (c:Char) : Boolean = {
        if (c == '8' || (c < '7' && c > '0')) return true;
        else return false;
    }

    def left (c:Char) : Boolean = {
        if ((c - '0') % 3 == 1 || c == '0') return false;
        else return true;
    }

    def right (c:Char) : Boolean = {
        if ((c - '0') % 3 == 0 || c == '0') return false;
        else return true;
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()
  val up = Set('1', '2', '3')
  val down = Set('7', '0', '9')
  val right = Set('3', '6', '9', '0')
  val left = Set('1', '4', '7', '0')
  List(left, right, down, up).exists(set => line.forall(i => !set.contains(i))) match {
    case false => println("YES")
    case true => println("NO")
  }
}

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

object _689A extends CodeForcesApp {

  val moves = Map(
    1 -> "DR",
    2 -> "DLR",
    3 -> "DL",
    4 -> "UDR",
    5 -> "UDLR",
    6 -> "UDL",
    7 -> "UR",
    8 -> "UDLR",
    9 -> "UL",
    0 -> "U"
  ).mapValues(_.toSet)

  override def apply(io: IO) = {import io.{read, write}
    val (_, d) = read[(Int, String)]
    val ans = "UDLR" find {c => d.forall(i => moves(i - '0').contains(c))}
    write(ans.isEmpty.toYesNo)
  }
}
/****************************[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 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 = t.head.ensuring(t.size == 1)
    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 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
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  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(n.min(x, y), n.max(x, y), 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
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

import java.util.Scanner

object Main{
  def ctoi(c: Char) = c.toInt - '0'.toInt

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

    val dp = new Array[Boolean](10)

    val key = Array((1, 3),
      (0,0), (1,0), (2,0),
      (0,1), (1,1), (2,1),
      (0,2), (1,2), (2,2)
    )

    var xl = 9
    var xr = -1
    var yl = 9
    var yr = -1

    for(i <- 0 until n){
      val now = ctoi(s(i))
      dp(now) = true
      val (nx, ny) = key(now)

      xl = Math.min(xl, nx)
      xr = Math.max(xr, nx)
      yl = Math.min(yl, ny)
      yr = Math.max(yr, ny)
    }

    val xz = xr - xl + 1
    val yz = yr - yl + 1

    val yes = "YES"
    val no = "NO"

    if(yz == 4)
      println(yes)
    else if(xz == 3 && yz == 3){
      if(dp(0) || (dp(8) && !dp(7) && !dp(9)))
        println(no)
      else
        println(yes)
    }
    else
      println(no)
  }
}

import scala.io.StdIn._

object A extends App {
  readInt()
  val M = readLine().toCharArray.map(_.asDigit)

  def delta(a: Int, b: Int): (Int, Int) = {
    val (y1, x1) = pos(a)
    val (y2, x2) = pos(b)
    (y2 - y1, x2 - x1)
  }

  def pos(a: Int) = {
    if (List(1, 2, 3).contains(a)) (0, a - 1)
    else if (List(4, 5, 6).contains(a)) (1, a % 4)
    else if (List(7, 8, 9).contains(a)) (2, a % 7)
    else (3, 1)
  }

  var prev = M.head
  val Deltas = M.tail.map { curr =>
    val d = delta(prev, curr)
    prev = curr
    d
  }

  def canMoveFromThisPoint(startY: Int, startX: Int): Boolean = {
    var y = startY
    var x = startX

    Deltas.foreach { case (dy, dx) =>
      y += dy
      x += dx

      if (y < 0 || x < 0 || y > 3 || x >= 3) return false
      else if (y == 3 && x != 1) return false
    }

    true
  }

  def existDifferentPath: Boolean = {
    val (startY, startX) = pos(M.head)
    for {
      y <- 0 to 3
      x <- 0 to 2
    } {
      val isIllegal = (y == 3 && x != 1) || (y == startY && x == startX)
      if (!isIllegal && canMoveFromThisPoint(y, x)) return true
    }

    false
  }

  val unique = !existDifferentPath
  println(if (unique) "YES" else "NO")
}

object main
{
	def main(args : Array[String] )
	{
		var n = Console.readLine.toInt;
		var str = Console.readLine;

		var pos = Array(Array(4,2),Array(1,1),Array(1,2),Array(1,3),Array(2,1),Array(2,2),Array(2,3),Array(3,1),Array(3,2),Array(3,3));

		var cnt = 0;
		var a = 0;
		for (a <- 0 to 9 )
		{
			var nowx = pos(a)(0);
			var nowy = pos(a)(1);
			var able = true;
			var b = 0;
			for (b <- 0 to n-2)
			{
				var dx = pos(str.charAt(b+1)-'0')(0)-pos(str.charAt(b)-'0')(0);
				var dy = pos(str.charAt(b+1)-'0')(1)-pos(str.charAt(b)-'0')(1);
				nowx += dx;
				nowy += dy;
				if (nowx < 1 || nowy < 1 || nowy>3) able=false;
				if (nowx>3 && (nowx!=4 || nowy!=2)) able=false;
			}
			if (able) cnt+=1;
		}
		if (cnt==1) println("YES");
		else println("NO");
}
}

import scala.io.StdIn._
import scala.util.control._

object cf689A {
    def main (args: Array[String]) {
        val n = readInt();
        val s = readLine();

        if (judge(s, up) || judge(s, down) || judge(s, left) || judge(s, right)) {
            println("NO");
        } else {
            println("YES");
        }
    }

    def judge (s:String, f: Char => Boolean) : Boolean = {
        var res:Boolean = true;
        for (i <- 0 until s.length()) {
            if (f(s(i)) == false) {
                res = false
            }
        }
        return res;
    }

    def up (c:Char) : Boolean = {
        if (c == '0' || c > '3') return true;
        else return false;
    }

    def down (c:Char) : Boolean = {
        if (c == '8' || c < '7') return true;
        else return false;
    }

    def left (c:Char) : Boolean = {
        if ((c - '0') % 3 == 1 || c == '0') return false;
        else return true;
    }

    def right (c:Char) : Boolean = {
        if ((c - '0') % 3 == 0 || c == '0') return false;
        else return true;
    }
}

import scala.io.StdIn._
import scala.util.control._

object cf689A {
    def main (args: Array[String]) {
        val n = readInt();
        val s = readLine();

        if (judge(s, up) || judge(s, down) || judge(s, left) || judge(s, right)) {
            println("NO");
        } else {
            println("YES");
        }
    }

    def judge (s:String, f: Char => Boolean) : Boolean = {
        var res:Boolean = true;
        for (i <- 0 until s.length()) {
            if (f(s(i)) == false) {
                res = false
            }
        }
        return res;
    }

    def up (c:Char) : Boolean = {
        if (c == '0' || c > '3') return true;
        else return false;
    }

    def down (c:Char) : Boolean = {
        if (c == '8' || c < '7') return true;
        else return false;
    }

    def left (c:Char) : Boolean = {
        if ((c - '0') % 3 == 1) return true;
        else return false;
    }

    def right (c:Char) : Boolean = {
        if ((c - '0') % 3 == 0 && c != '0') return true;
        else return false;
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()
  val up = Set('1', '2', '3')
  val down = Set('7', '0', '9')
  val right = Set('3', '6', '9', '0')
  val left = Set('1', '4', '7', '0')
  List(left, up, down, up).exists(set => line.forall(i => !set.contains(i))) match {
    case false => println("YES")
    case true => println("NO")
  }
}

import java.util.Scanner

object Main{
  def ctoi(c: Char) = c.toInt - '0'.toInt

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

    val key = Array((1, 3),
      (0,0), (1,0), (2,0),
      (0,1), (1,1), (2,1),
      (0,2), (1,2), (2,2)
    )

    var xl = 9
    var xr = -1
    var yl = 9
    var yr = -1

    for(i <- 0 until n){
      val (nx, ny) = key(ctoi(s(i)))
      xl = Math.min(xl, nx)
      xr = Math.max(xr, nx)
      yl = Math.min(yl, ny)
      yr = Math.max(yr, ny)
    }

    val xz = xr - xl + 1
    val yz = yr - yl + 1

    val yes = "YES"
    val no = "NO"

    if(yz == 4)
      println(yes)
    else if(xz == 3 && yz == 3)
      println(yes)
    else
      println(no)
  }
}

import scala.io.StdIn._

object A extends App {
  readInt()
  val M = readLine().toCharArray.map(_.asDigit)

  def delta(a: Int, b: Int): (Int, Int) = {
    val (y1, x1) = pos(a)
    val (y2, x2) = pos(b)
    (y2 - y1, x2 - x1)
  }

  def pos(a: Int) = {
    if (List(1, 2, 3).contains(a)) (0, a - 1)
    else if (List(4, 5, 6).contains(a)) (1, a % 4)
    else if (List(7, 8, 9).contains(a)) (2, a % 7)
    else (3, 1)
  }

  var prev = M.head
  val Deltas = M.tail.map { curr =>
    val d = delta(prev, curr)
    prev = curr
    d
  }

  def canMoveFromThisPoint(startY: Int, startX: Int): Boolean = {
    var y = startY
    var x = startX

    Deltas.foreach { case (dy, dx) =>
      y += dy
      x += dx

      if (y < 0 || x < 0 || y > 3 || x >= 3) return false
      else if (y == 3 && x != 1) return false
    }

    true
  }

  def existDifferentPath: Boolean = {
    val (startY, startX) = pos(M.head)
    for {
      y <- 0 to 3
      x <- 0 to 2
      if y != startY && x != startX
    } {
      if (canMoveFromThisPoint(y, x)) return true
    }

    false
  }

  val unique = !existDifferentPath
  println(if (unique) "YES" else "NO")
}

import scala.io.StdIn._

object A extends App {
  readInt()
  val M = readLine().toCharArray.map(_.asDigit)

  def delta(a: Int, b: Int): (Int, Int) = {
    val (y1, x1) = pos(a)
    val (y2, x2) = pos(b)
    (y2 - y1, x2 - x1)
  }

  def pos(a: Int) = {
    if (List(1, 2, 3).contains(a)) (0, a - 1)
    else if (List(4, 5, 6).contains(a)) (1, a % 4)
    else if (List(7, 8, 9).contains(a)) (2, a % 7)
    else (3, 1)
  }

  var prev = M.head
  val Deltas = M.tail.map { curr =>
    val d = delta(prev, curr)
    prev = curr
    d
  }

  def canMoveFromThisPoint(startY: Int, startX: Int): Boolean = {
    var y = startY
    var x = startX

    Deltas.foreach { case (dy, dx) =>
      y += dy
      x += dx

      if (y < 0 || x < 0 || y > 3 || x >= 3) return false
      else if (y == 3 && x != 1) return false
    }

    true
  }

  def existDifferentPath: Boolean = {
    val (startY, startX) = pos(M.head)
    for {
      y <- 0 to 3
      x <- 0 to 2
      if y != startY && x != startX
    } {
      val isIllegal = y == 3 && x != 1
      if (!isIllegal && canMoveFromThisPoint(y, x)) return true
    }

    false
  }

  val unique = !existDifferentPath
  println(if (unique) "YES" else "NO")
}

object main
{
	def main(args : Array[String] )
	{
		var n = Console.readLine.toInt;
		var str = Console.readLine;

		var a = 0;

		var minx = 3;
		var miny = 3;
		var maxx = 1;
		var maxy = 1;

		for ( a <- 0 to n-1 )
		{
			if (str.charAt(a)<='3')
			{
				minx=1;
			}
			if (str.charAt(a)<='6' && minx==3)
			{
				minx=2;
			}
			if (str.charAt(a)>='7')
			{
				maxx=3;
			}
			if (str.charAt(a)>='4' && maxx==1)
			{
				maxx=2;
			}
			if (str.charAt(a)=='1' || str.charAt(a)=='4' || str.charAt(a)=='7')
			{
				miny=1;
			}
			if ((str.charAt(a)=='2' || str.charAt(a)=='5' || str.charAt(a)=='8'))
			{
				if (miny==3)
				{
					miny=2;
				}
				if (maxy==1)
				{
					maxy=2;
				}
			}
			if (str.charAt(a)=='3' || str.charAt(a)=='6' || str.charAt(a)=='9')
			{
				maxy=3;
			}
		}
		if (minx==1 && maxx==3 && miny==1 && maxy==3)
		{
			println("YES");
		}
		else
		{
			println("NO");
		}
	}
}

object main
{
	def main(args : Array[String] )
	{
		var n = Console.readLine.toInt;
		var str = Console.readLine;

		var a = 0;

		var minx = 3;
		var miny = 3;
		var maxx = 1;
		var maxy = 1;

		for ( a <- 0 to n-1 )
		{
			if (str.charAt(a)<='3')
			{
				minx=1;
			}
			if (str.charAt(a)<='6' && minx==3)
			{
				minx=2;
			}
			if (str.charAt(a)>='7')
			{
				maxx=3;
			}
			if (str.charAt(a)>='4' && maxx==1)
			{
				maxx=2;
			}
			if (str.charAt(a)=='1' || str.charAt(a)=='4' || str.charAt(a)=='7')
			{
				miny=1;
			}
			if ((str.charAt(a)=='2' || str.charAt(a)=='5' || str.charAt(a)=='8'))
			{
				if (miny==3)
				{
					miny=2;
				}
				if (maxy==1)
				{
					maxy=2;
				}
			}
			if (str.charAt(a)=='3' || str.charAt(a)=='6' || str.charAt(a)=='9')
			{
				maxx=3;
			}
		}
		if (minx==1 && maxx==3 && miny==1 && maxy==3)
		{
			println("YES");
		}
		else
		{
			println("NO");
		}
	}
}


//package codeforces.contest1213

object EqualizingByDivision {

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

    val maxElement = elements.max

    val frequency = Array.ofDim[Int](maxElement + 1, 20) // frequency with steps

    for (e <- elements) {
      var temp = e
      var i = 0
      while (temp > 0) {
        frequency(temp)(i) += 1

        i += 1
        temp = temp / 2
      }
    }

    println {
      (1 to maxElement).foldLeft(Int.MaxValue) {
        case (acc, e) =>
          val (steps, count) = frequency(e).indices
            .foldLeft((0, 0)) {
              case ((steps, count), i) =>
                val c = frequency(e)(i)
                if (c != 0 && count < k)
                  if (count + c <= k) (steps + i * c, count + c)
                  else (steps + i * (k - count), k)
                else
                  (steps, count)
            }

          if (count == k) acc min steps else acc
      }
    }
  }
}

//package codeforces.contest1213

object EqualizingByDivision {

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

    val maxElement = elements.max

    val frequency = Array.ofDim[Int](maxElement + 1, 20) // frequency with steps

    for (e <- elements) {
      var temp = e
      var i = 0
      while (temp > 0) {
        frequency(temp)(i) += 1

        i += 1
        temp = temp / 2
      }
    }

    println {
      (1 to maxElement).foldLeft(Int.MaxValue) {
        case (acc, e) =>
          val (steps, count) = frequency(e).indices
            .foldLeft((0, 0)) {
              case ((steps, count), i) =>
                val c = frequency(e)(i)
                if (c != 0 && count < k)
                  if (count + c <= k) (steps + i * c, count + c)
                  else (steps + i * (count + c - k), k)
                else
                  (steps, count)
            }

          if (count == k) acc min steps else acc
      }
    }
  }
}


object A extends App {
  def l(n: Int): Int = n * (n + 1) / 2

  val a = scala.io.StdIn.readInt()
  val b = scala.io.StdIn.readInt()
  val n = (a - b).abs
  val m = n / 2

  val t = if (n == 1) 1
  else if (n % 2 == 0) 2 * l(m)
  else 2 * l(m) + (m + 1)

  println(t)
}

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

object a7 {
  def main(args: Array[String]): Unit = {
    def apsum(n:Int) = n*(n+1)/2
    val pos = Source.stdin.getLines().toArray.map(_.toInt)
    val (a,b)=(pos(0), pos(1))
    val diff = abs(a-b)
    println(apsum(diff/2)+apsum(diff-diff/2))
  }
}


//2.12.5 | JDoodle.Com & 2.12 | CodeForces.Com
import scala.io.Source

object Solution {
    def main(args: Array[String]) {
        val input = Source.stdin.getLines()

        val Array(grown_ups, children) = input.next().split(' ').map(_.toInt)

        if (grown_ups < 1 & children > 0)
            print("Impossible")
        else
            print(math.max(grown_ups, children) + " " + {if (children > 0) grown_ups + children - 1 else grown_ups})
    }
}

object Solution {
  def main(args: Array[String]) {
    val tokens = readLine().split(" ").map(_.toInt)
    val grownups = tokens(0)
    val kids = tokens(1)
    if (grownups == 0 && kids > 0) {
      println("Impossible")
    } else {
      printf("%d %d\n",
             grownups + (0 max (kids-grownups)),
             grownups + (0 max (kids-1)))
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  println((n, m) match {
    case(x, 0) => s"$x $x"
    case(0, x) => "Impossible"
    case(y, x) if y >= x => s"$y ${y + x - 1}"
    case(y, x) => s"$x ${y + x - 1}"
  })

}

//http://rextester.com scala 2.11.7
import scala.io.Source
object Rextester extends App{
    val a=Source.stdin.getLines();val Array(b,c)=a.next().split(' ').map(_.toInt)
    if(b<1&c>0)print("Impossible")
    else{
        var d=b+c-1
        if(c==0)d=b
        print(math.max(b,c)+" "+d)
    }
}

import scala.io.Source;object a{def main(args:Array[String]){val z=Source.stdin.getLines();val Array(a,b)=z.next().split(' ').map(_.toInt);if(a<1&b>0)print("Impossible")else print(math.max(a,b)+" "+{if(b>0)a+b-1 else a})}}

//rextester.com:2.11.7--codeforces.com:2.11.8
import scala.io.Source
object Rextester extends App{
    val z=Source.stdin.getLines();val Array(a,b)=z.next().split(' ').map(_.toInt)
    if(a<1&b>0)print("Impossible")
    else print(math.max(a,b)+" "+{if(b>0)a+b-1 else a})
}

//rextester.com:2.11.7--codeforces.com:2.11.8
import scala.io.Source
object a extends App{
    val z=Source.stdin.getLines();val Array(a,b)=z.next().split(' ').map(_.toInt)
    if(a<1&b>0)print("Impossible")
    else print(math.max(a,b)+" "+{if(b>0)a+b-1 else a})
}

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

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

  val N, M = sc.nextInt

  val res = (N, M) match {
      case (0, 0) => "0 0"
      case (0, _) => "Impossible"
      case (x, 0) => List(x, x).mkString(" ")
      case (x, y) => List(x max y, x + y - 1).mkString(" ")
  }

  out.println(res)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val min = n + (m - n).max(0)
    val max = n + (m - 1).max(0)
    if (n == 0 && m == 0) println("0 0")
    else if (n == 0) println("Impossible")
    else println(min + " " + max)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  println((n, m) match {
    case(0, x) => "Impossible"
    case(x, 0) => s"$x $x"
    case(y, x) if y >= x => s"$y ${y + x - 1}"
    case(y, x) => s"$x ${y + x - 1}"
  })

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  println((n, m) match {
    case(0, x) => "Impossible"
    case(y, x) if y >= x => s"$y ${y + x - 1}"
    case(y, x) => s"$x ${y + x - 1}"
  })

}

//http://rextester.com scala 2.11.7
import scala.io.Source
object Rextester extends App{
    val in=Source.stdin.getLines();val Array(a,b)=in.next().split(' ').map(_.toInt)
    if(a>0&b>=0){
        var c=a+b-1
        if(b==0)c=a
        print(math.max(a,b)+" "+c)
    }
    else print("Impossible")
}

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

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

  val N, M = sc.nextInt

  val res = (N, M) match {
      case (0, _) => "Impossible"
      case (x, 0) => List(x, x).mkString(" ")
      case (x, y) => List(x max y, x + y - 1).mkString(" ")
  }

  out.println(res)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val min = n + (m - n).max(0)
    val max = n + (m - 1).max(0)
    if (n == 0) println("Impossible")
    else println(min + " " + max)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val min = n + (m - n).max(0)
    val max = n + m - 1
    if (n == 0) println("Impossible")
    else println(min + " " + max)
  }
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val data = (1 to 8).map(_ => in.next())
  val lines = data.count(_.forall(_ == 'B'))
  val rows = data.find(_.exists(_ == 'W')).map(_.count(_ == 'B')).getOrElse(0)
  println(lines + rows)
}

object P7A {
    def main(args : Array[String]) {
        val a = Array.fill(8){readLine}
        val af = a filter {_ != "BBBBBBBB"}
        val c = 0 until 8 count {n => af exists {_(n) == 'B'}}
        println(8 - af.size + c)
    }
}

import java.util.Scanner

object A7Chess extends App {

  val scanner = new Scanner(System.in)

  val in = Array.ofDim[Cell](8, 8)

  var result = 0

  for (x <- 0 until 8) yield {
    val str = scanner.next()
    in(x) = str.map({
      case 'W' => Cell(color = false)
      case 'B' => Cell(color = true)
    }).toArray
  }

  (0 until 8) foreach(i => solve(in(_)(i)))
  (0 until 8) foreach(i => solve(in(i)(_)))

  println(result)

  def solve(function: (Int) => Cell): Unit = {
    if (paintedWithBlack(function)) {
      visit(function)
      result += 1
    }
  }

  def visit(function: (Int) => Cell): Unit = {
    (0 until 8).foreach(function(_).visited = true)
  }

  def paintedWithBlack(function: (Int) => Cell): Boolean = {
    (0 until 8).forall(function(_).color) && (0 until 8).exists(!function(_).visited)
  }

  case class Cell(color: Boolean, var visited: Boolean = false)

}

object A7 {

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

  def main(args: Array[String]): Unit = {
    val in = Array.fill(8)(read.toCharArray)
    val res = {
      (0 until 8).map{j => (0 until 8).map(i=>in(i)(j))}.count(_.forall(_ == 'B')) +
      in.count(_.forall(_ == 'B'))
    }
    if(res == 16)
      println("8")
    else
      println(res)
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object P7A {
    def main(args : Array[String]) {
        val a = Array.fill(8){readLine} filter {_ != "BBBBBBBB"}
        val c = 0 until 8 count {n => a exists {_(n) == 'B'}}
        println(8 - a.size + c)
    }
}

object P7A {
    def main(args : Array[String]) {
        val a = Array.fill(8){readLine}
        val af = a filter {_ != "BBBBBBBB"}
        val c = 0 until 8 count {n => af exists {_(n) == 'W'}}
        println(8 - af.size + c)
    }
}

object P7A {
    def main(args : Array[String]) {
        val a = Array.fill(8){readLine}
        val af = a filter {_ != "BBBBBBBB"}
        val c = 0 until 8 count {
            n : Int => af forall {_(n) == 'B'}
        }
        println(8 - af.size + c)
    }
}


import java.util.Scanner

object UnusualSequencesJudgeSolution {
  val MOD: Long = 1000000007

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

    def count(L: Int): Long = {
      if (L <= 2) 1
      else {
        def pow(b: Long, p: Long): Long = {
          if (p == 0) 1L
          else if (p % 2 == 0) {
            val result = pow(b, p / 2);
            (result * result) % MOD
          }
          else (b * pow(b, p - 1)) % MOD
        }
        def divisors(x: Int): List[Int] = {
          def divisorsRec(d: Int): List[Int] = {
            if (1L * d * d > x) List.empty
            else if (x % d == 0) {
              if (d * d == x) d :: divisorsRec(d + 1)
              else d :: x / d :: divisorsRec(d + 1)
            }
            else divisorsRec(d + 1)
          }
          divisorsRec(1)
        }

        val DP = collection.mutable.Map[Int, Long]()
        def D(l: Int): Long = {
          if (DP.contains(l)) DP(l)
          else {
            val result = (pow(2, l - 1) - divisors(l).filter(_ != l).map(d => D(d)).foldLeft(0L)((x, sum) => (x + sum) % MOD) + MOD) % MOD
            DP.update(l, result)
            result
          }
        }

        D(L)
      }
    }
    def solve(): Long = {
      if (y % x != 0) 0
      else {
        count(y / x)
      }
    }
    println(solve())
  }
}

import java.util.Scanner

object UnusualSequencesJudgeSolution {
  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }

  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }
  def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {
    override def apply(key: I) = getOrElseUpdate(key, f(key))
  }

  val MOD: Long = 1000000007

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

    def count(L: Int): Long = {
      if (L <= 2) 1
      else {
        def pow(b: Long, p: Long): Long = {
          if (p == 0) 1L
          else if (p % 2 == 0) {
            val result = pow(b, p / 2);
            (result * result) % MOD
          }
          else (b * pow(b, p - 1)) % MOD
        }
        def divisors(x: Int): List[Int] = {
          def divisorsRec(d: Int): List[Int] = {
            if (1L * d * d > x) List.empty
            else if (x % d == 0) {
              if (d * d == x) d :: divisorsRec(d + 1)
              else d :: x / d :: divisorsRec(d + 1)
            }
            else divisorsRec(d + 1)
          }
          divisorsRec(1)
        }

        lazy val D: Int => Long = memoize (l => (pow(2, l - 1) - divisors(l).filter(_ != l).map(d => D(d)).foldLeft(0L)((x, sum) => (x + sum) % MOD) + MOD) % MOD)

        D(L)
      }
    }
    def solve(): Long = {
      if (y % x != 0) 0
      else {
        count(y / x)
      }
    }
    println(solve())
  }
}

object Main extends App {

  import scala.io.StdIn
  val MOD: Integer = 1000000007

  val Array(x, y) = StdIn.readLine().split(" ").map(_.toInt)
  var mem = collection.mutable.Map[Integer, Integer]()

  if (y % x > 0) {
    println(0)
  }
  else {
    println(f(y/x))
  }

  def f(n: Integer): Integer = {

    if (n == 1) return 1

    if (mem contains(n))
      return mem(n)

    var res = pow2(n-1)

    for (d <- 2 to Math.round(Math.sqrt(1*n)).toInt)
      if (n % d == 0) {
        res = ((res - f(n / d))%MOD+MOD)%MOD
        if (d != n / d) res = ((res - f(d))%MOD+MOD)%MOD
      }
    res -= 1
    mem += n -> (res%MOD+MOD)%MOD
    mem(n)
  }

  def pow2(x: Integer): Integer = {
    x%2 match {
      case 0 if x > 0 => {
        val res = pow2(x/2)%MOD
        ((1l*res*res)%MOD).toInt
      }
      case 0 if x == 0 => 1
      case _ => {
        (2 * pow2(x-1) % MOD) % MOD
      }
    }
  }

}

object Main extends App {

  import scala.io.StdIn
  val MOD: Integer = 1000000007

  val Array(x, y) = StdIn.readLine().split(" ").map(_.toInt)
  var mem = collection.mutable.Map[Integer, Integer]()

  if (y % x > 0) {
    println(0)
  }
  else {
    println(f(y/x))
  }

  def f(n: Integer): Integer = {

    if (mem contains(n))
      return mem(n)

    var res = pow2(n-1)

    for (d <- 2 to Math.round(Math.sqrt(1*n)).toInt)
      if (n % d == 0) {
        res = ((res - f(n / d))%MOD+MOD)%MOD
        if (d != n / d) res = ((res - f(d))%MOD+MOD)%MOD
      }
    res -= 1
    mem += n -> (res%MOD+MOD)%MOD
    mem(n)
  }

  def pow2(x: Integer): Integer = {
    x%2 match {
      case 0 if x > 0 => {
        val res = pow2(x/2)%MOD
        ((1l*res*res)%MOD).toInt
      }
      case 0 if x == 0 => 1
      case _ => {
        (2 * pow2(x-1) % MOD) % MOD
      }
    }
  }

}

import java.util.Scanner

object UnusualSequences {
  val MOD: Long = 1000000007

  class Matrix (val M: Array[Array[Long]]) {
    val R = M.size
    val C = M(0).size
    def *(other: Matrix): Matrix = {
      val result = Array.tabulate(R, other.C)((r, c) => 0.until(C).map(x => M(r)(x) * other.M(x)(c)).sum)
      new Matrix(result)
    }
    def power(pow: Long): Matrix = {
      if (pow == 0) Matrix.getIdentity(R, C)
      else if (pow % 2 != 0) this * power(pow - 1)
      else {
        val result = power(pow / 2)
        result * result
      }
    }
  }
  object Matrix {
    def apply(M: Array[Array[Long]]) = new Matrix(M)
    def getIdentity(r: Int, c: Int) = {
      new Matrix(Array.tabulate(r, c)((i, j) => if (i == j) 1 else 0))
    }
  }

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

    def count(L: Int): Long = {
      if (L <= 2) 1
      else {
        val base = Matrix(Array(Array(1), Array(0), Array(1)))
        val matrix = Matrix(Array(Array(0, 1, 1), Array(1, 1, 0), Array(0, 0, 2)))

        val result = matrix.power(L - 1) * base
        result.M(0)(0)
      }
    }
    def solve(): Long = {
      if (y % x != 0) 0
      else {
        count(y / x)
      }
    }
    println(solve())
  }
}

import java.util.Scanner

object UnusualSequencesJudgeSolution {
  val MOD: Long = 1000000007

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

    def count(L: Int): Long = {
      if (L <= 2) 1
      else {
        def pow(b: Long, p: Long): Long = {
          if (p == 0) 1
          else if (p % 2 == 0) {
            val result = pow(b, p / 2);
            (result * result) % MOD
          }
          else (b * pow(b, p - 1)) % MOD
        }
        def divisors(x: Int): List[Int] = {
          def divisorsRec(d: Int): List[Int] = {
            if (1L * d * d > x) List.empty
            else if (x % d == 0) {
              if (d * d == x) d :: divisorsRec(d + 1)
              else d :: x / d :: divisorsRec(d + 1)
            }
            else divisorsRec(d + 1)
          }
          divisorsRec(1)
        }

        val DP = collection.mutable.Map[Int, Long]()
        def D(l: Int): Long = {
          if (DP.contains(l)) DP(l)
          else {
            val result = pow(2, l - 1) - divisors(l).filter(_ != l).map(d => D(d)).foldLeft(0L)((x, sum) => (x + sum) % MOD)
            DP.update(l, result)
            result
          }
        }

        D(L)
      }
    }
    def solve(): Long = {
      if (y % x != 0) 0
      else {
        count(y / x)
      }
    }
    println(solve())
  }
}


import scala.io.StdIn._
import scala.util.control.Breaks._

object Main {
  def main(args: Array[String]): Unit = {
      val t: Int = readInt()
      for (_ <- 1 to t) {
          var curr_door: Int = readInt()
          val A: Array[Int] = readLine().split(" ").map(_.toInt)
          var a: Boolean = true
          breakable {for (_ <- 1 to 3) {
              if (curr_door == 0) {
                  a = false
                  break
              }
              curr_door = A(curr_door-1)
          }}
          if (a) println("YES") else println("NO")
      }
    }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val A = new Array[Int](3)
      tokenizer = new StringTokenizer(input.readLine())
      A(0) = tokenizer.nextToken().toInt
      A(1) = tokenizer.nextToken().toInt
      A(2) = tokenizer.nextToken().toInt
      var t = false
      val a = A(n-1)
      if (a != 0) {
        val b = A(a-1)
        if (b!=0) {
          t = true
        }
      }
      if (t) {
        println("YES")
      }
      else {
        println("NO")
      }
    }
  }
}


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

object Solution {
  // VM options: -Xmx1024m -Xss1024m
  private val inputFilename = "input.txt"
  private val outputFilename = "output.txt"

  def main(args: Array[String]): Unit = {
    new Solution(args.contains("DEBUG_MODE")).run(args)
  }
}

case class Solution(isDebug: Boolean) {
  def solve(): Unit = {
    var l = nextInt
    var r = nextInt
    var a = nextInt
    val addL = Math.max(0, Math.min(r - l, a))
    l += addL
    a -= addL
    val addR = Math.max(0, Math.min(l - r, a))
    r += addR
    a -= addR
    l += a / 2
    r += a / 2
    println(s"${Math.min(l, r) * 2}")
  }

  def run(args: Array[String]): Unit = {
    if (isDebug) {
      in = new BufferedReader(new InputStreamReader(new FileInputStream(Solution.inputFilename)))
      //      in = new BufferedReader(new InputStreamReader(System.in))
    } else {
      in = new BufferedReader(new InputStreamReader(System.in))
    }
    out = new PrintWriter(System.out)
    //    out = new PrintWriter(outputFilename)

    //    val t = nextInt
    val t = 1
    (0 until t).foreach { i =>
      //      out.print(s"Case #${i + 1}: ")
      solve()
    }
    in.close()
    out.flush()
    out.close()
  }

  private var in: BufferedReader = _
  private var line: StringTokenizer = _
  private var out: PrintWriter = _

  private[this] def println(s: String = ""): Unit = out.println(s)

  private[this] def nextIntArray(n: Int) = (0 until n).map(_ => nextInt).toArray

  private[this] def nextLongArray(n: Int) = (0 until n).map(_ => nextLong).toArray

  private[this] def nextInt = nextToken.toInt

  private[this] def nextLong = nextToken.toLong

  private[this] def nextDouble = nextToken.toDouble

  private[this] def nextToken = {
    while (line == null || !line.hasMoreTokens) {
      line = new StringTokenizer(in.readLine)
    }
    line.nextToken
  }
}

object aTask1 {
  import scala.io.StdIn.{readLine, readInt}
  def main(args: Array[String]):Unit = {
    val l::r::a::Nil = readLine.split(" ").map(_.toInt).toList
    val p1 = math.min(l,r)
    val p2 = math.min(math.abs(l - r), a)
    val p3 = if (a - p2 >0) (a-p2)/2 else 0
    println((p1+p2+p3) * 2)
  }
}

object Solution {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val l, r, a = sc.nextInt
    val u = a.min((r - l).abs)

    println(2 * (l.min(r) + u + (a - u)/2))
  }
}

object A extends App {
  val Array(l, r, a) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val d = (l max r) - (l min r)
  val t = a min d
  val s = (l min r) + t + (0 max (a - t)) / 2

  println(2 * s)
}


import java.util.Scanner

object Main {

  def sqr(x: Long) = x * x

  def powmod(x: Long, n: Long, p: Long): Long = {
    if (n == 1) x
    else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p
    else sqr(powmod(x, n / 2, p)) % p
  }

  def C(n: Int, k: Int) = {
    var res = BigInt(1)
    for (i <- n - k + 1 to n) {
      res = res * i
    }
    for (i <- 1 to k.toInt) {
      res = res / i
    }
    res
  }

  def fact(n: Int) = {
    var res = BigInt(1)
    for (i <- 1 to n) {
      res = res * i
    }
    res
  }

  def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b)

  def lcm(a: Long, b: Long) = a / gcd(a, b) * b

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

    val s = in.nextLine()

    val t = "" + s(0) + s(2) + s(4) + s(3) + s(1)

    val x = BigInt(t)
    val y = (x * x * x * x * x).toString()

    println(y.substring(y.length() - 5))
  }
}

import scala.io.StdIn

object CrackingTheCode {

  def main(args: Array[String]) {
    val MOD = 100000
    val n = StdIn.readLong()
    val res = Array(n / 10000, (n / 100) % 10, n % 10, (n / 10) % 10, (n / 1000) % 10)
    val k = res(0) * 10000 + res(1) * 1000 + res(2) * 100 + res(3) * 10 + res(4)
    def pow(n : Int) : Long = {
      if (n == 0) 1
      else (k * pow(n - 1)) % MOD
    }
    println("%05d".format(pow(5)))
  }

}

import scala.io.StdIn

object CrackingTheCode {

  def main(args: Array[String]) {
    val MOD = 100000
    val n = StdIn.readLong()
    val res = Array(n / 10000, (n / 100) % 10, n % 10, (n / 10) % 10, (n / 1000) % 10)
    val k = res(0) * 10000 + res(1) * 1000 + res(2) * 100 + res(3) * 10 + res(4)
    def pow(n : Int) : Long = {
      if (n == 0) 1
      else (k * pow(n - 1)) % MOD
    }
    println(pow(5))
  }

}


import java.io._
import java.util.Locale
import scala.annotation.tailrec

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

  def calc(str: String): Double = {
    if(str.length == 0) 0
    else {
      val ch = str.head
      Math.ceil(0.2 * str.takeWhile(_ == ch).length) + calc(str.dropWhile(_ == ch))
    }
  }
  def ans = calc(readLine)

  def main(a: Array[String]) {
    println(ans.round)
  }
}

import scala.collection.mutable.ArrayBuffer

object Flask {
  def main(args: Array[String]): Unit = {
    var s = readLine
    var total = 0
    var symbol = s(0); var count = 1

    (1 until s.size).foreach(i => {
        if (s(i) == symbol && count < 5) count += 1
        else { count = 1; symbol = s(i); total += 1 }
    })
    println(total + 1)
  }
}

object main {
    def main(args: Array[String]) = {
        val str = readLine()

        var last:Char = str apply 0
        var n = 0
        var res = 0

        str foreach ((x:Char) => {
            if (last == x) {
                if (n == 5) {
                    n = 1
                    res += 1
                } else {
                    n += 1
                }
            } else {
                if (n != 0) {
                    res += 1
                }
                n = 1
                last = x

            }
        })

        println(res + 1)
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val res = str.tail.foldLeft((0, 1, str.head)) {
    case ((count, soFar, prev), el) if soFar == 5 => (count + 1, 1, el)
    case ((count, soFar, prev), el) if el == prev => (count, soFar + 1, el)
    case ((count, soFar, prev), el) => (count + 1, 1, el)
  }
  println(res._1 + (if (res._2 != 0) 1 else 0))
}

object A137 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    var res = 0
    var curr = 1
    for(i <- 1 to str.length) {
      if(i == str.length || str(i) != str(i-1)) {
        res += (curr+4)/5
        curr = 1
      } else {
        curr += 1
      }
    }
    out.println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object P137A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val CP = sc.nextLine.toList

  def solve(): Int = {

    @tailrec
    def loop(n: Int, carry: List[Char], wall: List[Char]): Int = (carry, wall) match {
        case (_, Nil) => n
        case (Nil, y :: ys) => loop(n, y :: Nil, ys)
        case (xs, ys) if xs.size == 5     => loop(n + 1, Nil, ys)
        case (x :: xs, y :: ys) if x == y => loop(n, y :: x :: xs, ys)
        case (x :: xs, y :: ys) if x != y => loop(n + 1, y :: Nil, ys)
      }

    loop(0, Nil, CP) + 1
  }

  out.println(solve)
  out.close
}

object A137 {
	def main(args: Array[String]) {
		val s: String = readLine
		var res: Int = 0
		var curc: Char = '?'
		var curval: Int = 5
		for (c <- s)
			if (c == curc && curval < 5)
				curval += 1
			else {
				res += 1
				curval = 1
				curc = c
			}
		println(res)
	}
}

object Main {
  def main(args: Array[String]) = {
    val s = readLine()

    var cur = ' '
    var inHands = 0
    var count = 0
    s.foreach{ c =>
      if (c != cur) {
        inHands = 0
        count += 1
        cur = c
      } else if (inHands == 5) {
        count += 1
        inHands = 0
      }
      inHands += 1
    }
    println(count)
  }
}

object main {
	def main(args: Array[String]) = {
		val str = readLine()

		var last:Char = str apply 0
		var n = 0
		var res = 1

		str foreach ((x:Char) => {
			if (last == x) {
				if (n == 5) {
					n = 0
					res += 1
				} else {
					n += 1
				}
			} else {
				if (n != 0) {
					res += 1
				}
				n += 1
				last = x

			}
		})

		println(res)
	}
}

object main {
    def main(args: Array[String]) = {
        val str = readLine()

        var last:Char = str apply 0
        var n = 0
        var res = 0

        str foreach ((x:Char) => {
            if (last == x) {
                if (n == 5) {
                    n = 1
                    res += 1
                } else {
                    n += 1
                }
            } else {
                if (n != 0) {
                    res += 1
                }
                n += 1
                last = x

            }
        })

        println(res + 1)
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val res = str.tail.foldLeft((0, 0, str.head)) {
    case ((count, soFar, prev), el) if soFar == 5 => (count + 1, 1, el)
    case ((count, soFar, prev), el) if el == prev => (count, 1, el)
    case ((count, soFar, prev), el) => (count + 1, 1, el)
  }
  println(res._1 + (if (res._2 != 0) 1 else 0))
}


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

import collection.Searching._
import scala.collection.mutable

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

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val widths = readIntLine()

    val sum = Array.ofDim[Int](widths.length, widths.length + 1)

    for (i <- widths.indices) {
      for (j <- i + 1 to widths.length) {
        sum(i)(j) = sum(i)(j - 1) + widths(j - 1)
      }
    }

    val minDiff = widths.indices.map{
      i =>
        (i + 1 to widths.length).map{
          j =>
            Math.abs(180 - sum(i)(j)) * 2
        }.min
    }.min

    println(minDiff)
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

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

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

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

object A extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)

  var min = 360

  for {
    i <- 0 until n
    j <- i to n
  } {
    val s1 = as.view(i, j).sum
    val s2 = 360 - s1
    val d = Math.abs(s1 - s2)
    if (d < min) min = d
  }

  println(min)
}

object A extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)

  var min = 360
  var s1 = 0
  var l, r = 0

  def check(s1: Int) = {
    val s2 = 360 - s1
    val d = Math.abs(s1 - s2)
    if (d < min) min = d
  }

  while (r < n) {
    while (s1 < 180 && r < n) {
      s1 += as(r)
      r += 1
      check(s1)
    }
    while (s1 >= 180) {
      s1 -= as(l)
      l += 1
      check(s1)
    }
  }

  println(min)
}

import java.util.Scanner
import scala.language.implicitConversions

object PizzaSeparation {

  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }

  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }

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

    val N = sc.nextInt()
    val A = for (i <- 0.until(N)) yield sc.nextInt()

    def bestPrefix(xs: List[Int], s: Int): Int = xs match {
      case Nil => 360
      case x :: rest => val ns = s + x; Math.min(Math.abs(360 - 2 * ns), bestPrefix(rest, ns))
    }

    def solve(xs: List[Int]): Int = xs match {
      case Nil => 360
      case x :: rest => Math.min(bestPrefix(xs, 0), solve(rest))
    }

    println(solve(A.toList))
  }
}

object A extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)

  var min = 360
  var s1 = 0
  var l, r = 0

  def check(s1: Int) = {
    val s2 = 360 - s1
    val d = Math.abs(s1 - s2)
    if (d < min) min = d
  }

  while (r < n) {
    while (s1 < 180 && r < n) {
      s1 += as(r)
      r += 1
    }
    check(s1)
    while (s1 >= 180) {
      s1 -= as(l)
      l += 1
    }
    check(s1)
  }

  println(min)
}


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

  def isGood(str: String) = {
    str.length >= 1 && str.length <= 16 && str.forall(ch => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_')
  }

  if (line.split("@", -1) match {
    case Array(first, second) if isGood(first) =>
      second.split("/", -1) match {
        case Array(hostname, resource) =>
          hostname.split("\\.", -1).forall(isGood) && isGood(resource) && hostname.length <= 32
        case Array(hostname) =>
          hostname.split("\\.", -1).forall(isGood)
        case _ => false
      }
    case _ => false
  })
    println("YES")
  else
    println("NO")
}

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2 ||  user.endsWith("@")) {
      out.println("NO")
      return 1
    }
    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).length <= 0 || part2.split("/")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("/")(0).split("\\.")
    if (part2.split("/")(0).startsWith(".") || part2.split("/")(0).endsWith(".")) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).contains(".") && hosts.length == 0) {
      out.println("NO")
      return 1
    }
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("/").length > 1) {
      val res = part2.split("/")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    if (user.endsWith("/")) {
      out.println("NO")
      return 1
    }
    out.println("YES")
    return 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 = io.Source.stdin.getLines()
  val line = in.next()

  def isGood(str: String) = {
    str.length >= 1 && str.length <= 16 && str.forall(ch => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_')
  }

  if (line.split('@') match {
    case Array(first, second) if isGood(first) =>
      second.split("/", -1) match {
        case Array(hostname, resource) =>
          hostname.split("\\.", -1).forall(isGood) && isGood(resource) && hostname.length <= 32
        case Array(hostname) =>
          hostname.split("\\.", -1).forall(isGood)
        case _ => false
      }
    case _ => false
  })
    println("YES")
  else
    println("NO")
}

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

  def isGood(str: String) = {
    str.length >= 1 && str.length <= 16 && str.forall(ch => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_')
  }

  if (line.split('@') match {
    case Array(first, second) if isGood(first) =>
      second.split('/') match {
        case Array(hostname, resource) =>
          hostname.split('.').forall(isGood) && isGood(resource) && hostname.length <= 32
        case Array(hostname) =>
          hostname.split('.').forall(isGood)
        case _ => false
      }
    case _ => false
  })
    println("YES")
  else
    println("NO")
}

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

  def isGood(str: String) = {
    str.length >= 1 && str.length <= 16 && str.forall(ch => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_')
  }

  if (line.split('@') match {
    case Array(first, second) if isGood(first) =>
      second.split('/') match {
        case Array(hostname, resource) =>
          hostname.split("\\.", -1).forall(isGood) && isGood(resource) && hostname.length <= 32
        case Array(hostname) =>
          hostname.split("\\.", -1).forall(isGood)
        case _ => false
      }
    case _ => false
  })
    println("YES")
  else
    println("NO")
}

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

  def isGood(str: String) = {
    str.length >= 1 && str.length <= 16 && str.forall(ch => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_')
  }

  if (line.split('@') match {
    case Array(first, second) =>
      second.split('/') match {
        case Array(hostname, resource) =>
          hostname.split('.').forall(isGood) && isGood(resource) && hostname.length <= 32
        case Array(hostname) =>
          hostname.split('.').forall(isGood)
        case _ => false
      }
    case _ => false
  })
    println("YES")
  else
    println("NO")
}

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

  def isGood(str: String) = {
    str.length >= 1 && str.length <= 16 && str.forall(ch => (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_')
  }

  if (line.split('@') match {
    case Array(first, second) =>
      second.split('/') match {
        case Array(hostname, resource) =>
          hostname.split('.').forall(isGood) && isGood(resource) && hostname.length <= 32
        case Array(hostname) =>
          println("HERE")
          hostname.split('.').forall(isGood)
        case _ => false
      }
    case _ => false
  })
    println("YES")
  else
    println("NO")
}

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }

    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "abcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("\\\\")(0).length <= 0 || part2.split("\\\\")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("\\\\")(0).split(".")
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("\\\\").length > 1) {
      val res = part2.split("\\\\")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    out.println("YES")
    return 1
  }

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

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }
    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).length <= 0 || part2.split("/")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("/")(0).split("\\.")
    if (part2.startsWith(".") || (part2.endsWith("."))) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).contains(".") && hosts.length == 0) {
      out.println("NO")
      return 1
    }
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("/").length > 1) {
      val res = part2.split("/")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    if (user.endsWith("/")) {
      out.println("NO")
      return 1
    }
    out.println("YES")
    return 1
  }

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

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }
    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).length <= 0 || part2.split("/")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("/")(0).split("\\.")
    if (part2.split("/")(0).startsWith(".") || part2.split("/")(0).endsWith(".")) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).contains(".") && hosts.length == 0) {
      out.println("NO")
      return 1
    }
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("/").length > 1) {
      val res = part2.split("/")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    if (user.endsWith("/")) {
      out.println("NO")
      return 1
    }
    out.println("YES")
    return 1
  }

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

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }
    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).length <= 0 || part2.split("/")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("/")(0).split(".")
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("/").length > 1) {
      val res = part2.split("/")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    if (user.endsWith("/")) {
      out.println("NO")
      return 1
    }
    out.println("YES")
    return 1
  }

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

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }
    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).length <= 0 || part2.split("/")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("/")(0).split(".")
    if (part2.startsWith(".") || (part2.endsWith("."))) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).contains(".") && hosts.length == 0) {
      out.println("NO")
      return 1
    }
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("/").length > 1) {
      val res = part2.split("/")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    if (user.endsWith("/")) {
      out.println("NO")
      return 1
    }
    out.println("YES")
    return 1
  }

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

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }
    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).length <= 0 || part2.split("/")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("/")(0).split(".")
    if (part2.startsWith(".") || (part2.endsWith("."))) {
      out.println("NO")
      return 1
    }
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("/").length > 1) {
      val res = part2.split("/")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    if (user.endsWith("/")) {
      out.println("NO")
      return 1
    }
    out.println("YES")
    return 1
  }

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

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }
    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).length <= 0 || part2.split("/")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("/")(0).split(".")
    if (part2.startsWith(".")) {
      out.println("NO")
      return 1
    }
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("/").length > 1) {
      val res = part2.split("/")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    if (user.endsWith("/")) {
      out.println("NO")
      return 1
    }
    out.println("YES")
    return 1
  }

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

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }
    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "abcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("/")(0).length <= 0 || part2.split("/")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("/")(0).split(".")
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("/").length > 1) {
      val res = part2.split("/")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    if (user.endsWith("/")) {
      out.println("NO")
      return 1
    }
    out.println("YES")
    return 1
  }

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

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }

    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    val filter: String = name.filter(x => allow.contains(x))
    if (filter.length != name.length) {
      out.println("NO")
      return 1
    }
    if (part2.split("\\\\")(0).length <= 0 || part2.split("\\\\")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("\\\\")(0).split(".")
    for (i <- 0 until hosts.length) {
      val filter1: String = hosts(i).filter(x => allow.contains(x))
      if (filter1.length != hosts(i).length) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("\\\\").length > 1) {
      val res = part2.split("\\\\")(1)
      val filter1: String = res.filter(x => allow.contains(x))
      if (filter1.length != res.length) {
        out.println("NO")
        return 1
      }
    }
    out.println("YES")
    return 1
  }

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

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

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 nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val user = next
    if (user.split("@").length != 2) {
      out.println("NO")
      return 1
    }

    val name = user.split("@")(0)
    if (name.length <= 0 || name.length > 16) {
      out.println("NO")
      return 1
    }
    val part2 = user.split("@")(1)
    val allow = "QWERTYUIOPASDFGHJKLZXCVBNMabcdefghijklmnopqrstuvwxyz1234567890_".toCharArray
    if (name.filter(x => !allow.contains(x)).length > 0) {
      out.println("NO")
      return 1
    }
    if (part2.split("\\\\")(0).length <= 0 || part2.split("\\\\")(0).length > 32) {
      out.println("NO")
      return 1
    }

    val hosts = part2.split("\\\\")(0).split(".")
    for (i <- 0 until hosts.length) {
      if (hosts(i).filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
      if (hosts(i).length <= 0 || hosts(i).length > 16) {
        out.println("NO")
        return 1
      }
    }

    if (part2.split("\\\\").length > 1) {
      val res = part2.split("\\\\")(1)
      if (res.filter(x => !allow.contains(x)).length > 0) {
        out.println("NO")
        return 1
      }
    }
    out.println("YES")
    return 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 _816A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    var Array(hh, mm) = read[String].split(':').map(_.toInt)
    var ans = 0
    while(!isPalindrome(hh, mm)) {
      val (nh, nm) = next(hh, mm)
      hh = nh
      mm = nm
      ans += 1
    }
    write(ans)
  }

  def pad(x: Int) = if (x < 10) s"0$x" else x.toString

  def isPalindrome(hh: Int, mm: Int) = {
    val t = s"${pad(hh)}:${pad(mm)}"
    t == t.reverse
  }

  def next(hh: Int, mm: Int) = {
    if (mm == 59) {
      ((hh + 1)%24, 0)
    } else {
      (hh, mm + 1)
    }
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def 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
      }
    }
  }
}

import java.util.Scanner

/**
  * Created by pinguinson on 6/17/2017.
  */
object A extends App {
 val sc = new Scanner(System.in)
  val palindromes = Seq((0,0),(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (10, 1), (11, 11), (12,21),(13,31), (14,41),(15,51),(20,2), (21,12), (22,22),(23,32))
  val s = sc.next()
  val h = s.substring(0, 2).toInt
  val m = s.substring(3, 5).toInt
  val togo = palindromes.find {
    case (hour, minute) => hour >= h && minute >= m
  } match {
    case Some((hr, min)) => (hr - h) * 60 + (min - m)
    case None => (23 - h) + (60 - m)
  }
  println(togo)
}