Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

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

object CF567B extends App {
  val n = readInt()

  implicit def intTimes(i: Int) = new {
    def times(fn: => Unit) = (1 to i) foreach (x => fn)
  }

  val present = mutable.Set[Int]()
  var result = 0
  var state = 0
  n.times {
    val line = readLine()

    val operation = line.split(" ")(0)
    val id = line.split(" ")(1).toInt

    operation match {
      case "+" =>
        present += id
        state += 1
        result = Math.max(result, state)
      case "-" =>
        if (present.contains(id)) {
          present -= id
          state -= 1
        }
        else result += 1
    }
  }

  println(result)
}

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

object Main {

  sealed trait Log
  case class In(i: Int)  extends Log
  case class Out(i: Int) extends Log
  case class R(who: Set[Int], cm: Int)
  // Document: http://www.scala-lang.org/api/current/#package
  // -----------------------------------------------------------------------------

  def main(args: Array[String]) : Unit = {
    val n = readLine().toInt
    val x = (1 to n).map(_ => {
                           val line  = readLine.split(" ")
                           val is_in = line(0) == "+"
                           val who   = line(1).toInt
                           if(is_in) In(who)
                           else      Out(who)
                         })
    val ret = x.foldLeft(R(Set[Int](),0))((r, c) => {
                                  c match {
                                    case In(i)  => R(r.who + i, r.cm max (r.who.size+1))
                                    case Out(i) if r.who contains i =>  R(r.who - i, r.cm)
                                    case Out(i) => R(r.who, r.cm + 1)
                                  }
                                }).cm
    println(ret)
  }
}

object B567 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n){
      val tl = tokenizeLine
      val status = tl.nextToken
      val user = tl.nextToken.toInt
      (status, user)
    }
    val set = cu.Set.empty[Int]
    val pre = cu.Set.empty[Int]
    for(i <- 0 until n) {
      val status = in(i)._1
      val user = in(i)._2
      if(status == "-") {
        if(set.contains(user))
          set.remove(user)
        else
          pre.add(user)
      } else {
        set.add(user)
      }
    }
    var res = pre.size
    for(i <- 0 until n) {
      val status = in(i)._1
      val user = in(i)._2
      if(status == "-") {
        pre.remove(user)
      } else {
        pre.add(user)
      }
      res = math.max(res, pre.size)
    }
    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

    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.immutable.HashMap
import scala.collection.mutable.ListBuffer

/**
 * <a href="http://codeforces.com/problemset/problem/567/B"/>
 *
 * @author pvasilyev
 * @since 14 Apr 2016
 */
object Problem151 extends App {
  val n: Int = scala.io.StdIn.readInt()
  var map: Map[String, Boolean] = new HashMap[String, Boolean]()
  var listOfOut = new ListBuffer[String]()
  var max: Int = 0
  var curr: Int = 0
  for (i <- 0 until n) {
    val Array(in, numAsString) = scala.io.StdIn.readLine().split(" ")
    curr = max
    if ("-".equals(in)) {
      if (map contains numAsString) {
        map -= numAsString
      } else {
        curr += 1
        listOfOut += numAsString
      }
    } else {
      if (listOfOut isEmpty) {
        curr = map.size + 1
      } else {
        listOfOut.remove(0)
      }
      map += (numAsString -> true)
    }
    max = Math.max(max, curr)
  }

  println(max)
}

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

import scala.collection.mutable

object B {

  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 in = new Array[Boolean](1e6.toInt + 1)
    var state = 0
    var ans = 0
    for (i <- 0 until n) {
      val sign = if (next == "+") 1 else 0
      val id = nextInt
      if (sign == 1) {
        in(id) = true
        state += 1
      } else {
        if (in(id)) {
          state -= 1
          in(id) = false
        } else {
          ans += 1
        }
      }
      ans = Math.max(ans, state)
    }
    out.println(ans)
    return 0
  }
}

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

object Solution {

  def main(args: Array[String]) {
    val n = readInt()
    val lib = Set[String]()
    val logs = (1 to n).map(_=>readLine().split(" "))
    logs.zipWithIndex
      .filter { case (l, i) => l(0) == "-" && !logs.take(i).exists(el => el(1) == l(1)) }
      .foreach { case (l, _) => lib.add(l(1)) }

    var res = lib.size

    logs.foreach { log =>
      if (log(0) == "+") {
        lib.add(log(1))
      } else {
        lib.remove(log(1))
      }
      res = Math.max(res, lib.size)
    }

    println(res)

  }

}

import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _567B extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val library = mutable.Set.empty[Int]
  var ans = 0
  for {_ <- 1 to n} {
    val (isEnter, id) = (next == "+", nextInt)
    if (isEnter) {
      require(library.add(id))
      ans = ans max library.size
    } else if (!library.remove(id)) {
      ans += 1
    }
    debug(isEnter, id, library, ans)
  }
  ans
})
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 def 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 counter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object B extends App {
  val n = readInt()
  val states = Array.ofDim[Boolean](1000001)
  val capacity = Array.ofDim[Int](n)

  var count = 0

  for (i <- capacity.indices) {
    val input = readLine().split(" ")
    val event = input(0)
    val id = input(1).toInt

    event match {
      case "+" =>
        states(id) = true
        count += 1
      case "-" if states(id) =>
        states(id) = false
        count -= 1
      case "-" if !states(id) =>
        for (j <- 0 to i) capacity(j) += 1
    }

    capacity(i) += count
  }

  println(capacity.max)

}

