Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).Help Daniel to process all queries.

The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries. The second line contains string s, consisting of n lowercase English letters and period signs. The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.

Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.

NoteNote to the first sample test (replaced periods are enclosed in square brackets).The original string is ".b..bz....". after the first query f(hb..bz....) = 4    ("hb[..]bz...."  →  "hb.bz[..].."  →  "hb.bz[..]."  →  "hb.bz[..]"  →  "hb.bz.") after the second query f(hbс.bz....) = 3    ("hbс.bz[..].."  →  "hbс.bz[..]."  →  "hbс.bz[..]"  →  "hbс.bz.") after the third query f(hbс.bz..f.) = 1    ("hbс.bz[..]f."  →  "hbс.bz.f.")Note to the second sample test.The original string is ".cc.". after the first query: f(..c.) = 1    ("[..]c."  →  ".c.") after the second query: f(....) = 3    ("[..].."  →  "[..]."  →  "[..]"  →  ".") after the third query: f(.a..) = 1    (".a[..]"  →  ".a.") after the fourth query: f(aa..) = 1    ("aa[..]"  →  "aa.")

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

import scala.collection.mutable

object C {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

  def solveBruteForce(str1: Array[Char], pos: Int, ch: Char) = {
    val str = new Array[Char](str1.length)
    Array.copy(str1, 0, str, 0, str1.length)
    str(pos) = ch
    var cnt = 0
    var fx = 0
    for (i <- 0 until str.length) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    fx
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val str = next.toCharArray
    var fx = 0
    var cnt = 0
    for (i <- 0 until n) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    for (i <- 0 until m) {
      val pos = nextInt - 1
      val ch = next.toCharArray()(0)
      if (n == 1) {
        out.println(0)
      } else {
//        out.print(solveBruteForce(str, pos, ch) + " ")
        if (ch != str(pos)) {
          if (ch == '.') {
            if (pos == 0) {
              if (str(1) == '.')
                fx += 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx += 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c += 1
              }
              if (str(pos + 1) == '.') {
                c += 1
              }
              fx += c
            }
          } else if (str(pos) == '.'){
            if (pos == 0) {
              if (str(1) == '.')
                fx -= 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx -= 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c -= 1
              }
              if (str(pos + 1) == '.') {
                c -= 1
              }
              fx += c
            }
          }
        }
        if (fx < 0) {
          fx = 0
        }
        str(pos) = ch
        out.println(fx)
      }
    }
    return 0
  }
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)

    val s = readLine()
    val f = Array.fill[Boolean](n+2)(false)

    var num = 0
    var seg = 0

    for (i <- (1 to n)) {
      if (s(i-1) == '.') {
        f(i) = true
        num += 1
        if (i == 1 || s(i-2) != '.') seg += 1
      }
    }

    val sb = new mutable.StringBuilder
    for (_ <- (1 to m)) {
      val Array(ids, ch) = readLine().split(" ")
      val id = ids.toInt
      val nc = (ch == ".")
      val c = f(id)
      if (nc != c) {
        f(id) = nc
        num = if (nc) num+1 else num-1
        if (f(id-1) && f(id+1) && nc) seg -= 1
        if (!f(id-1) && !f(id+1) && nc) seg += 1
        if (f(id-1) && f(id+1) && !nc) seg += 1
        if (!f(id-1) && !f(id+1) && !nc) seg -= 1
      }
      sb.append(num-seg).append('\n')
    }
    print(sb)

  }
}

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

import scala.collection.immutable.IndexedSeq

object _570C extends CodeForcesApp[Seq[Int]]({scanner => import scanner._
  def f(str: String, pos: Int = 0): Int = str.indexOf("..", pos) match {
    case -1 => 0
    case p => 1 + f(str, p+1)
  }

  def dotInt(c: Char) = if (c == '.') 1 else 0

  val (n, m, _s) = (nextInt, nextInt, next)

  var t = f(_s)
  var s: IndexedSeq[Int] = s"x${_s}x" map dotInt

  repeat(m) {
    val (i, c) = (nextInt, dotInt(next.head))

    val delta = (s(i-1), s(i), s(i+1), c) match {
      case (_, 1, _, 1) =>  0
      case (_, 0, _, 0) =>  0

      case (0, 1, 0, 0) =>  0
      case (0, 1, 1, 0) => -1
      case (1, 1, 0, 0) => -1
      case (1, 1, 1, 0) => -2

      case (0, 0, 0, 1) =>  0
      case (0, 0, 1, 1) =>  1
      case (1, 0, 0, 1) =>  1
      case (1, 0, 1, 1) =>  2
    }

    s = s.updated(i, c)
    t += delta

    t
  }
}) {
  override def format(result: Seq[Int]) = result mkString "\n"
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object C extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  //  val n = 299999
  //  val m = 300000
  //  val s = (" " + ("." * n) + " ").toCharArray
  val s = (" " + readLine() + " ").toCharArray

  var current = 0
  for (i <- 1 until n) {
    if (s(i) == '.' && s(i + 1) == '.') current += 1
  }

  def count(x: Int, c: Char): Int = {
    val curr = s(x)
    val isCurrPeriod = curr == '.'
    val isInsertedPeriod = c == '.'
    val isChange = isCurrPeriod ^ isInsertedPeriod

    if (isChange) {
      val prev = s(x - 1)
      val next  = s(x + 1)

      var amount = 0
      if (prev == '.') amount += 1
      if (next == '.') amount += 1

      if (isInsertedPeriod) {
        current += amount
      } else {
        current -= amount
      }

      s(x) = c
    }

    current
  }

  val sb = new scala.collection.mutable.StringBuilder
  for (_ <- 1 to m) {
    val Array(x, c) = readLine().split(" ")
    sb.append(count(x.toInt, c.head)).append('\n')
  }
  print(sb)

  //  for (i <- 1 to m) {
  ////    val arr = readLine().split(" ")
  //    val arr = s"$i .".split(" ")
  //    val x = Math.min(arr(0).toInt, n)
  //    val c = arr(1)(0)
  //    println(count(x, c))
  //  }

}

import scala.io.StdIn.readLine

/**
 * @author slie742
 */
