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

object Main extends App {

  val arr = StdIn.readLine.split(" ").map(_.toInt)
  val n = arr(0)
  val q = arr(1)
  val s = StdIn.readLine()
  val c = new Array[Char](n + 1)
  var cnt = 0
  for (i <- s.indices) {
    c(i + 1) = s(i)
  }
  for (i <- 3 to n) {
    if (c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a') {
      cnt += 1
    }
  }
  def ok(i: Int): Int = {
    if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')
      return 1
    if (
      i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(i - 1) == 'a'
    )
      return 1
    if (i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a')
      return 1
    return 0
  }
  var po = 0
  var r = ""
  for (j <- 1 to q) {
    val query = StdIn.readLine.split(" ")
    po = query(0).toInt
    r = query(1)
    cnt -= ok(po)
    c(po) = r(0)
    cnt += ok(po)
    println(cnt)
  }

  def check(kk: Int): Boolean = {
    return true
  }
  def bs(st: Int, en: Int): Int = {
    if (en - st <= 1) {
      if (check(en))
        return en
      else
        return st
    }
    val mid = (st + en) / 2
    if (check(mid))
      return bs(mid, en)
    else
      return bs(st, mid)
  }
}

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

object Main extends App {

  val arr = StdIn.readLine.split(" ").map(_.toInt)
  val n = arr(0)
  val q = arr(1)
  val s = StdIn.readLine()
  val c = new Array[Char](n + 1)
  var cnt = 0
  for (i <- s.indices) {
    c(i + 1) = s(i)
  }
  for (i <- 3 to n) {
    if (c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a') {
      cnt += 1
    }
  }
  def ok(i: Int): Int = {
    if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')
      return 1
    if (
      i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(i - 1) == 'a'
    )
      return 1
    if (i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a')
      return 1
    return 0
  }
  var po = 0
  var r = ""
  for (j <- 1 to q) {
    val (poa: String, ra: String) = StdIn.readf2("{0} {1}")
    po = poa.toInt
    r = ra
    cnt -= ok(po)
    c(po) = r(0)
    cnt += ok(po)
    println(cnt)
  }

  def check(kk: Int): Boolean = {
    return true
  }
  def bs(st: Int, en: Int): Int = {
    if (en - st <= 1) {
      if (check(en))
        return en
      else
        return st
    }
    val mid = (st + en) / 2
    if (check(mid))
      return bs(mid, en)
    else
      return bs(st, mid)
  }
}

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

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

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

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

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

    val t = 1//readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val c = new Array[Char](n+1)
        val q = readInt()
        val s = readString()
        var cnt = 0
        for (i <- s.indices) {
            c(i+1) = s(i)
        }
        for (i <- 3 to n) {
            if (c(i) == 'c' && c(i-1) == 'b' && c(i-2) == 'a') {
                cnt += 1
            }
        }
        def ok(i: Int): Int = {
            if (i >= 2 && c(i) == 'c' && c(i-1) == 'b' && c(i-2) == 'a')
                return 1
            if (i >= 1 && i+1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(i-1) == 'a')
                return 1
            if (i+2 <= n && c(i + 2) == 'c' && c(i+1) == 'b' && c(i) == 'a')
                return 1
            return 0
        }
        var po = 0
        var r = ""
        for (j <- 1 to q) {
            po = readInt()
            r = readString()
            cnt -= ok(po)
            c(po) = r(0)
            cnt += ok(po)
            writer.println(cnt)
        }

        def check(kk: Int): Boolean = {
            return true
        }
        def bs(st:Int, en:Int): Int = {
            if (en - st <= 1) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}

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

object Main extends App {
  val writer = new PrintWriter(System.out, false)
  val arr = StdIn.readLine.split(" ").map(_.toInt)
  val n = arr(0)
  val q = arr(1)
  var s = StdIn.readLine()
  val c = new Array[Char](n + 1)
  for (i <- s.indices) {
    c(i + 1) = s(i)
  }
  var num = 0
  c.indices
    .foreach(i => {
      if (c(i) == 'a' && i <= n - 2) {
        if (c(i + 1) == 'b' && c(i + 2) == 'c') {
          num += 1
        }
      }
    })

  (0 until q).foreach { i =>
    val (pos, char) = StdIn.readLine().split(" ") match {
      case Array(a, b) => (a.toInt, b.charAt(0))
    }
    if (char == c(pos)) {
      writer.println(num)
    } else {
      def ok(i: Int): Boolean = {
        if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')
          return true
        else if (
          i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(
            i - 1
          ) == 'a'
        )
          return true
        else if (
          i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a'
        )
          return true
        return false
      }
      val f1 = ok(pos)
      c(pos) = char
      val f2 = ok(pos)
      if (f1 && !f2) {
        num -= 1
      } else if (!f1 && f2) {
        num += 1
      }

      writer.println(num)
    }
  }
  writer.flush()
}

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

object Main extends App {
  val writer = new PrintWriter(System.out, false)
  val arr = StdIn.readLine.split(" ").map(_.toInt)
  val n = arr(0)
  val q = arr(1)
  var s = StdIn.readLine()
  val c = new Array[Char](n + 1)
  for (i <- s.indices) {
    c(i + 1) = s(i)
  }
  var num = 0
  c.indices
    .foreach(i => {
      if (c(i) == 'a' && i <= n - 2) {
        if (c(i + 1) == 'b' && c(i + 2) == 'c') {
          num += 1
        }
      }
    })

