Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.Consider two infinite sets of numbers. The first set consists of odd positive numbers ($$$1, 3, 5, 7, \ldots$$$), and the second set consists of even positive numbers ($$$2, 4, 6, 8, \ldots$$$). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage — the first two numbers from the second set, on the third stage — the next four numbers from the first set, on the fourth — the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out two times more numbers than at the previous one, and also changes the set from which these numbers are written out to another. The ten first written numbers: $$$1, 2, 4, 3, 5, 7, 9, 6, 8, 10$$$. Let's number the numbers written, starting with one.The task is to find the sum of numbers with numbers from $$$l$$$ to $$$r$$$ for given integers $$$l$$$ and $$$r$$$. The answer may be big, so you need to find the remainder of the division by $$$1000000007$$$ ($$$10^9+7$$$).Nazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.

The first line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq 10^{18}$$$) — the range in which you need to find the sum.

Print a single integer — the answer modulo $$$1000000007$$$ ($$$10^9+7$$$).

NoteIn the first example, the answer is the sum of the first three numbers written out ($$$1 + 2 + 4 = 7$$$).In the second example, the numbers with numbers from $$$5$$$ to $$$14$$$: $$$5, 7, 9, 6, 8, 10, 12, 14, 16, 18$$$. Their sum is $$$105$$$.

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 java.util.Arrays.sort

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

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

  def solve(): Unit = {
    val L, R = nl()

    def sum(k: Int): Long = {
      if (k < 0) 0
      else {
        (sum(k - 2) + (1L << k)) % MOD
      }
    }

    def cnt(x: Long): Long = {
      val k = log2(x)

      val cnt = sum(k - 2) + x - (1L << k) + 1
      debug(s"x:$x k:$k cnt:$cnt")
      // 偶数
      if ((k&1) == 1) {
        val a1 = BigInt(cnt) * BigInt(cnt + 1)
        val cnt2 = sum(k - 1)

        val a2 = BigInt(cnt2) * BigInt(cnt2 + 1) - cnt2
        debug(s"cnt2:$cnt2 a1:$a1 a2:$a2")
        val ans = (a1 + a2) % MOD
        ans.longValue()

      // 奇数
      } else {
        val a1 = BigInt(cnt) * BigInt(cnt + 1) - cnt
        val cnt2 = sum(k - 1)

        val a2 = BigInt(cnt2) * BigInt(cnt2 + 1)
        debug(s"cnt2:$cnt2 a1:$a1 a2:$a2")
        val ans = (a1 + a2) % MOD
        ans.longValue()
      }
    }

    val ans = (MOD + cnt(R) - (if (L == 1) 0 else cnt(L - 1))) % MOD
    out.println(ans)
  }

  def log2(x: Long): Int = {
    assert(x > 0)
    var a = x
    var i = 0 // 何回2で割ったら1になるか
    while(a > 1) {
      i += 1
      a >>>= 1
    }
    i
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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

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 java.util.Arrays.sort

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

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

  def solve(): Unit = {
    val L, R = nl()

    def sum(k: Int): Long = {
      if (k < 0) 0
      else {
        (sum(k - 2) + (1L << k)) % MOD
      }
    }

    def cnt(x: Long): Long = {
      val k = log2(x)

      val cnt = sum(k - 2) + x - (1L << k) + 1
      debug(s"x:$x k:$k cnt:$cnt")
      // 偶数
      if ((k&1) == 1) {
        val a1 = BigInt(cnt) * BigInt(cnt + 1)
        val cnt2 = sum(k - 1)

        val a2 = BigInt(cnt2) * BigInt(cnt2 + 1) - cnt2
        debug(s"cnt2:$cnt2 a1:$a1 a2:$a2")
        val ans = (a1 + a2) % MOD
        ans.longValue()

      // 奇数
      } else {
        val a1 = BigInt(cnt) * BigInt(cnt + 1) - cnt
        val cnt2 = sum(k - 1)

        val a2 = BigInt(cnt2) * BigInt(cnt2 + 1)
        debug(s"cnt2:$cnt2 a1:$a1 a2:$a2")
        val ans = (a1 + a2) % MOD
        ans.longValue()
      }
    }

    val ans = cnt(R) - (if (L == 1) 0 else cnt(L - 1))
    out.println(ans)
  }

  def log2(x: Long): Int = {
    assert(x > 0)
    var a = x
    var i = 0 // 何回2で割ったら1になるか
    while(a > 1) {
      i += 1
      a >>>= 1
    }
    i
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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


The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples:  $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points;  $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points;  $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point;  $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).

For each test case, print one integer — the maximum number of points a player can get for winning the game.

NoteTest cases of the example are described in the statement.

//package codeforces.contests._1359

object _1 {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val Array(n, m, k) = io.StdIn.readLine.split(" ").map(_.toInt)

      val each = n / k

      val first = each min m

      val remaining = m - first

      val second = remaining / (k - 1) + (if (remaining % (k-1) != 0) 1 else 0)

      println {
        if (first == second) 0 else first - second
      }
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 0 until t){
      val input = StdIn.readLine.trim.split(" ").map(_.toInt)
      val (n, m, k) = (input(0), input(1), input(2))
      val c = n / k
      val m1 = c min m
      if (k == 1) println(m)
      else {
        // k-1 person m - m1 joker
        val m2 = if ((m-m1) % (k-1) == 0) (m-m1)/(k-1) else (m-m1)/(k-1)+1
        println(0 max (m1 - m2))
      }
    }
  }
}

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

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

    val t = n / k
    val ans =
      if (t >= m) m
      else t - 1 - (m - t - 1) / (k - 1)

    println(ans)
  }
}

