object C extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

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

    n.times {
      val m = in.nextInt()
      val d = in.nextInt()

      val temLine = in.line()
      //      println(temLine)
      val line = "1" + ("0" * d) + temLine + ("0" * d) + "1"
      //      println(line)

      val tableStr = line.split("").map(_.toInt)
      //      printArr(tableStr)

      var r          = 0
      var wasLast1   = false
      var last1Index = 1
      for ((element, i) <- tableStr.zipWithIndex) {
        if (element == 1 && wasLast1) {
          val diff = (i + 1) - last1Index
          val l    = findD(diff - 1, d)
          //          println(s"L: ****************** = $l $last1Index ${i + 1}")
          r = r + l
          last1Index = i + 1
        } else if (element == 1) {
          wasLast1 = true
          last1Index = i + 1
        }
      }
      //      println("Result: =>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=> " + r)
      println(r)
    }
  }

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

  def findD(n: Int, d: Int): Int = {
    //    println("............")
    //    println(n, d)
    val base     = (2 * d) + 1
    val reminder = n - base
    if (reminder >= 0) {
      //      println(base)
      //      println(reminder)
      //      println((reminder / (d + 1)))
      val resu = (reminder / (d + 1)) + 1
      //      println("............")
      resu
    } else {
      0
    }

  }

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

//package codeforces.contests._1367

object _3 {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)
      val arr = io.StdIn.readLine.zipWithIndex

      val occupied = arr.collect { case (c, i) if c == '1' => i + 1 }.toVector

      println {
        if (occupied.isEmpty)
          (1 to n by k + 1).size
        else {
          val first = occupied.head
          val last = occupied.last

          val a = (1 until first by k + 1).count(_ + k < first)
          val b = occupied.sliding(2).map { case Vector(x, y) => (x + k + 1 until y).by(k + 1).count(_ + k < y); case _ => 0 }.sum
          val c = (last + k + 1 to n by k + 1).size
          a + b + c
        }
      }
    }
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nk = readIntLine()
      val l = readLine().toCharArray.map(_ == '1').toList
      handle(l, nk.last)
    }
  }

  def handle(list: List[Boolean], k: Int): Unit = {
    def helper(l: List[Boolean], prevDist: Int, acc: Int): Int = l match {
      case Nil => acc
      case b :: bs => if (b) if (prevDist < k) helper(bs, 0, acc - 1) else helper(bs, 0, acc)
      else if (prevDist < k) helper(bs, prevDist + 1, acc) else helper(bs, 0, acc + 1)
    }

    println(helper(list, k, 0))
  }

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

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

}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 1 to t) {
      val tmp = StdIn.readLine().split(" ").map(_.toInt)
      val (n, k) = (tmp(0), tmp(1))
      var str = StdIn.readLine()
      val blocks = str.split("1").filter(_.length>0)

      var i = 0
      var res = 0
      for (b <- blocks) {
        if (i == 0 && str.startsWith("0")) {
          res += (b.length / (k+1))
        } else if (i == blocks.length - 1 && str.endsWith("0")) {
          res += (b.length / (k+1))
        } else {
          res += math.max(0, (b.length - k) / (k+1))
        }
        i += 1
      }
      if (str.forall(ch => ch == '0') && str.length % (k+1) > 0) res += 1
      println(res)
    }
  }
}

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

  val t = readInt()

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

    val (ans, _) = (sn.zipWithIndex.collect { case (x, i) if x == 1 => i } :+ (n + k)).foldLeft((0, -k - 1)) {
      case ((c, l), r) =>
        (c + (r - l - 1 - k).max(0) / (k + 1), r)
    }

    println(ans)
  }
}

object Main extends App {
  val r = new FastScanner(java.lang.System.in)
  val o = new java.io.PrintWriter(java.lang.System.out)
  for(_ <- 1 to r.nextInt()) {
    val n = r.nextInt()
    val mindist = r.nextInt()
    val s = r.nextToken(n)
    def f(x: Int, prefix: Boolean, suffix: Boolean): Int = {
      var t = x
      if(prefix) t += mindist
      if(suffix) t += mindist
      if(t <= mindist) 0
      else ((t + 1) / (mindist + 1)) - 1
    }
    def loop(k: Int, t: Int, ans: Int): Int = {
      if(k == n) {
        if(t > 0) ans + f(t, t == n, true) else ans
      } else if(s(k) == '1') {
        loop(k + 1, 0, ans + f(t, t == k, false))
      } else {
        loop(k + 1, t + 1, ans)
      }
    }
    o.println(loop(0, 0, 0))
  }
  o.close()
}

