import scala.io.Source

object BPatchoulisMagicalTalisman {
  def main(args: Array[String]): Unit = {
        val file = Source.stdin.getLines
//    val file = Source.fromString(
//      "4\n2\n1 9\n3\n1 1 2\n3\n2 4 8\n3\n1049600 33792 1280"
//    ).getLines
    var t = file.next.toInt
    while (t > 0) {
      t-=1
      file.next
      val l = file.next.split(" ").map(_.toInt)
      val oddSize = l.count(_ % 2 == 1)
      val res = if (oddSize > 0) l.length - oddSize
      else {
        val unitIndex = l.map(_.toBinaryString.reverse).max.indexOf("1")
        unitIndex + l.length - 1
      }
      println(res)
    }
  }
}

import scala.io.StdIn
import scala.math.BigDecimal.double2bigDecimal

object Main {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()

    for(_ <- 0 until t) {
      val n = StdIn.readLong()

      val numbers = StdIn.readLine().split(" ").map(_.toLong)

      val evenNumbers =  numbers.count(x => x % 2 == 0)
      val oddNumbers = numbers.length - evenNumbers

      if(evenNumbers == 0) {
        println(0)
      } else if(oddNumbers == 0) {
        val (count, index) = numbers.filter(x => x % 2 == 0).zipWithIndex.map { case(n, index) => (howManyTwos(n), index) }.minBy(_._1)

        println(count + evenNumbers - 1)
      } else {
        println(evenNumbers)
      }
    }
  }

  def howManyTwos(number: Long): Long = {
    var count = 0
    var numberMut = number
    while(numberMut % 2 == 0) {
      numberMut /= 2
      count += 1
    }
    count
  }
}

import scala.io.StdIn
import scala.math.BigDecimal.double2bigDecimal

object Main {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()

    for(_ <- 0 until t) {
      val n = StdIn.readLong()

      val numbers = StdIn.readLine().split(" ").map(_.toLong)

      val evenNumbers =  numbers.count(x => x % 2 == 0)
      val oddNumbers = numbers.length - evenNumbers

      if(evenNumbers == 0) {
        println(0)
      } else {
        val (count, index) = numbers.filter(x => x % 2 == 0).zipWithIndex.map { case(n, index) => (howManyTwos(n), index) }.minBy(_._1)

        println(count + evenNumbers - 1)
      }
    }
  }

  def howManyTwos(number: Long): Long = {
    var count = 0
    var numberMut = number
    while(numberMut % 2 == 0) {
      numberMut /= 2
      count += 1
    }
    count
  }
}


object Main extends App {
import java.util._
import java.io._
//remove if not needed
import scala.collection.JavaConversions._

    input.init(System.in)
    val out = new PrintWriter(System.out)
    val n = input.nextInt()
    val k = input.nextInt()
    val ss = Array.ofDim[Int](n)
    val ms = Array.ofDim[Int](n)
    for (i <- 0 until n) {
      ss(i) = input.nextInt()
      ms(i) = input.nextInt()
    }
    val pq = new PriorityQueue[Long]()
    for (i <- 0 until n) {
      val start = Math.max(ss(i), if (pq.size < k) 0 else pq.poll())
      val end = start + ms(i)
      out.println(end)
      pq.add(end)
    }
    out.close()

  object input {

    var reader: BufferedReader = _

    var tokenizer: StringTokenizer = _

    def init(input: InputStream) {
      reader = new BufferedReader(new InputStreamReader(input))
      tokenizer = new StringTokenizer("")
    }

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

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

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

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

}

import scala.Array._
import scala.collection.mutable.PriorityQueue
import scala.math._

object C523 extends App{

  val res = readLine.split(" ").map(_.toInt)
  private final var n = res(0)
  val k = res(1)
  val q = new PriorityQueue[Long]
  var strResult : StringBuilder  = new StringBuilder

  (1 to k).foreach(x => q += 0)
  while(n > 0)
  {
    val str = readLine.split(" ").map(_.toLong)
    var x = str(0)
    val y = str(1)
    x = max(x, - q.dequeue) + y
    strResult.append(x)
    strResult.append('\n')
    q += -x
    n -= 1
  }
  println(strResult.toString)
}

object Main extends App {
import java.io._
import java.util._
//remove if not needed
import scala.collection.JavaConversions._

    val sc = new Scanner(System.in)
    val pw = new PrintWriter(System.out)
    val n:Int = sc.nextInt()
    val k:Long = sc.nextInt().toLong
    val q = new PriorityQueue[Long]()
    for (i <- 0 until n) {
      var s = sc.nextInt().toLong
      val d = sc.nextInt().toLong
      if (q.size >= k) {
        s = Math.max(s, q.poll().toInt)
      }
      val t = s + d
      q.offer(t)
      pw.println(t)
    }
    pw.flush()

}

object Main extends App {
import java.io._
import java.util._
//remove if not needed
import scala.collection.JavaConversions._

    val sc = new Scanner(System.in)
    val pw = new PrintWriter(System.out)
    val n = sc.nextInt()
    val k = sc.nextInt()
    val q = new PriorityQueue[Long]()
    for (i <- 0 until n) {
      var s = sc.nextInt()
      val d = sc.nextInt()
      if (q.size >= k) {
        s = Math.max(s, q.poll().toInt)
      }
      val t = s + d
      q.offer(t)
      pw.println(t)
    }
    pw.flush()

}

object Main extends App {
  import scala.collection.mutable.ListBuffer
  val Array(n, k) = readLine.split(" ").map(_.toLong)
  var servers1:List[Server] = List.empty[Server]
  (1L to k).foreach(n => servers1 = servers1 :+ Server(0L))
  def free_server1(load: Long, now: Long): Server = {
    servers1.find(serv => serv.peak_load < now ) match {
      case Some(serv) => serv.setLoad(load);serv
      case _ => val z = servers1.sortBy(s => s.peak_load).head;z.setLoad(load);z
    }
  }
  def serverAreFree(i: Long):Boolean = {
    servers1.filter(serv => serv.peak_load < i).length > 0
  }
  var videos1:Array[Array[Long]] = Array()
  (1L to n).map(nn => videos1 = videos1 :+ readLine.split(" ").map(_.toLong))

  var server_buffer1:Array[Long] = Array()

  def makeOut() = {
    videos1.foreach { video =>
      if (serverAreFree(video(0))){
        free_server1(video(1) + video(0), video(0))
        server_buffer1 = server_buffer1 :+ (video(1) + video(0))
      }
      if (!serverAreFree(video(0))){
        val vvv = servers1.sortBy(s => s.peak_load).head.peak_load + video(1)
        free_server1(vvv, video(0))
        server_buffer1 = server_buffer1 :+ vvv
      }

    }
  }
  makeOut()
  server_buffer1.foreach(c => println(c))

  case class Server(var peak_load: Long) {
    def setLoad(load: Long): Unit = {
      peak_load = load
    }
  }
}


import collection.mutable
import io.Source

object SimpleIOU {
    val netDebts = mutable.Map[Int, Int]().withDefaultValue(0)

    def main(args: Array[String]) = {
        val lines = Source.stdin.getLines()
        lines.next()

        lines.foreach(line => { val arr = line.split(" ").map(_.toInt); updateDebts(arr(0), arr(1), arr(2))})

        println(netDebts.foldLeft(0) {case (accum, (debtee, totalDebt)) => (0 max totalDebt) + accum})
    }

    def updateDebts(debtee: Int, debtor: Int, debt: Int) = {
        netDebts(debtee) += debt
        netDebts(debtor) -= debt
    }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val result = Array.ofDim[Int](n)
  (1 to m).foreach { _ =>
    val Array(from, to, amount) = in.next().split(' ').map(_.toInt)
    result(from - 1) += amount
    result(to - 1) -= amount
  }
  println(result.filter(_ > 0).sum)
}

import collection.mutable
import io.Source

object SimpleIOU {
    val netDebts = mutable.Map[Int, Int]().withDefaultValue(0)

    def main(args: Array[String]) = {
        val lines = Source.stdin.getLines()
        lines.next()

        lines.foreach(line => { val arr = line.split(" ").map(_.toInt); updateDebts(arr(0), arr(1), arr(2))})

        println(netDebts)
        println(netDebts.foldLeft(0) {case (accum, (debtee, totalDebt)) => (0 max totalDebt) + accum})
    }

    def updateDebts(debtee: Int, debtor: Int, debt: Int) = {
        netDebts(debtee) += debt
        netDebts(debtor) -= debt
    }
}


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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val ans = an
      .foldLeft((0L, 0L)) {
        case ((cost, damper), a) =>
          if (a < 0) (cost + (damper + a).min(0), (damper + a).max(0))
          else (cost, damper + a)
      }
      ._2

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val ans = an
      .foldRight((0L, 0L)) {
        case (el, (subSum, partSum)) =>
          (subSum max (partSum + el), partSum + el)
      }
      ._1

    println(ans)
  }
}

import scala.collection.mutable.ArrayBuffer

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m = in.nextInt()
      val data = in.nextLineInt(m)

      var posSum = 0L

      data.foreach(s => {
        if(s > 0){
          posSum += s
        } else {
          if( posSum + s <= 0) posSum = 0 else posSum += s
        }
      })

      println(posSum)
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}


object EDU47B extends App {