  (0 until q).foreach { i =>
    val (pos, char) = StdIn.readLine().split(" ") match {
      case Array(a, b) => (a.toInt, b.charAt(0))
    }
    if (char == c(pos)) {
      writer.println(num)
    } else {
      def testChar(char: Char) = char match {
        case 'a' => {
          if (pos <= n - 2) {
            c(pos + 1) == 'b' && c(pos + 2) == 'c'
          } else {
            false
          }
        }
        case 'b' => {
          if (pos <= n - 1 && pos >= 2) {
            c(pos - 1) == 'a' && c(pos + 1) == 'c'
          } else {
            false
          }
        }
        case 'c' => {
          if (pos >= 3) {
            c(pos - 1) == 'b' && c(pos - 2) == 'a'
          } else {
            false
          }
        }
      }
      val f1 = testChar(c(pos))
      val f2 = testChar(char)
      if (f1 && !f2) {
        num -= 1
      } else if (!f1 && f2) {
        num += 1
      }
      c(pos) = char
      writer.println(num)
    }
  }
  writer.flush()
}

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

object Main extends App {
  val writer = new PrintWriter(System.out, false)
  val arr = StdIn.readLine.split(" ").map(_.toInt)
  val n = arr(0)
  val q = arr(1)
  var s = StdIn.readLine()
  val c = new Array[Char](n + 1)
  for (i <- s.indices) {
    c(i + 1) = s(i)
  }
  var num = c.indices
    .map(i => {
      if (c(i) == 'a' && i <= n - 2) {
        if (c(i + 1) == 'b' && c(i + 2) == 'c') {
          1
        } else {
          0
        }
      } else {
        0
      }
    })
    .sum
  (0 until q).foreach { i =>
    val (pos, char) = StdIn.readLine().split(" ") match {
      case Array(a, b) => (a.toInt, b.charAt(0))
    }
    if (char == c(pos)) {
      writer.println(num)
    } else {
      def testChar(char: Char) = char match {
        case 'a' => {
          if (pos <= n - 2) {
            c(pos + 1) == 'b' && c(pos + 2) == 'c'
          } else {
            false
          }
        }
        case 'b' => {
          if (pos <= n - 1 && pos >= 2) {
            c(pos - 1) == 'a' && c(pos + 1) == 'c'
          } else {
            false
          }
        }
        case 'c' => {
          if (pos >= 3) {
            c(pos - 1) == 'b' && c(pos - 2) == 'a'
          } else {
            false
          }
        }
      }
      val f1 = testChar(c(pos))
      val f2 = testChar(char)
      if (f1 && !f2) {
        num -= 1
      } else if (!f1 && f2) {
        num += 1
      }
      c(pos) = char
      writer.println(num)
    }
  }
  writer.flush()
}

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

object Main extends App {
  val writer = new PrintWriter(System.out, false)
  val reader = new BufferedReader(new InputStreamReader(System.in))
  var st = new StringTokenizer("")
  def next(): String = {
    while (!st.hasMoreTokens) { st = new StringTokenizer(reader.readLine()) };
    st.nextToken()
  }
  def readInt(): Int = next().toInt
  def readLong(): Long = next().toLong
  def readString(): String = next()
  case class fenwick(n: Int) {
    val tree = new Array[Long](n + 1)
    def query(ind: Int): Long = {
      var idx = ind
      var ans = 0L
      while (idx > 0) {
        ans += tree(idx)
        idx -= (idx & -idx)
      }
      return ans
    }
    def update(ind: Int, value: Long): Unit = {
      var idx = ind
      while (idx <= n) {
        tree(idx) += value
        idx += (idx & -idx)
      }
    }
  }
  case class pair(val a: Int, val b: Int) extends Ordered[pair] {
    override def compare(that: pair): Int = {
      return -1 * a.compareTo(that.a)
    }
  }
  def gcd(a: Int, b: Int): Int = b match {
    case 0 => a
    case n => gcd(b, a % b)
  }
  val rem = 1000000007
  val maxn = 200010
  val mp = mutable.Map[Char, Int]()
  val t = 1 //readInt()
  for (tt <- 1 to t) {
    val n = readInt()
    val c = new Array[Char](n + 1)
    val q = readInt()
    val s = readString()
    var cnt = 0
    for (i <- s.indices) {
      c(i + 1) = s(i)
    }
    for (i <- 3 to n) {
      if (c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a') {
        cnt += 1
      }
    }
    def ok(i: Int): Int = {
      if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')
        return 1
      if (
        i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(
          i - 1
        ) == 'a'
      )
        return 1
      if (i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a')
        return 1
      return 0
    }
    var po = 0
    var r = ""
    for (j <- 1 to q) {
      po = readInt()
      r = readString()
      cnt -= ok(po)
      c(po) = r(0)
      cnt += ok(po)
      println(cnt)
    }

    def check(kk: Int): Boolean = {
      return true
    }
    def bs(st: Int, en: Int): Int = {
      if (en - st <= 1) {
        if (check(en))
          return en
        else
          return st
      }
      val mid = (st + en) / 2
      if (check(mid))
        return bs(mid, en)
      else
        return bs(st, mid)
    }
  }
}

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

object Main extends App {
  val writer = new PrintWriter(System.out, false)
  val reader = new BufferedReader(new InputStreamReader(System.in))
  var st = new StringTokenizer("")
  def next(): String = {
    while (!st.hasMoreTokens) { st = new StringTokenizer(reader.readLine()) };
    st.nextToken()
  }
  def readInt(): Int = next().toInt
  def readLong(): Long = next().toLong
  def readString(): String = next()
  case class fenwick(n: Int) {
    val tree = new Array[Long](n + 1)
    def query(ind: Int): Long = {
      var idx = ind
      var ans = 0L
      while (idx > 0) {
        ans += tree(idx)
        idx -= (idx & -idx)
      }
      return ans
    }
    def update(ind: Int, value: Long): Unit = {
      var idx = ind
      while (idx <= n) {
        tree(idx) += value
        idx += (idx & -idx)
      }
    }
  }
  case class pair(val a: Int, val b: Int) extends Ordered[pair] {
    override def compare(that: pair): Int = {
      return -1 * a.compareTo(that.a)
    }
  }
  def gcd(a: Int, b: Int): Int = b match {
    case 0 => a
    case n => gcd(b, a % b)
  }
  val rem = 1000000007
  val maxn = 200010
  val mp = mutable.Map[Char, Int]()
  val t = 1 //readInt()
  for (tt <- 1 to t) {
    val n = readInt()
    val c = new Array[Char](n + 1)
    val q = readInt()
    val s = readString()
    var cnt = 0
    for (i <- s.indices) {
      c(i + 1) = s(i)
    }
    for (i <- 3 to n) {
      if (c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a') {
        cnt += 1
      }
    }
    def ok(i: Int): Int = {
      if (i >= 2 && c(i) == 'c' && c(i - 1) == 'b' && c(i - 2) == 'a')
        return 1
      if (
        i >= 1 && i + 1 <= n && c(i + 1) == 'c' && c(i) == 'b' && c(
          i - 1
        ) == 'a'
      )
        return 1
      if (i + 2 <= n && c(i + 2) == 'c' && c(i + 1) == 'b' && c(i) == 'a')
        return 1
      return 0
    }
    var po = 0
    var r = ""
    for (j <- 1 to q) {
      po = readInt()
      r = readString()
      cnt -= ok(po)
      c(po) = r(0)
      cnt += ok(po)
      writer.println(cnt)
    }

    def check(kk: Int): Boolean = {
      return true
    }
    def bs(st: Int, en: Int): Int = {
      if (en - st <= 1) {
        if (check(en))
          return en
        else
          return st
      }
      val mid = (st + en) / 2
      if (check(mid))
        return bs(mid, en)
      else
        return bs(st, mid)
    }
  }
  writer.flush()
}

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

object Main extends App {
  val writer =  new PrintWriter(System.out, false)
  val arr = StdIn.readLine.split(" ").map(_.toInt)
  val n = arr(0)
  val q = arr(1)
  var s = StdIn.readLine()
  var num = s.indices
    .map(i => {
      if (s(i) == 'a' && i < n - 2) {
        if (s(i + 1) == 'b' && s(i + 2) == 'c') {
          1
        } else {
          0
        }
      } else {
        0
      }
    })
    .sum
  (0 until q).foreach { i =>
    val (pos, c) = StdIn.readLine().split(" ") match {
      case Array(a, b) => (a.toInt, b.charAt(0))
    }
    if (c == s(pos - 1)) {
      println(num)
    } else {
      def testChar(c: Char) = c match {
        case 'a' => {
          if (pos <= n - 2) {
            s(pos) == 'b' && s(pos + 1) == 'c'
          } else {
            false
          }
        }
        case 'b' => {
          if (pos <= n - 1 && pos >= 2) {
            s(pos - 2) == 'a' && s(pos) == 'c'
          } else {
            false
          }
        }
        case 'c' => {
          if (pos >= 3) {
            s(pos - 2) == 'b' && s(pos - 3) == 'a'
          } else {
            false
          }
        }
      }
      val f1 = testChar(s(pos - 1))
      val f2 = testChar(c)
      if (f1 && !f2) {
        num -= 1
      } else if (!f1 && f2) {
        num += 1
      }
      s = s.updated(pos - 1, c)
      writer.println(num)
    }
  }
  writer.flush()
}


import java.util.PriorityQueue

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object CE976B extends App {
  val nums = readLine().split(" ")
  val n = nums(0).toInt;
  val k = nums(1).toInt;
  var hotelCounts = 0;
  if (k % 2 == 1 && n % 2 == 0) {
    println("NO")
  }
  else {
    println("YES")
    var ans = Array.ofDim[Char](4, n)
    for (i <- 0 to 3) {

      for (j <- 0 until n) ans(i)(j) = '.'
    }
    if (k % 2 == 1) {
      if (k > n - 2) {
        ans = fillRow(ans, 1, n, n - 2)
        ans = fillRow(ans, 2, n, k - n + 2)
      } else {
        ans = fillRow(ans, 1, n, k)
      }
    } else {
      val dis = k / 2;
      for (i <- 1 to 2)
        for (j <- 1 until n - 1) {
          if (j <= dis) ans(i)(j) = '#'
        }
    }

    for (i <- 0 to 3) {
      for (j <- 0 to n - 1) {
        print(ans(i)(j))
      }
      println()
    }

  }

  def fillRow(ans: Array[Array[Char]], row: Int, n: Int, k: Int): Array[Array[Char]] = {
    var ret = ans
    val dis = (n - k) / 2;
    for (i <- 0 until n) {
      if (i >= dis && i < n - dis)
        ret(row)(i) = '#'
    }
    if (k % 2 == 0)
      ret(row)(n / 2) = '.'
    return ret
  }

}

import scala.io.StdIn;

object Necklace {
  def main(args: Array[String]): Unit = {
    val n :: k :: Nil = readLine split(" ") map (_.toInt) toList;
    val mid = n >> 1;
    def getCount (x: Int): Int = Math.min(x, n - x - 1) * 2
    def getPlacement(x: Int, y: Int): Char =
      if (y == 0 || y == n - 1) '.'
      else if (k == 2 * (n - 2)) '#'
      else if (y == mid) (if ((k % 2) == 1 && (x == 0)) '#' else '.')
      else if (x == 0) (if (getCount(y) <= k) '#' else '.')
      else if (getCount(y) <= (k - n + 3)) '#' else '.'
    println("YES");
    println("." * n);
    val lines = for (i <- 0 to 1) yield
      (for (j <- 0 to n - 1) yield getPlacement(i, j)).mkString("")
    println(lines.mkString("\n"));
    println("." * n);
  }
}

import java.util.PriorityQueue

import scala.collection.mutable

object CE976B extends App {
  val nums = readLine().split(" ")
  val n = nums(0).toInt;
  val k = nums(1).toInt;
  var hotelCounts = 0;
  println("YES")
  for (i <- 1 to 4) {
    for (j <- 1 to n) {
      if (i > 1 && i < 4 && j > 1 && j < n && hotelCounts < k) {
        print('#')
        hotelCounts += 1
      }
      else {
        print(".")
      }
    }
    println()
  }

}

object B extends App {
  //  3 <= n <= 99
  //  0 <= k <= 2 * (n - 2)
  val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  if (k >= n - 2) {
    println("YES")
    println("." * n)
    println("." + "#" * (n - 2) + ".")
    val r = k - n + 2
    println("." + "." * (n - 2 - r) + "#" * r + ".")
    println("." * n)
  } else if (k % 2 == 0) {
    println("YES")
    println("." * n)
    val r = k / 2
    println("." + "#" * r + "." * (n - 1 - r) )
    println("." + "#" * r + "." * (n - 1 - r) )
    println("." * n)
  } else {
    println("NO")
  }
}

import scala.io.StdIn;

object Necklace {
  def main(args: Array[String]): Unit = {
    val n :: k :: Nil = readLine split(" ") map (_.toInt) toList;
    val mid = n >> 1;
    def getCount (x: Int): Int = Math.min(x, n - x - 1) * 2
    def getPlacement(x: Int, y: Int): Char =
      if (y == 0 || y == n - 1) '.'
      else if (k == 2 * (n - 2)) '#'
      else if (y == mid) (if ((k % 2) == 1 && (x == 0)) '#' else '.')
      else if (x == 0) (if (getCount(y) <= k) '#' else '.')
      else if (getCount(y) <= (k - n + 2)) '#' else '.'
    println("YES");
    println("." * n);
    val lines = for (i <- 0 to 1) yield
      (for (j <- 0 to n - 1) yield getPlacement(i, j)).mkString("")
    println(lines.mkString("\n"));
    println("." * n);
  }
}


import scala.collection.mutable

//package e

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, k) = readInts(2)
  val us = readInts(2 * k).map(_ - 1).toSet