import java.util.Scanner
import scala.annotation._
import scala.math._

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

    val n  = scanner.nextInt

    val idSet = Set()

    var ans = 0

    @tailrec
    def iter(time: Int, idSet: Set[Int], ans: Int): Int = {
      if (time > n) ans
      else {
        val x = scanner.next
        val id = scanner.nextInt

        x match {
          case "-" =>
            if (idSet.contains(id)) {
              iter(time+1, idSet-id, ans)
            } else {
              iter(time+1, idSet, ans+1)
            }
          case "+" =>
            val nextIdSet = idSet+id
            iter(time+1, nextIdSet, max(ans, nextIdSet.size))
        }
      }
    }

    println(iter(1, Set[Int](), 0))
  }
}

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

object BerlandLibrary {

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

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

   def solve(events: List[String]) : Int = {
     def go(events: List[String], inroom: Set[String], cap: Int) : Int =
        events match {
       case Nil => cap
       case h :: tail =>
         if (h(0) == '+') {
           go(tail, inroom + h.split(' ')(1), Math.max(cap, inroom.size + 1))
         } else {
           val reg = h.split(' ')(1)
           if (inroom.contains(reg)) {
             go(tail, inroom - reg, cap)
           } else {
             go(tail,inroom,cap+1)
           }
         }

     }
     go(events,Set(),0)
   }

   def main(args: Array[String]) {
     val n = readInt
     val events = for {
       i <- 1 to n
       event = readLine
     } yield event
     println(solve(events.toList))
   }

}

import java.util

import scala.collection.immutable.HashMap
import scala.collection.mutable.ListBuffer
import scala.collection.parallel.mutable

/**
 * <a href="http://codeforces.com/problemset/problem/567/B"/>
 *
 * @author pvasilyev
 * @since 14 Apr 2016
 */
object Problem151 extends App {
  val n: Int = scala.io.StdIn.readInt()
  var map: Map[String, Boolean] = new HashMap[String, Boolean]()
  var listOfOut = new ListBuffer[String]()
  var max: Int = 0
  var curr: Int = 0
  for (i <- 0 until n) {
    val Array(in, numAsString) = scala.io.StdIn.readLine().split(" ")
    if ("-".equals(in)) {
      if (map contains numAsString) {
        map -= numAsString
      } else {
        max += 1
        listOfOut += numAsString
      }
    } else {
      if (listOfOut isEmpty) {
        max += 1
      } else {
        listOfOut.remove(0)
      }
      map += (numAsString -> true)
    }
  }

  println(max)
}

import java.util

import scala.collection.immutable.HashMap

/**
 * <a href="http://codeforces.com/problemset/problem/567/B"/>
 *
 * @author pvasilyev
 * @since 14 Apr 2016
 */
object Problem151 extends App {
  val n: Int = scala.io.StdIn.readInt()
  var map: Map[String, Boolean] = new HashMap[String, Boolean]()
  var list: util.LinkedList[String] = new util.LinkedList[String]()
  var max: Int = 0
  for (i <- 0 until n) {
    val Array(in, numAsString) = scala.io.StdIn.readLine().split(" ")
    if ("-".equals(in)) {
      if (map.contains(numAsString)) {
        map -= numAsString
      } else {
        map += (numAsString -> false)
        list.push(numAsString)
      }
    } else {
      if (map.contains(numAsString)) {
        map += (numAsString -> true)
      } else {
        var bCont = true
        while (!list.isEmpty && bCont) {
          val s = list.pop()
          map -= s
          bCont = false
        }
      }
    }
    max = Math.max(max, map.size)
  }

  println(max)
}

import scala.collection.immutable.HashMap

/**
 * <a href="http://codeforces.com/problemset/problem/567/B"/>
 *
 * @author pvasilyev
 * @since 14 Apr 2016
 */
object Problem151 extends App {
  val n: Int = scala.io.StdIn.readInt()
  var map: Map[String, Boolean] = new HashMap[String, Boolean]()
  var max: Int = 0
  for (i <- 0 until n) {
    val Array(in, numAsString) = scala.io.StdIn.readLine().split(" ")
    if ("-".equals(in)) {
      if (map.contains(numAsString)) {
        map -= numAsString
      } else {
        map += (numAsString -> false)
      }
    } else {
      map += (numAsString -> true)
    }
    max = Math.max(max, map.size)
  }

  println(max)
}

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

object Solution {

  def main(args: Array[String]) {
    val n = readInt()
    val lib = Set[String]()
    val logs = (1 to n).map(_=>readLine().split(" "))
    logs.zipWithIndex
      .filter { case (l, i) => l(0) == "-" && !logs.take(i).contains(l) }
      .foreach { case (l, _) => lib.add(l(1)) }

    var res = lib.size

    logs.foreach { log =>
      if (log(0) == "+") {
        lib.add(log(1))
      } else {
        lib.remove(log(1))
      }
      res = Math.max(res, lib.size)
    }

    println(res)

  }

}

import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _567B extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val library = mutable.Set.empty[Int]
  var ans = Int.MinValue
  for (i <- 1 to n) {
    val (isEnter, id) = (next == "+", nextInt)
    if (isEnter) {
      library += id
    } else if (library(id)) {
      library -= id
    } else {
      library += id
    }
    ans = ans max library.size
  }
  ans
})
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 def 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 counter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _567B extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val library = mutable.Set.empty[Int]
  var ans = 0
  for {_ <- 1 to n} {
    val (isEnter, id) = (next == "+", nextInt)
    if (isEnter) {
      library += id
    } else if (library(id)) {
      library -= id
    } else {
      ans = ans + 1
      library += id
    }
    ans = ans max library.size
    //debug(isEnter, id, library, ans)
  }
  ans
})
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 def 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 counter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}


There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≤ i ≤ n) and replace element ai with ai & x, where & denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.