  import java.io.PrintWriter
  import java.util.Scanner

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

  def solve = {
    val ternaryString = in.next.toCharArray

    val ones = ternaryString.filter(_ == '1')
    val remainder = ternaryString.filter(_ != '1')
    val start = remainder.takeWhile(_ != '2')
    val end = remainder.takeRight(remainder.length - start.length)

    val result = start ++ ones ++ end

    out.println(result.mkString)
  }

  solve
  out.flush
  out.close
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val inputString = readLine

    val withoutOnes = inputString.filter(_ != '1')
    val onesLength = inputString.length - withoutOnes.length

    withoutOnes.indexOf('2') match {
      case -1 => {
        print("0" * withoutOnes.length)
        print("1" * onesLength)
      }
      case idx => {
        print(withoutOnes.slice(0, idx))
        print("1" * onesLength)
        print(withoutOnes.slice(idx, withoutOnes.length))
      }
    }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    new Recurser(readLine).recurse()
  }
}

class Recurser(original: String) {
  @annotation.tailrec
  final def recurse(startAt: Int = 0): Unit = {
    if(startAt == original.length) return

    val counts = Array(0, 0, 0)
    var nextAt = startAt

    while(nextAt < original.length && (counts(0) == 0 || counts(2) == 0)) {
      counts(getNum(nextAt)) += 1
      if((counts(0) == 0 || counts(2) == 0)) nextAt += 1
    }

    printit(counts, nextAt)
    recurse(nextAt)
  }

  def printit(counts: Array[Int], nextAt: Int) = {
    counts.zipWithIndex.foreach { tuple =>
      tuple match {
        case (count, index) if(nextAt == original.length || getNum(nextAt) != index) => print(index.toString * count)
        case _ =>
      }
    }
  }

  def getNum(at: Int): Int = original(at).toInt - 48
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val inputString = readLine

    val withoutOnes = inputString.filter(_ != '1')
    val onesLength = inputString.length - withoutOnes.length

    withoutOnes.indexOf('2') match {
      case -1 => {
        print("0" * withoutOnes.length)
        print("1" * onesLength)
      }
      case idx => {
        print(withoutOnes.slice(0, idx))
        print("1" * onesLength)
        print(withoutOnes.slice(idx + 1, withoutOnes.length))
      }
    }
  }
}

object EDU47B extends App {

  import java.io.PrintWriter
  import java.util.Scanner

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

  def nextInt = in.nextInt
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve = {
    val ternaryString = nextString.toCharArray.map(_.asDigit)
    //val ternaryString = Array.fill(100000){scala.util.Random.nextInt(3)}

    def sort(string: Array[Int], alreadySorted: Array[Int]): Array[Int] = {
      if (string.isEmpty) return alreadySorted
      if (string.length == 1) return alreadySorted ++ string

      var n = 1
      var min, max = string.head
      var done = false
      while (!done) {
        // Read next character
        max = Math.max(max, string(n))
        min = Math.min(min, string(n))

        if (max - min > 1) done = true
        else if (n+1 == string.length) {
          done = true
          n += 1
        }
        else n += 1
      }

      sort(string.drop(n), alreadySorted ++ string.take(n).sorted)
    }

    out.println(ternaryString.mkString)
    out.println(sort(ternaryString, Array.emptyIntArray).mkString)
  }

  solve
  out.flush
  out.close

  /*try {
    solve
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush
    out.close
  }*/
}


import scala.io.StdIn.readLine
import scala.collection.mutable.ListBuffer

/* http://codeforces.com/contest/743/problem/E  */
object Cards extends App {

  def toBits(n: Int) =
    (0 to 7).map(i => ((1 << i) & n) != 0)

  def toFreqPattern(freq: Int, seq: Seq[Boolean]) =
    seq.map(if (_) freq + 1 else freq)

  def frequencyPatternsFor(n: Int) =
    (1 to 255).map(toBits).map(toFreqPattern(n, _))

  def isAcceptable(pattern: Seq[Int], frequency: Int): Boolean = {
    if (frequency * 8 > data.size) return false

    var index = 0
    var patternIndex = 0
    var counter = 0
    var result = 0

    while (true) {
      if (data(index) == pattern(patternIndex)) {
        counter += 1
        if (counter == frequency) {
          patternIndex += 1
          result += counter
          counter = 0
        }
      }
      index += 1

      if (index == data.size || patternIndex == pattern.size)
        return result == (8 * frequency)
    }
    return false
  }

  def getMaxFrequency(pattern: Seq[Int], initFrequency: Int): Int = {
    if (!isAcceptable(pattern, initFrequency)) {
      return 0;
    }
    var frequency = initFrequency
    while (true) {
      frequency += 1
      val canApplyPatternFreq = isAcceptable(pattern, frequency)
      if (!canApplyPatternFreq) return frequency - 1
    }
    return 0; // never reached
  }

  def scanData(pattern: Seq[Int], frequencyPattern: Seq[Int]): Int = {
    var index = 0
    var patternIndex = 0
    var counter = 0
    var result = 0

    while (true) {
      if (data(index) == pattern(patternIndex)) {
        counter += 1
        if (counter == frequencyPattern(patternIndex)) {
          patternIndex += 1
          result += counter
          counter = 0
        }
      }
      index += 1

      if (index == data.size || patternIndex == pattern.size)
        return result
    }
    return 0
  }

  def getMaxFrequencyPatterns = {
    var result: ListBuffer[Seq[Int]] = ListBuffer()
    var maxFreq = 1
    Array(1, 2, 3, 4, 5, 6, 7, 8).permutations
      .foreach { pattern =>
        val frq = getMaxFrequency(pattern, maxFreq)
        if (frq > maxFreq) {
          maxFreq = frq
          result = ListBuffer(pattern)
        } else if (frq == maxFreq) {
          result += pattern
        }
      }
    (maxFreq, result)
  }

  /* Solution */
  val n = readLine.toInt
  val data = readLine.split(" ").map(_.toInt)

  val distinct = data.distinct.size

  val result = if (distinct < 8) {
    distinct
  } else {
    val (maxFrequency, acceptedPatterns) = getMaxFrequencyPatterns
    frequencyPatternsFor(maxFrequency)
      .map(fPattern => acceptedPatterns.map(pattern =>
        scanData(pattern, fPattern)))
      .flatten
      .max max (maxFrequency * 8)
  }

  println(result)
}

import scala.io.StdIn.readLine
import scala.collection.mutable.ListBuffer

object Cards extends App {

  val n = readLine.toInt
  val a = readLine.split(" ").map(_.toInt)
  //test 8
//  val a = Array(3, 6, 6, 8, 8, 1, 1, 4, 4, 3, 3, 5, 5, 7, 7, 2, 2, 3)
//      val a = Array(1, 8, 1, 2, 8, 2, 3, 8, 3, 4, 8, 4, 5, 8, 5, 6, 8, 6, 7, 8, 7, 8, 8, 8)
//      val a = Array(1,2,3,4,5,6,7,8)
//      val a = Array(1, 1, 1)
//    val a = Array(6, 7, 8, 5, 2, 8, 5, 4, 6, 4, 3, 2, 5, 6, 5, 7, 5, 7, 1, 7, 4, 6, 4, 1, 4, 1, 1, 7, 6, 7, 3, 7, 4, 7, 4, 6, 4, 7, 6, 6, 6, 5, 5, 7, 3, 5, 3, 7, 2, 2, 4, 2, 5, 6, 8, 4, 1, 2, 2, 8, 3, 3, 2, 5, 6, 4, 3, 6, 2, 4, 1, 4, 2, 8, 8, 3, 7, 6, 4, 7, 2, 7, 3, 3, 8, 8, 6, 8, 7, 7, 6, 8, 3, 2, 5, 2, 6, 5, 7, 5, 7, 5, 3, 2, 6, 2, 6, 5, 7, 8, 7, 7, 2, 6, 5, 4, 2, 3, 1, 8)

  val ipattern = Array(1, 2, 3, 4, 5, 6, 7, 8)

  def toBits(n: Int) =
    (0 to 7).map(i => ((1 << i) & n) != 0)

  def toFreqs(freq: Int, seq: Seq[Boolean]) =
    seq.map(if (_) freq + 1 else freq)

  def freqsFor(n: Int) =
    (1 to 255).map(toBits).map(toFreqs(n, _))

  def canPass(initPattern: Seq[Int], freq: Int, a: Array[Int]): Boolean = {
    if (freq * 8 > a.size) return false

    var pos = 0
    var patternPos = 0
    var counter = 0
    var result = 0

    while (true) {
      if (a(pos) == initPattern(patternPos)) {
        counter += 1
        if (counter == freq) {
          patternPos += 1
          result += counter
          counter = 0
        }
      }
      pos += 1

      if (pos == a.size || patternPos == initPattern.size)
        return result == (8 * freq)
    }
    return false
  }

  def getMaxPass(initPattern: Seq[Int], initFreq: Int): Int = {
//    val distinct = a.distinct.size
//    if (distinct < 8) return 0

    if (!canPass(initPattern, initFreq, a)) {
      return 0;
    }
    var freq = initFreq + 1
    do {
      val cnps = canPass(initPattern, freq, a)
      //      println(s"canpass $initPattern, $freq, $cnps ")
      if (!cnps) return freq - 1
      freq += 1
    } while (true)

    return 0;
  }