object ProblemA extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val m = in.nextInt()
    val k = in.nextInt()

    val maxCount = math.min(m, n / k)
    val leftCount = m - maxCount
    val maxOponent = leftCount / (k - 1) + (if (leftCount % (k - 1) > 0) 1 else 0)

    println(math.max(0, maxCount - maxOponent))
  }

}

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

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

    val t = n / k
    val ans =
      if (t >= m) m
      else t - ((m - t) / (k - 1) + (m - t) % (k - 1))

    println(ans)
  }
}


Tanya has $$$n$$$ candies numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th candy has the weight $$$a_i$$$.She plans to eat exactly $$$n-1$$$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.Your task is to find the number of such candies $$$i$$$ (let's call these candies good) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.For example, $$$n=4$$$ and weights are $$$[1, 4, 3, 3]$$$. Consider all possible cases to give a candy to dad:  Tanya gives the $$$1$$$-st candy to dad ($$$a_1=1$$$), the remaining candies are $$$[4, 3, 3]$$$. She will eat $$$a_2=4$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$4+3=7$$$ and in even days she will eat $$$3$$$. Since $$$7 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$2$$$-nd candy to dad ($$$a_2=4$$$), the remaining candies are $$$[1, 3, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$3$$$. Since $$$4 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$3$$$-rd candy to dad ($$$a_3=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good).  Tanya gives the $$$4$$$-th candy to dad ($$$a_4=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_3=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good). In total there $$$2$$$ cases which should counted (these candies are good), so the answer is $$$2$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the weight of the $$$i$$$-th candy.

Print one integer — the number of such candies $$$i$$$ (good candies) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days.

NoteIn the first example indices of good candies are $$$[1, 2]$$$.In the second example indices of good candies are $$$[2, 3]$$$.In the third example indices of good candies are $$$[4, 5, 9]$$$.

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 = ni()
    val A = na(N)
    val cumE, cumO = Array.ofDim[Int](N + 1)
    REP(N) { i =>
      cumE(i + 1) = cumE(i)
      cumO(i + 1) = cumO(i)
      if (i % 2 == 0) cumE(i + 1) += A(i)
      else cumO(i + 1) += A(i)
    }

//    debug(cumE)
//    debug(cumO)

    var ans = 0
    REP(N) { i =>
      val even = cumE(i) + (cumO(N) - cumO(i + 1))
      val odd = cumO(i) + (cumE(N) - cumE(i + 1))
      if (even == odd) ans += 1
    }

    out.println(ans)
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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
  }
}

object CF_540_3_B {
// date: 19/02/2019