The first line contains integers n and x (2 ≤ n ≤ 100 000, 1 ≤ x ≤ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≤ ai ≤ 100 000), the elements of the array.

Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.

NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.

object And {

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

    val arr_set = arr.toSet

    if (arr_set.size < arr.length)
      println(0)
    else if (arr.exists{elm =>
      val andX = elm & x

      elm != andX && arr_set.contains(andX)
    })
      println(1)
    else {
      val arrAndX = arr.map(_ & x)
      if (arrAndX.length > arrAndX.toSet.size)
        println(2)
      else
        println(-1)
    }
  }

}

import scala.collection.mutable

object And extends App {
  var input = List.empty[String]
//  var input = "4 3\n7 3 2 1".split("\n")

  def readline() = {
    if(input.nonEmpty) {
       val next = input.head
       input = input.tail
       next
    } else {
      scala.io.StdIn.readLine()
    }
  }

  val dims  = readline().split(" ").map(_.toInt)

  val numbers = dims(0)
  val x = dims(1)

  val as = readline().split(" ").map(_.toInt)

  val a_set = new mutable.BitSet()
  val and_set = new mutable.BitSet()

  var minSteps = 3
  def updateSteps(steps: Int): Unit = {
    if(minSteps > steps) {
      minSteps = steps
      if(minSteps == 0) {
        println("0")
        sys.exit(0)
      }
    }
  }
  for(a <- as) {
    val a_and = a & x
    if(a_set.contains(a_and) || and_set.contains(a)) {
      updateSteps(1)
    } else if(and_set.contains(a_and)) {
      updateSteps(2)
    } else {
      and_set += a_and
    }

    if(a_set.contains(a)) {
      updateSteps(0)
    } else {
      a_set += a
    }
  }

  if(minSteps == 3)
    println(-1)
  else
    println(minSteps)
}

object And {

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

    val arr_set = arr.toSet

    if (arr_set.size < arr.length)
      println(0)
    else if (arr.exists{elm =>
      val andX = elm & x

      elm != andX && arr_set.contains(andX)
    })
      println(1)
    else
      println(-1)
  }

}

import scala.collection.mutable

object And extends App {
  var input = "3 7\n1 2 3".split('\n')

  def readline() = {
    if(input.nonEmpty) {
       val next = input.head
       input = input.tail
       next
    } else {
      scala.io.StdIn.readLine()
    }
  }

  val dims  = readline().split(" ").map(_.toInt)

  val numbers = dims(0)
  val x = dims(1)

  val as = readline().split(" ").map(_.toInt)

  val a_set = new mutable.BitSet()
  val and_set = new mutable.BitSet()

  var minSteps = 3
  def updateSteps(steps: Int): Unit = {
    if(minSteps > steps) {
      minSteps = steps
      if(minSteps == 0) {
        println("0")
        sys.exit(0)
      }
    }
  }
  for(a <- as) {
    val a_and = a & x
    if(a_set.contains(a_and)) {
      updateSteps(1)
    } else if(and_set.contains(a_and)) {
      updateSteps(2)
    } else {
      and_set += a_and
    }

    if(a_set.contains(a)) {
      updateSteps(0)
    } else {
      a_set += a
    }
  }

  if(minSteps == 3)
    println(-1)
  else
    println(minSteps)
}

import scala.collection.mutable

object And extends App {
  var input = List.empty[String]

  def readline() = {
    if(input.nonEmpty) {
       val next = input.head
       input = input.tail
       next
    } else {
      scala.io.StdIn.readLine()
    }
  }

  val dims  = readline().split(" ").map(_.toInt)

  val numbers = dims(0)
  val x = dims(1)

  val as = readline().split(" ").map(_.toInt)

  val a_set = new mutable.BitSet()
  val and_set = new mutable.BitSet()

  var minSteps = 3
  def updateSteps(steps: Int): Unit = {
    if(minSteps > steps) {
      minSteps = steps
      if(minSteps == 0) {
        println("0")
        sys.exit(0)
      }
    }
  }
  for(a <- as) {
    val a_and = a & x
    if(a_set.contains(a_and)) {
      updateSteps(1)
    } else if(and_set.contains(a_and)) {
      updateSteps(2)
    } else {
      and_set += a_and
    }

    if(a_set.contains(a)) {
      updateSteps(0)
    } else {
      a_set += a
    }
  }

  if(minSteps == 3)
    println(-1)
  else
    println(minSteps)
}


Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility).  Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world). Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2n possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.

The first line of input contains two integers n and m (1 ≤ n, m ≤ 104) — number of universes and number of groups respectively. The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, k > 0) followed by k integers vi, 1, vi, 2, ..., vi, k. If vi, j is negative, it means that Rick from universe number  - vi, j has joined this group and otherwise it means that Morty from universe number vi, j has joined it. Sum of k for all groups does not exceed 104.

In a single line print the answer to Summer's question. Print "YES" if she should cancel the event and "NO" otherwise.

NoteIn the first sample testcase, 1st group only contains the Rick from universe number 3, so in case he's a traitor, then all members of this group are traitors and so Summer should cancel the event.

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n = read[Int]
    val groups = read[Seq[Set[Int]]]
    val ans = groups.exists({group =>
      val g2: Set[Int] = group.map(_.abs)
      g2.size == group.size
    })
    write(ans.toEnglish)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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


Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps.  Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two.Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps.

The first line of input contains integer n (1 ≤ n ≤ 106), the number of weights. The second line contains n integers w1, ..., wn separated by spaces (0 ≤ wi ≤ 106 for each 1 ≤ i ≤ n), the powers of two forming the weights values.

Print the minimum number of steps in a single line.