object Replacement {
   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Char) = {
     val line = readLine.split(' ')
     (line(0).toInt,line(1).charAt(0))
   }

  def main(args: Array[String]) {
    val nm = readInts
    val n = nm(0)
    val m = nm(1)
    val s = ('x' + readLine + 'x').toArray
    var i = 1
    var total = 0
    while (i <= n) {
      if (s(i) == '.' && s(i-1) == '.') total +=1
      i += 1
    }
    i = 0
    val output = new Array[Int](m)
    while (i < m) {
      val (p,c) = readTuple
      if (c == '.') {
        if (s(p) != c) {
          if (s(p-1) == '.' && s(p+1) == '.') total +=2
          else if (s(p-1) == '.' || s(p+1) == '.') total +=1
        }
      } else { // s(p) != '.'
        if (s(p) == '.') {
           if (s(p-1) == '.' && s(p+1) == '.') total -=2
          else if (s(p-1) == '.' || s(p+1) == '.') total -=1
        }
      }
      s(p) = c
      output(i) = total
      i += 1
    }
    println(output.mkString("\n"))

  }
}

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

import scala.collection.mutable

object C {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

  def solveBruteForce(str1: Array[Char], pos: Int, ch: Char) = {
    val str = new Array[Char](str1.length)
    Array.copy(str1, 0, str, 0, str1.length)
    str(pos) = ch
    var cnt = 0
    var fx = 0
    for (i <- 0 until str.length) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    fx
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val str = next.toCharArray
    var fx = 0
    var cnt = 0
    for (i <- 0 until n) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    for (i <- 0 until m) {
      val pos = nextInt - 1
      val ch = next.toCharArray()(0)
      if (n == 1) {
        out.println(0)
      } else {
        out.print(solveBruteForce(str, pos, ch) + " ")
        if (ch != str(pos)) {
          if (ch == '.') {
            if (pos == 0) {
              if (str(1) == '.')
                fx += 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx += 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c += 1
              }
              if (str(pos + 1) == '.') {
                c += 1
              }
              fx += c
            }
          } else if (str(pos) == '.'){
            if (pos == 0) {
              if (str(1) == '.')
                fx -= 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx -= 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c -= 1
              }
              if (str(pos + 1) == '.') {
                c -= 1
              }
              fx += c
            }
          }
        }
        if (fx < 0) {
          fx = 0
        }
        str(pos) = ch
        out.println(fx)
      }
    }
    return 0
  }
}

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

import scala.collection.mutable

object C {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val str = next.toCharArray
    var fx = 0
    var cnt = 0
    for (i <- 0 until n) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    for (i <- 0 until m) {
      val pos = nextInt - 1
      val ch = next.toCharArray()(0)
      if (n == 1) {
        out.println(0)
      } else {
        if (ch != str(pos)) {
          if (ch == '.') {
            if (pos == 0) {
              if (str(1) == '.')
                fx += 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx += 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c += 1
              }
              if (str(pos + 1) == '.') {
                c += 1
              }
              fx += c
            }
          } else {
            if (pos == 0) {
              if (str(1) == '.')
                fx -= 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx -= 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c -= 1
              }
              if (str(pos + 1) == '.') {
                c -= 1
              }
              fx += c
            }
          }
        }
        if (fx < 0) {
          fx = 0
        }
        str(pos) = ch
        out.println(fx)
      }
    }
    return 0
  }
}

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

import scala.collection.mutable

object C {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val str = next.toCharArray
    var fx = 0
    var cnt = 0
    for (i <- 0 until n) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    for (i <- 0 until m) {
      val pos = nextInt - 1
      val ch = next.toCharArray()(0)
      if (n == 1) {
        out.println(0)
      } else {
        if (ch != str(pos)) {
          if (ch == '.') {
            if (pos == 0) {
              if (str(1) == '.')
                fx += 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx += 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c += 1
              }
              if (str(pos + 1) == '.') {
                c += 1
              }
              fx += c
            }
          } else {
            if (pos == 0) {
              if (str(1) == '.')
                fx -= 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx -= 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c -= 1
              }
              if (str(pos + 1) == '.') {
                c -= 1
              }
              fx += c
            }
          }
        }

        str(pos) = ch
        out.println(fx)
      }
    }
    return 0
  }
}

import scala.io.StdIn._

object C extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
//  val n = 299999
//  val m = 300000
//  val s = (" " + ("." * n) + " ").toCharArray
  val s = (" " + readLine() + " ").toCharArray

  var current = 0
  for (i <- 1 until n) {
    if (s(i) == '.' && s(i + 1) == '.') current += 1
  }

  def count(x: Int, c: Char): Int = {
    val prev = s(x - 1)
    val curr = s(x)
    val isCurrPeriod = curr == '.'
    val next  = s(x + 1)

    if (c == '.' && !isCurrPeriod) {
      if (prev == '.' && next == '.') {
        current += 2
      } else if (next == '.') {
        current += 1 // b[b]. <- .
      } else if (prev == '.') {
        current += 1 // b[b]. <- .
      }
    } else {
      if (prev == '.' && next == '.' && isCurrPeriod) {
        current -= 2
      } else if (next == '.') {
        current -= 1 // b[.]. <- b
      } else if (prev == '.') {
        current -= 1 // b[.]. <- b
      }

    }

    s(x) = c
    current
  }

  for (_ <- 1 to m) {
    val arr = readLine().split(" ")
    val (x, c) = (arr(0).toInt, arr(1).head)
    println(count(x, c))
  }

//  for (i <- 1 to m) {
////    val arr = readLine().split(" ")
//    val arr = s"$i .".split(" ")
//    val x = Math.min(arr(0).toInt, n)
//    val c = arr(1)(0)
//    println(count(x, c))
//  }

}


Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.

The single line contains four integers x, y, a, b (1 ≤ a ≤ x ≤ 100, 1 ≤ b ≤ y ≤ 100). The numbers on the line are separated by a space.

In the first line print integer n — the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di — the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci, di) in the strictly increasing order. Let us remind you that the pair of numbers (p1, q1) is less than the pair of numbers (p2, q2), if p1 < p2, or p1 = p2 and also q1 < q2.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(x, y, a, b) = in.next().split(' ').map(_.toInt)
  val res = (Math.max(a, b + 1) to x).flatMap(i => (b to Math.min(y, i - 1)).map(j => s"$i $j"))
  println(res.length)
  println(res.mkString("\n"))
}

import scala.io.StdIn
import scala.math.min

