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


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 {
      val arrAndX = arr.map(_ & x)
      if (arrAndX.length > arrAndX.toSet.size)
        println(2)
      else
        println(-1)
    }
  }

}

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


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

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


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

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

}


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

}

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

  }

}

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
}

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


import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
  }

  val allVoters = (0 until n).toArray.sortBy(voterCosts).reverse

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {

    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    val votes = Array.fill(voterCounts.length)(0)

    for (voter <- allVoters) {
      val candidate = voterFor(voter)
      if (candidate > 0) {
        if (votes(candidate) + 1 == votesToWin) {
          totalCost += voterCosts(voter)
          bribed += voter
          myVotes += 1
        } else votes(candidate) += 1
      }
    }

    var i = n - 1
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i -= 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
  }

  val allVoters = (0 until n).toArray.sortBy(voterCosts).reverse

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {

    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    val votes = Array.fill(voterCounts.length)(0)

    for {
      voter <- allVoters
      candidate = voterFor(voter)
      if candidate > 0
    } if (votes(candidate) + 1 == votesToWin) {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    } else votes(candidate) += 1

    var i = n - 1
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i -= 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.quickSort[Int](_)(Ordering.by(voterCosts))
  }

  val allVoters = (0 until n).toArray
  Sorting.quickSort[Int](allVoters)(Ordering.by(voterCosts))

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (pos < allVoters.size && bribed(allVoters(pos))) pos += 1
        if (pos == allVoters.size) {
          costToBribeCheapest = Long.MaxValue
          cnt = 0
        } else {
          costToBribeCheapest += voterCosts(allVoters(pos))
          //println(cnt, allVoters(pos))
          pos += 1
          cnt -= 1
        }
      }
      //println(numCandidatesWithMaxVoters, costToBribeFromBest, costToBribeCheapest)
      if (costToBribeFromBest <= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
        //while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        //bribe(allVoters(cheapestVoterPosition))
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))

  val allVoters = (0 until n).toArray.sortBy(voterCosts)
  //Sorting.stableSort(allVoters, voterCosts)
  if (n == 10) {
    println(allVoters.mkString(", "))
  }

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.stableSort(_, voterCosts)
  }

  val allVoters = (0 until n).toArray
  if (n == 10) {
    println(voterCosts.mkString(", "))
  }
  Sorting.stableSort(allVoters, voterCosts)

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.stableSort(_, voterCosts)
  }

  val allVoters = (0 until n).toArray
  Sorting.stableSort(allVoters, voterCosts)

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))

  val allVoters = (0 until n).toArray //.sortBy(voterCosts)
  Sorting.stableSort(allVoters, voterCosts)
  if (n == 10) {
    println(allVoters.mkString(", "))
  }

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest >= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        //        var cnt = numCandidatesWithMaxVoters + 1
        //
        //        while (cnt > 0) {
        //          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        //          bribe(allVoters(cheapestVoterPosition))
        //          cnt -= 1
        //        }
        while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        bribe(allVoters(cheapestVoterPosition))
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest >= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.quickSort[Int](_)(Ordering.by(voterCosts))
  }
  val allVoters = (0 until n).toArray.sortBy(voterCosts)

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.stableSort(_, voterCosts)
  }

  val allVoters = (0 until n).toArray
  Sorting.stableSort(allVoters, voterCosts)
  if (n == 10) {
    println(allVoters.mkString(", "))
  }

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest < costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
        //while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        //bribe(allVoters(cheapestVoterPosition))
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest <= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
        //while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        //bribe(allVoters(cheapestVoterPosition))
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  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 voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(voterPosition(c))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest >= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}


//package codeforces.contests._1367

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

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

      val freq = new Array[Int](26)
      s.foreach(c => freq(c - 'a') += 1)

      val kPairs = new Array[Int](n + 1)
      freq.foreach { f =>
        for (i <- 1 to f) kPairs(i) += f / i
      }
      /*
      n = 7, k = 1000
      abczgyo

      2 pairs are 3 and k = 4, e.g. "aabbcc", abab

      a -7
      b - 6
      c - 5

      abc abc abc a bc abc
      aabbc aabbc aabbc

      k = 10, 5 repetition thrice
       */

      println {
        (1 to n).foldLeft(0) { (acc, i) =>
          acc max {
            val x = (if (kPairs(i) > 0) {
              i * (kPairs(i) to 1 by -1).find(k % _ == 0).get
            } else 0) max (if (kPairs(i) >= k) i * k else 0) max (if (k % i == 0) i else 0) max (if (kPairs(i) >= 1) i else 0)
            x
          }
        }
      }
    }
  }
}

import scala.io.StdIn.readLine

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

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

  def handle(k: Int, list: Array[Char]): Int = {
    val gr = list.groupBy(i => i).map(tup => tup._2.length).toList.sortBy(t => t).reverse

    for (l <- (1 to list.length).reverse) {
      if (canSatisfy(l, gr, k)) return l
    }

    1
  }

  def canSatisfy(length: Int, bonds: List[Int], rawK: Int): Boolean = {
    def helper(groupSize: Int,  numGroups: Int, bs: List[Int]): Boolean = bs match {
      case Nil => numGroups <= 0
      case b :: bs => numGroups <= 0 || {
        if (groupSize > b) false else helper(groupSize, numGroups - b / groupSize, bs)
      }
    }

    val k = (rawK - 1) % length + 1
    val gcd = BigInt(length).gcd(BigInt(k)).toInt
    if (gcd == 1) bonds.head >= length else {
      val numOfGroups = length / gcd
      helper(numOfGroups, gcd, bonds)
    }
  }

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

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

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

}

object Main extends App {
  val r = new FastScanner(java.lang.System.in)
  val o = new java.io.PrintWriter(java.lang.System.out)
  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)
  for(_ <- 1 to r.nextInt()) {
    val n = r.nextInt()
    val k = r.nextInt()
    val s = r.nextToken(n)
    val c = Array.ofDim[Int](26)
    for(i <- s) c(i.toInt - 97) += 1
    val d = c.sorted.filter(_ > 0).reverse
    var res = 0
    for(l <- 1 to n) {
      //0, k, 2k, 3k, ... (mod l)
      //kx == y (mod l)
      val g = gcd(l, k)
      val gs = l / g
      //g groups, group size gs
      val t = d.foldLeft(0) { (acc, x) => acc + (x / gs) }
      if(t >= g) res = l
    }
    o.println(res)
  }
  o.close()
}

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

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

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

//package codeforces.contests._1367

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

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

      val freq = new Array[Int](26)
      s.foreach(c => freq(c - 'a') += 1)

      val kPairs = new Array[Int](n + 1)
      freq.foreach { f =>
        for (i <- 1 to f) kPairs(i) += f / i
      }
      /*
      n = 7, k = 1000
      abczgyo

      2 pairs are 3 and k = 4, e.g. "aabbcc", abab

      a -7
      b - 6
      c - 5

      abc abc abc a bc abc
      aabbc aabbc aabbc

      k = 10, 5 repetition thrice
       */

      println {
        (1 to n).foldLeft(0) { (acc, i) =>
          acc max {
            (if (kPairs(i) > 0 && k % kPairs(i) == 0) i * kPairs(i) else 0) max (if (kPairs(i) >= k) i * k else 0) max (if (k % i == 0) i else 0) max (if (kPairs(i) >= 1) i else 0)
          }
        }
      }
    }
  }
}