NoteIn the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two.In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toLong
  val maxn = (1000001l * 2).toInt
  val buffer = Array.ofDim[Int](maxn)
  val data = in.next().split(" ").map(_.toInt)
  data.foreach { i => buffer(i) += 1}

  println(buffer.indices.foldLeft(0) {
    case(acc, i) =>
      if (buffer(i) > 0)
        buffer(i + 1) += buffer(i) / 2
      acc + (if (buffer(i) % 2 == 1) 1 else 0)
  })
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val max_n = 1001000
    val x = Array.fill[Int](max_n)(0)
    REP(n) { _ =>
      val u = ni()
      x(u) += 1
    }

    var count = 0
    REP(max_n-1) { i =>
      x(i+1) += x(i) / 2
      count += x(i) % 2
    }
    out.println(count)
  }
}

object A extends App {

  final class BinHeap(limit: Int) {

    type T = Int
    @inline private def cmp(a: T, b: T): Boolean = a < b

    private var size = 0
    private val data = Array.ofDim[T](limit)

    @inline private def parent(i: Int) = i >> 1

    def isEmpty(): Boolean = size == 0

    def peek(): T = {
      assert(size > 0)
      data(0)
    }

    def add(x: T) {
      var i = size
      size += 1
      while (i > 0 && cmp(x, data(parent(i)))) {
        val p = parent(i)
        data(i) = data(p)
        i = p
      }
      data(i) = x
    }

    def poll(): T = {
      assert(size > 0)
      val result = data(0)
      size -= 1
      if (size > 0) {
        data(0) = data(size)
        heapify(0)
      }
      result
    }

    private def heapify(i: Int) {
      val l = i << 1
      val r = l + 1
      var top = if (l < size && cmp(data(l), data(i))) l else i
      if (r < size && cmp(data(r), data(top))) top = r
      if (top != i) {
        val tmp = data(i)
        data(i) = data(top)
        data(top) = tmp
        heapify(top)
      }
    }

  }

  @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 ws = readInts(n)

  val heap = new BinHeap(n)
  for (w <- ws) heap.add(w)

  var res = 0
  while (!heap.isEmpty) {
    val w = heap.poll()
    if (!heap.isEmpty && w == heap.peek) {
      heap.poll()
      heap.add(w + 1)
    } else res += 1
  }

  println(res)
}

import scala.collection._

object A extends App {

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

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

  val pq = new java.util.PriorityQueue[Int]()
  val cnts = Array.fill(ws.max * 2 + 1000) { 0 }

  for (w <- ws) cnts(w) += 1

  var res = 0
  for (i <- cnts.indices) {
    val c = cnts(i)
    if (c > 0) {
      res += c & 1
      cnts(i + 1) += (c >> 1)
    }
  }

  println(res)
}

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

object C_DuffAndWeightLifting_2 {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(t3.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = br.readLine().trim().split(" ")
    val number = line1(0).toInt
    val line2 = br.readLine().trim().split(" ")
//    val ww = new Array[Int](number)
//    for (i <- 0 until number) {
//      ww(i) = line2(i).toInt
//    }
    //---------------------------- parameters reading end --------------------------------

    val con = Array.fill[Int](1001000)(0)

    for (i <- line2) {
      con(i.toInt) += 1
    }

    var ones = 0
    var rest = 0
    for (i <- con) {
      val vv = i + rest
      if (vv % 2 == 1) ones += 1
      rest = (vv / 2).toInt
    }
    println(ones)

  }

//========================= samples ========================
val sa1 = """

"""

//========================= samples end ====================
}

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

object C_DuffAndWeightLifting {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(t3.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = br.readLine().trim().split(" ")
    val number = line1(0).toInt
    val tok = new StringTokenizer(br.readLine(), " ")
    //---------------------------- parameters reading end --------------------------------

    val con = new Array[Boolean](1001000)

    while (tok.hasMoreTokens()) {
      var pos = tok.nextToken().toInt
      while (con(pos)) {
        con(pos) = false
        pos += 1
      }
      con(pos) = true
    }

    var ones = 0
    for (i <- con) {
      if (i) {
        ones += 1
      }
    }
    println(ones)

  }

//========================= samples ========================
val sa1 = """

"""

//========================= samples end ====================
}

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

object C_DuffAndWeightLifting_2 {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(t3.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = br.readLine().trim().split(" ")
    val number = line1(0).toInt
    val line2 = br.readLine()
    val tok = new StringTokenizer(line2, " ")
//    val ww = new Array[Int](number)
//    for (i <- 0 until number) {
//      ww(i) = line2(i).toInt
//    }
    //---------------------------- parameters reading end --------------------------------

    val con = Array.fill[Int](1001000)(0)

    while (tok.hasMoreTokens()) {
      val ind = tok.nextToken().toInt
      con(ind) += 1
    }

    var ones = 0
    var rest = 0
    for (i <- con) {
      val vv = i + rest
      if (vv % 2 == 1) ones += 1
      rest = (vv / 2).toInt
    }
    println(ones)

  }

//========================= samples ========================
val sa1 = """
35
0 0 298 0 0 0 0 0 689063 65442 0 984598 2054 43668 0 369 0 2054 0 996220 0 16327 369 0 996220 0 0 0 4693 2054 348 0 118 0 0
"""

//========================= samples end ====================
}

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

object C_DuffAndWeightLifting {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(t3.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = br.readLine().trim().split(" ")
    val number = line1(0).toInt
    val line2 = br.readLine().trim().split(" ")
    val ww = new Array[Int](number)
    for (i <- 0 until number) {
      ww(i) = line2(i).toInt
    }
    //---------------------------- parameters reading end --------------------------------

    val con = new Array[Boolean](1001000)

    for (i <- ww) {
      var pos = i
      while (con(pos)) {
        con(pos) = false
        pos += 1
      }
      con(pos) = true
    }

    var ones = 0
    for (i <- con) {
      if (i) {
        ones += 1
      }
    }
    println(ones)

  }

//========================= samples ========================
val sa1 = """

"""

//========================= samples end ====================
}