object Main {
  def main(args: Array[String]): Unit = {
    val input = StdIn.readLine().split(" ").map(_.toInt)
    val (x, y, a, b) = (input(0), input(1), input(2), input(3))
    val arr: IndexedSeq[String] = for(i <- a to x; j <- b to min(i, y) if i > j) yield i + " " + j
    println(arr.length)
    arr.foreach(println(_))
  }
}

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

object Main extends App {
  val sc = new Scanner(System.in)

  val x, y, a, b = sc.nextInt()

  val ans = (a to x) flatMap { x => (b to (math.min(y, x - 1))).map(x + " " + _) }

  println(ans.length)
  println(ans.mkString("\n"))
}

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

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

  // Vasya => x times
  // Petya => y times
  // gets head => one point
  // more points win or draw

  val X, Y, A, B = sc.nextInt

  def solve(): Seq[List[Int]] = {
    for {
      i <- A to X
      j <- B to ((i - 1) min Y)
    }
    yield List(i, j)
  }

  val answer = solve
  out.println(answer.size)
  answer foreach { stats =>
    out.println(stats.mkString(" "))
  }
  out.close
}

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

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

  val Array(x, y, a, b) = readInts
  val outcomes = (for(i <- a to x) yield for(j <- b to y.min(i - 1)) yield Array(i, j)).flatMap(x => x)
  def ans = (outcomes.size +: outcomes.map(_.mkString(" "))).mkString("\n")

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

import java.util.Scanner

object Main extends App
{
	val sc=new Scanner(System.in)
	val x,y,a,b=sc.nextInt()
	val ans=for(i<-List.range(a,x+1) ;
				j<-List.range(b,y+1) if (i>j)) yield i.toString+' '+j.toString
	println(ans.length)
	println(ans.mkString("\n"))
}

object Main {
  def main(args: Array[String]) = {
    val xyab = readLine() split(" ") map(_.toInt)
    val x = xyab(0)
    val y = xyab(1)
    val a = xyab(2)
    val b = xyab(3)

    val s = for {
      i <- a to x
      j <- b to y
      if i > j
    } yield(i, j)
    println(s.size)
    s.foreach{ t => println(t._1 + " " + t._2) }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val input = StdIn.readLine().split(" ").map(_.toInt)
    val (x, y, a, b) = (input(0), input(1), input(2), input(3))
    val arr: IndexedSeq[String] = for(i <- a + 1 to x; j <- b until i) yield i + " " + j
    println(arr.length)
    arr.foreach(println(_))
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val input = StdIn.readLine().split(" ").map(_.toInt)
    val (x, y, a, b) = (input(0), input(1), input(2), input(3))
    val arr: IndexedSeq[String] = for(i <- a to x; j <- b until i) yield i + " " + j
    println(arr.length)
    arr.foreach(println(_))
  }
}

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

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

  // Vasya => x times
  // Petya => y times
  // gets head => one point
  // more points win or draw

  val X, Y, A, B = sc.nextInt

  def solve(): Seq[List[Int]] = {
    for {
      i <- A to X
      j <- B until (i max Y)
    }
    yield List(i, j)
  }

  val answer = solve
  out.println(answer.size)
  answer foreach { stats =>
    out.println(stats.mkString(" "))
  }
  out.close
}

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

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

  // Vasya => x times
  // Petya => y times
  // gets head => one point
  // more points win or draw

  val X, Y, A, B = sc.nextInt

  def solve(): Seq[List[Int]] = {
    for {
      i <- A to X
      j <- B until (i min Y)
    }
    yield List(i, j)
  }

  val answer = solve
  out.println(answer.size)
  answer foreach { stats =>
    out.println(stats.mkString(" "))
  }
  out.close
}

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

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

  // Vasya => x times
  // Petya => y times
  // gets head => one point
  // more points win or draw

  val X, Y, A, B = sc.nextInt

  def solve(): Seq[List[Int]] = {
    for {
      i <- A to X
      j <- B until i
    }
    yield List(i, j)
  }

  val answer = solve
  out.println(answer.size)
  answer foreach { stats =>
    out.println(stats.mkString(" "))
  }
  out.close
}


Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $$$n$$$ integers $$$a_i$$$.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $$$1$$$. Now Janusz wonders, for given sequence, how much elements should the player choose?

The first line contains an only integer $$$n$$$ ($$$1 \le n \le 300\,000$$$) — the number of integers in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 300\,000$$$).

If there is no subset of the given sequence with gcd equal to $$$1$$$, output -1. Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to $$$1$$$.

NoteIn the first example, selecting a subset of all numbers gives a gcd of $$$1$$$ and for all smaller subsets the gcd is greater than $$$1$$$.In the second example, for all subsets of numbers the gcd is at least $$$2$$$.

//package codeforces

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

/*

https://codeforces.com/contest/1043/problem/F

 */
object MakeItOne {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readIntArray(n: Int): Array[Int] = {
    val st = new StringTokenizer(br.readLine())

    val arr = new Array[Int](n)
    var i = 0
    while (st.hasMoreElements) {
      arr(i) = st.nextToken().toInt
      i += 1
    }

    arr
  }

  def readInt(): Int = {
    val st = new StringTokenizer(br.readLine())
    st.nextToken.toInt
  }

  def power(x: Long, y: Long): Long = {
    if (x == 0) 0
    else {
      var ans: Long = 1
      var temp: Long = x

      var i = y
      while (i > 0) {
        if ((i & 1) == 1) {
          ans = (ans * temp) % MOD
        }
        temp = (temp * temp) % MOD
        i = i / 2
      }

      ans
    }
  }

  val maxCount = 300001
  val MOD = 1000000009

  val factorialOf: Array[Long] = new Array[Long](maxCount)
  factorialOf(0) = 1
  for (i <- 1 until maxCount) factorialOf(i) = (i * factorialOf(i - 1)) % MOD

  val inverseModFactorialOf: Array[Long] = new Array[Long](maxCount)
  inverseModFactorialOf(maxCount - 1) = power(factorialOf(maxCount - 1), MOD - 2)

  for (i <- maxCount - 1 to 1 by -1) inverseModFactorialOf(i - 1) = (i * inverseModFactorialOf(i)) % MOD

  def nCr(n: Int, r: Int): Long = {
    if (r < 0 || n < r) 0
    else ((factorialOf(n) * inverseModFactorialOf(r) % MOD) * inverseModFactorialOf(n - r)) % MOD
  }

  def sub(x: Long, y: Long): Long = {
    x - y + (if (x >= y) 0 else MOD)
  }

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val arr = readIntArray(n)

