She is skilled in all kinds of magics, and is keen on inventing new one.—Perfect Memento in Strict SensePatchouli is making a magical talisman. She initially has $$$n$$$ magical tokens. Their magical power can be represented with positive integers $$$a_1, a_2, \ldots, a_n$$$. Patchouli may perform the following two operations on the tokens.  Fusion: Patchouli chooses two tokens, removes them, and creates a new token with magical power equal to the sum of the two chosen tokens.  Reduction: Patchouli chooses a token with an even value of magical power $$$x$$$, removes it and creates a new token with magical power equal to $$$\frac{x}{2}$$$. Tokens are more effective when their magical powers are odd values. Please help Patchouli to find the minimum number of operations she needs to make magical powers of all tokens odd values.

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The description of the test cases follows. For each test case, the first line contains one integer $$$n$$$ ($$$1 \leq n\leq 2\cdot 10^5$$$) — the initial number of tokens. The second line contains $$$n$$$ intergers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the initial magical power of the $$$n$$$ tokens. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the minimum number of operations Patchouli needs to make all tokens have an odd value of magical power. It can be shown that under such restrictions the required sequence of operations exists.

NoteTest case 1:$$$a$$$ consists solely of odd numbers initially.Test case 2:Choose the tokens with magical power of $$$1$$$ and $$$2$$$ and perform Fusion. Now $$$a=[1,3]$$$, both are odd numbers.Test case 3:Choose the tokens with magical power of $$$2$$$ and $$$8$$$ and perform Fusion. Now $$$a=[4,10]$$$.Choose the token with magical power of $$$10$$$ and perform Reduction. Now $$$a=[4,5]$$$.Choose the tokens with magical power of $$$4$$$ and $$$5$$$ and perform Fusion. Now $$$a=[9]$$$, and $$$9$$$ is an odd number.It can be shown that you can not make all the magical powers odd numbers in less than $$$3$$$ moves, so the answer is $$$3$$$.

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


Mark is asked to take a group photo of $$$2n$$$ people. The $$$i$$$-th person has height $$$h_i$$$ units.To do so, he ordered these people into two rows, the front row and the back row, each consisting of $$$n$$$ people. However, to ensure that everyone is seen properly, the $$$j$$$-th person of the back row must be at least $$$x$$$ units taller than the $$$j$$$-th person of the front row for each $$$j$$$ between $$$1$$$ and $$$n$$$, inclusive.Help Mark determine if this is possible.

The first line contains one integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains two positive integers $$$n$$$ and $$$x$$$ ($$$1\leq n\leq 100$$$, $$$1\leq x\leq 10^3$$$) — the number of people in each row and the minimum difference Mark wants. The second line of each test case contains $$$2n$$$ positive integers $$$h_1,h_2,\ldots,h_{2n}$$$ ($$$1\leq h_i\leq 10^3$$$) — the height of each person in units. Note that the sum of $$$n$$$ over all test cases is not bounded.

For each test case, print a single line containing "YES" if Mark could arrange people satisfying his condition and "NO" otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answers).

NoteIn the first test case, one possible order is to have the third, fifth, and sixth person on the back row and the second, first, and fourth on the front row. The heights of the people will look like this. Back$$$9$$$$$$12$$$$$$16$$$Front$$$3$$$$$$1$$$$$$10$$$ It works because   $$$h_3-h_2 = 9-3 \geq 6$$$,    $$$h_5-h_1 = 12-1\geq 6$$$, and    $$$h_6-h_4 = 16-10\geq 6$$$. In the second test case, it can be shown there is no way to order people in a way that satisfies the condition.In the third test case, the only way to arrange people to satisfy the condition is to have the first person on the back row and the second person on the front row.

import scala.io.StdIn._
import scala.util.control.Breaks.break
object Main extends App{
  var x=readInt()
  while(x!=0){
    val y=readLine().split(" ").map(_.toInt)
    val h=y(1)
    val z=readLine().split(" ").map(_.toInt).sorted
    val pad= y(0)
    var flag=1
    for(i <- 0 until pad){
      if((z(i+pad)-z(i))<h){
        flag=0
      }
    }
    if(flag==1) println("Yes") else println("No")
    x=x-1
  }
}