object A extends App {

  final class BinHeap(limit: Int) {

    type T = Int
    @inline private def cmp(a: T, b: T): Boolean = a < b

    private var size = 0
    private val data = Array.ofDim[T](limit)

    @inline private def parent(i: Int) = i >> 1

    def isEmpty(): Boolean = size == 0

    def peek(): T = {
      assert(size > 0)
      data(0)
    }

    def add(x: T) {
      var i = size
      size += 1
      while (i > 0 && cmp(x, data(parent(i)))) {
        val p = parent(i)
        data(i) = data(p)
        i = p
      }
      data(i) = x
    }

    def poll(): T = {
      assert(size > 0)
      val result = data(0)
      size -= 1
      if (size > 0) {
        data(0) = data(size)
        heapify(0)
      }
      result
    }

    private def heapify(i: Int) {
      val l = i << 1
      val r = l + 1
      var top = if (l < size && cmp(data(l), data(r))) l else i
      if (r < size && cmp(data(r), data(top))) top = r
      if (top != i) {
        val tmp = data(i)
        data(i) = data(top)
        data(top) = tmp
        heapify(top)
      }
    }

  }

  @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 ws = readInts(n)

  val heap = new BinHeap(n)
  for (w <- ws) heap.add(w)

  var res = 0
  while (!heap.isEmpty) {
    val w = heap.poll()
    if (!heap.isEmpty && w == heap.peek) {
      heap.poll()
      heap.add(w + 1)
    } else res += 1
  }

  println(res)
}


As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues.Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T.Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k.

The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual.

Print the single number — the answer to the problem modulo k.

NoteThe first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link.The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it.The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime.

//package round110.div1

//package round110.div2

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 05.03.12
 * Time: 6:21
 * To change this template use File | Settings | File Templates.
 */

object D {
  val Array(evidCount, refCount, mod) = readLine split ' ' map (_ toInt)
  var all: List[Evidence] = Nil
  val evid = Array.ofDim[Evidence](evidCount)

  for (_ <- 1 to refCount) readLine split ' ' map (_ toInt) match {
    case Array(left, right) => evidence(left) refer evidence(right)
  }
  val result = {
    val setNums = all filter (_ isMain) map (_.count.toLong)

    if (setNums.length + evidCount - all.length == 1) 1 % mod
    else {
      val mull = setNums match {
        case Nil => 1
        case List(a) => a
        case list => list reduce ((left, right) => (left * right) % mod)
      }
      val summ = fastPow(evidCount, setNums.length + evidCount - all.length - 2)
      (mull.toLong * summ) % mod
    }
  }

  def main(args: Array[String]) = println(result)

  def fastPow(base: Int, pow: Int): Int = {
    if (base == 1) return 1
    var acc = 1L
    var mul = base toLong
    var bit = 1L
    while (bit <= pow) {
      if ((pow & bit) != 0) acc = (acc * mul) % mod
      mul = (mul * mul) % mod
      bit <<= 1
    }
    return acc toInt
  }

  def evidence(index: Int) = {
    evid(index - 1) match {
      case null => {
        val created = new Evidence
        evid(index - 1) = created
        created
      }
      case existing => existing
    }
  }

  class Evidence {
    private var parent = this
    private var rank = 0
    private[this] var _count: Int = 1

    def count = _count

    private def count_=(count: Int) = _count = count

    all ::= this

    def main: Evidence = {
      if (this.parent != this) this.parent = this.parent main;
      this.parent
    }

    def isMain = this.parent == this

    def absorb(that: Evidence) {
      count += that.count
      that.parent = this
      if (this.rank == that.rank) this.rank += 1
    }

    def refer(that: Evidence) {
      val thisMain = this main;
      val thatMain = that main;
      if (thisMain == thatMain) return;
      if (thisMain.rank <= thatMain.rank) thatMain absorb thisMain
      else thisMain absorb thatMain
    }
  }

}

//package round110.div1

//package round110.div2

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 05.03.12
 * Time: 6:21
 * To change this template use File | Settings | File Templates.
 */

object D {
  val Array(evidCount, refCount, mod) = readLine split ' ' map (_ toInt)
  var all: List[Evidence] = Nil
  val evid = Array.ofDim[Evidence](evidCount)

  for (_ <- 1 to refCount) readLine split ' ' map (_ toInt) match {
    case Array(left, right) => evidence(left) refer evidence(right)
  }

  val setNums = all filter (_ isMain) map (_.count.toLong)
  val mull = setNums match {
    case Nil => 1
    case List(a) => a
    case list => list reduce ((left, right) => (left * right) % mod)
  }
  val summ = fastPow(evidCount, setNums.length + evidCount - all.length - 2)
  val result = (mull.toLong * summ) % mod

  def main(args: Array[String]) = println(result)

  def fastPow(base: Int, pow: Int): Int = {
    if (base == 1) return 1
    var acc = 1L
    var mul = base toLong
    var bit = 1L
    while (bit <= pow) {
      if ((pow & bit) != 0) acc = (acc * mul) % mod
      mul = (mul * mul) % mod
      bit <<= 1
    }
    return acc toInt
  }

  def evidence(index: Int) = {
    evid(index - 1) match {
      case null => {
        val created = new Evidence
        evid(index - 1) = created
        created
      }
      case existing => existing
    }
  }

  class Evidence {
    private var parent = this
    private var rank = 0
    private[this] var _count: Int = 1