  def check(initPattern: Seq[Int], freqs: Seq[Int], a: Array[Int]): Int = {
    var pos = 0
    var patternPos = 0
    var counter = 0
    var result = 0

    while (true) {
      if (a(pos) == initPattern(patternPos)) {
        counter += 1
        if (counter == freqs(patternPos)) {
          patternPos += 1
          result += counter
          counter = 0
        }
      }
      pos += 1

      if (pos == a.size || patternPos == initPattern.size)
        return result
    }
    return 0
  }

  val d = a.distinct.size
  if (d < 8) {
    println(d)
  } else {

    val (maxFreq, maxPassPatterns) = getPassPatterns

//        println(s"maxFreq: $maxFreq")
//        println(s"maxPassPatterns size: ${maxPassPatterns.size}")

    val result = freqsFor(maxFreq)
      .map(feqPattern => maxPassPatterns
        .map(iptrn => check(iptrn, feqPattern, a))).flatten.max max (maxFreq * 8)
    println(result)

  }

  def getPassPatterns = {
    var ans: ListBuffer[Array[Int]] = ListBuffer()
    var maxFreq = 1
    ipattern.permutations.foreach(perPattern => {
      val frq = getMaxPass(perPattern, maxFreq)
      if (frq > maxFreq) {
        maxFreq = frq
        ans = ListBuffer(perPattern)
      } else if (frq == maxFreq) {
        ans += perPattern
      }
    })
    (maxFreq, ans)
  }

}

import scala.io.StdIn.readLine
import scala.collection.mutable.ListBuffer

object Cards extends App {

  def toBits(n: Int) =
    (0 to 7).map(i => ((1 << i) & n) != 0)

  def toFreqPattern(freq: Int, seq: Seq[Boolean]) =
    seq.map(if (_) freq + 1 else freq)

  def frequencyPatternsFor(n: Int) =
    (1 to 255).map(toBits).map(toFreqPattern(n, _))

  def isAcceptable(pattern: Seq[Int], frequency: Int): Boolean = {
    if (frequency * 8 > data.size) return false

    var pos = 0
    var patternPos = 0
    var counter = 0
    var result = 0

    while (true) {
      if (data(pos) == pattern(patternPos)) {
        counter += 1
        if (counter == frequency) {
          patternPos += 1
          result += counter
          counter = 0
        }
      }
      pos += 1

      if (pos == data.size || patternPos == pattern.size)
        return result == (8 * frequency)
    }
    return false
  }

  def getMaxFrequency(pattern: Seq[Int], initFrequency: Int): Int = {
    if (!isAcceptable(pattern, initFrequency)) {
      return 0;
    }
    var frequency = initFrequency
    while (true) {
      frequency += 1
      val canApplyPatternFreq = isAcceptable(pattern, frequency)
      if (!canApplyPatternFreq) return frequency - 1
    }
    return 0; // never reached
  }

  def scanData(pattern: Seq[Int], frequencyPattern: Seq[Int]): Int = {
    var index = 0
    var patternIndex = 0
    var counter = 0
    var result = 0

    while (true) {
      if (data(index) == pattern(patternIndex)) {
        counter += 1
        if (counter == frequencyPattern(patternIndex)) {
          patternIndex += 1
          result += counter
          counter = 0
        }
      }
      index += 1

      if (index == data.size || patternIndex == pattern.size)
        return result
    }
    return 0
  }

  def getMaxFrequencyPatterns = {
    var result: ListBuffer[Seq[Int]] = ListBuffer()
    var maxFreq = 1
    Array(1, 2, 3, 4, 5, 6, 7, 8).permutations
      .foreach { pattern =>
        val frq = getMaxFrequency(pattern, maxFreq)
        if (frq > maxFreq) {
          maxFreq = frq
          result = ListBuffer(pattern)
        } else if (frq == maxFreq) {
          result += pattern
        }
      }
    (maxFreq, result)
  }

  /* Solution */
  val n = readLine.toInt
  val data = readLine.split(" ").map(_.toInt)

  val distinct = data.distinct.size

  val result = if (distinct < 8) {
    distinct
  } else {
    val (maxFrequency, acceptedPatterns) = getMaxFrequencyPatterns
    frequencyPatternsFor(maxFrequency)
      .map(fPattern => acceptedPatterns.map(pattern =>
        scanData(pattern, fPattern)))
      .flatten
      .max max (maxFrequency * 8)
  }

  println(result)
}

import scala.io.StdIn.readLine
import scala.collection.mutable.ListBuffer

object Cards extends App {

    val n = readLine.toInt
    val a = readLine.split(" ").map(_.toInt)
//    val a = Array(1, 8, 1, 2, 8, 2, 3, 8, 3, 4, 8, 4, 5, 8, 5, 6, 8, 6, 7, 8, 7, 8, 8, 8)
  //    val a = Array(1, 1, 1)
//  val a = Array(6, 7, 8, 5, 2, 8, 5, 4, 6, 4, 3, 2, 5, 6, 5, 7, 5, 7, 1, 7, 4, 6, 4, 1, 4, 1, 1, 7, 6, 7, 3, 7, 4, 7, 4, 6, 4, 7, 6, 6, 6, 5, 5, 7, 3, 5, 3, 7, 2, 2, 4, 2, 5, 6, 8, 4, 1, 2, 2, 8, 3, 3, 2, 5, 6, 4, 3, 6, 2, 4, 1, 4, 2, 8, 8, 3, 7, 6, 4, 7, 2, 7, 3, 3, 8, 8, 6, 8, 7, 7, 6, 8, 3, 2, 5, 2, 6, 5, 7, 5, 7, 5, 3, 2, 6, 2, 6, 5, 7, 8, 7, 7, 2, 6, 5, 4, 2, 3, 1, 8)

  val ipattern = Array(1, 2, 3, 4, 5, 6, 7, 8)

  def toBits(n: Int) =
    (0 to 7).map(i => ((1 << i) & n) != 0)

  def toFreqs(freq: Int, seq: Seq[Boolean]) =
    seq.map(if (_) freq + 1 else freq)

  def freqsFor(n: Int) =
    (1 to 255).map(toBits).map(f => toFreqs(n, f))

  def canPass(initPattern: Seq[Int], freq: Int, a: Array[Int]): Boolean = {
    if (freq * 8 > a.size) return false

    var pos = 0
    var patternPos = 0
    var counter = 0
    var result = 0

    while (true) {
      if (a(pos) == initPattern(patternPos)) {
        counter += 1
        if (counter == freq) {
          patternPos += 1
          result += counter
          counter = 0
        }
      }
      pos += 1

      if (pos == a.size || patternPos == initPattern.size)
        return result == (8 * freq)
    }
    return false
  }

  def getMaxPass(initPattern: Seq[Int], initFreq: Int): Int = {
    val distinct = a.distinct.size
    if (distinct < 8) return 0

    if (!canPass(initPattern, initFreq, a)) {
      return 0;
    }
    var freq = initFreq + 1
    do {
      val cnps = canPass(initPattern, freq, a)
//      println(s"canpass $initPattern, $freq, $cnps ")
      if (!cnps) return freq - 1
      freq += 1
    } while (true)

    return 0;
  }

  def check(initPattern: Seq[Int], freqs: Seq[Int], a: Array[Int]): Int = {
    var pos = 0
    var patternPos = 0
    var counter = 0
    var result = 0

    while (true) {
      if (a(pos) == initPattern(patternPos)) {
        counter += 1
        if (counter == freqs(patternPos)) {
          patternPos += 1
          result += counter
          counter = 0
        }
      }
      pos += 1

      if (pos == a.size || patternPos == initPattern.size)
        return result
    }
    return 0
  }

  val d = a.distinct.size
  if (d < 8) {
    println(d)
  } else {

    val (maxFreq, maxPassPatterns) = getPassPatterns

//    println(s"maxFreq: $maxFreq")
//    println(s"maxPassPatterns : ${maxPassPatterns.size}")

    val result = freqsFor(maxFreq)
      .map(feqPattern => maxPassPatterns
        .map(iptrn => check(iptrn, feqPattern, a))).flatten.max
    println(result)

  }

  def getPassPatterns = {
    var ans: ListBuffer[Array[Int]] = ListBuffer()
    var maxFreq = 1
    ipattern.permutations.foreach(perPattern => {
      val frq = getMaxPass(perPattern, maxFreq)
      if (frq > maxFreq) {
        maxFreq = frq
        ans = ListBuffer(perPattern)
      } else if (frq == maxFreq) {
        ans += perPattern
      }
    })
    (maxFreq, ans)
  }

}

import scala.io.StdIn.readLine
import scala.collection.mutable.ListBuffer

object Cards extends App {