import scala.annotation.tailrec
import scala.collection.mutable.StringBuilder

object FastScanner {
  val zero = 0.toByte
  val cr = '\r'.toByte
  val nl = '\n'.toByte
  val BUFFER_SIZE = 0x10000
}

class FastScanner(private val input: java.io.InputStream) {
  private val b = new Array[Byte](FastScanner.BUFFER_SIZE)
  private var n = 0
  private var pos = 0
  private var eof = false
  private def read ():Boolean = {
    if (eof) {
      return false
    }
    pos = 0
    n = input.read(b)
    if (n < 0) {
      eof = true
    }
    n > 0
  }
  private def nextByte(): Byte = {
    if (pos >= n && !read ()) {
      0
    } else {
      val r = b(pos)
      pos += 1
      r
    }
  }
  def nextToken(k: Int = -1): String = {
    val sb = if(k >= 0) new StringBuilder(k) else new StringBuilder()
    var b = skipBlanks()
    assert(b > 0)
    while(b > 32) {
      sb.append(b.toChar)
      b = nextByte()
    }
    //sb.append('1')
    sb.toString
  }
  @tailrec
  private def skipBlanks(): Byte = {
    val b = nextByte()
    if(b > 32 || b < 1) b else skipBlanks()
  }
  def nextInt():Int = {
    val b = skipBlanks()
    @tailrec
    def f(t: Int): Int = {
      val b = nextByte ()
      if (b <= 32) t else f(10 * t + (b - 48))
    }
    require(b > 0)
    if (b < 48) -f(0) else f(b - 48)
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 1 to t) {
      val tmp = StdIn.readLine().split(" ").map(_.toInt)
      val (n, k) = (tmp(0), tmp(1))
      var str = StdIn.readLine()
      val blocks = str.split("1").filter(_.length>0)

      var i = 0
      var res = 0
      for (b <- blocks) {
        if (i == 0 && str.startsWith("0")) {
          res += (b.length / (k+1))
        } else if (i == blocks.length - 1 && str.endsWith("0")) {
          res += (b.length / (k+1))
        } else {
          res += math.max(0, (b.length - k) / (k+1))
        }
        i += 1
      }
      if (str.forall(ch => ch == '0') && str.length < k+1) res += 1
      println(res)
    }
  }
}


object C extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val (i, j)      = (k / (n - 1), k % (n - 1))
    val rs         = i * n + (if (j == 0) j - 1 else j)
    println(rs)
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.collection.mutable.ListBuffer
import scala.io.StdIn

object Test extends App {

  val s = StdIn.readLine().toInt
  (1 to s).foreach{_ =>
    var arr = StdIn.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val k = arr(1)

    val ans = ListBuffer.empty[Int]
    var l: Long = 1
    var r: Long = 100000000000L
    while (Math.abs(r - l) > 1){
      var mid: Long = (r + l) / 2L
      val x: Long = mid / n
      val y: Long = mid - x
      if(y == k && mid % n != 0){
        l = mid
        r = mid
      }else if (y < k){
        l = mid
      }else{
        r = mid
      }
    }
    println(l)
  }
}

import scala.io.StdIn

object C {

   def solution(n: Int, k: Int): Int = k + (k - 1) / (n - 1)

   def main(args: Array[String]): Unit = {
      for (_ <- (0 until StdIn.readLine.toInt)) {
         val Seq(n, k) = StdIn.readLine.split(" ").toSeq.map(_.toInt)
         println(solution(n, k))
      }
   }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C640B(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val k = ni()

      val gap = n - 1

      val r =if(k % gap == 0) - 1 else k % gap
      val x = k / gap
      out.println(x * n + r)
    }
  }
}

object C extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val (i, j)      = (k / (n - 1), k % (n - 1))
    val ans         = i * n + (if (j == 0) j - 1 else j)

    println(ans)
  }
}