  val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(parent: Int, u: Int): (Int, Long) = {
//    var cables = cables0
    var resBelow = 0L
    var uCountBelow = 0

    if (us(u)) {
      uCountBelow += 1
    }

    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (v != parent) {
        val (uBel, resBel) = dfs(u, v)
        resBelow += resBel
        uCountBelow += uBel
      }
      i += 1
    }
//println(u, (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow)))
    (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow))
  }

  val res = dfs(-1, 0)

  println(res._2)
}

import scala.collection.immutable.BitSet
import scala.collection.mutable

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

  val Array(n, k) = readInts(2)
  val us = BitSet.empty ++ readInts(2 * k).map(_ - 1)

  val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(parent: Int, u: Int): (Int, Long) = {

    var resBelow = 0L
    var uCountBelow = 0

    if (us(u)) {
      uCountBelow += 1
    }

    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (v != parent) {
        val (uBel, resBel) = dfs(u, v)
        resBelow += resBel
        uCountBelow += uBel
      }
      i += 1
    }

    (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow))
  }

  val (_, res) = dfs(-1, 0)

  println(res)
}

import scala.collection.mutable.BitSet
import scala.collection.mutable

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

  val Array(n, k) = readInts(2)
  val us = new BitSet(n)
  us ++= readInts(2 * k).map(_ - 1)

  val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(parent: Int, u: Int): (Int, Long) = {

    var resBelow = 0L
    var uCountBelow = 0

    if (us(u)) {
      uCountBelow += 1
    }

    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (v != parent) {
        val (uBel, resBel) = dfs(u, v)
        resBelow += resBel
        uCountBelow += uBel
      }
      i += 1
    }

    (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow))
  }

  val (_, res) = dfs(-1, 0)

  println(res)
}