  val n = readLine.toInt
  val a = readLine.split(" ").map(_.toInt)
//      val a = Array(1, 8, 1, 2, 8, 2, 3, 8, 3, 4, 8, 4, 5, 8, 5, 6, 8, 6, 7, 8, 7, 8, 8, 8)
//      val a = Array(1,2,3,4,5,6,7,8)
//      val a = Array(1, 1, 1)
//    val a = Array(6, 7, 8, 5, 2, 8, 5, 4, 6, 4, 3, 2, 5, 6, 5, 7, 5, 7, 1, 7, 4, 6, 4, 1, 4, 1, 1, 7, 6, 7, 3, 7, 4, 7, 4, 6, 4, 7, 6, 6, 6, 5, 5, 7, 3, 5, 3, 7, 2, 2, 4, 2, 5, 6, 8, 4, 1, 2, 2, 8, 3, 3, 2, 5, 6, 4, 3, 6, 2, 4, 1, 4, 2, 8, 8, 3, 7, 6, 4, 7, 2, 7, 3, 3, 8, 8, 6, 8, 7, 7, 6, 8, 3, 2, 5, 2, 6, 5, 7, 5, 7, 5, 3, 2, 6, 2, 6, 5, 7, 8, 7, 7, 2, 6, 5, 4, 2, 3, 1, 8)

  val ipattern = Array(1, 2, 3, 4, 5, 6, 7, 8)

  def toBits(n: Int) =
    (0 to 7).map(i => ((1 << i) & n) != 0)

  def toFreqs(freq: Int, seq: Seq[Boolean]) =
    seq.map(if (_) freq + 1 else freq)

  def freqsFor(n: Int) =
    (1 to 255).map(toBits).map(toFreqs(n, _))

  def canPass(initPattern: Seq[Int], freq: Int, a: Array[Int]): Boolean = {
    if (freq * 8 > a.size) return false

    var pos = 0
    var patternPos = 0
    var counter = 0
    var result = 0

    while (true) {
      if (a(pos) == initPattern(patternPos)) {
        counter += 1
        if (counter == freq) {
          patternPos += 1
          result += counter
          counter = 0
        }
      }
      pos += 1

      if (pos == a.size || patternPos == initPattern.size)
        return result == (8 * freq)
    }
    return false
  }

  def getMaxPass(initPattern: Seq[Int], initFreq: Int): Int = {
//    val distinct = a.distinct.size
//    if (distinct < 8) return 0

    if (!canPass(initPattern, initFreq, a)) {
      return 0;
    }
    var freq = initFreq + 1
    do {
      val cnps = canPass(initPattern, freq, a)
      //      println(s"canpass $initPattern, $freq, $cnps ")
      if (!cnps) return freq - 1
      freq += 1
    } while (true)

    return 0;
  }

  def check(initPattern: Seq[Int], freqs: Seq[Int], a: Array[Int]): Int = {
    var pos = 0
    var patternPos = 0
    var counter = 0
    var result = 0

    while (true) {
      if (a(pos) == initPattern(patternPos)) {
        counter += 1
        if (counter == freqs(patternPos)) {
          patternPos += 1
          result += counter
          counter = 0
        }
      }
      pos += 1

      if (pos == a.size || patternPos == initPattern.size)
        return result
    }
    return 0
  }

  val d = a.distinct.size
  if (d < 8) {
    println(d)
  } else {

    val (maxFreq, maxPassPatterns) = getPassPatterns

//        println(s"maxFreq: $maxFreq")
//        println(s"maxPassPatterns size: ${maxPassPatterns.size}")

    val result = freqsFor(maxFreq)
      .map(feqPattern => maxPassPatterns
        .map(iptrn => check(iptrn, feqPattern, a))).flatten.max max 8
    println(result)

  }

  def getPassPatterns = {
    var ans: ListBuffer[Array[Int]] = ListBuffer()
    var maxFreq = 1
    ipattern.permutations.foreach(perPattern => {
      val frq = getMaxPass(perPattern, maxFreq)
      if (frq > maxFreq) {
        maxFreq = frq
        ans = ListBuffer(perPattern)
      } else if (frq == maxFreq) {
        ans += perPattern
      }
    })
    (maxFreq, ans)
  }

}

import scala.io.StdIn.readLine
import scala.collection.mutable.ListBuffer

object Cards extends App {

  val n = readLine.toInt
  val a = readLine.split(" ").map(_.toInt)
//      val a = Array(1, 8, 1, 2, 8, 2, 3, 8, 3, 4, 8, 4, 5, 8, 5, 6, 8, 6, 7, 8, 7, 8, 8, 8)
//      val a = Array(1,2,3,4,5,6,7,8)
//      val a = Array(1, 1, 1)
//    val a = Array(6, 7, 8, 5, 2, 8, 5, 4, 6, 4, 3, 2, 5, 6, 5, 7, 5, 7, 1, 7, 4, 6, 4, 1, 4, 1, 1, 7, 6, 7, 3, 7, 4, 7, 4, 6, 4, 7, 6, 6, 6, 5, 5, 7, 3, 5, 3, 7, 2, 2, 4, 2, 5, 6, 8, 4, 1, 2, 2, 8, 3, 3, 2, 5, 6, 4, 3, 6, 2, 4, 1, 4, 2, 8, 8, 3, 7, 6, 4, 7, 2, 7, 3, 3, 8, 8, 6, 8, 7, 7, 6, 8, 3, 2, 5, 2, 6, 5, 7, 5, 7, 5, 3, 2, 6, 2, 6, 5, 7, 8, 7, 7, 2, 6, 5, 4, 2, 3, 1, 8)

  val ipattern = Array(1, 2, 3, 4, 5, 6, 7, 8)

  def toBits(n: Int) =
    (0 to 7).map(i => ((1 << i) & n) != 0)

  def toFreqs(freq: Int, seq: Seq[Boolean]) =
    seq.map(if (_) freq + 1 else freq)

  def freqsFor(n: Int) =
    (1 to 255).map(toBits).map(toFreqs(n, _))

  def canPass(initPattern: Seq[Int], freq: Int, a: Array[Int]): Boolean = {
    if (freq * 8 > a.size) return false

    var pos = 0
    var patternPos = 0
    var counter = 0
    var result = 0

    while (true) {
      if (a(pos) == initPattern(patternPos)) {
        counter += 1
        if (counter == freq) {
          patternPos += 1
          result += counter
          counter = 0
        }
      }
      pos += 1

      if (pos == a.size || patternPos == initPattern.size)
        return result == (8 * freq)
    }
    return false
  }

  def getMaxPass(initPattern: Seq[Int], initFreq: Int): Int = {
//    val distinct = a.distinct.size
//    if (distinct < 8) return 0

    if (!canPass(initPattern, initFreq, a)) {
      return 0;
    }
    var freq = initFreq + 1
    do {
      val cnps = canPass(initPattern, freq, a)
      //      println(s"canpass $initPattern, $freq, $cnps ")
      if (!cnps) return freq - 1
      freq += 1
    } while (true)

    return 0;
  }

  def check(initPattern: Seq[Int], freqs: Seq[Int], a: Array[Int]): Int = {
    var pos = 0
    var patternPos = 0
    var counter = 0
    var result = 0

    while (true) {
      if (a(pos) == initPattern(patternPos)) {
        counter += 1
        if (counter == freqs(patternPos)) {
          patternPos += 1
          result += counter
          counter = 0
        }
      }
      pos += 1

      if (pos == a.size || patternPos == initPattern.size)
        return result
    }
    return 0
  }

  val d = a.distinct.size
  if (d < 8) {
    println(d)
  } else {

    val (maxFreq, maxPassPatterns) = getPassPatterns

        println(s"maxFreq: $maxFreq")
        println(s"maxPassPatterns size: ${maxPassPatterns.size}")

    val result = freqsFor(maxFreq)
      .map(feqPattern => maxPassPatterns
        .map(iptrn => check(iptrn, feqPattern, a))).flatten.max max 8
    println(result)

  }

  def getPassPatterns = {
    var ans: ListBuffer[Array[Int]] = ListBuffer()
    var maxFreq = 1
    ipattern.permutations.foreach(perPattern => {
      val frq = getMaxPass(perPattern, maxFreq)
      if (frq > maxFreq) {
        maxFreq = frq
        ans = ListBuffer(perPattern)
      } else if (frq == maxFreq) {
        ans += perPattern
      }
    })
    (maxFreq, ans)
  }

}


object CF1 extends App{
  import scala.io.StdIn
  val arr = StdIn.readLine().split(' ').map(_.toInt)
  val n = arr(0)
  val k = arr(1)

  var ans = ((n - k) to 1 by (-k * 2 - 1)).toList.reverse

  if (ans.isEmpty){
    println(1)
    if (n >= 2)
      println(n / 2)
    else
      println(1)
  }else{
    ans = ans match {
      case x :: xs if x - k > 1 && 1 + k > x - k =>
        val r = (1 + k) - (x - k) + 1
        1 :: ans.map(_+r).filter(_<=n)

      case x :: xs if x - k > 1 => 1 :: ans.map(_+1)
      case _ => ans
    }

    println(ans.size)
    ans.foreach(el => print(s"$el "))
  }
}

import java.util.Scanner

object BBQ extends App {
  val sc = new Scanner(System.in)
  val in = sc.nextLine().split(" ").map(_.toInt)
  val k = in.head
  val n = in.last
  val done = (for (i <- 0 until k) yield true).toArray
  val res = (for (i <- 0 to n+1) yield run(init(), List(i), 0)).filter(_._2 != Nil)
  if (res.nonEmpty) {
    val min = res.minBy(_._1)
    println(min._1)
    println(min._2.reverse.map(_ + 1).mkString(" "))
  } else println("no solution")