object C extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val ans         = k + (k - 1) / (n - 1)

    println(ans)
  }
}


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

object Codeforces extends App {
  val Array(n, k) = readLine split ' ' map(_.toLong)
  val players = readLine split ' ' map(_.toInt)
  val window = math.min(n, k)
  val queue = mutable.Queue[Int](players: _*)
  var current = queue.dequeue()
  var winCount = 0
  while (queue.nonEmpty && winCount < window) {
    for (_ <- 1L to window) {
      if (winCount < window) {
        val player = queue.dequeue()
        if (player < current) {
          winCount += 1
          queue.enqueue(player)
        }
        else {
          winCount = 1
          queue.enqueue(current)
          current = player
        }
      }
    }
  }
  println(current)
}

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val k = io.read[Long]
    val powers = io.read[List, Int](n)
    val best = powers.max

    @tailrec
    def fight(players: List[Int], wins: Int): Int = {
      players match {
        case p1 :: ps if wins >= k || p1 == best => p1
        case p1 :: p2 :: ps if p1 > p2 => fight(players = p1 :: (ps :+ p2), wins = wins + 1)
        case p1 :: p2 :: ps if p1 < p2 => fight(players = p2 :: (ps :+ p1), wins = 1)
      }
    }

    val ans = fight(players = powers, wins = 0)
    io.write(ans)
  }
}
/****************************[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
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  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 getBit(i: Int): Int = (x >> i) & 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 getBit(i: Int): Long = (x >> i) & 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative.getOrElse(f)   //e.g. students.indexOf("Greg").whenNegative(Int.MaxValue)
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val k = io.read[Long]
    val powers = io.read[List, Int](n)
    val best = powers.max

    @tailrec
    def fight(players: List[Int], wins: Int): Int = {
      players match {
        case p1 :: ps if wins >= k || p1 == best => p1
        case p1 :: p2 :: ps if p1 > p2 => fight(players = p1 :: (ps :+ p2), wins = wins + 1)
        case p1 :: p2 :: ps if p1 < p2 => fight(players = p2 :: (ps :+ p1), wins = 0)
      }
    }

    val ans = fight(players = powers, wins = 0)
    io.write(ans)
  }
}
/****************************[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
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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


object A {
  import InOut._
  def main(args: Array[String]): Unit = {}

  val n, m = nextInt
  val s, t = nextLine.split(" ")
  val q = nextInt

  for (_ <- 1 to q) {
    val y = nextInt - 1
    val j = y % n
    val i = y % m
    val res = s(j) + t(i)
    out.println(res)
  }

  out.flush()

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

import scala.io.StdIn

object NewYearAndNaming extends App {

  val l1 = StdIn.readLine().split(" ")
  val n = l1(0).toInt
  val m = l1(1).toInt

  val s = StdIn.readLine().split(" ")
  val t = StdIn.readLine().split(" ")

  val q = StdIn.readLine().toInt

  for (i <- 1 to q) {
    val year = StdIn.readLine().toInt
    if (i == q) {
      print(impl(s, t, n, m, year))
    } else {
      println(impl(s, t, n, m, year))
    }
  }

  def impl(s: Array[String], t: Array[String], n: Int, m: Int, year: Int): String = {
    val sIndex = year % n match {
      case 0 => n - 1
      case notZero => notZero - 1
    }

    val tIndex = year % m match {
      case 0 => m - 1
      case notZero => notZero - 1
    }

    s(sIndex) + t(tIndex)
  }
}

object S extends App {
    val lengths = readLine().split(' ').map(_.toInt)
    val arr1 = readLine().split(' ')
    val arr2 = readLine().split(' ')
    val cnt = readLine().toInt

    1.to(cnt).map(_ => readLine().toInt).foreach {year =>
        val (ind1, ind2) = ((year - 1) % lengths(0), (year - 1) % lengths(1))
        val res = arr1(ind1) + arr2(ind2)
        System.out.println(res)
    }
}

import scala.io.StdIn

object Codeforces1284A extends App {
  StdIn.readLine()
  val s = StdIn.readLine().split("\\s+")
  val t = StdIn.readLine().split("\\s+")
  var q = StdIn.readLine().toInt
  while (q > 0) {
    val y = StdIn.readLine().toLong - 1
    println(s((y % s.length).toInt) + t((y % t.length).toInt))
    q -= 1
  }
}


import scala.collection.Set

object Multithreading extends App {

  val t = readInt //num tests
  val threads = readLine.split(' ').map(_.toInt)

  var i = t - 1;
  while (i > 0 && threads(i) > threads(i - 1)) {
    i -= 1
  }
  println(i)
}

object cf165b extends App {
  val n = readLine.toInt
  val arr = readLine.split(' ').map(_.toInt).reverse.toList
  println(n - (arr zip ((n + 2) :: arr)).span(p => p._1 < p._2)._1.length)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  println(n - 1 - in.next().split(' ').map(_.toInt - 1).reverse.sliding(2).takeWhile(i => i.last < i.head).length)
}

import collection.mutable.Queue

object test6 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)
    var i=a.length-2
    while(i>=0 && a(i)<a(i+1)) i-=1
    println(i+1)
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val r =
      if(n == 1) 0
      else n - 1 - a.reverse.sliding(2).takeWhile(t => t(0) > t(1) ).size
    println(r)
  }
}

object cf165b extends App {
  val n = readLine.toInt
  val arr = readLine.split(' ').map(_.toInt).reverse.toList
  println((arr zip ((n + 2) :: arr)).span(p => p._1 < p._2)._1.length)
}

object cf165b extends App {
  val n = readLine.toInt
  var ans = 0
  var arr = Array.ofDim[Boolean](n + 1)
  var nxt = 1
  readLine.split(' ').map(_.toInt).map { i =>
    arr(i) = true
    if (nxt != i) ans += 1
    while (nxt <= n && arr(nxt)) nxt += 1
  }
  println(ans)
}

object cf165b extends App {
  val n = readLine.toInt
  var ans = 0
  var arr = Array.ofDim[Boolean](n + 1)
  var nxt = 1
  def ans(xs: List[Int]): Int = {
    if (xs.isEmpty) 0 else {
      val (ys, m :: zs) = xs.span(_ != xs.min)
      ys.length + ans(zs)
    }
  }
  readLine.split(' ').map(_.toInt).map { i =>
    arr(i) = true
    if (nxt < i) ans += 1
    while (nxt <= n && arr(nxt)) nxt += 1
  }
  println(ans)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  println(in.next().split(' ').map(_.toInt - 1).reverse.sliding(2).takeWhile(i => i.last < i.head).length)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val visited = Array.ofDim[Boolean](n)
  val line = in.next().split(' ').map(_.toInt - 1).foldLeft(0, 0) {
    case ((k, sum), el) if el == k =>
      visited(el) = true
      ((k + 1 until n).find(i => !visited(i)).getOrElse(-1), sum)
    case ((k, sum), el) if el > k =>
      visited(el) = true
      (k, sum + 1)
    case ((k, sum), el) =>
      visited(el) = true
      (k, sum)
  }
  println(line._2)
}

import collection.mutable.Queue

object test6 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)
    var count=0
    var i=0
    while(a(i)!=1) {count+=1;i+=1}
    println(count)
}

object Main {

  class Node(val value: Int) {
    var left: Option[Node] = None
    var right: Option[Node] = None

    def leftCount: Int =
      Seq(left.map(_.leftCount), right.map(_.leftCount), left.map(_ => 1)).flatten.sum

    def add(node: Node) {
      if (node.value < this.value) {
        left match {
          case None => left = Some(node)
          case Some(n0) => n0.add(node)
        }
      } else {
        right match {
          case None => right = Some(node)
          case Some(n0) => n0.add(node)
        }
      }
    }

    def add(ls: TraversableOnce[Int]) {
      for(i <- ls) {
        val node = new Node(i)
        this.add(node)
      }
    }
  }

  object Tree {
    private var root: Option[Node] = None

    def add(ls: Array[Int]) {
      val rs = if (root == None) {
        root = Some(new Node(ls.head))
        ls.tail
      } else ls
      root.map(_.add(rs))
    }

    def count = root.map(_.leftCount).get
  }

  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    Tree.add(a)
    println(Tree.count)
  }
}

object Multithreading extends App {

  val t = readInt //num tests
  val threads = readLine.split(' ').map((s: String) => s.toInt)

  var num = 0
  for (i <- Range(0, t - 1)) {
    if (threads(i) > threads(i + 1)) {
      num += 1
    }
  }
  println(num)
}

import scala.collection.Set

object Multithreading extends App {

  val t = readInt //num tests
  val threads = readLine.split(' ').map((s: String) => s.toInt)
  var set = Set[Int]() ++ threads

  var num = 0
  for (i <- Range(0, t)) {
    set = set - threads(i)
    if (set.exists((x) => x < threads(i))) {
      num += 1
      num += threads.slice(0, i).filter(_ < threads(i)).size
    }
  }
  println(num)
}

import scala.collection.Set

object Multithreading extends App {

  val t = readInt //num tests
  val threads = readLine.split(' ').map((s: String) => s.toInt)
  var set = Set[Int]() ++ threads

  var num = 0
  for (i <- Range(0, t - 1)) {
    set = set - threads(i)
    if (set.exists((x) => x < threads(i))) {
      num += 1
    }
  }
  println(num)
}


import scala.io.StdIn._

object Main extends App {
  readInt()
  val a = readLine().map(_.asDigit)
  val b = readLine().map(_.asDigit)
  val ans = a.zip(b).map { case (x, y) => val d = (x - y).abs; d min (10 - d) }.sum
  println(ans)
}

/**
 * Created by przemek on 30.04.15.
 */