    val isPresent = new Array[Boolean](maxCount)
    arr.foreach(i => isPresent(i) = true)

    val countOfElementsThatDivide = new Array[Int](maxCount)
    for {
      i <- 1 until maxCount
      j <- i until maxCount by i if isPresent(j)
    } countOfElementsThatDivide(i) += 1

    val dp = Array.ofDim[Long](8, maxCount)

    for {
      i <- 1 to 7
      j <- maxCount - 1 to 1 by -1
    } {
      dp(i)(j) = nCr(countOfElementsThatDivide(j), i)
      var k = 2
      while (k * j < maxCount) {
        dp(i)(j) = sub(dp(i)(j), dp(i)(k * j))
        k += 1
      }

      if (dp(i)(1) > 0) {
        println(i)
        System.exit(0)
      }
    }

    println(-1)
  }
}


Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.There are $$$n_1$$$ different types of first courses Ivan can buy (the $$$i$$$-th of them costs $$$a_i$$$ coins), $$$n_2$$$ different types of second courses (the $$$i$$$-th of them costs $$$b_i$$$ coins), $$$n_3$$$ different types of drinks (the $$$i$$$-th of them costs $$$c_i$$$ coins) and $$$n_4$$$ different types of desserts (the $$$i$$$-th of them costs $$$d_i$$$ coins).Some dishes don't go well with each other. There are $$$m_1$$$ pairs of first courses and second courses that don't go well with each other, $$$m_2$$$ pairs of second courses and drinks, and $$$m_3$$$ pairs of drinks and desserts that don't go well with each other.Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!

The first line contains four integers $$$n_1$$$, $$$n_2$$$, $$$n_3$$$ and $$$n_4$$$ ($$$1 \le n_i \le 150000$$$) — the number of types of first courses, second courses, drinks and desserts, respectively. Then four lines follow. The first line contains $$$n_1$$$ integers $$$a_1, a_2, \dots, a_{n_1}$$$ ($$$1 \le a_i \le 10^8$$$), where $$$a_i$$$ is the cost of the $$$i$$$-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way ($$$1 \le b_i, c_i, d_i \le 10^8$$$). The next line contains one integer $$$m_1$$$ ($$$0 \le m_1 \le 200000$$$) — the number of pairs of first and second courses that don't go well with each other. Each of the next $$$m_1$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n_1$$$; $$$1 \le y_i \le n_2$$$) denoting that the first course number $$$x_i$$$ doesn't go well with the second course number $$$y_i$$$. All these pairs are different. The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other ($$$0 \le m_2, m_3 \le 200000$$$).

If it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print $$$-1$$$. Otherwise, print one integer — the minimum total cost of the dinner.

NoteThe best option in the first example is to take the first course $$$2$$$, the second course $$$1$$$, the drink $$$2$$$ and the dessert $$$1$$$.In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner.

import scala.collection.mutable

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

    case class Course(id: Int, cost: Int)

    val nA, nB, nC, nD = nextInt
    val as0 = nextInts(nA)
    val bs0 = nextInts(nB)
    val cs0 = nextInts(nC)
    val ds0 = nextInts(nD)

    val m1 = nextInt
    val badAB = Array.fill(nA)(new mutable.ArrayBuilder.ofInt)
    for (_ <- 0 until m1) {
      val x, y = nextInt
      badAB(x - 1) += y - 1
    }
    val badABs = badAB.map(_.result().toSet)

    val m2 = nextInt
    val badBC = Array.fill(nB)(new mutable.ArrayBuilder.ofInt)
    for (_ <- 0 until m2) {
      val x, y = nextInt
      badBC(x - 1) += y - 1
    }
    val badBCs = badBC.map(_.result().toSet)

    val m3 = nextInt
    val badCD = Array.fill(nC)(new mutable.ArrayBuilder.ofInt)
    for (_ <- 0 until m3) {
      val x, y = nextInt
      badCD(x - 1) += y - 1
    }
    val badCDs = badCD.map(_.result().toSet)

    val as = (0 until nA).iterator.map(i => Course(i, as0(i))).toArray.sortBy(_.cost)

    for (i <- bs0.indices) {
      var j = 0
      while (j < as.length && badABs(as(j).id)(i)) {
        j += 1
      }
      if (j < as.length) {
        bs0(i) += as(j).cost
      } else {
        bs0(i) = -1
      }
    }

    val bs = (0 until nB).iterator.filter(i => bs0(i) > 0).map(i => Course(i, bs0(i))).toArray.sortBy(_.cost)

    for (i <- cs0.indices) {
      var j = 0
      while (j < bs.length && badBCs(bs(j).id)(i)) {
        j += 1
      }
      if (j < bs.length) {
        cs0(i) += bs(j).cost
      } else {
        cs0(i) = -1
      }
    }

    val cs = (0 until nC).iterator.filter(i => cs0(i) > 0).map(i => Course(i, cs0(i))).toArray.sortBy(_.cost)

    for (i <- ds0.indices) {
      var j = 0
      while (j < cs.length && badCDs(cs(j).id)(i)) {
        j += 1
      }
      if (j < cs.length) {
        ds0(i) += cs(j).cost
      } else {
        ds0(i) = -1
      }
    }

    val goodD = ds0.filterNot(_ == -1)
    val res = if (goodD.isEmpty) -1 else goodD.min
    out.println(res)

    out.flush()
  }

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


An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.  The second line contains n integers pi (1 ≤ pi ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

Print a single integer — the minimum number of actions needed to sort the railway cars.

NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.

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

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val a = new Array[Int](n)
    val was = new Array[Boolean](n)
    val good = new Array[Boolean](n)
    for (i <- 0 until n) {
      a(i) = in.nextInt() - 1
      was(a(i)) = true
      if (a(i) != 0 && was(a(i) - 1)) {
        good(a(i)) = true
      }
    }
    var cur, best = 1
    for (i <- 0 until n) if (good(i)) {
      cur += 1
      if (cur > best) best = cur
    } else {
      cur = 1
    }
    out.println(n - best)
  }

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

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val block = data.foldLeft(Map.empty[Int, Int]) {
    case (map, value) if map.contains(value - 1) => map + (value -> (map(value - 1) + 1)) - (value - 1)
    case (map, value) => map + (value -> 1)
  }
  println(n - block.values.max)

}

object b extends App {
  var n = readInt
  var arr = readLine.split("\\s+").map(_.toInt)
  var dp = new Array[Int](n + 1)