import scala.collection.mutable

//package e

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, k) = readInts(2)
  val us = readInts(2 * k).map(_ - 1).toSet

  val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(parent: Int, u: Int, cables0: Int): (Int, Long) = {
//    var cables = cables0
    var resBelow = 0L
    var uCountBelow = 0

    if (us(u)) {
      uCountBelow += 1
//      if (uCount <= k) cables += 1
//      else cables -= 1
    }

    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (v != parent) {
        val (uBel, resBel) = dfs(u, v, cables0)
        resBelow += resBel
        uCountBelow += uBel
      }
      i += 1
    }
//println(u, (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow)))
    (uCountBelow, resBelow + Math.min(2 * k - uCountBelow, uCountBelow))
  }

  val res = dfs(-1, 0, 0)

  println(res._2)
}


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

  (0 until t).foreach { _ =>
    val Array(n, _, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val s = (0 until n).map(i => ('a' + i % b).toChar).mkString("")

    println(s)
  }
}

object B extends App {
  case class Sub(n: Int, a: Int, b: Int)

  private def construct(s: Sub): String =
    (Range('a', 'z' + 1).take(s.b).map(_.toChar).mkString("") * (1 + s.n / s.b))
      .take(s.n)

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

  val input = (0 until t)
    .foldLeft(List.empty[Sub]) { (acc, _) =>
      val Array(n, a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      Sub(n, a, b) :: acc
    }
    .reverse

  val output = input.map(construct)

  output.foreach(println)
}

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

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

    val s = (('a' to 'z').take(b).mkString("") * (1 + n / b)).take(n)

    println(s)
  }
}

import scala.io.StdIn

object Solution_B extends App {
  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val input = StdIn.readLine().split(" ").map{_.toInt}
    val N = input(0)
    val A = input(1)
    val B = input(2)
    val result = new StringBuilder()
    val pattern = Array.fill[Char](A)('a')
    for (c <- A - B + 1 until A) {
      pattern(c) = (pattern(c - 1) + 1).toChar
    }
    var offset = 0
    for (c <- 0 until N) {
      result.append(pattern(offset))
      offset += 1
      offset %= A
    }
    println(result.toString())
  }
}

object Main extends App {
  import scala.io.StdIn._
  val t = readInt
  val alphabets = ('a' to 'z').mkString
  for(_ <- 0 until t) {
    val Array(n, a, b) = readLine.trim.split(' ').map(_.toInt)
    println(((alphabets.take(b) + "a" * (a - b)) * ((n + a - 1) / a)).take(n))
  }
}

object B extends App {
  case class Sub(n: Int, a: Int, b: Int)

  private def construct(s: Sub): String =
    (Range('a', 'z').take(s.b).map(_.toChar).mkString("") * (s.n / s.b + 1))
      .take(s.n)

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

  val input = (0 until t)
    .foldLeft(List.empty[Sub]) { (acc, _) =>
      val Array(n, a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      Sub(n, a, b) :: acc
    }
    .reverse

  val output = input.map(construct)

  output.foreach(println)
}


import scala.collection.JavaConversions._
import scala.collection.mutable._

object Codeforces546B {
    def main(args: Array[String]) {
        val n = scala.io.StdIn.readLine().toInt
        val ar = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted
        var coins = 0
        for (i <- 1 until n) {
            if (ar(i) <= ar(i-1)) {
                coins += (ar(i-1) + 1 - ar(i))
                ar(i) = ar(i-1) + 1
            }
        }
        println(coins)
    }
}

object Main {
  def main(args:Array[String]) {
    val sc = new java.util.Scanner(System.in)
    var pre, ans = 0
    Array.fill(sc.nextInt)(sc.nextInt).sorted.foreach { cur =>
      val up = Seq(cur - pre - 1, 0).min.abs
      ans += up
      pre = cur + up
    }
    println(ans)
  }
}

import java.util.StringTokenizer

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

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

  val n = next.toInt
  val a = (1 to n).map(i => next.toInt)
  val cnt = Array.fill(2 * n + 10)(0)
  a.foreach(i => cnt(i) += 1)

  def doit(i: Int, acc: Int): Int = {
//    println(cnt.toList)
    if (i == cnt.length) acc
    else {
      val delta = (cnt(i) - 1) max 0
      cnt(i) -= delta
      if (i + 1 < cnt.length) cnt(i + 1) += delta
      doit(i + 1, acc + delta)
    }
  }

  println(doit(0, 0))
}

/**
 * Created by r on 5/23/15.
 */
object badge {
  def main (args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt //最初の整数が読み込まれる
    var ar = new Array[Int](n)
    for (i <- 0 to n-1)
      ar(i) = sc.nextInt
    scala.util.Sorting.quickSort(ar)
    var coin = 0
    var flg = false
    do {
      flg = false
      for (i <- 0 to n-2) {
        if (ar(i) >= ar(i + 1)) {
          ar(i + 1) = ar(i + 1) + 1
          coin = coin + 1
          flg = true
        }
      }
    } while(flg == true)

    println(coin)
  }
}

object R304_SoldierAndBadges extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextLine().toInt
  val a = sc.nextLine().split(" ").map(_.toInt).sorted

  var ans = 0
  var bef = a(0)
  (1 to a.length - 1).foreach { i =>
    var tmp = 0
    while (bef >= a(i) + tmp)  {
      tmp += 1
      ans += 1
    }
    bef = a(i) + tmp
  }
  println(ans)
}

import scala.annotation.tailrec