object A extends App  {

  def solve(state: Array[Int], comb: Array[Int]): Int = {
    var sum = 0
    for ((s, k) <- state.zip(comb)) {
      val m = math.min(math.abs(s-k),math.min(10-k+s, 10-s+k))
      sum += m
    }
    sum
  }

  val L = readLine()
  val state = readLine().toCharArray().map(_.toInt)
  val comb = readLine().toCharArray().map(_.toInt)

  println(solve(state, comb))

}

import Array._

object main extends App with fastIO {

  var Array(n) = readLine split(" ") map(_.toInt)
  println(readLine.map(_ - '0').zip(readLine map(_ - '0'))
      .foldLeft(0)((s, v) => s + ((v._1 - v._2).abs min (10 - (v._1 - v._2).abs))))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

object Solve extends App with fastIO{
  val n = nextInt
  val cur = next.map(_.toString.toInt)
  val res = next.map(_.toString.toInt)

  println(
    (for(i <- 0 until n) yield Math.min(Math.min(Math.abs(cur(i)-res(i)), Math.abs((cur(i)+res(i)))),
    Math.min(Math.abs(10+cur(i)-res(i)),Math.abs(10+res(i)-cur(i))))).sum
  )

  flush
}

trait fastIO {
  import java.io._
  val isFile = false
  val input = "file.in"
  val output = "file.out"
  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }
  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }
  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }
  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }
  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object main{
  object Solver extends InputReader{
    def solve(){
      val n = getInt()
      val a = getStr()
      val b = getStr()

      val diffs = for(i <- 0 to n - 1) yield {
        val aa = a(i)
        val bb = b(i)
        val diff: Int = Math.abs(aa - bb)
        diff min 10 - diff
      }

      println(diffs.sum)
    }
  }

  // TEMPLATE ------------------------

  def main(args: Array[String]){
    Solver.solve()
  }

  trait InputReader{
    import java.io._
    import java.util._
    protected val stream = System.in
    private val reader = new BufferedReader(new InputStreamReader(stream))
    private var tokenizer = new StringTokenizer(reader.readLine())

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

    def getInt(): Int = getStr().toInt
    def getLong(): Long = getStr().toLong
    def getDouble(): Double = getStr().toDouble
  }
}