  for (i <- 0 to n - 1)
    dp(arr(i)) = dp(arr(i) - 1) + 1

  println(n - dp.max)
}

/*
 * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/
 */

object Main extends App {
  import java.{util => ju}
  import scala.annotation._
  import scala.collection._
  import scala.collection.{mutable => mu}
  import scala.collection.JavaConverters._
  import scala.math._

  val sc = new ju.Scanner(System.in)

  val n = sc.nextInt
  val a = Array.fill(n)(sc.nextInt - 1)
  val b = Array.fill(n + 1)(-1)
  (0 until n) foreach {i => b(a(i)) = i}
  var ma = 0
  var cur, start = 0
  (0 to n) foreach {i =>
    if (b(i) < cur) {
      ma = ma max (i - start)
      start = i
    }
    cur =  b(i)
  }
  println(n - ma)

}

object C extends App {

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

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

  val len = Array.fill(n + 1){ 0 }

  for (p <- ps) len(p) = len(p - 1) + 1

  println(n - len.max)
}

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

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val a = new Array[Int](n)
    val was = new Array[Boolean](n)
    val good = new Array[Boolean](n)
    for (i <- 0 until n) {
      a(i) = in.nextInt() - 1
      was(a(i)) = true
      if (a(i) == 0 || was(a(i) - 1)) {
        good(a(i)) = true
      }
    }
    var cur, best = 0
    for (i <- 0 until n) if (good(i)) {
      cur += 1
      if (cur > best) best = cur
    } else {
      cur = 0
    }
    out.println(n - best)
  }

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

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

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

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val a = new Array[Int](n)
    val was = new Array[Boolean](n)
    val good = new Array[Boolean](n)
    for (i <- 0 until n) {
      a(i) = in.nextInt() - 1
      was(a(i)) = true
      if (a(i) != 0 && was(a(i) - 1)) {
        good(a(i)) = true
      }
    }
    var cur, best = 0
    for (i <- 0 until n) if (good(i)) {
      cur += 1
      if (cur > best) best = cur
    } else {
      cur = 1
    }
    out.println(n - best)
  }

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

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

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

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val a = new Array[Int](n)
    val was = new Array[Boolean](n)
    val good = new Array[Boolean](n)
    for (i <- 0 until n) {
      a(i) = in.nextInt() - 1
      was(a(i)) = true
      if (a(i) != 0 && was(a(i) - 1)) {
        good(a(i)) = true
      }
    }
    var cur, best = 1
    println(cur + " " + best)
    for (i <- 0 until n) if (good(i)) {
      cur += 1
      if (cur > best) best = cur
    } else {
      cur = 1
    }
    out.println(n - best)
  }

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

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

object b extends App {
  var n = readInt
  var arr = readLine.split("\\s+").map(_.toInt)

  def solve(arr: Array[Int], pos: Int, took: Int, op: (Int, Int) => Int): Int =
    if (pos >= arr.length || pos < 0)
      took
    else
      if (arr(pos) == op(took, 1))
        solve(arr, op(pos, 1), op(took, 1), op)
      else
        solve(arr, op(pos, 1), took, op)

  println((n - solve(arr, 0, 0, _ + _)) min (solve(arr, n - 1, n + 1, _ - _) - 1))
}


Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows.  The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 10^9$$$) which location must be found.

For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \ge 1$$$) separated by spaces — the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val k = readInt()

    val i = {
      @annotation.tailrec
      def go(i: Int): Int = if (i * i >= k) i else go(i + 1)
      go(1)
    }

    val j = k - (i - 1) * (i - 1)

    val (r, c) = if (j <= i) (j, i) else (i, i - (j - i))

    println(s"$r $c")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val k = readInt()

    val row        = math.sqrt(k).ceil.toInt
    val (from, to) = ((row - 1) * (row - 1) + 1, row * row)
    val length     = to - from + 1
    val half       = length / 2
    val index      = k - from

    val (r, c) =
      if (index < half) (index + 1, row)
      else if (index > half) (row, length - index)
      else (row, row)

    println(s"$r $c")
  }
}

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

object Solution {
    val reader = new Scanner(System.in)
    val writer =  new PrintWriter(System.out)

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def solve(t: Int = 0): Unit = {
        val n = reader.nextInt()
        var c = 0
        while (f(c) < n) c += 1

        if (f(c) == n) {
            writer.println(s"1 ${c + 1}")
            return
        }

        val sub = n - f(c - 1)
        if (c - 1 == sub)
            writer.println(s"$c $c")
        else if (c - 1 > sub)
            writer.println(s"${1 + sub} $c")
        else
            writer.println(s"$c ${2*c - sub - 1}")
    }

    def multiTest(f: Int => Unit): Unit = {
        val t = reader.nextInt()
        for (i <- 1 to t) f(i)
    }

    val f = new Array[Int](40000)
    def main(args: Array[String]) {
        var i = 1
        var c = 1
        var size = 1
        f(0) = c
        while (c < 1000000000) {
            c += i
            i += 2
            f(size) = c
            size += 1
        }
        multiTest(solve)
        //solve()
        writer.flush()
    }
}


AquaMoon has two binary sequences $$$a$$$ and $$$b$$$, which contain only $$$0$$$ and $$$1$$$. AquaMoon can perform the following two operations any number of times ($$$a_1$$$ is the first element of $$$a$$$, $$$a_2$$$ is the second element of $$$a$$$, and so on): Operation 1: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{min}(a_1,a_2)$$$, and remove the first element of $$$a$$$. Operation 2: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{max}(a_1,a_2)$$$, and remove the first element of $$$a$$$.Note that after a removal of the first element of $$$a$$$, the former $$$a_2$$$ becomes the first element of $$$a$$$, the former $$$a_3$$$ becomes the second element of $$$a$$$ and so on, and the length of $$$a$$$ reduces by one.Determine if AquaMoon can make $$$a$$$ equal to $$$b$$$ by using these operations.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2\,000$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 50$$$, $$$m \leq n$$$) — the lengths of $$$a$$$ and $$$b$$$ respectively. The second line of each test case contains a string $$$a$$$ of length $$$n$$$, consisting only $$$0$$$ and $$$1$$$. The third line of each test case contains a string $$$b$$$ of length $$$m$$$, consisting only $$$0$$$ and $$$1$$$.

For each test case, output "YES" if AquaMoon can change $$$a$$$ to $$$b$$$ by using these options; otherwise, output "NO". You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).