  private def init() = (for (i <- 0 until k) yield false).toArray

  private def turn(index: Int, n: Int, switch: Array[Boolean]) = {
    def go(from: Int, to: Int) = {
      for (i <- from to to) {
        switch(i) = !switch(i)
      }
      switch
    }

    if (index - n < 0 && index + n >= switch.length-1) go(0, switch.length-1)
    else if (index - n < 0 && index + n < switch.length-1) go(0, index + n)
    else if (index - n >= 0 && index + n < switch.length-1) go(index - n, index + n)
    else go(index - n, switch.length - 1)
  }

  private def run(turned: Array[Boolean], indexes: List[Int], step: Int): (Int, List[Int]) = {
    if (indexes.head < turned.length && !done.sameElements(turned))
      run(turn(indexes.head, n, turned), (indexes.head + 2*n + 1) :: indexes, step + 1)
    else if (done.sameElements(turned)) (step, indexes.tail)
    else (step, Nil)
  }

}

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)

  def solve(): Unit = {
    val N, K = ni()
    val L = 2 * K + 1

    if (K == 0) {
      val ans = map(N)(i => i + 1)
      out.println(N)
      out.println(ans.mkString(" "))
    } else if (L >= N) {
      out.println(1)
      out.println(N / 2 + 1)
    } else {
      val ans = ArrayBuffer[Int]()
      def add(from: Int, to: Int): Unit = {
        rep((to - from) / L) { i =>
          ans += i * L + from + K
        }
      }
      val p = N / L
      val r =  N - p * L
      if (r == 0) {
        add(0, N)
      } else if (r < K + 1) {
        def find(): Unit = {
          rep(K) { a =>
            val b = r - 1 - a
            if (b >= 0) {
              ans += a
              add(a + K + 1, N - (b + K + 1))
              ans += N - 1 - b
              return
            }
          }
        }
        find()

      } else { // r >= K + 1
        ans += r - K - 1
        add(r, N)
      }

      out.println(ans.length)
      out.println(ans.map(_ + 1).mkString(" "))
    }
  }

  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)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): 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
  }
}

object CF1 extends App{
  import scala.io.StdIn
  val arr = StdIn.readLine().split(' ').map(_.toInt)
  val n = arr(0)
  val k = arr(1)

  val ans = (k + 1) to n by (k + 1)

  if (ans.isEmpty){
    println(1)
    println(n / 2)
  }else{
    println(ans.size)
    ans.foreach(el => print(s"$el "))
  }
}

object CF1 extends App{
  import scala.io.StdIn
  val arr = StdIn.readLine().split(' ').map(_.toInt)
  val n = arr(0)
  val k = arr(1)

  var ans = (n - k) to 1 by (-k * 2 - 1) toList

  if (ans.isEmpty){
    println(1)
    if (n >= 2)
      println(n / 2)
    else
      println(1)
  }else{
    ans = if (ans.last - k > 1) 1 :: ans.map(_+1).reverse else ans.reverse

    println(ans.size)
    ans.foreach(el => print(s"$el "))
  }
}

object CF1 extends App{
  import scala.io.StdIn
  val arr = StdIn.readLine().split(' ').map(_.toInt)
  val n = arr(0)
  val k = arr(1)

  var ans = (n - k) to 1 by (-k * 2 - 1) toList

  if (ans.isEmpty){
    println(1)
    println(n / 2)
  }else{
    ans = if (ans.last - k > 1) 1 :: ans.map(_+1).reverse else ans.reverse

    println(ans.size)
    ans.foreach(el => print(s"$el "))
  }
}

object CF1 extends App{
  import scala.io.StdIn
  val arr = StdIn.readLine().split(' ').map(_.toInt)
  val n = arr(0)
  val k = arr(1)

  val ans = (k + 1) to n by (k * 2)

  if (ans.isEmpty){
    println(1)
    println(n / 2)
  }else{
    println(ans.size)
    ans.foreach(el => print(s"$el "))
  }
}

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)

  def solve(): Unit = {
    val N, K = ni()
    val L = 2 * K + 1

    if (L >= N) {
      out.println(N / 2 + 1)
    } else if (K == 0) {
      val ans = map(N)(i => i + 1)
      out.println(ans.mkString(" "))
    } else {
      val ans = ArrayBuffer[Int]()
      def add(from: Int, to: Int): Unit = {
        rep((to - from) / L) { i =>
          ans += i * L + from + K
        }
      }
      val p = N / L
      val r =  N - p * L
      if (r == 0) {
        add(0, N)
      } else if (r < K + 1) {
        def find(): Unit = {
          rep(K) { a =>
            val b = r - 1 - a
            if (b >= 0) {
              ans += a
              add(a + K + 1, N - (b + K + 1))
              ans += N - 1 - b
              return
            }
          }
        }
        find()

      } else { // r >= K + 1
        ans += r - K - 1
        add(r, N)
      }

      out.println(ans.length)
      out.println(ans.map(_ + 1).mkString(" "))
    }
  }

  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)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): 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
  }
}

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)

  def solve(): Unit = {
    val N, K = ni()
    val L = 2 * K + 1

    if (L >= N) {
      out.println(N / 2 + 1)
    } else {
      val ans = ArrayBuffer[Int]()
      def add(from: Int, to: Int): Unit = {
        rep((to - from) / L) { i =>
          ans += i * L + from + K
        }
      }
      val p = N / L
      val r =  N - p * L
      if (r == 0) {
        add(0, N)
      } else if (r < K + 1) {
        def find(): Unit = {
          rep(K) { a =>
            val b = r - 1 - a
            if (b >= 0) {
              ans += a
              add(a + K + 1, N - (b + K + 1))
              ans += N - 1 - b
              return
            }
          }
        }
        find()

      } else { // r >= K + 1
        ans += r - K - 1
        add(r, N)
      }

      out.println(ans.length)
      out.println(ans.map(_ + 1).mkString(" "))
    }
  }

  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)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): 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
  }
}

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)

  def solve(): Unit = {
    val N, K = ni()
    val L = 2 * K + 1

    if (L >= N) {
      out.println(N / 2)
    } else {
      val ans = ArrayBuffer[Int]()
      def add(from: Int, to: Int): Unit = {
        rep((to - from) / L) { i =>
          ans += i * L + from + K
        }
      }
      val p = N / L
      val r =  N - p * L
      if (r == 0) {
        add(0, N)
      } else if (r < K + 1) {
        def find(): Unit = {
          rep(K) { a =>
            val b = r - 1 - a
            if (b >= 0) {
              ans += a
              add(a + K + 1, N - (b + K + 1))
              ans += N - 1 - b
              return
            }
          }
        }
        find()

      } else { // r >= K + 1
        ans += r - K - 1
        add(r, N)
      }

      out.println(ans.length)
      out.println(ans.map(_ + 1).mkString(" "))
    }
  }

  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)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): 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
  }
}

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)

  def solve(): Unit = {
    val N, K = ni()
    val L = 2 * K + 1

    if (L >= N) {
      out.println(N / 2)
    } else {
      val ans = ArrayBuffer[Int]()
      def add(from: Int, to: Int): Unit = {
        rep((to - from) / L) { i =>
          ans += i * L + from + K
        }
      }
      val p = N / L
      val r =  N - p * L
      if (r == 0) {
        add(0, N)
      } else if (r < K + 1) {
        def find(): Unit = {
          rep(K) { a =>
            val b = r - 1 - a
            if (b >= 0) {
              ans += a
              add(a + K + 1, N - (b + K + 1))
              ans += N - 1 - K
              return
            }
          }
        }
        find()

      } else { // r >= K + 1
        ans += r - K - 1
        add(r, N)
      }

      out.println(ans.length)
      out.println(ans.map(_ + 1).mkString(" "))
    }
  }

  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)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): 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
  }
}

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)

  def solve(): Unit = {
    val N, K = ni()
    val L = 2 * K + 1

    if (L >= N) {
      out.println(N / 2)
    } else {
      val ans = ArrayBuffer[Int]()
      def add(from: Int, to: Int): Unit = {
        rep((to - from) / L) { i =>
          ans += i * L + from + K
        }
      }
      val p = N / L
      val r =  N - p * L
      if (r == 0) {
        add(0, N)
      } else {
//      } else if (r < K + 1) {
        def find(): Unit = {
          rep(K) { a =>
            val b = r - 1 - a
            if (b >= 0) {
              ans += a
              add(a + K + 1, N - (b + K + 1))
              ans += N - 1 - b
              return
            }
          }
        }
        find()
//
//      } else { // r >= K + 1
//        ans += r - K - 1
//        add(r, N)
      }

      out.println(ans.length)
      out.println(ans.map(_ + 1).mkString(" "))
    }
  }

  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)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): 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
  }
}

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)

  def solve(): Unit = {
    val N, K = ni()
    val L = 2 * K + 1

    if (K == 0) {
      val ans = map(N)(i => i + 1)
      out.println(ans.mkString(" "))
    } else if (L >= N) {
      out.println(N / 2 + 1)
    } else {
      val ans = ArrayBuffer[Int]()
      def add(from: Int, to: Int): Unit = {
        rep((to - from) / L) { i =>
          ans += i * L + from + K
        }
      }
      val p = N / L
      val r =  N - p * L
      if (r == 0) {
        add(0, N)
      } else if (r < K + 1) {
        def find(): Unit = {
          rep(K) { a =>
            val b = r - 1 - a
            if (b >= 0) {
              ans += a
              add(a + K + 1, N - (b + K + 1))
              ans += N - 1 - b
              return
            }
          }
        }
        find()

      } else { // r >= K + 1
        ans += r - K - 1
        add(r, N)
      }

      out.println(ans.length)
      out.println(ans.map(_ + 1).mkString(" "))
    }
  }

  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)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): 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
  }
}