A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.For each video find the moment it stops being recompressed.

The first line of the input contains integers n and k (1 ≤ n, k ≤ 5·105) — the number of videos and servers, respectively. Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 ≤ si, mi ≤ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.

Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.

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


Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.

The first line contains two integers n and m (1 ≤ n ≤ 100; 0 ≤ m ≤ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ ci ≤ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x).

Print a single integer — the minimum sum of debts in the optimal rearrangement.

NoteIn the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10.In the second sample, there are no debts.In the third sample, you can annul all the debts.

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


You're given an array $$$a$$$ of $$$n$$$ integers, such that $$$a_1 + a_2 + \cdots + a_n = 0$$$.In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$), decrement $$$a_i$$$ by one and increment $$$a_j$$$ by one. If $$$i < j$$$ this operation is free, otherwise it costs one coin.How many coins do you have to spend in order to make all elements equal to $$$0$$$?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 5000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$)  — the number of elements. The next line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). It is given that $$$\sum_{i=1}^n a_i = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the minimum number of coins we have to spend in order to make all elements equal to $$$0$$$.

NotePossible strategy for the first test case:   Do $$$(i=2, j=3)$$$ three times (free), $$$a = [-3, 2, 0, 1]$$$.  Do $$$(i=2, j=1)$$$ two times (pay two coins), $$$a = [-1, 0, 0, 1]$$$.  Do $$$(i=4, j=1)$$$ one time (pay one coin), $$$a = [0, 0, 0, 0]$$$.

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

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

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


You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).For example, for string "010210" we can perform the following moves:   "010210" $$$\rightarrow$$$ "100210";  "010210" $$$\rightarrow$$$ "001210";  "010210" $$$\rightarrow$$$ "010120";  "010210" $$$\rightarrow$$$ "010201". Note than you cannot swap "02" $$$\rightarrow$$$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).String $$$a$$$ is lexicographically less than string $$$b$$$ (if strings $$$a$$$ and $$$b$$$ have the same length) if there exists some position $$$i$$$ ($$$1 \le i \le |a|$$$, where $$$|s|$$$ is the length of the string $$$s$$$) such that for every $$$j < i$$$ holds $$$a_j = b_j$$$, and $$$a_i < b_i$$$.

The first line of the input contains the string $$$s$$$ consisting only of characters '0', '1' and '2', its length is between $$$1$$$ and $$$10^5$$$ (inclusive).

Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).

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

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 = {
    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
  }*/
}


You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make  as large as possible, where  denotes the bitwise OR. Find the maximum possible value of  after performing at most k operations optimally.

The first line contains three integers n, k and x (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 10, 2 ≤ x ≤ 8). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).

Output the maximum value of a bitwise OR of sequence elements after performing operations.

NoteFor the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is . For the second sample if we multiply 8 by 3 two times we'll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result.

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, k, x) = readInts(3)
  val as = readLongs(n)
  val prefix = as.scanLeft(0L)(_ | _)
  val suffix = as.scanRight(0L)(_ | _)

  var mult = 1L
  for (_ <- 0 until k) mult *= x

  var res = 0L

  for (i <- 0 until n) {
    val or = prefix(i) | suffix(i + 1) | as(i) * mult
    if (or > res) res = or
  }

  println(res)
}

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, k, x) = readInts(3)
  val as = readLongs(n)
  var res = as.max
  val maxPos = as.indexOf(res)

  for (_ <- 0 until k) res *= x

  for (i <- 0 until n) if (i != maxPos) res |= as(i)

  println(res)
}