NoteIn the first test case, you can use Operation 2 four times to make $$$a$$$ equals to $$$b$$$.In the second test case, you can use Operation 1 four times to make $$$a$$$ equals to $$$b$$$.In the third test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fourth test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fifth test case, you can use Operation 2 three times to make $$$a$$$ become $$$10101$$$, so the first element of $$$a$$$ equals to the first element of $$$b$$$, but it can be proved that no matter how to operate, the second to the fifth elements of $$$a$$$ can't be the same as $$$b$$$.

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

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

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

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      var c = true
      tokenizer = new StringTokenizer(input.readLine())
      val l1 = tokenizer.nextToken().toInt
      val l2 = tokenizer.nextToken().toInt
      tokenizer = new StringTokenizer(input.readLine())
      val a = tokenizer.nextToken()
      tokenizer = new StringTokenizer(input.readLine())
      val b = tokenizer.nextToken()
      for (i <- 1 until b.length()) {
        if (a(l1-l2 + i) != b(i)) {
          c = false
        }
      }
      var bb = false
      for (i <- 0 to l1-l2) {
        if (b.head == a(i)) {
          bb = true
        }
      }
      if (!bb) {
        c = false
      }
      if (c){
        println("YES")
      }
      else {
        println("NO")
      }
    }
  }
}

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

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

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

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      var c = true
      tokenizer = new StringTokenizer(input.readLine())
      val l1 = tokenizer.nextToken().toInt
      val l2 = tokenizer.nextToken().toInt
      tokenizer = new StringTokenizer(input.readLine())
      val a = tokenizer.nextToken()
      tokenizer = new StringTokenizer(input.readLine())
      val b = tokenizer.nextToken()
      for (i <- 1 until b.length()) {
        if (a(l1-l2 + i) != b(i)) {
          c = false
        }
      }
      var bb = false
      if (l1==l2){
        bb=true
      }
      for (i <- 0 until l1-l2) {
        if (b.head == a(i)) {
          bb = true
        }
      }
      if (!bb) {
        c = false
      }
      if (c){
        println("YES")
      }
      else {
        println("NO")
      }
    }
  }
}

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

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

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

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      var c = true
      tokenizer = new StringTokenizer(input.readLine())
      val l1 = tokenizer.nextToken().toInt
      val l2 = tokenizer.nextToken().toInt
      tokenizer = new StringTokenizer(input.readLine())
      val a = tokenizer.nextToken()
      tokenizer = new StringTokenizer(input.readLine())
      val b = tokenizer.nextToken()
      for (i <- 1 until b.length()) {
        if (a(l1-l2 + i) != b(i)) {
          c = false
        }
      }
      var bb = false
      for (i <- 0 until l1-l2) {
        if (b.head == a(i)) {
          bb = true
        }
      }
      if (!bb) {
        c = false
      }
      if (c){
        println("YES")
      }
      else {
        println("NO")
      }
    }
  }
}


You are given a picture consisting of $$$n$$$ rows and $$$m$$$ columns. Rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom, columns are numbered from $$$1$$$ to $$$m$$$ from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers $$$x$$$ and $$$y$$$, where $$$1 \le x \le n$$$ and $$$1 \le y \le m$$$, such that all cells in row $$$x$$$ and all cells in column $$$y$$$ are painted black.For examples, each of these pictures contain crosses:  The fourth picture contains 4 crosses: at $$$(1, 3)$$$, $$$(1, 5)$$$, $$$(3, 3)$$$ and $$$(3, 5)$$$.Following images don't contain crosses:  You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?You are also asked to answer multiple independent queries.

The first line contains an integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^4$$$) — the number of queries. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^4$$$, $$$n \cdot m \le 4 \cdot 10^5$$$) — the number of rows and the number of columns in the picture. Each of the next $$$n$$$ lines contains $$$m$$$ characters — '.' if the cell is painted white and '*' if the cell is painted black. It is guaranteed that $$$\sum n \le 5 \cdot 10^4$$$ and $$$\sum n \cdot m \le 4 \cdot 10^5$$$.

Print $$$q$$$ lines, the $$$i$$$-th line should contain a single integer — the answer to the $$$i$$$-th query, which is the minimum number of minutes you have to spend so the resulting picture contains at least one cross.

NoteThe example contains all the pictures from above in the same order.The first 5 pictures already contain a cross, thus you don't have to paint anything.You can paint $$$(1, 3)$$$, $$$(3, 1)$$$, $$$(5, 3)$$$ and $$$(3, 5)$$$ on the $$$6$$$-th picture to get a cross in $$$(3, 3)$$$. That'll take you $$$4$$$ minutes.You can paint $$$(1, 2)$$$ on the $$$7$$$-th picture to get a cross in $$$(4, 2)$$$.You can paint $$$(2, 2)$$$ on the $$$8$$$-th picture to get a cross in $$$(2, 2)$$$. You can, for example, paint $$$(1, 3)$$$, $$$(3, 1)$$$ and $$$(3, 3)$$$ to get a cross in $$$(3, 3)$$$ but that will take you $$$3$$$ minutes instead of $$$1$$$.There are 9 possible crosses you can get in minimum time on the $$$9$$$-th picture. One of them is in $$$(1, 1)$$$: paint $$$(1, 2)$$$ and $$$(2, 1)$$$.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

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

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val n, m = ni()
      val g = nm_c(n, m)
      val rowCnt = Array.ofDim[Int](n)
      val colCnt = Array.ofDim[Int](m)
      REP(n) { i =>
        REP(m) { j =>
          if (g(i)(j) == '.') {
            rowCnt(i) += 1
            colCnt(j) += 1
          }
        }
      }
      var ans = n + m
      REP(n) { i =>
        REP(m) { j =>
          val v = rowCnt(i) + colCnt(j) - (if (g(i)(j) == '.') 1 else 0)
          ans = min(ans, v)
        }
      }
      out.println(ans)
    }
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

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

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val n, m = ni()
      val g = nm_c(n, m)
      val rowCnt = Array.ofDim[Int](n)
      val colCnt = Array.ofDim[Int](m)
      REP(n) { i =>
        REP(m) { j =>
          if (g(i)(j) == '.') {
            rowCnt(i) += 1
            colCnt(j) += 1
          }
        }
      }
      var ans = max(n, m)
      REP(n) { i =>
        REP(m) { j =>
          val v = rowCnt(i) + colCnt(j) - (if (g(i)(j) == '.') 1 else 0)
          ans = min(ans, v)
        }
      }
      out.println(ans)
    }
  }
}