object BBQ extends App {
  val k = 5 //val k = args(0)
  val n = 1 //val n = args(1)
  val done = (for (i <- 0 until k) yield true).toArray
  val res = (for (i <- done.indices) yield run(init(), List(i), 0)).filter(_._2 != Nil)
  if (res.nonEmpty) {
    val min = res.minBy(_._1)
    println(min._1)
    println(min._2.reverse.map(_ + 1).mkString(" "))
  } else println("no solution")

  private def init() = (for (i <- 0 until k) yield false).toArray

  private def turn(index: Int, n: Int, switch: Array[Boolean]) = {
    def go(from: Int, to: Int) = {
      for (i <- from to to) {
        switch(i) = !switch(i)
      }
      switch
    }

    if (index - n < 0 && index + n >= switch.length-1) go(0, switch.length-1)
    else if (index - n < 0 && index + n < switch.length-1) go(0, index + n)
    else if (index - n >= 0 && index + n < switch.length-1) go(index - n, index + n)
    else go(index - n, switch.length - 1)
  }

  private def run(turned: Array[Boolean], indexes: List[Int], step: Int): (Int, List[Int]) = {
    if (indexes.head < turned.length && !done.sameElements(turned))
      run(turn(indexes.head, n, turned), (indexes.head + 2*n + 1) :: indexes, step + 1)
    else if (done.sameElements(turned)) (step, indexes.tail)
    else (step, Nil)
  }

}


import scala.collection._

object B 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, b) = readInts(2)
  val res = Array.fill(n) { -1L }

  case class Task(id: Int, t: Int, d: Int)

  val tasks = Array.tabulate(n) { id =>
    val Array(t, d) = readInts(2)
    Task(id, t, d)
  }.sortBy(_.t)

  val queue = mutable.Queue.empty[Task]

  var time = 0L
  for (i <- tasks.indices) {
    val task = tasks(i)
    while (time <= task.t && queue.nonEmpty) {
      val queued = queue.dequeue()
      time += queued.d
      res(queued.id) = time
    }
    if (time < task.t) time = task.t
    if (queue.size < b) queue += task
  }

  while (queue.nonEmpty) {
    val queued = queue.dequeue()
    time += queued.d
    res(queued.id) = time
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString(" "))
  Console.flush
}

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

object Solution {

  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines.toList
    val (firstLine, rest) =
      lines match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, queueSize) =
      firstLine.split(" ") match {
        case Array(x, y) => (x.toInt, y.toInt)
      }

    val jobs = (for {
      line <- rest.zipWithIndex
    } yield parseLine(line)).toList

    val finishedJobs = processQueries(jobs, numQueries, queueSize).sortBy(_.getId)
    finishedJobs.foreach(x => print(x.getEndTime + " "))
    println
  }

  def processQueries(pendingJobs: List[PendingJob], numQueries: Int, queueSize: Int): Vector[FinishedJob] = {
    val queue = Queue[PendingJob]()
    val finishedJobs: ArrayBuffer[FinishedJob] = ArrayBuffer.empty[FinishedJob]
    val remainingJobs: ListBuffer[PendingJob] = pendingJobs.to[ListBuffer]

    def queuePendingJobs(curTime: Long) = {
      while (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime < curTime) {
        val head = remainingJobs.remove(0)
        if (queue.size == queueSize) {
          finishedJobs += head.fail
        } else {
          queue enqueue head
        }
      }
    }

    def getNextRunningJob(curTime: Long): Option[PendingJob] = {
      if (!queue.isEmpty) {
        val job = queue.dequeue
        finishedJobs += job.run(curTime)
        Some(job)
      }
      else if (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime == curTime) {
        val job = remainingJobs.remove(0)
        finishedJobs += job.run(curTime)
        Some(job)
      }
      else
        None
    }

    def loop(curJob: Option[CompleteJob], curTime: Long): Vector[FinishedJob] = {
      if (queue.isEmpty && remainingJobs.isEmpty) {
        finishedJobs.toVector
      } else if (!queue.isEmpty && remainingJobs.isEmpty) {
        var currentTime = curTime
        while (!queue.isEmpty) {
          val curJob = queue.dequeue
          val runJob = curJob.run(currentTime)
          finishedJobs += runJob
          currentTime = currentTime + curJob.processTime
        }
        finishedJobs.toVector
      } else {
        queuePendingJobs(curTime)

        val f = () => {
          val nextJob = getNextRunningJob(curTime)
          nextJob match {
            case Some(y) => {
              val completeNextJob = y.run(curTime)
              Some(completeNextJob)
            }
            case _ => None
          }
        }
        val nextRunningJob: Option[CompleteJob] =
          curJob match {
            case Some(x) if (x.endTime <= curTime) => f()
            case Some(x) => Some(x)
            case None => f()
          }

        val getNextStartTime: Long =
          nextRunningJob match {
            case Some(x) => x.endTime
            case None    => if (!remainingJobs.isEmpty) remainingJobs.head.arrivalTime else curTime + 1
          }
        loop(nextRunningJob, getNextStartTime)
      }
    }

    loop(None, 0)
  }

  def parseLine(line: Tuple2[String, Int]): PendingJob = {
    line._1.split(" ") match {
      case Array(x, y) => PendingJob(line._2, x.toInt, y.toInt)
    }
  }

}

case class PendingJob(id: Int, arrivalTime: Long, processTime: Long) {
  def run(curTime: Long): CompleteJob = CompleteJob(id, processTime + curTime)
  def fail: FailedJob = FailedJob(id)
}
trait FinishedJob {
  def getId: Int
  def getEndTime: Long
}
case class CompleteJob(id: Int, endTime: Long) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = endTime
}
case class FailedJob(id: Int) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = -1L
}

import scala.collection._

object B 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, b) = readInts(2)
  val res = Array.fill(n) { -1 }

  case class Task(id: Int, t: Int, d: Int)

  val tasks = Array.tabulate(n) { id =>
    val Array(t, d) = readInts(2)
    Task(id, t, d)
  }.sortBy(_.t)

  val queue = mutable.Queue.empty[Task]

  var time = 0
  for (i <- tasks.indices) {
    val task = tasks(i)
    while (time <= task.t && queue.nonEmpty) {
      val queued = queue.dequeue()
      time += queued.d
      res(queued.id) = time
    }
    if (time < task.t) time = task.t
    if (queue.size < b) queue += task
  }

  while (queue.nonEmpty) {
    val queued = queue.dequeue()
    time += queued.d
    res(queued.id) = time
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString(" "))
  Console.flush
}

import scala.collection.immutable.Queue

object Solution {

  def main(args: Array[String]): Unit = {
    val (firstLine, lines) =
      scala.io.Source.stdin.getLines.toList match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, sizeOfQueue) =
      firstLine.split(" ").map(_.toInt) match {
        case Array(x, y) => (x, y)
      }

    val jobs: List[PendingJob] =
      for {
        lineWithIndex <- lines.zipWithIndex
      } yield parseJob(lineWithIndex._1, lineWithIndex._2)

    processJobs(jobs, numQueries, sizeOfQueue).sortWith(_.index < _.index).foreach(x => print(x + " "))
    println
  }

  def processJobs(jobs: List[PendingJob], numQueries: Int, sizeOfQueue: Int): Vector[FinishedJob] = {
    @scala.annotation.tailrec
    def loop(curJob: Option[RunningJob], remainingJobs: List[PendingJob], queue: Queue[PendingJob], curTime: Long, processedJobs: Vector[FinishedJob]): Vector[FinishedJob] = {
      def getNextStartTime = {
        remainingJobs match {
          case x::_ => x.arrivalTime
          case Nil => curJob.get.endTime
        }
      }
      if (remainingJobs.isEmpty && queue.isEmpty) {
        processedJobs
      } else {
        val (currentlyArrivingJob, newRemainingJobs) =
          remainingJobs match {
            case x::xs if x.arrivalTime == curTime => (Some(x), xs)
            case _ => (None, remainingJobs)
          }

        val curRunningJob: Option[RunningJob] =
          curJob match {
            case Some(x) if x.endTime <= curTime => None
            case _ => curJob
          }
        var nextStartTime = curTime + 1
        val (nextRunningJob, newQueue, newProcessedJobs) =
          (currentlyArrivingJob, curRunningJob) match {
            case (None, Some(_)) => {
              nextStartTime = getNextStartTime
              (curRunningJob, queue, processedJobs)
            }
            case (None, None) => {
              if (queue.isEmpty) {
                nextStartTime = getNextStartTime
                (None, queue, processedJobs)
              } else {
                val (nextJob, q) = queue.dequeue
                val newRunningJob = nextJob.start(curTime)
                (Some(newRunningJob), q, processedJobs :+ newRunningJob)
              }
            }
            case (Some(x), None) => {
              if (queue.isEmpty) {
                val newRunningJob = x.start(curTime)
                (Some(newRunningJob), queue, processedJobs :+ newRunningJob)
              } else {
                val (nextJob, q) = queue.dequeue
                val newRunningJob: RunningJob = nextJob.start(curTime)
                (Some(newRunningJob), q enqueue x, processedJobs :+ newRunningJob)
              }
            }
            case (Some(x), Some(_)) if queue.size < sizeOfQueue =>
              (curRunningJob, queue enqueue x, processedJobs)
            case (Some(x), _) =>
              val failedPendingJob = x.start(curTime)
              (curRunningJob, queue, processedJobs :+ FailedJob(x.index))
          }

        loop(nextRunningJob, newRemainingJobs, newQueue, nextStartTime, newProcessedJobs)
      }
    }
    loop(None, jobs, Queue[PendingJob](), 0, Vector[RunningJob]())
  }

  //Parses a single line of input into a job
  private def parseJob(line: String, index: Int): PendingJob = {
    val startAndProcess: Array[Int] = line.split(" ").map(_.toInt)
    PendingJob(index, startAndProcess(0), startAndProcess(1))
  }
}