  type In  = (Int, Seq[Int])
  type Out = Int

  def solve(in: In): Out = {
    val (n, xs) = in
    val totals = Array(0,0)
    val m = collection.mutable.Map[Int,Int]() withDefaultValue 0
    xs.indices foreach { i =>
      m += (i -> (xs(i) + totals(i%2)))
      totals(i%2) += xs(i)
    }
    xs.indices count { i =>
      m(i-1) + totals(i%2) - m(i) == m(i-2) + totals((i+1)%2) - m(i-1)
    }
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object CF_540_3_B {
// date: 19/02/2019

  type In  = (Int, Seq[Int])
  type Out = Int

  def solve(in: In): Out = {
    val (n, xs) = in
    val arr = Array.ofDim[Int](xs.length)
    val totals = Array(0,0)
    val m = collection.mutable.Map[Int,Int]() withDefaultValue 0
    for {
      i <- arr.indices
    } {
      m += (i -> (xs(i) + totals(i%2)))
      totals(i%2) += xs(i)
    }
    var goodCount = 0
    for {
      i <- arr.indices
    } {
      val E1 = m(i-1) + totals(i%2) - m(i)
      val E2 = m(i-2) + totals((i+1)%2) - m(i-1)
      if(E1 == E2) goodCount += 1
    }
    goodCount
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}


Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell . The following condition is satisfied for the vector: , where  is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.

The first line contains integers n, m, dx, dy(1 ≤ n ≤ 106, 1 ≤ m ≤ 105, 1 ≤ dx, dy ≤ n) — the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≤ xi, yi ≤ n - 1) — the coordinates of apples. One cell may contain multiple apple trees.

Print two space-separated numbers — the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.

NoteIn the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)In the second sample: (0, 0) - (1, 1) - (0, 0)

import scala.collection._

object E 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, m, dx, dy) = readInts(4)

  val idx = BigInt(dx).modInverse(n).toLong
  val idy = BigInt(dy).modInverse(n).toLong

  val cnt = Array.fill(n){ 0 }

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    val s = idx * (n - x) % n
    val Y = (y + dy * s) % n
    cnt(Y.toInt) += 1
  }

  var maxPos = 0

  for (i <- 0 until n) if (cnt(i) > cnt(maxPos)) maxPos = i

  println(s"0 $maxPos")
}

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

import scala.util.Sorting

object Solution {
  def gcd(a: Long, b: Long): (Long, Long) = {
    if (a == 0)
      return (0, 1)
    if (b == 0)
      return (1, 0)
    val t = gcd(b % a, a)
    val x = t._2 - (b / a) * t._1
    val y = t._1
    return (x, y)
  }

  def getInv(x: Long, mod: Long): Long = {
    val t = gcd(x, mod)
    return t._1
  }

  def solve(in: FastScanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val m = in.nextInt()
    val dx = in.nextInt()
    val dy = in.nextInt()
    val count = new Array[Int](n)
    for (i <- 0 until m) {
      val x = in.nextInt()
      val y = in.nextInt()
      val inv: Long = getInv(dx, n)
      val k: Long = (-x * inv % n + n) % n
      val startY: Int = ((y + k * dy) % n).toInt
      count(startY) += 1
    }
    var maxY = 0
    for (i <- 0 until n)
      if (count(i) > count(maxY))
        maxY = i
    out.println(0 + " " + maxY)
  }

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

  class FastScanner(val in: InputStream) {
    var st: StringTokenizer = null
    var br = new BufferedReader(new InputStreamReader(in))

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

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

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

    def close(): Unit = {
      br.close()
    }
  }

}


Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.

The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.  The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.