You are a programmer and you have a New Year Tree (not the traditional fur tree, though) — a tree of four vertices: one vertex of degree three (has number 1), connected with three leaves (their numbers are from 2 to 4).On the New Year, programmers usually have fun. You decided to have fun as well by adding vertices to the tree. One adding operation looks as follows:  First we choose some leaf of the tree with number v.  Let's mark the number of vertices on the tree at this moment by variable n, then two vertexes are added to the tree, their numbers are n + 1 and n + 2, also you get new edges, one between vertices v and n + 1 and one between vertices v and n + 2. Your task is not just to model the process of adding vertices to the tree, but after each adding operation print the diameter of the current tree. Come on, let's solve the New Year problem!

The first line contains integer q (1 ≤ q ≤ 5·105) — the number of operations. Each of the next q lines contains integer vi (1 ≤ vi ≤ n) — the operation of adding leaves to vertex vi. Variable n represents the number of vertices in the current tree. It is guaranteed that all given operations are correct.

Print q integers — the diameter of the current tree after each operation.

import java.util
import java.io.PrintWriter

object Main {
  var tokenizer = new util.StringTokenizer("")
  val out = new PrintWriter(System.out)

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

  def readInt = readToken.toInt

  val ancLevel = 18
  val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)
  val dep = Array.ofDim[Int](1000000 + 20)

  def getLca(x: Int, y: Int) = {
    var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)
    for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)
    if (a == b) {
      a
    } else {
      for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {
        a = anc(lv)(a)
        b = anc(lv)(b)
      }
      anc(0)(a)
    }
  }

  var d = 2

  def check(cur: Int, far: Int) = {
    val lca = getLca(cur, far)
    val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)
    if (curD > d) {
      d = curD
      true
    } else {
      false
    }
  }

  def main(args: Array[String]) {
    var p1 = 2
    var p2 = 3
    val q = readInt

    for (i <- 2 to 4) {
      anc(0)(i) = 1
      dep(i) = 1
    }

    var n = 4
    for (i <- 0 until q) {
      val x = readLine.toInt
      anc(0)(n + 1) = x
      anc(0)(n + 2) = x
      n += 2
    }

    for (p <- 5 to n) {
      dep(p)= dep(anc(0)(p)) + 1
      for (lv <- 1 until ancLevel) {
        anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))
      }
    }

    n = 4
    for (i <- 0 until q) {
      if (check(n + 1, p1)) {
        p2 = n + 1
      } else if (check(n + 1, p2)) {
        p1 = n + 1
      }
      out.println(d)
      n += 2
    }
    out.flush()
  }
}

import java.util
import java.io.PrintWriter
import java.io.BufferedReader
import java.io.InputStreamReader

object Main {
  var tokenizer = new util.StringTokenizer("")
  val out = new PrintWriter(System.out)
  val br = new BufferedReader(new InputStreamReader(System.in))

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

  def readInt = readToken.toInt

  val ancLevel = 18
  val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)
  val dep = Array.ofDim[Int](1000000 + 20)

  def getLca(x: Int, y: Int) = {
    var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)
    for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)
    if (a == b) {
      a
    } else {
      for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {
        a = anc(lv)(a)
        b = anc(lv)(b)
      }
      anc(0)(a)
    }
  }

  var d = 2

  def check(cur: Int, far: Int) = {
    val lca = getLca(cur, far)
    val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)
    if (curD > d) {
      d = curD
      true
    } else {
      false
    }
  }

  def main(args: Array[String]) {
    var p1 = 2
    var p2 = 3
    val q = br.readLine.toInt

    for (i <- 2 to 4) {
      anc(0)(i) = 1
      dep(i) = 1
    }

    var n = 4
    for (i <- 0 until q) {
      val x = br.readLine.toInt
      anc(0)(n + 1) = x
      anc(0)(n + 2) = x
      n += 2
    }

    for (p <- 5 to n) {
      dep(p)= dep(anc(0)(p)) + 1
      for (lv <- 1 until ancLevel) {
        anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))
      }
    }

    n = 4
    for (i <- 0 until q) {
      if (check(n + 1, p1)) {
        p2 = n + 1
      } else if (check(n + 1, p2)) {
        p1 = n + 1
      }
      out.println(d)
      n += 2
    }
    out.flush()
  }
}

import java.util
import java.io.PrintWriter

object Main {
  var tokenizer = new util.StringTokenizer("")
  val out = new PrintWriter(System.out)

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

  def readInt = readToken.toInt

  val ancLevel = 18
  val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)
  val dep = Array.ofDim[Int](1000000 + 20)

  def getLca(x: Int, y: Int) = {
    var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)
    for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)
    if (a == b) {
      a
    } else {
      for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {
        a = anc(lv)(a)
        b = anc(lv)(b)
      }
      anc(0)(a)
    }
  }

  var d = 2

  def check(cur: Int, far: Int) = {
    val lca = getLca(cur, far)
    val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)
    if (curD > d) {
      d = curD
      true
    } else {
      false
    }
  }

  def main(args: Array[String]) {
    var p1 = 2
    var p2 = 3
    val q = readLine.toInt

    for (i <- 2 to 4) {
      anc(0)(i) = 1
      dep(i) = 1
    }

    var n = 4
    for (i <- 0 until q) {
      val x = readLine.toInt
      anc(0)(n + 1) = x
      anc(0)(n + 2) = x
      n += 2
    }

    for (p <- 5 to n) {
      dep(p)= dep(anc(0)(p)) + 1
      for (lv <- 1 until ancLevel) {
        anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))
      }
    }

    n = 4
    for (i <- 0 until q) {
      if (check(n + 1, p1)) {
        p2 = n + 1
      } else if (check(n + 1, p2)) {
        p1 = n + 1
      }
      out.println(d)
      n += 2
    }
    out.flush()
  }
}

import java.util
import java.io.PrintWriter

object Main {
  var tokenizer = new util.StringTokenizer("")
  val out = new PrintWriter(System.out)

  def readToken = {
    while (!tokenizer.hasMoreTokens)
		tokenizer = new util.StringTokenizer(scala.io.StdIn.readLine)
    tokenizer.nextToken
  }

  def readInt = readToken.toInt