import java.util.StringTokenizer

object _540 extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = next
  val b = next
  val ans = (0 until n).map(i => { val diff = (0 + a(i) - b(i)).abs; diff min (10 - diff) }).sum
  println(ans)
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input1 = scala.io.StdIn.readLine
    val input2 = scala.io.StdIn.readLine
    var res = 0
    for(i <- 0 until n) {
      res += math.min(math.abs(input1(i) - input2(i)), if(input1(i) > input2(i)) 10 - input1(i) + input2(i) else 10 - input2(i) + input1(i)  )
    }
    println(res)
  }
}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def cost(a: Int, b: Int) = math.min(math.abs(a - b), 10 - math.abs(a - b))

  def cost(p: (Char, Char)): Int = cost(p._1.toInt, p._2.toInt)

  def solve(): Unit = {
    val n = nextInt
    val srcs: String = next
    val dest: String = next
    out.println((srcs zip dest).foldLeft(0)(_  + cost(_)))
  }

  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.io._
import java.util._

import scala.collection.mutable

object A {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val s1 = next.toCharArray
    val s2 = next.toCharArray
    var res = 0
    for (i <- 0 until n) {
      if (s1(i) != s2(i)) {
        val x1 = Math.max(s1(i), s2(i)) - 48
        val x2 = Math.min(s1(i), s2(i)) - 48
        res += Math.min(x1 - x2, x2 - x1 + 10)
      }
    }
    out.println(res)
    return 0
  }
}