object _546B extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = List[Int]
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt)
  }

  override def solve(input: Input) = {
    val used = mutable.Set.empty[Int]
    @tailrec
    def f(badges: List[Int], acc: Int): Int = badges match {
      case Nil => acc
      case x :: xs if used contains x =>
        val y = (Stream.from(x+1) find {i => !(used contains i)}).head
        f(y :: xs, (y - x) + acc)
      case x :: xs =>
        used += x
        f(xs, acc)
    }
    f(input, 0)
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

object _546B extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = List[Int]
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt)
  }

  override def solve(input: Input) = {
    val used = mutable.Set.empty[Int]

    def f(badges: List[Int]): Int = badges match {
      case Nil => 0
      case (x :: xs) if used contains x =>
        val y = ((x+1 to 10000) find (i => !(used contains i))).get
        used += y
        (y - x) + f(xs)
      case (x :: xs) =>
        used += x
        f(xs)
    }
    f(input)
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

object _546B extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = List[Int]
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt)
  }

  override def solve(input: Input) = {
    val used = mutable.Set.empty[Int]

    def f(badges: List[Int]): Int = badges match {
      case Nil => 0
      case x :: xs if used contains x =>
        val y = (Stream.from(x+1) find {i => !(used contains i)}).head
        (y - x) + f(y :: xs)
      case x :: xs =>
        used += x
        f(xs)
    }
    f(input)
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

import scala.io.StdIn

object Main {
  val a = Array.fill(6001)(0);
  var r = 0;

  def main(args: Array[String]): Unit = {
    StdIn.readLine(); // ignore
    StdIn.readLine().split(" ").map(Integer.parseInt).foreach(a(_)+=1);

    for(i <- 0 to 6000) {
      if ( a(i) > 1 ) {
        val d = a(i) - 1;
        a(i+1) += d;
        r += d;
      }
    }

    println(r);
  }
}

import scala.io.StdIn
import scala.collection.SeqView

object Main {
  val a = Array.fill(6001)(0);
  var r = 0;

  def main(args: Array[String]): Unit = {
    StdIn.readLine(); // ignore
    StdIn.readLine().split(" ").map(Integer.parseInt).foreach(a(_)+=1);

    for(i <- (0 to 6000).view if (a(i) > 1); d = a(i) - 1) {
      a(i+1) += d;
      r += d;
    }

    println(r);
  }
}

import scala.io.StdIn._

object B extends App {
  readInt()
  val input = readLine().split(" ").map(_.toInt).sorted
  val counter = new Array[Boolean](3000 * 3000 + 1)

  def solve() = {
    var answer = 0
    for (i <- input) {
      if (!counter(i)) counter(i) = true
      else {
        var find = i
        while (counter(find)) {
          answer += 1
          find += 1
        }
        counter(find) = true
      }
    }
    answer
  }

  println(solve())
}

import scala.io.StdIn._

/**
 * Created by przemek on 23.05.15.
 */
object Badges {
  def main(args: Array[String]) = {
    val N = readInt()
    val badges = readLine().split(" ").map(_.toInt).sortWith(_ < _)
    solve(N, badges)
  }

  def solve(N: Int, badges: Array[Int]) {
    var c = 0
    for (i <- 1 to N - 1) {
      if (badges(i) <= badges(i-1)) {
        c += badges(i-1) + 1 - badges(i)
        badges(i) = badges(i-1) + 1
      }
    }
    println(c)
  }
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n =nextInt
    val a=Array.fill(n)(0)
    for(i<-0 until n){a(i)=nextInt}
    scala.util.Sorting.quickSort(a)
    var sum=0
    for(i<-0 until n-1){
      var l=1+i
      while(l<n&& a(l)==a(i)){
        a(l)+=1
        sum+=1
        l+=1
      }

    }
    out.println(sum)
    //code ends here
    out.flush
    out.close
  }
}

import java.util.StringTokenizer

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

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

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

  def doit(a: List[Int], acc: Int): Int =
    if (a == Nil) acc
    else if (a.count(i => i == a.head) > 1) doit(a.head + 1 :: a.tail, acc + 1)
    else doit(a.tail, acc)

  println(doit(a.toList, 0))
}

import java.util.StringTokenizer

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

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

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

  def doit(a: List[Int], acc: Int): Int = {
    if (a == Nil) acc
    else if (a.count(i => i == a.head) > 1) doit(a.head + 1 :: a.tail, acc + 1)
    else doit(a.tail, acc)
  }

  println(doit(a.toList, 0))
}

object _546B extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = List[Int]
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt)
  }

  override def solve(input: Input) = {
    def f(badges: List[Int]): Int = badges match {
      case Nil => 0
      case (x :: xs) if xs contains x =>
        val y = ((x+1 to 10000) find (i => !(xs contains i))).get
        (y - x) + f(y :: xs)
      case (x :: xs) => f(xs)
    }
    f(input)
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

import scala.io.StdIn

object Main {
  val a = Array.fill(6001)(0);
  var r = 0;

  def main(args: Array[String]): Unit = {
    StdIn.readLine(); // ignore
    StdIn.readLine().split(" ").map(Integer.parseInt).foreach(a(_)+=1);

    for(i <- 0 to 6000 if a(i) > 1) {
      a(i+1) += 1;
      r += 1;
    }

    println(r);
  }
}

import scala.io.StdIn

object Main {
  val a = Array.fill(6001)(0);
  var r = 0;

  def main(args: Array[String]): Unit = {
    StdIn.readLine(); // ignore
    StdIn.readLine().split(" ").map(Integer.parseInt).foreach(a(_)+=1);

    for(i <- 0 to 6000 if a(i) > 1; d = a(i) - 1) {
      a(i+1) += d;
      r += d;
    }

    println(r);
  }
}

import scala.io.StdIn._

/**
 * Created by przemek on 23.05.15.
 */
object Badges {
  def main(args: Array[String]) = {
    val N = readInt()
    val badges = readLine().split(" ").map(_.toInt).sortWith(_ < _)
    println(badges.mkString(" "))
    solve(N, badges)
  }

  def solve(N: Int, badges: Array[Int]) {
    var c = 0
    for (i <- 1 to N - 1) {
      if (badges(i) <= badges(i-1)) {
        c += badges(i-1) + 1 - badges(i)
        badges(i) = badges(i-1) + 1
      }
    }
    println(c)
  }
}

import scala.io.StdIn._

/**
 * Created by przemek on 23.05.15.
 */
object Badges {
  def main(args: Array[String]) = {
    val N = readInt()
    val badges = readLine().split(" ").map(_.toInt).sortWith(_ < _)

    var prev = 0
    var c = 0
    for (i <- 0 to N - 1) {
      if (badges(i) == prev) {
        badges(i) += 1
        c += 1
      }
      prev = badges(i)
    }
    println(c)
  }

}

import scala.io.StdIn._

/**
 * Created by przemek on 23.05.15.
 */
object Badges {
  def main(args: Array[String]) = {
    val N = readInt()
    val badges = readLine().split(" ").map(_.toInt).sortWith(_ < _)

    var prev = 0
    var c = 0
    for (i <- 0 to N - 1) {
      if (badges(i) <= prev) {
        badges(i) = prev +1
        c += badges(i) - prev
      }
      prev = badges(i)
    }
    println(c)
  }

}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(a, b, c, d) = in.next().split(' ').map(_.toDouble)
  val ab = a / b
  val cd = c / d * (1 - ab)
  println(ab / (ab + cd))
}

object Main {
  def main(args: Array[String]) {
    val Array(a, b, c, d) = readLine().split(" ").map(_.toDouble)
    val p1 = a / b
    val p2 = c / d
    println(p1 / (1 - (1 - p1) * (1 - p2)))
  }
}

object P312B extends App {
  var str = readLine();
  var data_str = str.split(" ");
  var datas = new Array[Integer](4);
  for (i <- 0 to 3) {
    datas.update(i, data_str(i).toInt);
  }
  var p = Array(1.0 * datas(0) / datas(1),1.0 * datas(2) / datas(3));
  //無限等比数列でした。。
  var answer =p(0)/(1-(1-p(0))*(1-p(1)))
  print(answer);
}