  val ancLevel = 18
  val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)
  val dep = Array.ofDim[Int](1000000 + 20)

  def getLca(x: Int, y: Int) = {
    var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)
    for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)
    if (a == b) {
      a
    } else {
      for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {
        a = anc(lv)(a)
        b = anc(lv)(b)
      }
      anc(0)(a)
    }
  }

  var d = 2

  def check(cur: Int, far: Int) = {
    val lca = getLca(cur, far)
    val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)
    if (curD > d) {
      d = curD
      true
    } else {
      false
    }
  }

  def main(args: Array[String]) {
    var p1 = 2
    var p2 = 3
    val q = scala.io.StdIn.readLine.toInt

    for (i <- 2 to 4) {
      anc(0)(i) = 1
      dep(i) = 1
    }

    var n = 4
    for (i <- 0 until q) {
      val x = scala.io.StdIn.readLine.toInt
      anc(0)(n + 1) = x
      anc(0)(n + 2) = x
      n += 2
    }

    for (p <- 5 to n) {
      dep(p)= dep(anc(0)(p)) + 1
      for (lv <- 1 until ancLevel) {
        anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))
      }
    }

    n = 4
    for (i <- 0 until q) {
      if (check(n + 1, p1)) {
        p2 = n + 1
      } else if (check(n + 1, p2)) {
        p1 = n + 1
      }
      out.println(d)
      n += 2
    }
    out.flush()
  }
}


The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example  and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.

The first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers.  The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets.

In the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers. In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u. In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c. If there are multiple answers, print any of them.

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val p = in.next().split(' ').map(_.toInt)

  var pMap = mutable.Map.empty[Int, List[Int]]

  val s = in.next().split(' ').map(_.toInt)
  val sIndex = Array.ofDim[Int](m)
  (0 until m).foreach {i => sIndex(i) = i}

  (0 until n).foreach { i =>
    if (pMap.contains(p(i)))
      pMap(p(i)) ::= i
    else
      pMap(p(i)) = List(i)
  }

  val pUsed = Array.ofDim[Int](n)
  val sCount = Array.ofDim[Int](m)
  var step = 0
  var length = m

  while(length != 0) {
    var nLength = 0
    var i = 0
    while (i < length) {
      val power = s(i)
      val index = sIndex(i)
      if (pMap.contains(power)) {
        val (x :: xs) = pMap(power)
        sCount(index) = step
        pUsed(x) = index + 1
        if (xs.isEmpty)
          pMap -= power
        else
          pMap += power -> xs
      } else if (power != 1) {
        s(nLength) = (power + 1) / 2
        sIndex(nLength) = index
        nLength += 1
      }
      i += 1
    }
    length = nLength
    step += 1
  }

  val c = pUsed.count(_ != 0)
  val u = sCount.sum
  println(s"$c $u")
  println(sCount.mkString(" "))
  println(pUsed.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val p = in.next().split(' ').map(_.toInt)
  val s = in.next().split(' ').map(_.toInt)
  var sorted = s.zipWithIndex.sorted
  var pMap = p.zipWithIndex.groupBy(_._1).map(i => i._1 -> i._2.map(_._2))
  var pIndexMap = pMap.map(i => i._1 -> (i._2.length - 1))
  val pUsed = Array.ofDim[Int](n)
  val sCount = Array.ofDim[Int](m)
  var c = 0
  var u = 0

  sorted.foreach {
    case (power, index) =>
      var nPower = power
      var i = 0
      while(pIndexMap.getOrElse(nPower, -1) == -1 && nPower != 1) {
        nPower = (nPower + 1) / 2
        i += 1
      }
      val offset = pIndexMap.getOrElse(nPower, -1)
      if (offset != -1) {
        val list = pMap(nPower)
        val plug = list(offset)
        pUsed(plug) = index + 1
        u += 1
        c += index + 1
        sCount(index) = i
        pIndexMap += nPower -> (offset - 1)
      }
  }

//  val c = pUsed.count(_ != 0)
//  val u = sCount.sum
  println(s"$c $u")
  println(sCount.mkString(" "))
  println(pUsed.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val p = in.next().split(' ').map(_.toInt)
  val s = in.next().split(' ').map(_.toInt)
  var sorted = s.zipWithIndex.sorted
  var pMap = p.zipWithIndex.groupBy(_._1).map(i => i._1 -> i._2.map(_._2))
  var pIndexMap = pMap.map(i => i._1 -> (i._2.length - 1))
  val pUsed = Array.ofDim[Int](n)
  val sCount = Array.ofDim[Int](m)
  var c = 0
  var u = 0

  sorted.foreach {
    case (power, index) =>
      var nPower = power
      var i = 0
      while(pIndexMap.getOrElse(nPower, -1) == -1 && nPower != 1) {
        nPower = (nPower + 1) / 2
        i += 1
      }
      val offset = pIndexMap.getOrElse(nPower, -1)
      if (offset != -1) {
        val list = pMap(nPower)
        val plug = list(offset)
        pUsed(plug) = index + 1
        u += index + 1
        c += 1
        sCount(index) = i
        pIndexMap += nPower -> (offset - 1)
      }
  }

  println(s"$c $u")
  println(sCount.mkString(" "))
  println(pUsed.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val p = in.next().split(' ').map(_.toInt)
  val s = in.next().split(' ').map(_.toInt)
  var sorted = s.zipWithIndex.sorted
  var pMap = p.zipWithIndex.groupBy(_._1).map(i => i._1 -> i._2.map(_._2))
  var pIndexMap = pMap.map(i => i._1 -> 0)
  val pUsed = Array.ofDim[Int](n)
  val sCount = Array.ofDim[Int](m)
  var step = 0

  sorted.foreach {
    case (power, index) =>
      var nPower = power
      var i = 0
      while(!pMap.contains(nPower) && nPower != 1) {
        nPower = (nPower + 1) / 2
        i += 1
      }
      if (pMap.contains(nPower)) {
        val list = pMap(nPower)
        val offset = pIndexMap(nPower)
        val plug = list(offset)
        pUsed(plug) = index + 1
        sCount(index) = i
        if (list.length - 1 == offset)
          pMap -= nPower
        else
          pIndexMap += nPower -> (offset + 1)
      }
  }

  val c = pUsed.count(_ != -1)
  val u = sCount.sum
  println(s"$c $u")
  println(sCount.mkString(" "))
  println(pUsed.mkString(" "))
}