In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.  In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val (_, ans) = line.foldLeft(k, List.empty[Int]) {
    case((left, ans), el) =>
      val today = el + Math.max(0, k - left - el)
      (today, today :: ans)
  }
  println(ans.sum - line.sum)
  println(ans.reverse.mkString(" "))
}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {

  def gcd (a: Int, b: Int): Int = if(b == 0) a else gcd(b,a%b)
  def lcm (a: Int, b: Int) = a*b/gcd(a,b)
  case class Res(val lst: List[Int], val cnt: Int)

  def additional_days(xs: List[Int], counter: Int, k: Int, buf: Int): Res = {
    if (xs.isEmpty) Res(List(buf), counter)
    else {
      var res = Res(List(), 0)
      if (buf + xs.head >= k) res = additional_days(xs.tail, counter, k, xs.head)
      else res = additional_days(xs.tail, counter + (k-(buf+xs.head)), k, k-buf)
      Res(buf :: res.lst, res.cnt)
    }
  }

  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val k = sc.nextInt()
  val xs = List.range(0, n).map(_ => sc.nextInt())
  val res = additional_days(xs.tail, 0, k, xs.head)
  println(res.cnt)
  res.lst foreach { x => print(x); print(' ')}
}

import java.io._
import scala.io.Source

import scala.annotation.tailrec

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  import math._

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {

    val line1 = lines.next()
    val line1Strings = line1.split(" ")
    val n = line1Strings(0).toInt
    val k = line1Strings(1).toInt
    val line2 = lines.next()
    val aValues = line2.split(" ").map(_.toInt)
    val soln = solve(n, k, aValues)
    bw.write(soln.extraWalks.toString)
    bw.newLine()
    bw.write(soln.b.mkString(" "))
    bw.newLine()
  }

  case class Solution(val extraWalks: Int, val b: Seq[Int])

  def solve(n: Int, k: Int, a: IndexedSeq[Int]): Solution = {
    case class Accumulator(walksOnPreviousDay: Int, solution: Solution)

    val b = Array.ofDim[Int](n)
    b(0) = a(0)
    for (i <- 1 until n) {
      b(i) = math.max(a(i), k - b(i - 1))
    }
    val extraWalks = a.zip(b).map(x => x._2 - x._1).sum
    Solution(extraWalks, b)
  }
}

object B732 {
  @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, k) = readInts(2)
    val input = readInts(n)
    val sum = input.sum
    for(i <- 1 until n) {
      if(input(i) + input(i-1) < k)
        input(i) += math.max(k - input(i) - input(i-1), 0)
    }
    println(input.sum - sum)
    println(input.mkString(" "))
  }
}

object B732 extends App {
  val init = readLine split " " map(_.toInt)
  val k = init(1)

  val steps = readLine split " " map(_.toInt)
  var n = 0
  val result = steps.tail.foldLeft(List(steps head))((a, el) =>
      if (a.head + el < k) {
        val t  = k - el - a.head
            n  = n + t
        (t + el) :: a
      } else el :: a
    )

  println(n)
  println(result.reverse.mkString(" "))
}

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