object Main {
  def main(args: Array[String]) {
    val Array(a, b, c, d) = readLine().split(" ").map(_.toInt)
    val p1 = a.toFloat / b.toFloat
    val p2 = c.toFloat / d.toFloat
    println(p1 / (1 - (1 - p1) * (1 - p2)))
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(a, b, c, d) = readLine().split(" ").map(_.toInt)
    val p1 = a.toFloat / b.toFloat
    val p2 = c.toFloat / d.toFloat
    println(p1 / (1 - p1 * p2))
  }
}


import java.util
import scala.collection.mutable.ArrayBuffer
import scala.util.control.Breaks._

object Main {
  def main(args: Array[String]) {
    val max = 1e7.toInt
    val cnt, sum = Array.ofDim[Int](max + 1)
    val (primes, fact) = getPrimes(max)

    val n = readToken().toInt
    for (i <- readLine.split(" ")) {
      var x = i.toInt
      var prev = -1
      while (x != 1) {
        val t = fact(x)
        if (t != prev) {
          cnt(t) += 1
          prev = t
        }
        x /= t
      }
    }

    (2 to max).foreach(i => sum(i) = sum(i - 1) + cnt(i))

    val m = readToken().toInt
    (0 until m).foreach(i => {
      val t = readLine.split(" ").map(_.toInt)
      val l = t(0).min(max + 1)
      val r = t(1).min(max)
      println(sum(r) - sum(l - 1))
    })
  }

  def getPrimes(n: Int): (Array[Int], Array[Int]) = {
    val primes = ArrayBuffer.empty[Int]
    val maxFact = Array.ofDim[Int](n + 1)

    for (i <- 2 to n; if maxFact(i) == 0) {
      (i to n by i).foreach(maxFact(_) = i)
      primes += i
    }

    (primes.toArray, maxFact)
  }

  var st = new util.StringTokenizer("")

  def readToken() = {
    while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)
    st.nextToken
  }
}

import java.util
import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]) {
    val max = 1e7.toInt
    val cnt, sum = Array.fill(max + 1)(0)
    val (primes, fact) = getPrimes(max)

    val n = readToken().toInt
    for (i <- 0 until n) {
      var x = readToken().toInt
      var prev = -1
      while (x != 1) {
        if (fact(x) != prev) {
          cnt(fact(x)) += 1
          prev = fact(x)
        }
        x /= fact(x)
      }
    }

    (2 to max).foreach(i => sum(i) = sum(i - 1) + cnt(i))

    val m = readToken().toInt
    for (i <- 0 until m) {
      val t = readLine.split(" ").map(_.toInt)
      val l = t(0).min(max + 1)
      val r = t(1).min(max)
      println(sum(r) - sum(l - 1))
    }
  }

  def getPrimes(n: Int): (Array[Int], Array[Int]) = {
    val primes = ArrayBuffer.empty[Int]
    val maxFact = Array.fill(n + 1)(1)

    for (i <- 2 to n; if maxFact(i) == 1) {
      (i to n by i).foreach(maxFact(_) = i)
      primes += i
    }

    (primes.toArray, maxFact)
  }

  var st = new util.StringTokenizer("")

  def readToken() = {
    while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)
    st.nextToken
  }
}


object B741 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m, w) = readInts(3)
    val wi = readInts(n)
    val bi = readInts(n)
    val G = {
      val _G = Array.fill(n)(cu.ArrayBuffer.empty[Int])
      (1 to m).foreach{ _ =>
        val Array(a, b) = readInts(2).map(_-1)
        _G(a).append(b)
        _G(b).append(a)
      }
      _G.map(_.toArray)
    }
    // All connected groups
    val groups = {
      val _groups = cu.ArrayBuffer.empty[Array[Int]]
      val vis = Array.fill(n)(false)

      def dfs(i: Int): cu.ArrayBuffer[Int] = {
        val ret = cu.ArrayBuffer.empty[Int]
        if (!vis(i)) {
          vis(i) = true

          ret.append(i)
          for (a <- G(i))
            ret.appendAll(dfs(a))
        }
        ret
      }

      for (i <- 0 until n if !vis(i)) {
        val g = dfs(i).toArray
        _groups.append(g)
      }
      _groups
    }
    val gW = groups.map(_.map(wi).sum)
    val gB = groups.map(_.map(bi).sum)
    //knapsack
    val dp = Array.ofDim[Int](groups.length, w+1)
    for(i <- groups.indices; j <- 0 to w)
      dp(i)(j) = -1
    def solve(pos: Int, wLeft: Int): Int = {
      if(pos >= groups.length)
        0
      else if (dp(pos)(wLeft) != -1)
        dp(pos)(wLeft)
      else {
        var res = 0
        for(a <- groups(pos)) {
          if(wi(a) <= wLeft) {
            res = math.max(res, solve(pos+1, wLeft-wi(a)) + bi(a))
          }
        }
        if(gW(pos) <= wLeft) {
          res = math.max(res, solve(pos+1, wLeft-gW(pos)) + gB(pos))
        }
        res = math.max(res, solve(pos+1, wLeft))
        dp(pos)(wLeft) = res
        res
      }
    }
    println(solve(0, w))
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B741 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m, w) = readInts(3)
    val wi = readInts(n)
    val bi = readInts(n)
    val G = {
      val _G = Array.fill(n)(cu.ArrayBuffer.empty[Int])
      (1 to m).foreach{ _ =>
        val Array(a, b) = readInts(2).map(_-1)
        _G(a).append(b)
        _G(b).append(a)
      }
      _G.map(_.toArray)
    }
    // All connected groups
    val groups = {
      val _groups = cu.ArrayBuffer.empty[Array[Int]]
      val vis = Array.fill(n)(false)

      def dfs(i: Int): cu.ArrayBuffer[Int] = {
        val ret = cu.ArrayBuffer.empty[Int]
        if (!vis(i)) {
          vis(i) = true

          ret.append(i)
          for (a <- G(i))
            ret.appendAll(dfs(a))
        }
        ret
      }

      for (i <- 0 until n if !vis(i)) {
        val g = dfs(i).toArray
        _groups.append(g)
      }
      _groups.map(_.map(i => (wi(i), bi(i)))).map{ arr =>
        arr ++ Array((arr.map(_._1).sum, arr.map(_._2).sum))
      }.toArray
    }
    //knapsack
    val dp = Array.ofDim[Int](groups.length, w+1)
    for(i <- groups.indices; j <- 0 to w)
      dp(i)(j) = -1
    def solve(pos: Int, wLeft: Int): Int = {
      if(pos >= groups.length)
        0
      else if (dp(pos)(wLeft) != -1)
        dp(pos)(wLeft)
      else {
        var res = 0
        res = math.max(res, solve(pos+1, wLeft))
        for((w, b) <- groups(pos)) {
          if(w <= wLeft) {
            res = math.max(res, solve(pos+1, wLeft-w) + b)
          }
        }
        dp(pos)(wLeft) = res
        res
      }
    }
    println(solve(0, w))
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B741 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m, w) = readInts(3)
    val wi = readInts(n)
    val bi = readInts(n)
    val G = {
      val _G = Array.fill(n)(cu.ArrayBuffer.empty[Int])
      (1 to m).foreach{ _ =>
        val Array(a, b) = readInts(2).map(_-1)
        _G(a).append(b)
        _G(b).append(a)
      }
      _G.map(_.toArray)
    }
    // All connected groups
    val groups = {
      val _groups = cu.ArrayBuffer.empty[Array[Int]]
      val vis = Array.fill(n)(false)

      def dfs(i: Int): cu.ArrayBuffer[Int] = {
        val ret = cu.ArrayBuffer.empty[Int]
        if (!vis(i)) {
          vis(i) = true

          ret.append(i)
          for (a <- G(i))
            ret.appendAll(dfs(a))
        }
        ret
      }

      for (i <- 0 until n if !vis(i)) {
        val g = dfs(i).toArray
        _groups.append(g)
      }
      _groups
    }
    val gW = groups.map(_.map(wi).sum)
    val gB = groups.map(_.map(bi).sum)
    //knapsack
    val dp = Array.ofDim[Int](groups.length, w+1)
    for(i <- groups.indices; j <- 0 to w)
      dp(i)(j) = -1
    def solve(pos: Int, wLeft: Int): Int = {
      if(pos >= groups.length)
        0
      else if (dp(pos)(wLeft) != -1)
        dp(pos)(wLeft)
      else {
        var res = 0
        res = math.max(res, solve(pos+1, wLeft))
        for(a <- groups(pos)) {
          if(wi(a) <= wLeft) {
            res = math.max(res, solve(pos+1, wLeft-wi(a)) + bi(a))
          }
        }
        if(gW(pos) <= wLeft) {
          res = math.max(res, solve(pos+1, wLeft-gW(pos)) + gB(pos))
        }
        dp(pos)(wLeft) = res
        res
      }
    }
    println(solve(0, w))
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