//a single processing job
trait Job
case class PendingJob(index: Int, arrivalTime: Long, processTime: Long) extends Job {
  def start(curTime: Long) = RunningJob(index, curTime + processTime)
}
abstract class FinishedJob(val index: Int, val endTime: Long) {
  override def toString = endTime.toString
}
case class RunningJob(theIndex: Int, theEndTime: Long) extends FinishedJob(theIndex, theEndTime)
case class FailedJob(theIndex: Int) extends FinishedJob(theIndex, -1)

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

object Solution {

  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines.toList
    val (firstLine, rest) =
      lines match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, queueSize) =
      firstLine.split(" ") match {
        case Array(x, y) => (x.toInt, y.toInt)
      }

    val jobs = (for {
      line <- rest.zipWithIndex
    } yield parseLine(line)).toList

    val finishedJobs = processQueries(jobs, numQueries, queueSize).sortBy(_.getId)
    finishedJobs.foreach(x => print(x.getEndTime + " "))
    println
  }

  def processQueries(pendingJobs: List[PendingJob], numQueries: Int, queueSize: Int): Vector[FinishedJob] = {
    val queue = Queue[PendingJob]()
    val finishedJobs: ArrayBuffer[FinishedJob] = ArrayBuffer.empty[FinishedJob]
    val remainingJobs: ListBuffer[PendingJob] = pendingJobs.to[ListBuffer]

    def queuePendingJobs(curTime: Long) = {
      if(!remainingJobs.isEmpty)println(remainingJobs.head.arrivalTime)
      while (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime < curTime) {
        val head = remainingJobs.remove(0)
        if (queue.size == queueSize) {
          finishedJobs += head.fail
        } else {
          queue enqueue head
          finishedJobs += head.run(curTime)
        }
      }
    }

    def getNextRunningJob(curTime: Long): Option[PendingJob] = {
      if (!queue.isEmpty)
        Some(queue.dequeue)
      else if (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime == curTime) {
        val job = remainingJobs.remove(0)
        finishedJobs += job.run(curTime)
        Some(job)
      }
      else
        None
    }

    def loop(curJob: Option[CompleteJob], curTime: Long): Vector[FinishedJob] = {
      println("Current time is " + curTime)
      if (queue.isEmpty && remainingJobs.isEmpty) {
        finishedJobs.toVector
      } else if (!queue.isEmpty && remainingJobs.isEmpty) {
        var currentTime = curTime
        while (!queue.isEmpty) {
          val curJob = queue.dequeue
          val runJob = curJob.run(currentTime)
          finishedJobs += runJob
          currentTime = currentTime + curJob.processTime
        }
        finishedJobs.toVector
      } else {
        queuePendingJobs(curTime)

        val f = () => {
          val nextJob = getNextRunningJob(curTime)
          nextJob match {
            case Some(y) => {
              val completeNextJob = y.run(curTime)
              Some(completeNextJob)
            }
            case _ => None
          }
        }
        val nextRunningJob: Option[CompleteJob] =
          curJob match {
            case Some(x) if (x.endTime <= curTime) => f()
            case Some(x) => Some(x)
            case None => f()
          }

        val getNextStartTime: Long =
          nextRunningJob match {
            case Some(x) => x.endTime
            case None    => if (!remainingJobs.isEmpty) remainingJobs.head.arrivalTime else curTime + 1
          }
        loop(nextRunningJob, getNextStartTime)
      }
    }

    loop(None, 0)
  }

  def parseLine(line: Tuple2[String, Int]): PendingJob = {
    line._1.split(" ") match {
      case Array(x, y) => PendingJob(line._2, x.toInt, y.toInt)
    }
  }

}

case class PendingJob(id: Int, arrivalTime: Long, processTime: Long) {
  def run(curTime: Long): CompleteJob = CompleteJob(id, processTime + curTime)
  def fail: FailedJob = FailedJob(id)
}
trait FinishedJob {
  def getId: Int
  def getEndTime: Long
}
case class CompleteJob(id: Int, endTime: Long) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = endTime
}
case class FailedJob(id: Int) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = -1L
}

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

object Solution {

  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines.toList
    val (firstLine, rest) =
      lines match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, queueSize) =
      firstLine.split(" ") match {
        case Array(x, y) => (x.toInt, y.toInt)
      }

    val jobs = (for {
      line <- rest.zipWithIndex
    } yield parseLine(line)).toList

    val finishedJobs = processQueries(jobs, numQueries, queueSize).sortBy(_.getId)
    finishedJobs.foreach(x => print(x.getEndTime + " "))
    println
  }

  def processQueries(pendingJobs: List[PendingJob], numQueries: Int, queueSize: Int): Vector[FinishedJob] = {
    val queue = Queue[PendingJob]()
    val finishedJobs: ArrayBuffer[FinishedJob] = ArrayBuffer.empty[FinishedJob]
    val remainingJobs: ListBuffer[PendingJob] = pendingJobs.to[ListBuffer]

    def queuePendingJobs(curTime: Long) = {
      while (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime < curTime) {
        val head = remainingJobs.remove(0)
        if (queue.size == queueSize) {
          finishedJobs += head.fail
        } else {
          queue enqueue head
          finishedJobs += head.run(curTime)
        }
      }
    }

    def getNextRunningJob(curTime: Long): Option[PendingJob] = {
      if (!queue.isEmpty)
        Some(queue.dequeue)
      else if (!remainingJobs.isEmpty && remainingJobs.head.arrivalTime == curTime) {
        val job = remainingJobs.remove(0)
        finishedJobs += job.run(curTime)
        Some(job)
      }
      else
        None
    }

    def loop(curJob: Option[CompleteJob], curTime: Long): Vector[FinishedJob] = {
      if (queue.isEmpty && remainingJobs.isEmpty) {
        finishedJobs.toVector
      } else if (!queue.isEmpty && remainingJobs.isEmpty) {
        var currentTime = curTime
        while (!queue.isEmpty) {
          val curJob = queue.dequeue
          val runJob = curJob.run(currentTime)
          finishedJobs += runJob
          currentTime = currentTime + curJob.processTime
        }
        finishedJobs.toVector
      } else {
        queuePendingJobs(curTime)

        val f = () => {
          val nextJob = getNextRunningJob(curTime)
          nextJob match {
            case Some(y) => {
              val completeNextJob = y.run(curTime)
              Some(completeNextJob)
            }
            case _ => None
          }
        }
        val nextRunningJob: Option[CompleteJob] =
          curJob match {
            case Some(x) if (x.endTime <= curTime) => f()
            case Some(x) => Some(x)
            case None => f()
          }

        val getNextStartTime: Long =
          nextRunningJob match {
            case Some(x) => x.endTime
            case None    => if (!remainingJobs.isEmpty) remainingJobs.head.arrivalTime else curTime + 1
          }
        loop(nextRunningJob, getNextStartTime)
      }
    }

    loop(None, 0)
  }

  def parseLine(line: Tuple2[String, Int]): PendingJob = {
    line._1.split(" ") match {
      case Array(x, y) => PendingJob(line._2, x.toInt, y.toInt)
    }
  }

}

case class PendingJob(id: Int, arrivalTime: Long, processTime: Long) {
  def run(curTime: Long): CompleteJob = CompleteJob(id, processTime + curTime)
  def fail: FailedJob = FailedJob(id)
}
trait FinishedJob {
  def getId: Int
  def getEndTime: Long
}
case class CompleteJob(id: Int, endTime: Long) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = endTime
}
case class FailedJob(id: Int) extends FinishedJob {
  override def getId: Int = id
  override def getEndTime = -1L
}

import scala.collection.immutable.Queue

object Solution {

  def main(args: Array[String]): Unit = {
    val (firstLine, lines) =
      scala.io.Source.stdin.getLines.toList match {
        case x::xs => (x, xs)
        case _ => throw new RuntimeException
      }

    val (numQueries, sizeOfQueue) =
      firstLine.split(" ").map(_.toInt) match {
        case Array(x, y) => (x, y)
      }

    val jobs: List[PendingJob] =
      for {
        line <- lines
      } yield parseJob(line)

    processJobs(jobs, numQueries, sizeOfQueue).foreach(x => print(x + " "))
    println
  }