    def count = _count

    private def count_=(count: Int) = _count = count

    all ::= this

    def main: Evidence = {
      if (this.parent != this) this.parent = this.parent main;
      this.parent
    }

    def isMain = this.parent == this

    def absorb(that: Evidence) {
      count += that.count
      that.parent = this
      if (this.rank == that.rank) this.rank += 1
    }

    def refer(that: Evidence) {
      val thisMain = this main;
      val thatMain = that main;
      if (thisMain == thatMain) return;
      if (thisMain.rank <= thatMain.rank) thatMain absorb thisMain
      else thisMain absorb thatMain
    }
  }

}

//package round110.div1

//package round110.div2

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 05.03.12
 * Time: 6:21
 * To change this template use File | Settings | File Templates.
 */

object D {
  val Array(evidCount, refCount, mod) = readLine split ' ' map (_ toInt)
  var all: List[Evidence] = Nil
  val evid = Array.ofDim[Evidence](evidCount)

  for (_ <- 1 to refCount) readLine split ' ' map (_ toInt) match {
    case Array(left, right) => evidence(left) refer evidence(right)
  }

  val setNums = all filter (_ isMain) map (_.count.toLong)
  val mull = setNums match {
    case Nil => 1
    case List(a) => a
    case list => list reduce ((left, right) => (left * right) % mod)
  }
  val summ = fastPow(evidCount, setNums.length + evidCount - all.length - 2)
  val result = (mull.toLong * summ) % mod

  def main(args: Array[String]) = println(result)

  def fastPow(base: Int, pow: Int): Int = {
    if (base == 1) return 1
    var acc = 1L
    var mul = base toLong
    var bit = 1L
    while (bit <= pow) {
      if ((pow & bit) != 0) acc = (acc * mul) % mod
      mul = (mul * mul) % mod
      bit <<= 1
    }
    return acc toInt
  }

  def evidence(index: Int) = {
    evid(index - 1) match {
      case null => {
        val created = new Evidence
        evid(index - 1) = created
        created
      }
      case existing => existing
    }
  }

  class Evidence {
    private var parent = this
    private var rank = 0
    private[this] var _count: Int = 1

    def count = _count

    private def count_=(count: Int) = _count = count

    all ::= this

    def main: Evidence = {
      if (this.parent != this) this.parent = this.parent main;
      this.parent
    }

    def isMain = this.parent == this

    def absorb(that: Evidence) {
      count += that.count
      that.parent = this
      if (this.rank == that.rank) this.rank += 1
    }

    def refer(that: Evidence) {
      val thisMain = this main;
      val thatMain = that main;
      if (thisMain.rank <= thatMain.rank) thatMain absorb thisMain
      else thisMain absorb thatMain
    }
  }

}


You are given two binary strings $$$a$$$ and $$$b$$$ of the same length. You can perform the following two operations on the string $$$a$$$:  Swap any two bits at indices $$$i$$$ and $$$j$$$ respectively ($$$1 \le i, j \le n$$$), the cost of this operation is $$$|i - j|$$$, that is, the absolute difference between $$$i$$$ and $$$j$$$.  Select any arbitrary index $$$i$$$ ($$$1 \le i \le n$$$) and flip (change $$$0$$$ to $$$1$$$ or $$$1$$$ to $$$0$$$) the bit at this index. The cost of this operation is $$$1$$$. Find the minimum cost to make the string $$$a$$$ equal to $$$b$$$. It is not allowed to modify string $$$b$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the strings $$$a$$$ and $$$b$$$. The second and third lines contain strings $$$a$$$ and $$$b$$$ respectively. Both strings $$$a$$$ and $$$b$$$ have length $$$n$$$ and contain only '0' and '1'.

Output the minimum cost to make the string $$$a$$$ equal to $$$b$$$.

NoteIn the first example, one of the optimal solutions is to flip index $$$1$$$ and index $$$3$$$, the string $$$a$$$ changes in the following way: "100" $$$\to$$$ "000" $$$\to$$$ "001". The cost is $$$1 + 1 = 2$$$.The other optimal solution is to swap bits and indices $$$1$$$ and $$$3$$$, the string $$$a$$$ changes then "100" $$$\to$$$ "001", the cost is also $$$|1 - 3| = 2$$$.In the second example, the optimal solution is to swap bits at indices $$$2$$$ and $$$3$$$, the string $$$a$$$ changes as "0101" $$$\to$$$ "0011". The cost is $$$|2 - 3| = 1$$$.

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

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

  val MOD = 1000000007
  val out = new PrintWriter(System.out)
  val sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val A, B = ns(N)

    var ans = 0
    rep(N) { i =>
      if (A(i) != B(i)) ans += 1
    }

    var i = 0
    while (i < N - 1) {
      if (A(i) != B(i) && A(i + 1) != B(i + 1) && A(i) != A(i + 1)) {
        ans -= 1
        i += 1
      }
      i += 1
    }

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

import java.util.StringTokenizer

import scala.io.StdIn

object C extends App with Reader {
  read()
  val n = int()
  val s1 = StdIn.readLine().toCharArray.map(_ == '1')
  val s2 = StdIn.readLine().toCharArray.map(_ == '1')

  var res = 0
  for (i <- 0 until n) {
    if (s1(i) != s2(i)) {
      if ((i + 1 < n) && (s1(i) != s1(i+1)) && (s1(i+1) != s2(i+1))) {
        s1(i) = !s1(i)
        s1(i+1) = !s1(i+1)
        res += 1
      } else {
        s1(i) = !s1(i)
        res += 1
      }
    }
  }

  println(res)
}