import scala.collection.mutable

object D344 {
  @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 input = scala.io.StdIn.readLine
    val stack = mutable.Stack[Char]()
    for(i <- input.indices) {
      if(stack.nonEmpty && stack.top == input(i)) {
        stack.pop()
      } else {
        stack.push(input(i))
      }
    }
    if(stack.isEmpty) {
      println("Yes")
    } else {
      println("No")
    }
  }
}

import scala.collection.mutable

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

  line.tail.foreach { i =>
    if (stack.isEmpty)
      stack.push(i)
    else if (stack.top != i) {
      stack.push(i)
    } else {
      stack.pop()
    }
  }

  if (stack.isEmpty)
    println("Yes")
  else
    println("No")

}

object D extends App {

  var prev = ' '
  var cnt = 0

  for (c <- Console.readLine)
    if (cnt == 0) {
      prev = c
      cnt = 1
    } else {
      if (c == prev) cnt -= 1 else cnt += 1
      prev = if (prev == '-') '+' else '-'
    }

  println(if (cnt == 0) "Yes" else "No")
}

import scala.collection._

object D extends App {

  def readString = Console.readLine

  val s = readString

  val st = mutable.Stack[Char]()

  for (c <- s) {
    if (st.nonEmpty && st.head == c) {
      st.pop
    } else {
      st.push(c)
    }
  }

  println(if (st.isEmpty) "Yes" else "No")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  if (line.length % 2 == 1 || (0 until line.length / 2).exists(i => line(i) != line(line.length - 1 - i)))
    println("No")
  else
    println("Yes")

}

import scala.collection.mutable

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

  line.tail.foreach { i =>
    if (stack.nonEmpty && stack.top != i) {
      val top = stack.pop()
      if (stack.nonEmpty && stack.top == top) {
        while (stack.nonEmpty && stack.top == top) {
          stack.pop()
        }
      } else {
        stack.push(top)
      }
    }
    stack.push(i)
  }

  if (stack.nonEmpty) {
    val top = stack.pop()
    if (stack.nonEmpty && stack.top == top) {
      while (stack.nonEmpty && stack.top == top) {
        stack.pop()
      }
    } else {
      stack.push(top)
    }
  }

  if (stack.isEmpty)
    println("Yes")
  else
    println("No")

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  if (line.length == 1 || (0 until line.length / 2).exists(i => line(i) != line(line.length - 1 - i)))
    println("No")
  else
    println("Yes")

}


import scala.:+
import scala.+:
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {
  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val numbers = readInts()
    val (a, b)  = numbers.zipWithIndex.partition { case (value, _) => value == numbers(0)}
    val answer = 1 + (if (a.length == 1) a(0)._2 else b(0)._2)
    println(answer)
  }
}

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