  def processJobs(jobs: List[PendingJob], numQueries: Int, sizeOfQueue: Int): Vector[Int] = {
    def loop(curJob: Option[RunningJob], remainingJobs: List[PendingJob], queue: Queue[PendingJob], curTime: Int, processedJobs: Vector[Int]): Vector[Int] = {
      if (remainingJobs.isEmpty && queue.isEmpty) {
        processedJobs
      } else {
        val (currentlyArrivingJob, newRemainingJobs) =
          remainingJobs match {
            case x::xs if x.arrivalTime == curTime => (Some(x), xs)
            case _ => (None, remainingJobs)
          }

        val curRunningJob: Option[RunningJob] =
          curJob match {
            case Some(x) if x.endTime == curTime => None
            case _ => curJob
          }

        val (nextRunningJob, newQueue, newProcessedJobs) =
          (currentlyArrivingJob, curRunningJob) match {
            case (None, Some(_)) => (curRunningJob, queue, processedJobs)
            case (None, None) => {
              if (queue.isEmpty) {
                (None, queue, processedJobs)
              } else {
                val (nextJob, q) = queue.dequeue
                val newRunningJob = nextJob.start(curTime)
                (Some(newRunningJob), q, processedJobs :+ newRunningJob.endTime)
              }
            }
            case (Some(x), None) => {
              if (queue.isEmpty) {
                val newRunningJob = x.start(curTime)
                (Some(newRunningJob), queue, processedJobs :+ newRunningJob.endTime)
              } else {
                val (nextJob, q) = queue.dequeue
                val newRunningJob: RunningJob = nextJob.start(curTime)
                (Some(newRunningJob), q enqueue x, processedJobs :+ newRunningJob.endTime)
              }
            }
            case (Some(x), Some(_)) if queue.size < sizeOfQueue =>
              (curRunningJob, queue enqueue x, processedJobs)
            case _ =>
              (curRunningJob, queue, processedJobs :+ -1)
          }

        loop(nextRunningJob, newRemainingJobs, newQueue, curTime + 1, newProcessedJobs)
      }
    }
    loop(None, jobs, Queue[PendingJob](), 0, Vector[Int]())
  }

  //Parses a single line of input into a job
  private def parseJob(line: String): PendingJob = {
    val startAndProcess: Array[Int] = line.split(" ").map(_.toInt)
    PendingJob(startAndProcess(0), startAndProcess(1))
  }
}

//a single processing job
trait Job
case class PendingJob(arrivalTime: Int, processTime: Int) extends Job {
  def start(curTime: Int) = RunningJob(curTime + processTime)
}
case class RunningJob(endTime: Int) extends Job


import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
	//val in=new Scanner(System.in)
    //val out=new PrintWriter(System.out)

	val n=in.nextLine.toInt
	var olyms=new Array[Olym](n)
	for(i<-0 until n) olyms(i)=new Olym(in.nextLine.split(" ").map(_.toInt))
	olyms=olyms.sortBy(_.start)
	var hm=collection.mutable.Map[Int,Int]()
	for(o<-olyms)
	{
		o.start until o.end foreach{i=>
			hm(i)=hm.getOrElse(i, 0)+o.p
		}
	}

	out.println(hm.values.max)
	out.close
}

class Olym(input:Array[Int]){
    private[this] val months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
    val end=months.slice(0,input(0)).sum+input(1)
    val start=end-input(3)
    val p=input(2)

    override def toString="%d:%d:%d".format(start,end,p)

    def isOverlap(o:Olym):Boolean={
        ((start until end toSet) & (o.start until o.end toSet)).size>0
    }
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
	//val in=new Scanner(System.in)
    //val out=new PrintWriter(System.out)
	val months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
	val n=in.nextLine.toInt
	var hm=collection.mutable.Map[Int,Int]()

	for(i<-0 until n){
	    val Array(m,d,p,t)=in.nextLine.split(" ").map(_.toInt)
	    val end=months.slice(0,m).sum+d
	    val start=end-t

	    start until end foreach{j=>
	    	hm(j)=hm.getOrElse(j, 0)+p
	    }
	}

	out.println(hm.values.max)
	out.close
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
	//val in=new Scanner(System.in)
    //val out=new PrintWriter(System.out)

	val n=in.nextLine.toInt
	var olyms=new Array[Olym](n)
	for(i<-0 until n) olyms(i)=new Olym(in.nextLine.split(" ").map(_.toInt))
	olyms=olyms.sortBy(_.day)

	var max=0
	var start=0
	var total=0
	for(i<-0 until n)
	{
		var j=0
		while(j<i && !olyms(j).isOverlap(olyms(i)))
		{
			total-=olyms(j).p
			j+=1
		}
		start=j
	    total+=olyms(i).p
	    max=math.max(max,total)
	}

	out.println(max)
	out.close
}
class Olym(input:Array[Int]){
    private[this] val months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
    val day=months.slice(0,input(0)).sum+input(1)
    val p=input(2)
    val t=input(3)

    override def toString="%d:%d:%d".format(day,p,t)

    def isOverlap(o:Olym):Boolean={
        ((day-t until day toSet) & (o.day-o.t until o.day toSet)).size>0
    }
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
	//val in=new Scanner(System.in)
    //val out=new PrintWriter(System.out)

	val n=in.nextLine.toInt
	var olyms=new Array[Olym](n)
	for(i<-0 until n) olyms(i)=new Olym(in.nextLine.split(" ").map(_.toInt))
	olyms=olyms.sortBy(_.day)

	var max=0
	var start=0
	var total=0
	for(i<-0 until n)
	{
		var j=0
		while(j<i && !olyms(j).isOverlap(olyms(i)))
		{
			total-=olyms(j).p
			j+=1
		}
		start=j
	    total+=olyms(i).p
	    max=math.max(max,total)
	}

	println(max)
}
class Olym(input:Array[Int]){
    private[this] val months=Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
    val day=months.slice(0,input(0)).sum+input(1)
    val p=input(2)
    val t=input(3)

    override def toString="%d:%d:%d".format(day,p,t)

    def isOverlap(o:Olym):Boolean={
        ((day-t until day toSet) & (o.day-o.t until o.day toSet)).size>0
    }
}


object A extends App {

  implicit final class StringOps(private val input: String) extends AnyVal {
    def abBalance: String = {
      require(input.nonEmpty, "The given string should not be empty.")

      input.sliding(2).foldLeft(0) {
        case (count, "ab") => count + 1
        case (count, "ba") => count - 1
        case (count, _)    => count
      } match {
        case 0  => input
        case 1  => s"b${input.tail}"
        case -1 => s"a${input.tail}"
      }
    }
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val s = nextLine()

    out.println(s.abBalance)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

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

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

    case class pair(var s: Int, var a:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (a == that.a && s == that.s)
                return 0
            if (a > that.s && that.a <= s)
                return 1
            if (a <= that.s && that.a > s)
                return -1
            if (a == that.a) {
                if (s < that.s)
                    return -1
                else
                    return 1
            }
            if (a < that.a)
                return -1
            else
                return 1
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        var s = readString()
        var a = 0
        var b = 0
        for (i <- 0 until s.length - 1) {
            if (s(i) == 'a' && s(i+1) == 'b')
                a += 1
            if (s(i) == 'b' && s(i+1) == 'a')
                b += 1
        }
        if (a != b) {
            if(s(0) == 'a')
                s = 'b' + s.substring(1)
            else
                s = 'a' + s.substring(1)
        }
        writer.println(s)
    }
    writer.flush()
}

object A extends App {

  implicit final class StringOps(private val str: String) extends AnyVal {
    def abBalance: String = {
      require(str.nonEmpty, "The given string should not be empty.")

      val intervals = str.indices.tail.foldLeft((0, 0) :: Nil) {
        case ((p, q) :: intervals, i) if str(i) == str(q) => (p, i) :: intervals
        case (intervals, i)                               => (i, i) :: intervals
      }

      if ((intervals.length - 1) % 2 == 0) str
      else {
        val (fl, fr) = intervals.head
        val (ll, lr) = intervals.last
        val (l, r)   = if (fr - fl < lr - ll) (fl, fr) else (ll, lr)

        val slice = (if (str(l) == 'a') "b" else "a") * (r - l + 1)

        s"${str.slice(0, l)}$slice${str.slice(r + 1, str.length)}"
      }
    }
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val s = nextLine()

    out.println(s.abBalance)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}

object A extends App {

  implicit final class StringOps(private val str: String) extends AnyVal {
    def abBalance: String = {
      require(str.nonEmpty, "The given string should not be empty.")

      val intervals = str.indices.tail.foldLeft((0, 0) :: Nil) {
        case ((p, q) :: intervals, i) if str(i) == str(q) => (p, i) :: intervals
        case (intervals, i)                               => (i, i) :: intervals
      }

      if ((intervals.length - 1) % 2 == 0) str
      else {
        val (p, q) = intervals.minBy { case (p, q) => q - p }
        val slice  = (if (str(p) == 'a') "b" else "a") * (q - p + 1)

        s"${str.slice(0, p)}$slice${str.slice(q + 1, str.length)}"
      }
    }
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val s = nextLine()

    out.println(s.abBalance)
  }

  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }

}