object _732B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n, k = read[Int]
    val walks = read[Array, Int](n)
    var ans = 0

    until(n-1) foreach {i =>
      val d1 = walks(i)
      val d2 = walks(i + 1)
      val needed = k - (d1 + d2)
      if (needed > 0) {
        walks(i + 1) += needed
        ans += needed
      }
    }

    writeLine(ans).writeAll(walks, " ")
  }
}
/****************************[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
  }
  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 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")

  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 = "\n"): 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

import scala.language.postfixOps
import scala.math.max

object TaskB extends App {
  val sc = new Scanner(System.in)
  val (n, k) = (sc.nextInt, sc.nextInt)
  // val as = new Array[Int](n)
  var walks = 0
  var prev = 0

  val out = 0 until n map { i =>
    val a = sc.nextInt
    val b = if (i > 0) max(k - a - prev, 0) else 0
    walks += b
    prev = a + b
    prev
  } mkString " "

  println(walks)
  println(out)
}


Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t - 1 gestures (if the icon is on the screen t), and then make another gesture — press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.

The first line of the input contains three numbers n, m, k (1 ≤ n, m, k ≤ 105) — the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains n integers, permutation a1, a2, ..., an — the initial order of icons from left to right in the menu (from the first to the last one), ai —  is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai. The third line contains m integers b1, b2, ..., bm(1 ≤ bi ≤ n) — the ids of the launched applications in the planned order. One application may be launched multiple times.

Print a single number — the number of gestures that Anya needs to make to launch all the applications in the desired order.

NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1, 2, 3, the second screen contains icons 4, 5, 6, the third screen contains icons 7, 8. After application 7 is launched, we get the new arrangement of the icons — (123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures.

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val a: Array[Int] = in.next().split(' ').map(_.toInt - 1)
  val reverse = Array.ofDim[Int](n)
  a.indices.foreach {
    i => reverse(a(i)) = i
  }
  val b: Array[Int] = in.next().split(' ').map(_.toInt - 1)
  println(b.foldLeft(0l) {
    case(count, el) if reverse(el) == 0 => count + 1
    case(count, el) =>
      val position = reverse(el)
      val prevElement = a(position - 1)
      val press = 1 + position / k
      a(position - 1) = el
      a(position) = prevElement
      reverse(prevElement) = position
      reverse(el) = position - 1
      count + press
  })
}

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

object C {

  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 n = nextInt
    val m = nextInt
    val k = nextInt
    //    val screenNumber = new Array[Int](n)
    val rank = new Array[Int](n)
    val valueByRank = new util.HashMap[Int, Int]()
    for (i <- 0 until n) {
      val j: Int = nextInt - 1
      //      screenNumber(j) = Math.ceil(i / k).toInt
      rank(j) = i
      valueByRank.put(i, j)
    }
    var ans = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += Math.ceil(rank(b) / k).toInt + 1
      if (rank(b) != 0) {
        val next = valueByRank.get(rank(b) - 1)
        val pS = rank(b)
        val pN = rank(next)
        rank(b) = pN
        rank(next) = pS
        valueByRank.put(pN, b)
        valueByRank.put(pS, next)
      }
    }
    out.println(ans)
    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.io._
import java.util
import java.util._

object C {

  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 n = nextInt
    val m = nextInt
    val k = nextInt
    val order = new Array[Int](n)
    val rank = new Array[Int](n)
    for (i <- 0 until n) {
      val j = nextInt - 1
      order(i) = j
      rank(j) = i
    }
    var ans:Long = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += Math.ceil(rank(b) / k).toLong + 1
      if (rank(b) != 0) {
        val next = order(rank(b) - 1)
        val pS = rank(b)
        val pN = rank(next)
        rank(b) = pN
        rank(next) = pS
        order(pN) = b
        order(pS) = next
      }
    }
    out.println(ans)
    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 scala.io.StdIn._

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

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

  def solve(as: IndexedSeq[Int], launchOrder: List[Int], k: Int) : Int = {
    def go(order : List[Int], id2Loc : Map[Int,Int], loc2Id: Map[Int,Int], moves: Int) : Int = order match {
      case Nil => moves
      case h :: t =>
        if (id2Loc(h) > 0) {
          /*println(s"launching $h")
          println(s"id2Loc = $id2Loc")
          println(s"loc2Id= $loc2Id")*/
          /*assert(id2Loc.keySet == (0 until as.size).toSet, "keys van id2Loc verkeerd")
          assert(id2Loc.keySet.forall{p => loc2Id(id2Loc(p)) == p}, "id2Loc and loc2Id not inverse")*/
          val prevApp = loc2Id(id2Loc(h) - 1)
          go(t,
            id2Loc - h - prevApp + (h -> (id2Loc(h)-1)) + (prevApp -> id2Loc(h)),
            loc2Id - id2Loc(h) - (id2Loc(h)-1)  + (id2Loc(h)->prevApp) + ((id2Loc(h)-1)-> h),
            moves + id2Loc(h) / k + 1)
        } else {
          go(t,id2Loc,loc2Id,moves+1)
        }
    }
    go(launchOrder,
       as.zipWithIndex.toMap,
       as.zipWithIndex.map{ case (x,y) => (y,x)}.toMap,
       0)
  }

  def solve2(as: Array[Int], launchOrder: List[Int], k: Int) : Long = {
    val id2Loc = as.zipWithIndex.toList.sortBy(_._1).map(_._2).toArray
    val loc2Id = as.clone()
    def go(order : List[Int], moves: Long) : Long = order match {
      case Nil => moves
      case h :: t => {
       /* println(s"launching $h")
        println(s"id2Loc = " + id2Loc.mkString(","))
        println(s"loc2Id= " + loc2Id.mkString(","))
        assert((0 until id2Loc.length).forall{i => id2Loc(loc2Id(i)) == i}, "not inverse")*/
        val curAppLoc = id2Loc(h)
        if (curAppLoc > 0) {
          val prevAppIdd = loc2Id(curAppLoc - 1)
          loc2Id(curAppLoc) = prevAppIdd
          loc2Id(curAppLoc - 1) = h
          id2Loc(h) = curAppLoc - 1
          id2Loc(prevAppIdd) = curAppLoc
          go(t, moves + curAppLoc/k + 1)
        } else {
          go(t, moves + 1)
        }
      }
    }
    go(launchOrder, 0)

  }

  def main (args: Array[String]) {
    val (n,m,k) = readTriple()
    val as = readInts().map(_ - 1)
    val launchOrder = readInts().map(_ - 1)

    println(solve2(as,launchOrder.toList,k))

  }

}