// http://codeforces.com/contest/540/submission/10942295
object Test2A540 extends App {
  import java.util.Scanner

  type Input = (Seq[(Int, Int)])
  type Output = Int

  def read(scanner: Scanner): Input = {
    import scanner._
    nextInt
    nextLine
    val (src, target) = (nextLine map {_ - '0'}, nextLine map {_ - '0'})
    src zip target
  }

  def solve(problem: Input): Output = {
    problem map { case (a, b) =>
      val (x, y) = if (a < b) (a, b) else (b, a)
      val l = (y - x).abs
      val r = x + (10 - y)
      l min r
    } sum
  }

  def format(result: Output): String = result.toString

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

// http://codeforces.com/contest/540/submission/10942295
object TestA540 extends App {
  import java.util.Scanner

  type Input = (Seq[(Int, Int)])
  type Output = Int

  def read(scanner: Scanner): Input = {
    import scanner._
    nextInt
    nextLine
    val (src, target) = (nextLine map {_ - '0'}, nextLine map {_ - '0'})
    src zip target
  }

  def solve(problem: Input): Output = {
    problem map { case (a, b) =>
      val (x, y) = if (a < b) (a, b) else (b, a)
      val l = (y - x).abs
      val r = x + (10 - y)
      l min r
    } sum
  }

  def format(result: Output): String = result.toString

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object A540 extends App {
  import java.util.Scanner

  type Input = (Seq[(Int, Int)])
  type Output = Int

  def read(scanner: Scanner): Input = {
    import scanner._
    nextInt
    nextLine
    val (src, target) = (nextLine map {_ - '0'}, nextLine map {_ - '0'})
    src zip target
  }

  def solve(problem: Input): Output = {
    problem map { case (a, b) =>
      val (x, y) = if (a < b) (a, b) else (b, a)
      val l = (y - x).abs
      val r = x + (10 - y)
      l min r
    } sum
  }

  def format(result: Output): String = result.toString

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

import scala.io.StdIn._

object A extends App {
  readInt()
  val start = readLine().map(_.toString.toInt)
  val end = readLine().map(_.toString.toInt)

  def diff(ss: Int, tt: Int): Int = {
    val s = Math.min(ss, tt)
    val t = Math.max(ss, tt)

    val p1 = Math.abs(s - t)
    val p2 = Math.abs(s + 10 - t)
    Math.min(p1, p2)
  }

  def solve(s: Seq[Int], t: Seq[Int]): Int = {
    var sum = 0
    for (i <- 0 until s.length) {
      sum += diff(s(i), t(i))
    }
    sum
  }

  println(solve(start, end))

}

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

import Math.min
import Math.abs

object CombinationLock {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readLongs() : Array[Long] =
      readLine.split(' ').map(_.toLong)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     val n = readInt
     val now = readLine.map(_.toInt)
     val secret = readLine.map(_.toInt)
     println(now.zip(secret).foldLeft(0)
         { case (t, (n,s)) => t + min(abs(n-s),10-abs(n-s))})
   }

}


import java.util

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

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

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

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