trait Reader {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(StdIn.readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong
}

object C1037 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val from = stdin.readLine()
    val to = stdin.readLine()
    var i = 0
    var ans = 0
    while (i < n){
      if (i + 1 < n){
        if (from(i) != to(i) && from(i+1) != to(i+1) && from(i) != from(i+1)) {
          ans += 1
          i += 1
        } else {
          if (from(i) != to(i)) ans += 1
        }
      } else {
        if (from(i) != to(i)) ans += 1
      }
      i += 1
    }
    print(ans)
  }
}

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

object C extends App {

  case class Point(x: Int, segId: Int, isBegin: Boolean)

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val a = in.next
    val b = in.next
    var ans = 0
    var i = 0
    while (i < n) {
      if (i == n - 1) {
        if (a(i) != b(i))
          ans += 1
      } else {
        if (a(i) != b(i) && !(a(i) == b(i + 1) && a(i + 1) == b(i)))
          ans += 1
        else if (a(i) != b(i) && (a(i) == b(i + 1) && a(i + 1) == b(i))) {
          ans += 1
          i += 1
        }
      }
      i += 1
    }
    println(ans)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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

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

  val MOD = 1000000007
  val out = new PrintWriter(System.out)
  val sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val A, B = ns(N)

    var ans = 0
    rep(N) { i =>
      if (A(i) != B(i)) ans += 1
    }

    var i = 0
    while (i < N - 1) {
      if (A(i) != B(i) && A(i + 1) != B(i + 1)) {
        ans -= 1
        i += 1
      }
      i += 1
    }

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object C1037 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val from = stdin.readLine()
    val to = stdin.readLine()
    var i = 0
    var ans = 0
    while (i < n){
      if (i + 1 < n){
        if (from(i) != to(i) && from(i+1) != to(i+1) && from(i) != to(i)) {
          ans += 1
          i += 1
        } else {
          if (from(i) != to(i)) ans += 1
        }
      } else {
        if (from(i) != to(i)) ans += 1
      }
      i += 1
    }
    print(ans)
  }
}

object C1037 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val from = stdin.readLine()
    val to = stdin.readLine()
    var i = 0
    var ans = 0
    while (i < n){
      if (i + 1 < n){
        if (from(i) != to(i) && from(i+1) != to(i+1)) {
          ans += 1
          i += 1
        } else {
          if (from(i) != to(i)) ans += 1
        }
      } else {
        if (from(i) != to(i)) ans += 1
      }
      i += 1
    }
    print(ans)
  }
}

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

object C extends App {

  case class Point(x: Int, segId: Int, isBegin: Boolean)

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val a = in.next
    val b = in.next
    var ans = 0
    var i = 0
    while (i < n) {
      if (i == n - 1) {
        if (a(i) != b(i))
          ans += 1
      } else {
        if (a(i) != b(i) && a(i) == a(i + 1))
          ans += 1
        else if (a(i) == '1' && b(i) == '0' && a(i + 1) == '0' && b(i + 1) == '1') {
          ans += 1
          i += 1
        } else if (a(i) == '0' && b(i) == '1' && a(i + 1) == '1' && b(i + 1) == '0') {
          ans += 1
          i += 1
        }
      }
      i += 1
    }
    println(ans)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}


You want to perform the combo on your opponent in one popular fighting game. The combo is the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $$$s$$$. I.e. if $$$s=$$$"abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend $$$m$$$ wrong tries to perform the combo and during the $$$i$$$-th try you will make a mistake right after $$$p_i$$$-th button ($$$1 \le p_i < n$$$) (i.e. you will press first $$$p_i$$$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $$$m+1$$$-th try you press all buttons right and finally perform the combo.I.e. if $$$s=$$$"abca", $$$m=2$$$ and $$$p = [1, 3]$$$ then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the length of $$$s$$$ and the number of tries correspondingly. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of each test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i < n$$$) — the number of characters pressed right during the $$$i$$$-th try. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ both does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$). It is guaranteed that the answer for each letter does not exceed $$$2 \cdot 10^9$$$.

For each test case, print the answer — $$$26$$$ integers: the number of times you press the button 'a', the number of times you press the button 'b', $$$\dots$$$, the number of times you press the button 'z'.

3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4

NoteThe first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is $$$4$$$, 'b' is $$$2$$$ and 'c' is $$$2$$$.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is $$$9$$$, 'd' is $$$4$$$, 'e' is $$$5$$$, 'f' is $$$3$$$, 'o' is $$$9$$$, 'r' is $$$3$$$ and 's' is $$$1$$$.

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

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

      val s = ns(n)

      val p = na(m)

      val cnt = Array.fill[Int](26)(0)

      REP(n) { i =>
        cnt(s(i) - 'a') += 1
      }
      g = Array.ofDim[Array[Int]](26)
      REP(26) { i =>
        g(i) = Array.ofDim[Int](cnt(i))
      }

      REP_r(n) { i =>
        g(s(i) - 'a')(cnt(s(i) - 'a') - 1) = i
        cnt(s(i) - 'a') -= 1
      }
      ans = Array.fill[Long](26)(0)
      REP(m) { i =>
        bs(p(i) - 1)
      }
      REP(n) { i =>
        ans(s(i) - 'a') += 1
      }
      out.println(ans.mkString(" "))
    }
  }
  var g: Array[Array[Int]] = _
  var ans: Array[Long] = _

  def bs(v: Int): Unit = {
    REP(26) { i =>
      if(g(i).length > 0) {
        var l = 0
        var r = g(i).length - 1
        while (r - l > 1) {
          val m = l + (r - l) / 2
          if (g(i)(m) > v) r = m - 1
          else l = m
        }
        if (g(i).length > 0 && g(i)(r) <= v) ans(i) += (r+1)
        else if (g(i).length > 0 && g(i)(l) <= v) ans(i) += (l+1)
      }
    }
  }
}


Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that:  he pointed at the person with index (bi + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y);  if j ≥ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice;  the turn went to person number (bi + 1) mod n. The person who was pointed on the last turn did not make any actions.The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.You can assume that in any scenario, there is enough juice for everybody.