import scala.collection.mutable.HashMap

object Main extends App {

   val Array(n,m,k) = readLine.split(" ").map(_.toInt)
   val as = readLine.split(" ").map(_.toInt)
   val bs = readLine.split(" ").map(_.toInt)

   def touch(pos: Int): Int = (pos / k) + 1

   val front = HashMap[Int, Int]()
   val back = HashMap[Int, Int]()

   as.zipWithIndex foreach { case (v, pos) =>
     front += (v -> pos)
     back += (pos -> v)
   }

   println(bs.map({ app =>
     val pos = front.getOrElse(app, 0)
     if(pos != 0) {
       val prevApp = back.getOrElse(pos-1, 0)
       front += (app -> (pos - 1))
       front += (prevApp -> pos)
       back += ((pos-1) -> app)
       back += (pos -> prevApp)
     }
     touch(pos)
   }).map(_.toLong).sum)

}

object Smartphone {
  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = readLine.split(' ').map(_.toLong)
    val aa = readLine.split(' ').map(_.toLong).toList
    val bb = readLine.split(' ').map(_.toLong).toList

    val positionToApp = scala.collection.mutable.Map(aa.zipWithIndex.map(_.swap): _*)
    val appToPosition = scala.collection.mutable.Map(aa.zipWithIndex: _*)

    val steps = for (currentApp <- bb) yield {
      val currentAppPosition = appToPosition(currentApp)
      if (currentAppPosition > 0) {
        // Swap
        val appToSwap = positionToApp(currentAppPosition - 1)
        // swap positionToApp Map
        val temp1 = positionToApp(currentAppPosition)
        positionToApp(currentAppPosition) = positionToApp(currentAppPosition - 1)
        positionToApp(currentAppPosition - 1) = temp1
        // swap appToPosition Map
        val temp2 = appToPosition(currentApp)
        appToPosition(currentApp) = appToPosition(appToSwap)
        appToPosition(appToSwap) = temp2
      }
      currentAppPosition / k + 1
    }
    val result = steps.sum

    println(result)
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val a: Array[Int] = in.next().split(' ').map(_.toInt - 1)
  val reverse = Array.ofDim[Int](n)
  a.indices.foreach {
    i => reverse(a(i)) = i
  }
  val b: Array[Int] = in.next().split(' ').map(_.toInt - 1)
  println(b.foldLeft(0) {
    case(count, el) if reverse(el) == 0 => count + 1
    case(count, el) =>
      val position = reverse(el)
      val prevElement = a(position - 1)
      val press = 1 + position / k
      a(position - 1) = el
      a(position) = prevElement
      reverse(prevElement) = position
      reverse(el) = position - 1
      count + press
  })
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt - 1).zipWithIndex.toMap
  val b = in.next().split(' ').map(_.toInt - 1)
  println(b.foldLeft((a, a.map(i => i._2 -> i._1), 0)) {
    case((map, reverse, count), 0) =>
      val position = map(0)
      (map, reverse, count + 1)
    case((map, reverse, count), el) =>
      val position = map(el)
      val prevElement = reverse(position - 1)
      val press = 1 + position / k
      (map + (el -> (position - 1)) + (prevElement -> position),
        reverse + (position -> prevElement) + ((position - 1) -> el), count + press)
  }._3)
}

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