The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a $$$n \times m$$$ rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as $$$0$$$) some trees were set on fire. At the beginning of minute $$$0$$$, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of $$$8$$$ neighboring trees. At the beginning of minute $$$T$$$, the fire was extinguished.The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of $$$T$$$ (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of $$$T$$$ (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.Note that you'd like to maximize value $$$T$$$ but the set of trees can be arbitrary.

The first line contains two integer $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le n \cdot m \le 10^6$$$) — the sizes of the map. Next $$$n$$$ lines contain the map. The $$$i$$$-th line corresponds to the $$$i$$$-th row of the map and contains $$$m$$$-character string. The $$$j$$$-th character of the $$$i$$$-th string is "X" if the corresponding tree is burnt and "." otherwise. It's guaranteed that the map contains at least one "X".

In the first line print the single integer $$$T$$$ — the maximum time the Forest was on fire. In the next $$$n$$$ lines print the certificate: the map ($$$n \times m$$$ rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".".

10 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._

  /**
    * 単調減少
    * [l, h) 方式
    */
  def findMax(f: Int => Boolean, min: Int, max: Int): Int = {
    var l = min
    var h = max + 1
    while(h - l > 1) {
      val x = (h + l) / 2
      if (f(x)) l = x
      else h = x
    }
    l
  }

  def add(a: Array[Array[Int]], x1: Int, y1: Int, x2: Int, y2: Int, v: Int): Unit = {
    a(y1)(x1) += 1
    a(y1)(x2 + 1) -= 1
    a(y2 + 1)(x1) -= 1
    a(y2 + 1)(x2 + 1) += 1
  }

  def imos(a: Array[Array[Int]]) = {
    val n = a.length - 1
    val m = a(0).length - 1
    REP(n + 1) { i =>
      REP(m) { j =>
        a(i)(j + 1) += a(i)(j)
      }
    }
    REP(m + 1) { j =>
      REP(n) { i =>
        a(i + 1)(j) += a(i)(j)
      }
    }
  }
}

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val g = Array.fill[Char](N + 2, M + 2)('.')
    REP(N) { i =>
      val s = ns(M)
      REP(M) { j =>
        g(i + 1)(j + 1) = s(j)
      }
    }
    val MAX = (min(N, M) - 1) / 2
    val flg = Array.ofDim[Int](MAX * 2 + N + 3, MAX * 2 + M + 3)
    val campus = Array.ofDim[Int](N + 1, M + 1)

    debug(g.map(_.mkString).mkString("\n"))
    debug(s"MAX:$MAX")

    def mkFlg(x: Int): Unit = {
      REP(flg.length) { i =>
        import java.util
        util.Arrays.fill(flg(i), 0)
      }
      REP(N + 2) { i =>
        REP(M + 2) { j =>
          if (g(i)(j) == '.') {
            add(flg, MAX + j - x, MAX + i - x, MAX + j + x, MAX + i + x, 1)
          }
        }
      }
      imos(flg)
    }

    def paint(x: Int): Unit = {
      REP(campus.length) { i =>
        import java.util
        util.Arrays.fill(campus(i), 0)
      }
      REP(N) { i =>
        REP(M) { j =>
          if (flg(MAX + i + 1)(MAX + j + 1) == 0) {
            add(campus, j - x, i - x, j + x, i + x, 1)
          }
        }
      }
      imos(campus)
    }

    def testCampus: Boolean = {
      REP(N) { i =>
        REP(M) { j =>
          val actual = campus(i)(j) == 0
          val expected = g(i + 1)(j + 1) == '.'
//          debug(s"$i:$j $actual $expected")
          if (actual != expected) {
            debug(s"RETURN $i:$j $actual $expected")
            return false
          }
        }
      }
      true
    }

    def test(x: Int): Boolean = {
      debug(s"test($x)")
      mkFlg(x)
      debug("show flag")
      debugDim(flg)
      paint(x)
      debug("show campus")
      debugDim(campus)
      val res = testCampus
      debug(s"test($x)=$res")
      res
    }

    val k = findMax(test, 0, MAX)
    mkFlg(k)
    val ans = Array.ofDim[Char](N, M)
    REP(N) { i =>
      REP(M) { j =>
        ans(i)(j) = if (flg(MAX + i + 1)(MAX + j + 1) == 0) 'X' else '.'
      }
    }

    out.println(k)
    REP(N) { i =>
      out.println(ans(i).mkString)
    }
  }
}


Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions:  the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers  the condition |ci - cj| ≤ 1 must hold.  if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.

The first line contains single integer n (1 ≤ n ≤ 1000) — the number of cards in Vladik's sequence. The second line contains the sequence of n positive integers not exceeding 8 — the description of Vladik's sequence.

Print single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.

NoteIn the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.

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

}


Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands:  Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end.  Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!