The first line contains a single integer n (4 ≤ n ≤ 2000) — the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.

Print a single integer — the number of glasses of juice Vasya could have drunk if he had played optimally well.

NoteIn both samples Vasya has got two turns — 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val str = in.next()
  if (str.length < 4)
    println(0)
  else {
    val res = (1 until str.length).foldLeft((0, 1, str.tail.head)) {
      case ((glasses, soFar, prev), i) if i % n == 0 && soFar >= 3 =>
        if (i == str.length - 1)
          (glasses + 1, soFar + 1, str(i))
        else {
          val next = str(i + 1)
          if (next == prev)
            (glasses + 1, soFar + 1, next)
          else
            (glasses + 1, 1, next)
        }
      case ((glasses, soFar, prev), i) if i % n == 0 =>
        if (i == str.length - 1)
          (glasses, soFar + 1, str(i))
        else {
          val next = str(i + 1)
          if (next == prev)
            (glasses, soFar + 1, next)
          else
            (glasses, 1, next)
        }
      case (acc@(glasses, soFar, prev), i) =>
//        println("last")
//        println(acc)
        if (i == str.length - 1) (glasses, soFar, str(i))
        else if (str(i) == prev) (glasses, soFar + 1, prev)
        else (glasses, 1, str(i))
    }
    println(res._1)

  }

}

object Main1 extends App {

  val n = readInt();
  val s = readLine().toCharArray();

  var cups = 0;

  for(i <- n to(s.length - 1, n)){
    if(s(i-1) == s(i-2) && s(i-2) == s(i-3)){
      cups = cups + 1;
    }
  }

  println(cups);

}

import java.util.Scanner

object DownTheHatch {
	def main(args: Array[String]) {
		val in = new Scanner(System.in)
		val n = in.nextInt()
		val s = in.next()
		var res = 0
		for (i <- 0 until s.length by n) {
			if (i >= 4){
				if (s(i - 1) == s(i - 2) && s(i - 2) == s(i - 3)) {
					res += 1
				}
			}
		}
		println(res)
	}
}

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

object P253A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N: Int = sc.nextInt
  sc.nextLine
  val turns: List[Char] = sc.nextLine.toList

  val answer: Int = turns.drop(N - 3).sliding(4, N).count {
      case List(x, y, z, _) => x == y && y == z
      case _                => false
    }

  out.println(answer)
  out.close
}

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

    var count = 0
    for (i <- n to s.size - 1 by n) {
      if (s(i - 3) == s(i - 2) && s(i - 3) == s(i - 1)) count += 1
    }

    println(count)
  }
}

import java.util.Scanner

object DownTheHatch {
	def main(args: Array[String]) {
		val in = new Scanner(System.in)
		val n = in.nextInt()
		val s = in.next()
		var res = 0
		for (i <- n until s.length by (n + 1)) {
			if (s(i - 1) == s (i - 2) && s(i - 2) == s(i - 3)) {
				res += 1
			}
		}
		println(res)
	}
}

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

    var count = 0
    for (i <- n to s.size by n) {
      if (s(i - 3) == s(i - 2) && s(i - 3) == s(i - 2)) count += 1
    }

    println(count)
  }
}

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

    var count = 0
    for (i <- n to s.size by n) {
      if (s(i - 3) == s(i - 2) && s(i - 3) == s(i - 1)) count += 1
    }

    println(count)
  }
}


Ashish has a string $$$s$$$ of length $$$n$$$ containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions:   Length of the substring is at least $$$2$$$  'a' occurs strictly more times in this substring than 'b'  'a' occurs strictly more times in this substring than 'c'  Ashish is busy planning his next Codeforces round. Help him solve the problem.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^{5})$$$  — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \le n \le 10^{6})$$$  — the length of the string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting only of characters 'a', 'b' and 'c'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^{6}$$$.

For each test case, output the length of the smallest substring which satisfies the given conditions or print $$$-1$$$ if there is no such substring.

NoteConsider the first test case. In the substring "aa", 'a' occurs twice, while 'b' and 'c' occur zero times. Since 'a' occurs strictly more times than 'b' and 'c', the substring "aa" satisfies the condition and the answer is $$$2$$$. The substring "a" also satisfies this condition, however its length is not at least $$$2$$$.In the second test case, it can be shown that in none of the substrings of "cbabb" does 'a' occur strictly more times than 'b' and 'c' each.In the third test case, "cacabccc", the length of the smallest substring that satisfies the conditions is $$$3$$$.

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 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 mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val s = readString()

        def check(k:Int): Boolean = {
            var a = 0
            var b = 0
            var c = 0
            for (i <- 0 until s.length) {
                if (s(i) == 'a')
                    a += 1
                if (s(i) == 'b')
                    b += 1
                if (s(i) == 'c')
                    c += 1
                if (i >= k) {
                    if (s(i-k) == 'a')
                        a -= 1
                    if (s(i-k) == 'b')
                        b -= 1
                    if (s(i-k) == 'c')
                        c -= 1
                }
                if (i >= k-1 && a > b && a > c)
                    return true
            }
            false
        }

        def bs(st: Int, en: Int): Int = {
            for (i <- st to en)
                if (check(i))
                    return i
            return -1
        }

        writer.println(bs(2, min(7, n)))
    }
    writer.flush()
}