object C {

  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 n = nextInt
    val m = nextInt
    val k = nextInt
    val a = new Array[Int](n)
    val screenNumber = new Array[Int](n)
    for (i <- 0 until n) {
      screenNumber(nextInt - 1) = Math.ceil((i + 1) / k).toInt
    }
    var ans = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += screenNumber(b) + 1
      if (b != 0) {
        val prevS = screenNumber(b)
        val prevN = screenNumber(b - 1)
        screenNumber(b) = prevN
        screenNumber(b - 1) = prevS
      }
    }
    out.println(ans)
    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.io._
import java.util
import java.util._

object C {

  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 n = nextInt
    val m = nextInt
    val k = nextInt
    //    val screenNumber = new Array[Int](n)
    val rank = new Array[Int](n)
    val valueByRank = new util.HashMap[Int, Int]()
    for (i <- 0 until n) {
      val j: Int = nextInt - 1
      //      screenNumber(j) = Math.ceil(i / k).toInt
      rank(j) = i
      valueByRank.put(i, j)
    }
    var ans = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += Math.ceil(rank(b) / k).toInt + 1
      if (b != 0) {
        val next = valueByRank.get(rank(b) - 1)
        val pS = rank(b)
        val pN = rank(next)
        rank(b) = pN
        rank(next) = pS
        valueByRank.put(pN, b)
        valueByRank.put(pS, next)
      }
    }
    out.println(ans)
    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.io._
import java.util._

object C {

  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 n = nextInt
    val m = nextInt
    val k = nextInt
    val a = new Array[Int](n)
    val screenNumber = new Array[Int](n)
    for (i <- 0 until n) {
      screenNumber(nextInt - 1) = Math.ceil(i / k).toInt
    }
    var ans = 0L
    for (i <- 0 until m) {
      val b = nextInt - 1
      ans += screenNumber(b) + 1
      if (b != 0) {
        val prevS = screenNumber(b)

        val prevN = screenNumber(b - 1)
        screenNumber(b) = prevN
        screenNumber(b - 1) = prevS
      }
    }
    out.println(ans)
    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 scala.io.StdIn._

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

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

  def solve(as: IndexedSeq[Int], launchOrder: List[Int], k: Int) : Int = {
    def go(order : List[Int], id2Loc : Map[Int,Int], loc2Id: Map[Int,Int], moves: Int) : Int = order match {
      case Nil => moves
      case h :: t =>
        if (id2Loc(h) > 0) {
          /*println(s"launching $h")
          println(s"id2Loc = $id2Loc")
          println(s"loc2Id= $loc2Id")*/
          /*assert(id2Loc.keySet == (0 until as.size).toSet, "keys van id2Loc verkeerd")
          assert(id2Loc.keySet.forall{p => loc2Id(id2Loc(p)) == p}, "id2Loc and loc2Id not inverse")*/
          val prevApp = loc2Id(id2Loc(h) - 1)
          go(t,
            id2Loc - h - prevApp + (h -> (id2Loc(h)-1)) + (prevApp -> id2Loc(h)),
            loc2Id - id2Loc(h) - (id2Loc(h)-1)  + (id2Loc(h)->prevApp) + ((id2Loc(h)-1)-> h),
            moves + id2Loc(h) / k + 1)
        } else {
          go(t,id2Loc,loc2Id,moves+1)
        }
    }
    go(launchOrder,
       as.zipWithIndex.toMap,
       as.zipWithIndex.map{ case (x,y) => (y,x)}.toMap,
       0)
  }