  def solve(): Unit = {
    val N, T = ni()

//    val W = 5
    val W = 80
    val Width = W
    val MAX = Width * Width

    val g = Array.ofDim[Int](MAX)
    val set = Array.fill(2)(new util.BitSet(MAX))

    case class Coord(x: Int, y: Int)
    val D = Array(Coord(1, 0), Coord(-1, 0),  Coord(0, 1), Coord(0, -1))

    g(0) = N

    var cnt = 0

    var i = 0
    set(0).set(0)
    while(set(i % 2).cardinality() > 0) {
      val ii = i % 2
      set(ii ^ 1).clear()
      var v = set(ii).nextSetBit(0)
      while(v != -1) {
        if (g(v) >= 4) {
          cnt += 1
          val q = g(v) / 4

          g(v) -= q * 4

          val x = v / Width
          val y = v % Width

          REP(4) { i =>
            val d = D(i)
            if (x + d.x >= 0 && y + d.y >= 0) {
              val toXAxis = x + d.x == 0 && d.x == -1
              val toYAxis = y + d.y == 0 && d.y == -1
              val mult =
                if (toXAxis) 2
                else if (toYAxis) 2
                else if (toXAxis && toYAxis) 4
                else 1

              val next = (x + d.x) * Width + y + d.y
              g(next) += q * mult
              set(ii ^ 1).set(next)
            }
          }
        }

        v = set(ii).nextSetBit(v + 1)
      }
      i += 1
    }

    System.err.println(cnt)
    System.err.println(i)

    def sum = {
      val zero = g(0)

      val axis = map(MAX)(identity).filter { v =>
        v != 0 && (v % Width == 0 || v / Width == 0)
      }.map(g).sum

      val other = map(MAX)(identity).filter { v =>
        v % Width > 0 && v / Width > 0
      }.map(g).sum
      zero + axis * 2 + other * 4
    }

//    assert(sum == N)

    REP(T) { _ =>
      val x, y = ni()
      if (x > -W && x < W && y > -W && y < W) {
        val v = abs(x) * Width + abs(y)
        out.println(g(v))
      } else {
        out.println(0)
      }
    }
  }

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

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

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

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

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

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

import java.util

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

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

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

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

  def solve(): Unit = {
    val N, T = ni()

//    val W = 5
    val W = 80
    val Width = W
    val MAX = Width * Width

    val g = Array.ofDim[Int](MAX)
    val set = new util.BitSet(MAX)

    case class Coord(x: Int, y: Int)
    val D = Array(Coord(1, 0), Coord(-1, 0),  Coord(0, 1), Coord(0, -1))

    g(0) = N

    var cnt = 0

//    var i = 0
    set.set(0)
    var v = set.nextSetBit(0)
    while(v != -1) {
      if (g(v) >= 4) {
        cnt += 1
        val q = g(v) / 4

        g(v) -= q * 4

        val x = v / Width
        val y = v % Width

        REP(4) { i =>
          val d = D(i)
          if (x + d.x >= 0 && y + d.y >= 0) {
            val toXAxis = x + d.x == 0 && d.x == -1
            val toYAxis = y + d.y == 0 && d.y == -1
            val mult =
              if (toXAxis) 2
              else if (toYAxis) 2
              else if (toXAxis && toYAxis) 4
              else 1

            val next = (x + d.x) * Width + y + d.y
            g(next) += q * mult
            set.set(next)
          }
        }
      }

      set.clear(v)
      v = set.nextSetBit(v + 1)
      if (v == -1) v = set.nextSetBit(0)
    }

    System.err.println(cnt)
//    System.err.println(i)

    def sum = {
      val zero = g(0)

      val axis = map(MAX)(identity).filter { v =>
        v != 0 && (v % Width == 0 || v / Width == 0)
      }.map(g).sum

      val other = map(MAX)(identity).filter { v =>
        v % Width > 0 && v / Width > 0
      }.map(g).sum
      zero + axis * 2 + other * 4
    }

//    assert(sum == N)

    REP(T) { _ =>
      val x, y = ni()
      if (x > -W && x < W && y > -W && y < W) {
        val v = abs(x) * Width + abs(y)
        out.println(g(v))
      } else {
        out.println(0)
      }
    }
  }

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

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

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

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

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

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