The first line contains integer n (1 ≤ n ≤ 105) — the number of Inna's commands. Then n lines follow, describing Inna's commands. Each line consists an integer:   Integer a (1 ≤ a ≤ 105) means that Inna gives Dima a command to add number a into one of containers.  Integer 0 shows that Inna asks Dima to make at most three extractions from different containers.

Each command of the input must correspond to one line of the output — Dima's action. For the command of the first type (adding) print one word that corresponds to Dima's choice:   pushStack — add to the end of the stack;  pushQueue — add to the end of the queue;  pushFront — add to the beginning of the deck;  pushBack — add to the end of the deck.  For a command of the second type first print an integer k (0 ≤ k ≤ 3), that shows the number of extract operations, then print k words separated by space. The words can be:   popStack — extract from the end of the stack;  popQueue — extract from the beginning of the line;  popFront — extract from the beginning from the deck;  popBack — extract from the end of the deck.  The printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers. The printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.

0
pushStack
1 popStack
pushStack
pushQueue
2 popStack popQueue
pushStack
pushQueue
pushFront
3 popStack popQueue popFront

import scala.collection._

object C extends App {

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  val n = readInt
  val as = Array.fill(n)(readInt)

  var end = 0

  while (end < as.size) {
    val start = end
    val end0 = as.indexWhere(_ == 0, start)
    end = if (end0 < 0) as.size else end0
    val bs = as.slice(start, end)
    val k = math.min(bs.size, 3)
    val sorted = bs.sorted.reverse
    var toQueue = if (k > 0) sorted(0) else -1
    var toStack = if (k > 1) sorted(1) else -1
    var toDeck = if (k > 2) sorted(2) else -1

    for (b <- bs) {
      if (b == toQueue) {
        println("pushQueue")
        toQueue = -1
      } else if (b == toStack) {
        println("pushStack")
        toStack = -1
      } else if (b == toDeck) {
        println("pushFront")
        toDeck = -1
      } else  {
        println("pushBack")
      }
    }

    if (end0 >= 0) {
      print(k)
      if (k > 0) print(" popQueue")
      if (k > 1) print(" popStack")
      if (k > 2) print(" popFront")
      println
      end += 1
    }

  }

  Console.flush
}


Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.This time Miroslav laid out $$$n$$$ skewers parallel to each other, and enumerated them with consecutive integers from $$$1$$$ to $$$n$$$ in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number $$$i$$$, it leads to turning $$$k$$$ closest skewers from each side of the skewer $$$i$$$, that is, skewers number $$$i - k$$$, $$$i - k + 1$$$, ..., $$$i - 1$$$, $$$i + 1$$$, ..., $$$i + k - 1$$$, $$$i + k$$$ (if they exist). For example, let $$$n = 6$$$ and $$$k = 1$$$. When Miroslav turns skewer number $$$3$$$, then skewers with numbers $$$2$$$, $$$3$$$, and $$$4$$$ will come up turned over. If after that he turns skewer number $$$1$$$, then skewers number $$$1$$$, $$$3$$$, and $$$4$$$ will be turned over, while skewer number $$$2$$$ will be in the initial position (because it is turned again).As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all $$$n$$$ skewers with the minimal possible number of actions. For example, for the above example $$$n = 6$$$ and $$$k = 1$$$, two turnings are sufficient: he can turn over skewers number $$$2$$$ and $$$5$$$.Help Miroslav turn over all $$$n$$$ skewers.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 1000$$$, $$$0 \leq k \leq 1000$$$) — the number of skewers and the number of skewers from each side that are turned in one step.

The first line should contain integer $$$l$$$ — the minimum number of actions needed by Miroslav to turn over all $$$n$$$ skewers. After than print $$$l$$$ integers from $$$1$$$ to $$$n$$$ denoting the number of the skewer that is to be turned over at the corresponding step.

NoteIn the first example the first operation turns over skewers $$$1$$$, $$$2$$$ and $$$3$$$, the second operation turns over skewers $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$.In the second example it is also correct to turn over skewers $$$2$$$ and $$$5$$$, but turning skewers $$$2$$$ and $$$4$$$, or $$$1$$$ and $$$5$$$ are incorrect solutions because the skewer $$$3$$$ is in the initial state after these operations.

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

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

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

}