  def solve2(as: Array[Int], launchOrder: List[Int], k: Int) : Int = {
    val id2Loc = as.zipWithIndex.toList.sortBy(_._1).map(_._2).toArray
    val loc2Id = as.clone()
    def go(order : List[Int], moves: Int) : Int = order match {
      case Nil => moves
      case h :: t => {
       /* println(s"launching $h")
        println(s"id2Loc = " + id2Loc.mkString(","))
        println(s"loc2Id= " + loc2Id.mkString(","))
        assert((0 until id2Loc.length).forall{i => id2Loc(loc2Id(i)) == i}, "not inverse")*/
        val curAppLoc = id2Loc(h)
        if (curAppLoc > 0) {
          val prevAppIdd = loc2Id(curAppLoc - 1)
          loc2Id(curAppLoc) = prevAppIdd
          loc2Id(curAppLoc - 1) = h
          id2Loc(h) = curAppLoc - 1
          id2Loc(prevAppIdd) = curAppLoc
          go(t, moves + curAppLoc/k + 1)
        } else {
          go(t, moves + 1)
        }
      }
    }
    go(launchOrder, 0)

  }

  def main (args: Array[String]) {
    val (n,m,k) = readTriple()
    val as = readInts().map(_ - 1)
    val launchOrder = readInts().map(_ - 1)

    println(solve2(as,launchOrder.toList,k))

  }

}

import scala.io.StdIn._

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

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

  def solve(as: IndexedSeq[Int], launchOrder: List[Int], k: Int) : Int = {
    def go(order : List[Int], id2Loc : Map[Int,Int], loc2Id: Map[Int,Int], moves: Int) : Int = order match {
      case Nil => moves
      case h :: t =>
        if (id2Loc(h) > 0) {
          val prevApp = loc2Id(id2Loc(h) - 1)
          go(t,
            id2Loc - h - prevApp + (h -> (id2Loc(h)-1)) + (prevApp -> id2Loc(h)),
            loc2Id - loc2Id(h) - (loc2Id(h)-1)  + (loc2Id(h)->prevApp) + ((loc2Id(h)-1)-> h),
            moves + id2Loc(h) / k + 1)
        } else {
          go(t,id2Loc,loc2Id,moves+1)
        }
    }
    go(launchOrder,
       as.zipWithIndex.toMap,
       as.zipWithIndex.map{ case (x,y) => (y,x)}.toMap,
       0)
  }

  def main (args: Array[String]) {
    val (n,m,k) = readTriple()
    val as = readInts().map(_ - 1)
    val launchOrder = readInts().map(_ - 1)

    println(solve(as,launchOrder.toList,k))

  }

}

import scala.collection.mutable.HashMap

object Main extends App {

   val Array(n,m,k) = readLine.split(" ").map(_.toInt)
   val as = readLine.split(" ").map(_.toInt)
   val bs = readLine.split(" ").map(_.toInt)

   def touch(pos: Int): Int = (pos / k) + 1

   val front = HashMap[Int, Int]()
   val back = HashMap[Int, Int]()

   as.zipWithIndex foreach { case (v, pos) =>
     front += (v -> pos)
     back += (pos -> v)
   }

   println(bs.map({ app =>
     val pos = front.getOrElse(app, 0)
     if(pos != 0) {
       val prevApp = back.getOrElse(pos-1, 0)
       front += (app -> (pos - 1))
       front += (prevApp -> pos)
       back += ((pos-1) -> app)
       back += (pos -> prevApp)
     }
     touch(pos)
   }).sum)

}

object Smartphone {
  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = readLine.split(' ').map(_.toInt)
    val aa = readLine.split(' ').map(_.toInt).toList
    val bb = readLine.split(' ').map(_.toInt).toList

    val positionToApp = scala.collection.mutable.Map(aa.zipWithIndex.map(_.swap): _*)
    val appToPosition = scala.collection.mutable.Map(aa.zipWithIndex: _*)

    val steps = for (currentApp <- bb) yield {
      val currentAppPosition = appToPosition(currentApp)
      if (currentAppPosition > 0) {
        // Swap
        val appToSwap = positionToApp(currentAppPosition - 1)
        // swap positionToApp Map
        val temp1 = positionToApp(currentAppPosition)
        positionToApp(currentAppPosition) = positionToApp(currentAppPosition - 1)
        positionToApp(currentAppPosition - 1) = temp1
        // swap appToPosition Map
        val temp2 = appToPosition(currentApp)
        appToPosition(currentApp) = appToPosition(appToSwap)
        appToPosition(appToSwap) = temp2
      }
      currentAppPosition / k + 1
    }
    val result = steps.sum

    println(result)
  }
}