object A1512 {
    def main(args: Array[String]){
        val t = readInt()

        for(i <- 1 to t) {
            val n = readInt()
            var arr = readLine.split(" ").map(_.toInt)
            println(if(arr.count(_ == arr.min) > arr.count(_ == arr.max)) arr.indexOf(arr.max) + 1
                    else arr.indexOf(arr.min) + 1)
        }
    }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object CodeForces extends App {
  val t = readLine.toInt
  for( _ <- (1 to t)){
    val n = readLine.toInt
    val list = readLine.split(' ').map(x => x.toInt).toList.zipWithIndex
    val a = list(0)._1
    val b = list(1)._1
    val c = list(2)._1
    val mode = if (a == b) a else (if (a == c) a else b)
    val spy = list.find(x => x._1 != mode)
    println(spy.get._2 + 1)
  }

}

import scala.util.control._
object Main{
    def main(args : Array[String]):Unit = {
        var t = scala.io.StdIn.readInt()
        val outloop = new Breaks;
        val inloop = new Breaks;
        outloop.breakable{
            for (i<-1 to t){
                var n = scala.io.StdIn.readInt()
                var arr = scala.io.StdIn.readLine().split(" ").map(_.toInt)
                inloop.breakable{
                    if ((arr(0)!=arr(1))&&(arr(0)!=arr(2))){
                        println(1)
                    }
                    else if((arr(n-1)!=arr(n-2)) && (arr(n-1)!=arr(n-3))){
                        println(n)
                    }
                    else{
                        for (j<-1 to (n-2)){
                            if((arr(j)!=arr(j-1)) && (arr(j)!=arr(j+1))){
                                println(j+1)
                                inloop.break
                            }
                        }
                    }
                }
            }
        }
    }
}

import scala.io.StdIn

object Main {
  def test(): Unit = {
    val n = StdIn.readLine().toInt
    val arr = StdIn.readLine().split(" ").map(_.toInt).zipWithIndex
    val a = arr(0)
    lazy val b = arr.find { _._1 != a._1 }.toRight()
    if (arr.count(_._1 == a._1) > 1)
      System.out.println(b.getOrElse((0, 0))._2 + 1)
   else
      System.out.println(a._2 + 1)
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().toInt
    (1 to t) foreach {
      _ => test()
    }
  }
}

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

object A1512 {
    def main(args: Array[String]){
        val t = readInt()

        for(i <- 1 to t) {
            val n = readInt()
            var arr = readLine.split(" ").map(_.toInt)
            println(if(arr.count(_ == arr.min) > arr.count(_ == arr.max)) arr.indexOf(arr.min) + 1
                    else arr.indexOf(arr.max) - 1)
        }
    }
}

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

object A1512 {
    def main(args: Array[String]){
        val t = readInt()

        for(i <- 1 to t) {
            val n = readInt()
            var arr = readLine.split(" ").map(_.toInt)
            println(if(arr.count(_ == arr.min) > arr.count(_ == arr.max)) arr.min
                    else arr.max)
        }
    }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object CodeForces extends App {
  val t = readLine.toInt
  for( _ <- (1 to t)){
    val n = readLine.toInt
    val list = readLine.split(' ').map(x => x.toInt).toList.zipWithIndex
    println(list)
    val a = list(0)._1
    val b = list(1)._1
    val c = list(2)._1
    val mode = if (a == b) a else (if (a == c) a else b)
    val spy = list.find(x => x._1 != mode)
    println(spy.get._2 + 1)
  }

}

import scala.io.StdIn.readLine

object CodeForces extends App {
  val t = readLine.toInt
  for( _ <- (1 to t)){
    val n = readLine.toInt
    val list = readLine.split(' ').map(x => x.toInt).toList
    val a = list(0)
    val b = list(1)
    val c = list(2)
    val mode = if (a == b) a else (if (a == c) a else b)
    val spy = list.find(x => x != mode)
    println(spy.get)
  }

}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object CodeForces extends App {
  val t = readLine.toInt
  for( _ <- (1 to t)){
    val n = readLine.toInt
    val list = readLine.split(' ').map(x => x.toInt).toList
    val a = list(0)
    val b = list(1)
    val c = list(2)
    val mode = if (a == b) a else c
    val spy = list.find(x => x != mode)
    println(spy.get)
  }

}


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

object D {

  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 mod = (1e9 + 7).toInt
    val t = nextInt
    val k = nextInt
    val dp = new Array[Int](1e5.toInt + 1)
    dp(0) = 1
    for (i <- 1 until dp.length) {
      if (i == k) {
        dp(i) = 2
      }
      else if (i > k) {
        dp(i) = (dp(i - 1) % mod + dp(i - k) % mod) % mod
      } else {
        dp(i) = 1
      }
    }
    val prefixSum = new Array[Int](1e5.toInt + 1)
    prefixSum(0) = dp(0)
    for (i <- 1 until prefixSum.length) {
      prefixSum(i) = (dp(i) % mod + prefixSum(i - 1) % mod) % mod
    }
    for (i <- 0 until t) {
      val a = nextInt
      val b = nextInt
      out.println((prefixSum(b) - prefixSum(a - 1) + mod) % mod)
    }
    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.Scanner
import scala.language.implicitConversions

object Main{

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

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

  import Lazy._

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val T = sc.nextInt
    val K = sc.nextInt
    val MAXN = 100005
    val MOD: Int = 1000000007

    lazy val DP: Array[Lazy[Int]] = Array.tabulate(MAXN)(x => if (x < K) 1 else (DP(x - K) + DP(x - 1)) % MOD)
    lazy val P: Array[Lazy[Int]] = Array.tabulate(MAXN)(x => if (x == 0) DP(0) else (DP(x) + P(x - 1)) % MOD)

    val ranges = for (i <- 0.until(T)) yield (sc.nextInt, sc.nextInt)
    ranges.map{case (s, e) =>
      {
        val startValue: Int = if (s == 0) 0 else P(s - 1);
        (P(e) - startValue + MOD) % MOD
      }
    }.foreach(println)
  }
}

object D474 {

  import IO._
  import collection.{mutable => cu}
  val MOD = 1000000007L
  def main(args: Array[String]): Unit = {
    val Array(t, k) = readInts(2)
    val dp = Array(0L) ++ Array.fill(k-1)(1L) ++ Array(2L) ++ Array.fill(100010-k)(0L)
    for(i <- k+1 until 100010) {
      dp(i) = (dp(i-1) + dp(i-k))%MOD
    }
    for(i <- 1 until 100010) {
      dp(i) = (dp(i) + dp(i-1))%MOD
    }
    for(_ <- 1 to t) {
      val Array(a, b) = readInts(2)
      println((dp(b) - dp(a-1) + 2*MOD)%MOD)
    }
  }

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

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Long](maxB + 1)
  val sumCache = Array.ofDim[Long](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = (cache(i - 1) + cache(i - k)) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007l + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Long](maxB + 1)
  val sumCache = Array.ofDim[Long](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = (cache(i - 1) + (if (i % k == 0) 2 else 1)) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007l + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Long](maxB + 1)
  val sumCache = Array.ofDim[Long](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = cache(i - 1) + (if (i % k == 0) 2 else 1) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007 + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Long](maxB + 1)
  val sumCache = Array.ofDim[Long](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = cache(i - 1) + (if (i % k == 0) 2 else 1) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007l + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(t, k) = in.next().split(' ').map(_.toInt)
  val ans = (1 to t).map{_ =>
    val data = in.next().split(' ').map(_.toInt)
    (data.head, data.last)
  }
  val maxB = ans.maxBy(_._2)._2
  val cache = Array.ofDim[Int](maxB + 1)
  val sumCache = Array.ofDim[Int](maxB + 1)
  (1 until k).foreach(i => cache(i) = 1)
  cache(k) = 2
  (k + 1 to maxB).foreach{
    i => cache(i) = cache(i - 1) + (if (i % k == 0) 2 else 1) % 1000000007
  }
  (1 to maxB).foreach { i =>
    sumCache(i) = (sumCache(i - 1) + cache(i)) % 1000000007
  }

  val res = ans.map {
    case(0, b) => sumCache(b)
    case(a, b) => (1000000007 + sumCache(b) - sumCache(a - 1)) % 1000000007
  }
  println(res.mkString("\n"))
}

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

object D {

  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 mod = (1e9 + 7).toInt
    val t = nextInt
    val k = nextInt
    val dp = new Array[Int](1e5.toInt + 1)
    dp(0) = 1
    for (i <- 1 until dp.length) {
      if (i == k) {
        dp(i) = 2
      }
      else if (i > k) {
        dp(i) = (dp(i - 1) % mod + dp(i - k) % mod) % mod
      } else {
        dp(i) = 1
      }
    }
    val prefixSum = new Array[Int](1e5.toInt + 1)
    prefixSum(0) = dp(0)
    for (i <- 1 until prefixSum.length) {
      prefixSum(i) = (dp(i) % mod + prefixSum(i - 1) % mod) % mod
    }
    for (i <- 0 until t) {
      val a = nextInt
      val b = nextInt
      out.println((Math.abs(prefixSum(b)) - Math.abs(prefixSum(a - 1))) % mod)
    }
    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
  }
}