Sereja has an n × m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size h × w, then the component must contain exactly hw cells.A connected component of the same values is a set of cells of the table that meet the following conditions:  every two cells of the set have the same value;  the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table);  it is impossible to add any cell to the set unless we violate the two previous conditions. Can Sereja change the values of at most k cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?

The first line contains integers n, m and k (1 ≤ n, m ≤ 100; 1 ≤ k ≤ 10). Next n lines describe the table a: the i-th of them contains m integers ai1, ai2, ..., aim (0 ≤ ai, j ≤ 1) — the values in the cells of the i-th row.

Print -1, if it is impossible to meet the requirement. Otherwise, print the minimum number of cells which should be changed.

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N, M, K = sc.nextInt
    val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)

    def a2l(a: Array[Int]): Long = a.foldLeft(0L) { (r, i) => (r << 1) + i }

    def solveSmall(): Int = {
      val cols = A.transpose.map(a2l)
      val patterns = List.range(0, 1 << N)
      val mask = (1 << N) - 1
      patterns.map { pat =>
        val shadow = pat ^ mask
        cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum
      }.min
    }

    def solveLarge(): Int = {
      val a2ll: Array[Int] => List[Long] = { a =>
        val (a0, a1) = a.splitAt(50)
        List(a0, a1).map(a2l)
      }
      val b = A.map(a2ll)
      val List(mask0, mask1) = a2ll(Array.fill(M)(1))
      val patterns = b.take(K + 1)
      patterns.map { pat =>
        val List(pat0, pat1) = pat
        val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)
        b.map { row =>
          val List(x0, x1) = row
          val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)
          val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)
          res0 min res1
        }.sum
      }.min

    }

    val res = if (N <= K) solveSmall
              else solveLarge
    if (res <= K) res
    else -1
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N, M, K = sc.nextInt
    val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)

    @inline
    def a2l(a: Array[Int]): Long = a.foldLeft(0L) { (r, i) => (r << 1) + i }

    def solveSmall(): Int = {
      val cols = A.transpose.map(a2l)
      val patterns = List.range(0, 1 << N)
      val mask = (1 << N) - 1
      patterns.map { pat =>
        val shadow = pat ^ mask
        cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum
      }.min
    }

    def solveLarge(): Int = {

      @inline
      def a2ll(a: Array[Int]): List[Long] = {
        val (a0, a1) = a.splitAt(50)
        List(a0, a1).map(a2l)
      }

      val List(mask0, mask1) = a2ll(Array.fill(M)(1))
      val b = A.map(a2ll)
      val patterns = b.take(K + 1)
      patterns.map { pat =>
        val List(pat0, pat1) = pat
        val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)
        b.map { row =>
          val List(x0, x1) = row
          val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)
          val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)
          res0 min res1
        }.sum
      }.min

    }

    val res = if (N <= K) solveSmall
              else solveLarge
    if (res <= K) res
    else -1
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N, M, K = sc.nextInt
    val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)

    def a2l(a: Array[Int]): Long = a.foldLeft(0L) { (r, i) => (r << 1) + i }

    def solveSmall(): Int = {
      val cols = A.transpose.map(a2l)
      val patterns = List.range(0, 1 << N)
      val mask = (1 << N) - 1
      patterns.map { pat =>
        val shadow = pat ^ mask
        cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum
      }.min
    }

    def solveLarge(): Int = {

      def a2ll(a: Array[Int]): List[Long] = {
        val (a0, a1) = a.splitAt(50)
        List(a0, a1).map(a2l)
      }

      val List(mask0, mask1) = a2ll(Array.fill(M)(1))
      val b = A.map(a2ll)
      val patterns = b.take(K + 1)
      patterns.map { pat =>
        val List(pat0, pat1) = pat
        val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)
        b.map { row =>
          val List(x0, x1) = row
          val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)
          val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)
          res0 min res1
        }.sum
      }.min

    }

    val res = if (N <= K) solveSmall
              else solveLarge
    if (res <= K) res
    else -1
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N, M, K = sc.nextInt
    val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)

    def solveSmall(): Int = {
      val a2i: Array[Int] => Int = a => a.foldLeft(0) { (r, x) => (r << 1) + x }
      val cols = A.transpose.map(a2i)
      val patterns = List.range(0, 1 << N)
      val mask = (1 << N) - 1
      patterns.map { pat =>
        val shadow = pat ^ mask
        cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum
      }.min
    }

    def solveLarge(): Int = {
      val a2ll: Array[Int] => List[Long] = { a =>
        val (a0, a1) = a.splitAt(50)
        List(a0, a1).map { x => x.foldLeft(0L) { (r, i) => (r << 1) + i } }
      }
      val B = A.map(a2ll)
      val List(mask0, mask1) = a2ll(Array.fill(M)(1))
      val patterns = B.take(K + 1)
      patterns.map { pat =>
        val List(pat0, pat1) = pat
        val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)
        B.map { row =>
          val List(x0, x1) = row
          val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)
          val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)
          res0 min res1
        }.sum
      }.min

    }

    val res = if (N <= K) solveSmall
              else solveLarge
    if (res <= K) res
    else -1
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def countDiff(x: Array[Int], y: Array[Int]): Int = {
    val z = x.map(_ ^ 1)
    List(x, z).map { w =>
      (w, y).zipped.map(_ ^ _).sum
    }.min
  }

  def solveSmall(n: Int, m: Int, k: Int, a: Array[Array[Int]]): Int = {
    val colPatterns: List[Array[Int]] = {
      List.range(0, 1 << n).map { i =>
        Array.tabulate(n) { i : Int => (i >> n) & 1 }
      }
    }
    val b = a.transpose
    colPatterns.map { p =>
      b.map(countDiff(p, _)).sum
    }.min
  }

  def solveLarge(n: Int, m: Int, k: Int, a: Array[Array[Int]]): Int = {
    val colPatterns = a.take(k + 1)
    colPatterns.map { p =>
      a.map(countDiff(p, _)).sum
    }.min
  }

  def solve(): Int = {
    val N, M, K = sc.nextInt
    val A: Array[Array[Int]] = Array.fill(N)(Array.fill(M)(sc.nextInt))

    val res = if (N <= K) solveSmall(N, M, K, A)
              else solveLarge(N, M, K, A)
    if (res <= K) res
    else -1
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N, M, K = sc.nextInt

    def line2code(m: Int): Long = {

      @tailrec
      def loop(x: Long, i: Int): Long = {
        if (i == m) x
        else loop((x << 1) + sc.nextLong, i + 1)
      }

      loop(0L, 0)
    }

    val A: List[Long] = List.fill(N)(line2code(M))
    val patterns: List[Long] = if (N <= K) List.range[Long](0L, (1L << M))
                               else A.take(K + 1)

    @inline
    def countChange(x: Long): Int = A.map { y: Long =>
        val mask: Long = (1L << M) - 1
        val a = x ^ y
        val b = x ^ mask ^ y
        bitCount(a) min bitCount(b)
      }.sum

    val res: Int = patterns.map(countChange).min
    if (res <= K) res
    else -1
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N, M, K = sc.nextInt
    val A: Array[Array[Int]] = Array.fill(N, M)(sc.nextInt)

    def solveSmall(): Int = {
      val a2i: Array[Int] => Int = a => a.foldLeft(0) { (r, x) => (r << 1) + x }
      val cols = A.transpose.map(a2i)
      val patterns = List.range(0, 1 << N)
      val mask = (1 << N) - 1
      patterns.map { pat =>
        val shadow = pat ^ mask
        cols.map { x => bitCount(x ^ pat) min bitCount(x ^ shadow) }.sum
      }.min
    }

    def solveLarge(): Int = {
      val a2ll: Array[Int] => List[Long] = { a =>
        val (a0, a1) = a.splitAt(50)
        List(a0, a1).map { x => x.foldLeft(0L) { (r, i) => (r << 1) + i } }
      }
      val B = A.map(a2ll)
      val List(mask0, mask1) = a2ll(Array.fill(M)(1))
      val patterns = B.take(K + 1)
      patterns.map { pat =>
        val List(pat0, pat1) = pat
        val List(shadow0, shadow1) = List(pat0 ^ mask0, pat1 ^ mask1)
        B.map { row =>
          val List(x0, x1) = row
          val res0 = bitCount(x0 ^ pat0) + bitCount(x1 ^ pat1)
          val res1 = bitCount(x0 ^ shadow0) + bitCount(x1 ^ shadow1)
          res0 min res1
        }.sum
      }.min

    }

    val res = if (N <= K) solveSmall
              else solveLarge
    res
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def countDiff(x: Array[Int], y: Array[Int]): Int = {
    val z = x.map(_ ^ 1)
    List(x, z).map { w =>
      (w, y).zipped.map(_ ^ _).sum
    }.min
  }

  def solveSmall(n: Int, m: Int, k: Int, a: Array[Array[Int]]): Int = {
    val colPatterns: List[Array[Int]] = {
      List.range(0, 1 << n).map { i =>
        Array.tabulate(n) { i : Int => (i >> n) & 1 }
      }
    }
    val b = a.transpose
    colPatterns.map { p =>
      b.map(countDiff(p, _)).sum
    }.min
  }

  def solveLarge(n: Int, m: Int, k: Int, a: Array[Array[Int]]): Int = {
    val colPatterns = a.take(k + 1)
    colPatterns.map { p =>
      a.map(countDiff(p, _)).sum
    }.min
  }

  def solve(): Int = {
    val N, M, K = sc.nextInt
    val A: Array[Array[Int]] = Array.fill(N)(Array.fill(M)(sc.nextInt))

    if (N <= K) solveSmall(N, M, K, A)
    else solveLarge(N, M, K, A)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N, M, K = sc.nextInt

    def line2code(m: Int): Long = {

      @tailrec
      def loop(x: Long, i: Int): Long = {
        if (i == m) x
        else loop((x << 1) + sc.nextLong, i + 1)
      }

      loop(0L, 0)
    }

    val A: List[Long] = List.fill(N)(line2code(M))
    val patterns: List[Long] = if (M <= K) List.range[Long](0L, (1L << M))
                               else A.take(K + 1)

    @inline
    def countChange(x: Long): Int = A.map { y: Long =>
        val mask: Long = (1L << M) - 1
        val a = x ^ y
        val b = x ^ (y ^ mask)
        bitCount(a) min bitCount(b)
      }.min

    val res: Int = patterns.map(countChange).min
    if (res <= K) res
    else -1
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N, M, K = sc.nextInt

    def line2code(m: Int): Long = {

      @tailrec
      def loop(x: Long, i: Int): Long = {
        if (i == m) x
        else loop((x << 1) + sc.nextLong, i + 1)
      }

      loop(0L, 0)
    }

    val A: List[Long] = List.fill(N)(line2code(M))
    val patterns: List[Long] = if (M <= K) List.range[Long](0L, (1L << M))
                               else A.take(K + 1)

    @inline
    def countChange(x: Long): Int = A.map { y: Long =>
        val mask: Long = (1L << M) - 1
        val a = x ^ y
        val b = x ^ mask ^ y
        bitCount(a) min bitCount(b)
      }.sum

    val res: Int = patterns.map(countChange).min
    if (res <= K) res
    else -1
  }

  out.println(solve)
  out.close
}


The only difference between easy and hard versions are constraints on $$$n$$$ and $$$k$$$.You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $$$k$$$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $$$0$$$).Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.You (suddenly!) have the ability to see the future. You know that during the day you will receive $$$n$$$ messages, the $$$i$$$-th message will be received from the friend with ID $$$id_i$$$ ($$$1 \le id_i \le 10^9$$$).If you receive a message from $$$id_i$$$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.Otherwise (i.e. if there is no conversation with $$$id_i$$$ on the screen):  Firstly, if the number of conversations displayed on the screen is $$$k$$$, the last conversation (which has the position $$$k$$$) is removed from the screen.  Now the number of conversations on the screen is guaranteed to be less than $$$k$$$ and the conversation with the friend $$$id_i$$$ is not displayed on the screen.  The conversation with the friend $$$id_i$$$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $$$n$$$ messages.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 200)$$$ — the number of messages and the number of conversations your smartphone can show. The second line of the input contains $$$n$$$ integers $$$id_1, id_2, \dots, id_n$$$ ($$$1 \le id_i \le 10^9$$$), where $$$id_i$$$ is the ID of the friend which sends you the $$$i$$$-th message.

In the first line of the output print one integer $$$m$$$ ($$$1 \le m \le min(n, k)$$$) — the number of conversations shown after receiving all $$$n$$$ messages. In the second line print $$$m$$$ integers $$$ids_1, ids_2, \dots, ids_m$$$, where $$$ids_i$$$ should be equal to the ID of the friend corresponding to the conversation displayed on the position $$$i$$$ after receiving all $$$n$$$ messages.

NoteIn the first example the list of conversations will change in the following way (in order from the first to last message):  $$$[]$$$;  $$$[1]$$$;  $$$[2, 1]$$$;  $$$[3, 2]$$$;  $$$[3, 2]$$$;  $$$[1, 3]$$$;  $$$[1, 3]$$$;  $$$[2, 1]$$$. In the second example the list of conversations will change in the following way:  $$$[]$$$;  $$$[2]$$$;  $$$[3, 2]$$$;  $$$[3, 2]$$$;  $$$[1, 3, 2]$$$;  and then the list will not change till the end.

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

object taskA {
  def main(args: Array[String]): Unit = {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val arr :Array[Int] = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    val queue =  mutable.Queue[Int]()

    for(i <- 0 to n - 1) {
      val current_id = arr(i)
      if(!map.contains(current_id) || map(current_id) == 0) {
        if(map.contains(current_id)) map(current_id) += 1
        else map(current_id) = 1
        queue.enqueue(current_id)
        if(queue.size == k + 1) {
          map(queue.dequeue()) -= 1
        }
      }
    }
    println(queue.length)
    queue.reverse.foreach(id => print(id + " "))
  }
}

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

  override def apply(io: IO): io.type = {
    val n, k = io.read[Int]
    val msgs = io.read[Seq, Int](n)

    val ans = boundedSet[Int](k)
    for {
      msg <- msgs if !ans.contains(msg)
    } ans.add(msg)

    io.writeLine(ans.size()).writeAll(ans.toArray.reverse)
  }

  def boundedSet[E](limit: Int) = {
    import java.{util => ju}
    ju.Collections.newSetFromMap[E](new ju.LinkedHashMap[E, java.lang.Boolean]() {
      override def removeEldestEntry(eldest: ju.Map.Entry[E, java.lang.Boolean]) = size() > limit
    })
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val n, k = io.read[Int]
    val msgs = io.read[Seq, Int](n)
    val ans = mutable.ArrayBuffer.empty[Int]
    val currentlyTalking = mutable.Set.empty[Int]
    for {
      msg <- msgs
      if currentlyTalking.add(msg)
    } {
      ans.prepend(msg)
      if (ans.length > k) currentlyTalking -= ans.remove(k)
    }

    io.writeLine(ans.length).writeAll(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object B1 extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  import scala.annotation.tailrec
  import scala.io.Codec

  /**
   * Faster Scanner in Scala by wrick
   * https://codeforces.com/blog/entry/21074
   *
   * Scala implementation of a faster java.util.Scanner
   * See: http://codeforces.com/blog/entry/7018
   */
  class Scanner(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 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() = tokenizer().get.nextToken()
    override def hasNext = tokenizer().nonEmpty
    override def close() = reader.close()
  }

  def read2(): (Int, Seq[Int]) = {
    val in = new Scanner(System.in)
    val n = in.nextInt()
    val k = in.nextInt()
    val letters = (0 until n).map(_ => in.nextInt())
    (k, letters)
  }

  @tailrec
  def res(seq: Vector[Int])(acc: Vector[Int], k: Int): Vector[Int] = seq match {
    case Vector() => acc.reverse
    case x +: xs if acc.contains(x) => res(xs)(acc, k)
    case x +: xs if acc.length < k => res(xs)(acc :+ x, k)
    case x +: xs => res(xs)(acc.drop(1) :+ x, k)
  }

  val (k, letters) = read2()
  val r = res(letters.toVector)(Vector(), k)
  println(r.length)
  println(r mkString " ")
}

object Ex2 extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  import scala.io.Codec
  import scala.annotation.tailrec

  /**
   * Faster Scanner in Scala by wrick
   * https://codeforces.com/blog/entry/21074
   *
   * Scala implementation of a faster java.util.Scanner
   * See: http://codeforces.com/blog/entry/7018
   */
  class Scanner(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 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() = tokenizer().get.nextToken()
    override def hasNext = tokenizer().nonEmpty
    override def close() = reader.close()
  }

  def read2(): (Int, Seq[Int]) = {
    val in = new Scanner(System.in)
    val n = in.nextInt()
    val k = in.nextInt()
    val letters = (0 until n).map(_ => in.nextInt())
    (k, letters)
  }

  @tailrec
  def res(seq: List[Int], k: Int)(acc: List[Int]): List[Int] = {
    if (acc.length == k) acc
    else seq match {
      case Nil => acc
      case x :: xs if !acc.contains(x) => res(xs, k)(x :: acc)
      case _ :: xs => res(xs, k)(acc)
    }
  }

  val (k, letters) = read2()
  val r = res(letters.toList, k)(Nil)
  println(r mkString " ")
}

object Ex2 extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  import scala.io.Codec
  import scala.annotation.tailrec

  /**
   * Faster Scanner in Scala by wrick
   * https://codeforces.com/blog/entry/21074
   *
   * Scala implementation of a faster java.util.Scanner
   * See: http://codeforces.com/blog/entry/7018
   */
  class Scanner(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 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() = tokenizer().get.nextToken()
    override def hasNext = tokenizer().nonEmpty
    override def close() = reader.close()
  }

  def read2(): (Int, Seq[Int]) = {
    val in = new Scanner(System.in)
    val n = in.nextInt()
    val k = in.nextInt()
    val letters = (0 until n).map(_ => in.nextInt())
    (k, letters)
  }

  @tailrec
  def res(seq: List[Int], k: Int)(acc: List[Int]): List[Int] = {
    if (acc.length == k) acc
    else seq match {
      case Nil => acc
      case x :: xs if !acc.contains(x) => res(xs, k)(x :: acc)
      case _ :: xs => res(xs, k)(acc)
    }
  }

  val (k, letters) = read2()
  val r = res(letters.toList, k)(Nil)
  println(r.length)
  println(r mkString " ")
}


The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$.    The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.

The input contains one or more test cases. The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. One test case is given on two lines. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of figures in the carousel. Figures are numbered from $$$1$$$ to $$$n$$$ in order of carousel moving. Assume that after the $$$n$$$-th figure the figure $$$1$$$ goes. The second line of the test case contains $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$1 \le t_i \le 2 \cdot 10^5$$$), where $$$t_i$$$ is the type of the animal of the $$$i$$$-th figure. The sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

Print $$$q$$$ answers, for each test case print two lines. In the first line print one integer $$$k$$$ — the minimum possible number of distinct colors of figures. In the second line print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is the color of the $$$i$$$-th figure. If there are several answers, you can print any.

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

  for (_ <- 1 to nextInt) {
    val n = nextInt
    val ts = nextInts(n)

    val res = Array.ofDim[Int](n)
    var prev = ts(0)
    var prevC = 1
    var lastSpan = -1
    for (i <- 1 until n) {
      if (ts(i) == prev) {
        lastSpan = i
        res(i) = prevC
      } else {
        prevC = 3 - prevC
        res(i) = prevC
      }
      prev = ts(i)
    }

    if (lastSpan == -1 && ts(0) != prev && n % 2 == 1) {
      res(0) = 3
    } else {
      if (ts(0) == prev) {
        res(0) = if (ts(0) == ts(1)) res(1) else 3 - res(1)
      } else {
        val for0 = 3 - prevC
        if (ts(0) == ts(1) || res(1) != for0) {
          res(0) = for0
        } else {
          for (i <- 1 until lastSpan) {
            res(i) = 3 - res(i)
          }
          res(0) = for0
        }
      }
    }

    out.println(res.max)
    out.println(res.mkString(" "))
  }

  out.flush()

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val q = in.nextInt()
    val c = Array.fill(200001)(0)
    val t = Array.fill(200001)(0)
    (1 to q).foreach{ _ =>
      val n = in.nextInt()
      (0 until n).foreach(i => {
        t(i) = in.nextInt()

      })
      c(0) = 0
      var ans = 1
      var moreThan1 = false
      var indexToChange = 0
      (1 until n).foreach(i => {

        if(t(i-1) == t(i)){
          c(i) = c(i-1)
          moreThan1 = true
          indexToChange = i
        }else{
          c(i) = 1-c(i-1)
          ans=2
        }

      })

      val numColors = if(t(0) == t(n-1)){
        ans
      }else{
        if(c(0) == c(n-1)){
          if(moreThan1){
            (indexToChange until n).foreach{ i =>
              c(i) = 1 - c(i)
            }
            ans
          }else{
            c(0) = 2
            3
          }

        }else{
          ans
        }
      }

      //println(numColors)
      //println(c.slice(0,n).map(_ + 1).mkString(" "))
      out.println(numColors)
      out.println(c.slice(0,n).map(_ + 1).mkString(" "))

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

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

  for (_ <- 1 to nextInt) {
    val n = nextInt
    val ts = nextInts(n)

    val res = Array.ofDim[Int](n)
    var prev = ts(0)
    var prevC = 1
    var lastSpan = -1
    for (i <- 1 until n) {
      if (ts(i) == prev) {
        lastSpan = i
        res(i) = prevC
      } else {
        prevC = 3 - prevC
        res(i) = prevC
      }
      prev = ts(i)
    }

    if (lastSpan == -1 && ts(0) != prev && n % 2 == 1) {
      res(0) = 3
    } else {
      val for0 = if (ts(0) == prev) prevC else 3 - prevC
      if (ts(0) == ts(1) || res(1) != for0) {
        res(0) = for0
      } else {
        for (i <- 1 until lastSpan) {
          res(i) = 3 - res(i)
        }
        res(0) = for0
      }
    }

    out.println(res.max)
    out.println(res.mkString(" "))
  }

  out.flush()

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val q = in.nextInt()
    val c = Array.fill(200001)(0)
    val t = Array.fill(200001)(0)
    (1 to q).foreach{ _ =>
      val n = in.nextInt()
      (0 until n).foreach(i => {
        t(i) = in.nextInt()

      })
      c(0) = 0
      var ans = 1
      (1 until n).foreach(i => {

        if(t(i-1) == t(i)){
          c(i) = c(i-1)
        }else{
          c(i) = 1-c(i-1)
          ans=2
        }

      })

      val numColors = if(t(0) == t(n-1)){
        ans
      }else{
        if(c(0) == c(n-1)){
          if((t(1) == t(0) && t(2) == t(1)) || (t(n-1) == t(n-2) && t(n-2) == t(n-3))){
            ans
          }else{
            c(0) = 2
            3
          }

        }else{
          ans
        }
      }

      out.println(numColors)
      out.println(c.slice(0,n).map(_ + 1).mkString(" "))

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val q = in.nextInt()
    val c = Array.fill(200001)(0)
    val t = Array.fill(200001)(0)
    (1 to q).foreach{ _ =>
      val n = in.nextInt()
      (0 until n).foreach(i => {
        t(i) = in.nextInt()

      })
      c(0) = 0
      var ans = 1
      (1 until n).foreach(i => {

        if(t(i-1) == t(i)){
          c(i) = c(i-1)
        }else{
          c(i) = 1-c(i-1)
          ans=2
        }

      })

      val numColors = if(t(0) == t(n-1)){
        ans
      }else{
        if(c(0) == c(n-1)){

          c(0) = 2
          3
        }else{
          ans
        }
      }

      out.println(numColors)
      out.println(c.slice(0,n).map(_ + 1).mkString(" "))

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $$$2 \cdot n$$$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $$$n$$$ people in each row). Students are numbered from $$$1$$$ to $$$n$$$ in each row in order from left to right.  Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all $$$2n$$$ students (there are no additional constraints), and a team can consist of any number of students. Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of students in each row. The second line of the input contains $$$n$$$ integers $$$h_{1, 1}, h_{1, 2}, \ldots, h_{1, n}$$$ ($$$1 \le h_{1, i} \le 10^9$$$), where $$$h_{1, i}$$$ is the height of the $$$i$$$-th student in the first row. The third line of the input contains $$$n$$$ integers $$$h_{2, 1}, h_{2, 2}, \ldots, h_{2, n}$$$ ($$$1 \le h_{2, i} \le 10^9$$$), where $$$h_{2, i}$$$ is the height of the $$$i$$$-th student in the second row.

Print a single integer — the maximum possible total height of players in a team Demid can choose.

NoteIn the first example Demid can choose the following team as follows:   In the second example Demid can choose the following team as follows:

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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  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()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

class 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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val A = nm(2, N)
    val dp = Array.ofDim[Long](N + 1, 3)
    dp(0)(2) = 0
    REP(N) { i =>
      REP(3) { j => // 直前に選ばれている状態
        if (j == 2) {
          dp(i + 1)(0) = max(dp(i + 1)(0), dp(i)(j) + A(0)(i))
          dp(i + 1)(1) = max(dp(i + 1)(1), dp(i)(j) + A(1)(i))
        } else {
          dp(i + 1)(j^1) = max(dp(i + 1)(j^1), dp(i)(j) + A(j^1)(i)) // A(i, j^1)を選んだ
        }
        dp(i + 1)(j) = max(dp(i + 1)(j), dp(i)(j)) // 選ばなかった
      }
    }

    val ans = dp(N).max
    out.println(ans)
  }
}


If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat.  However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat.  You have met a cat. Can you figure out whether it's normal or grumpy?

NotePlease make sure to use the stream flushing operation after each query in order not to leave part of your output in some buffer.

object Solution {
  def main(args: Array[String]) {
    val normal = Set("cool", "great", "not bad", "don't think so", "don't touch me")
    val grumpy = Set("terrible", "worse", "don't even", "go die in a hole", "are you serious")

    for (i <- 0 to 9) {
      println(i)
      val reaction = readLine
      if (normal.contains(reaction)) {
        println("normal")
      } else if (grumpy.contains(reaction)) {
        println("grumpy")
      }
    }
  }
}

import scala.io.StdIn

object GrumpyCat {
  def main(args:Array[String]): Unit={
    var res = "normal"
    print("9\n")
    val sequen = List("go die in a hole","are you serious?","terrible","worse","no way","don't even")
    val nk = StdIn.readLine()
    if (sequen.contains(nk)){
      res = "grumpy"
    }

    print(res)

  }
}

object Solution {
  def main(args: Array[String]) {
    val reactions = (0 to 9).map(i => { println(i); Console.flush(); readLine }).filter(_ == "cool")
    println(if (reactions.isEmpty) "grumpy" else "normal")
  }
}

object Solution {
  def main(args: Array[String]) {
    val normal = Set("cool", "great!", "not bad", "don't think so", "don't touch me!")
    val grumpy = Set("terrible", "worse", "don't even", "go die in a hole", "are you serious?")

    for (i <- 0 to 9) {
      println(i)
      val reaction = readLine
      if (normal.contains(reaction)) {
        println("normal")
      } else if (grumpy.contains(reaction)) {
        println("grumpy")
      }
    }
  }
}

object Solution {
  def main(args: Array[String]) {
    val normal = Set("cool", "great", "not bad", "don't think so", "don't even")
    val grumpy = Set("terrible", "worse", "don't even", "go die in a hole", "are you serious")

    for (i <- 0 to 9) {
      println(i)
      val reaction = readLine
      if (normal.contains(reaction)) {
        println("normal")
      } else if (grumpy.contains(reaction)) {
        println("grumpy")
      }
    }
  }
}

object Solution {
  def main(args: Array[String]) {
    (0 to 9).foreach(println)
    val reactions = (0 to 9).map(_ => readLine).filter(_ == "cool")
    println(if (reactions.isEmpty) "grumpy" else "normal")
  }
}

object Solution {
  def main(args: Array[String]) {
    val flag = false
    (0 to 9).foreach{ x => println(x); Console.flush() }
    val reactions = (0 to 9).map(_ => readLine).filter(_ == "cool")
    println(if (reactions.isEmpty) "grumpy" else "normal")
  }
}

object Solution {
  def main(args: Array[String]) {
    val normal = Set("cool", "great!", "not bad", "don't think so")
    val grumpy = Set("terrible", "worse", "don't even", "go die in a hole")

    for (i <- 0 to 9) {
      println(i)
      val reaction = readLine
      if (normal.contains(reaction)) {
        println("normal")
      } else if (grumpy.contains(reaction)) {
        println("grumpy")
      }
    }
  }
}

import scala.io.StdIn

object GrumpyCat {
  def main(args:Array[String]): Unit={
    print("9\n")
    val nk = StdIn.readLine()
    val read = nk.split(" ").map(_.toInt)
    var res = "normal"
    for(iterator <-0 to  9){
      if(read(iterator) > 9){
        res = "grumpy"
      }
    }

    print(res)
  }
}

import scala.io.StdIn

object GrumpyCat {
  def main(args:Array[String]): Unit={
    print("9")
    print("\n\n\n")
    val nk = StdIn.readLine()
    val read = nk.split(" ").map(_.toInt)
    var res = "normal"
    for(iterator <-0 to  9){

      if(read(iterator) > 9){
        res = "grumpy"
      }
    }

    print(res)

  }
}

import scala.io.StdIn

object GrumpyCat {
  def main(args:Array[String]): Unit={
    println("9\n")

    val nk = StdIn.readLine()
    val read = nk.split(" ").map(_.toInt)
    var res = "normal"
    for(iterator <-0 to  9){

      if(read(iterator) > 9){
        res = "grumpy"
      }
    }

    print(res)
  }
}

object GrumpyCat {
   def main(args:Array[String]): Unit={
     print("normal")
   }

}

import scala.io.StdIn

object GrumpyCat {
  def main(args:Array[String]): Unit={
    print("9")
    print("0\n")
    val nk = StdIn.readLine()
    val read = nk.split(" ").map(_.toInt)
    var res = "normal"
    for(iterator <-0 to  9){

      if(read(iterator) > 9){
        res = "grumpy"
      }
    }

    print(res)

  }
}

import scala.io.StdIn

object GrumpyCat {
   def main(args:Array[String]): Unit={
     print("9\n")
     val nk = StdIn.readLine().split(" ").map(_.toInt)
     var res = "normal"
     for(iterator <-0 to  9){

       if(nk(iterator) > 9){
         res = "grumpy"
       }
     }

     print(res)

  }
}

import scala.io.StdIn

object GrumpyCat {
   def main(args:Array[String]): Unit={
     println("9")
     val nk = StdIn.readLine().split(" ").map(_.toInt)
     var res = "normal"
     for(iterator <-0 to  9){

       if(nk(iterator) > 9){
         res = "grumpy"
       }
     }

     print(res)

  }
}


One beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R - R, 0), (4R - R, 0), ..., (2Rm - R, 0), respectively. Circles with numbers from m + 1 to 2m had centers at points (2R - R, 2R), (4R - R, 2R), ..., (2Rm - R, 2R), respectively. Naturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for m2 days. Each day of the experiment got its own unique number from 0 to m2 - 1, inclusive. On the day number i the following things happened:   The fly arrived at the coordinate plane at the center of the circle with number  ( is the result of dividing number x by number y, rounded down to an integer).  The fly went along the coordinate plane to the center of the circle number  ( is the remainder after dividing number x by number y). The bear noticed that the fly went from the center of circle v to the center of circle u along the shortest path with all points lying on the border or inside at least one of the 2m circles. After the fly reached the center of circle u, it flew away in an unknown direction. Help Vasily, count the average distance the fly went along the coordinate plane during each of these m2 days.

The first line contains two integers m, R (1 ≤ m ≤ 105, 1 ≤ R ≤ 10).

In a single line print a single real number — the answer to the problem. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.

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

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

  val Array(m, r) = readInts
  val d = Array.ofDim[Double](m + 1)
  def sqr(i: Long) = i * i
  d(1) = Math.sqrt(2.0) + 2
  for(i <- 2 to m) {
    d(i) = d(i - 1) + 2 * (Math.sqrt(2.0) + i - 1)
  }
  val ans = (for(i <- 1 to m) yield 2 + d(i - 1) + d(m - i)).sum * r

  def main(a: Array[String]) {
    println("%.10f".formatLocal(Locale.US, ans / sqr(m)))
  }
}

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

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

  val Array(m, r) = readInts
  val d = Array.ofDim[Double](m + 1)
  def sqr(i: Long) = i * i
  def dist(l: Int) = Math.sqrt(2.0) + 2 * l
  for(i <- 1 to m) {
    d(i) = d(i - 1) + dist(i)
  }
  val ans = (for(i <- 1 to m) yield 2 + d(i - 1) + d(m - i)).sum * r

  def main(a: Array[String]) {
    println("%.10f".formatLocal(Locale.US, ans / sqr(m)))
  }
}


Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds:  $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$;  There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i < b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j < i$$$.

The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.

For each test case, output a single line containing a single string, which is either   the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them;  three dashes (the string "---" without quotes) if it is impossible.

3
AZAMON APPLE
AZAMON AAAAAAAAAAALIBABA
APPLE BANANA

NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".

import scala.util.Random

case class Pair(amazonName: String, nonAmazonName: String)

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val t = stdin.next().toInt
  println(stdin.take(t).map(_.split(' ')).map(pair => Pair(pair.head, pair.last)).map(solve).mkString("\n"))

  def solve(pair: Pair) = {
    val newName = updateName(pair.amazonName)
    if (newName < pair.nonAmazonName) newName else "---"
  }

  def updateName(str: String): String = {
    val sorted = str.sorted
    val res = (0 until str.length).find(i => str(i) != sorted(i))
    res match {
      case None => str
      case Some(i) =>
        val ch = sorted(i)
        val index = str.lastIndexOf(ch)
        val arr = str.toCharArray
        val tmp = str(i)
        arr(i) = ch
        arr(index) = tmp
        arr.mkString("")
    }
  }

}


For an array $$$[b_1, b_2, \ldots, b_m]$$$ define its number of inversions as the number of pairs $$$(i, j)$$$ of integers such that $$$1 \le i < j \le m$$$ and $$$b_i>b_j$$$. Let's call array $$$b$$$ odd if its number of inversions is odd. For example, array $$$[4, 2, 7]$$$ is odd, as its number of inversions is $$$1$$$, while array $$$[2, 1, 4, 3]$$$ isn't, as its number of inversions is $$$2$$$.You are given a permutation $$$[p_1, p_2, \ldots, p_n]$$$ of integers from $$$1$$$ to $$$n$$$ (each of them appears exactly once in the permutation). You want to split it into several consecutive subarrays (maybe just one), so that the number of the odd subarrays among them is as large as possible. What largest number of these subarrays may be odd?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)  — the size of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct)  — the elements of the permutation. The sum of $$$n$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case output a single integer  — the largest possible number of odd subarrays that you can get after splitting the permutation into several consecutive subarrays.

NoteIn the first and third test cases, no matter how we split our permutation, there won't be any odd subarrays.In the second test case, we can split our permutation into subarrays $$$[4, 3], [2, 1]$$$, both of which are odd since their numbers of inversions are $$$1$$$.In the fourth test case, we can split our permutation into a single subarray $$$[2, 1]$$$, which is odd.In the fifth test case, we can split our permutation into subarrays $$$[4, 5], [6, 1, 2, 3]$$$. The first subarray has $$$0$$$ inversions, and the second has $$$3$$$, so it is odd.

import scala.io.StdIn._
object Solution {
  def main(args: Array[String]): Unit = {
    val tcases = readInt
    for (tcase <- 1 to tcases) {
      val n = readInt
      var arr = readLine.split(" ").map(_.toInt)
      var ans = 0
      var i = 1
      while (i < arr.length) {
        if (arr(i) < arr(i-1)) {
          ans += 1
          i += 1
        }
        i += 1
      }

      println(ans)
    }
  }
}


Pchelyonok decided to give Mila a gift. Pchelenok has already bought an array $$$a$$$ of length $$$n$$$, but gifting an array is too common. Instead of that, he decided to gift Mila the segments of that array!Pchelyonok wants his gift to be beautiful, so he decided to choose $$$k$$$ non-overlapping segments of the array $$$[l_1,r_1]$$$, $$$[l_2,r_2]$$$, $$$\ldots$$$ $$$[l_k,r_k]$$$ such that:  the length of the first segment $$$[l_1,r_1]$$$ is $$$k$$$, the length of the second segment $$$[l_2,r_2]$$$ is $$$k-1$$$, $$$\ldots$$$, the length of the $$$k$$$-th segment $$$[l_k,r_k]$$$ is $$$1$$$  for each $$$i<j$$$, the $$$i$$$-th segment occurs in the array earlier than the $$$j$$$-th (i.e. $$$r_i<l_j$$$)  the sums in these segments are strictly increasing (i.e. let $$$sum(l \ldots r) = \sum\limits_{i=l}^{r} a_i$$$ — the sum of numbers in the segment $$$[l,r]$$$ of the array, then $$$sum(l_1 \ldots r_1) < sum(l_2 \ldots r_2) < \ldots < sum(l_k \ldots r_k)$$$). Pchelenok also wants his gift to be as beautiful as possible, so he asks you to find the maximal value of $$$k$$$ such that he can give Mila a gift!

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$2 \cdot t$$$ lines contain the descriptions of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the maximum possible value of $$$k$$$.

import java.io._
import java.util.StringTokenizer
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 myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val k = 2 * sqrt(n).toInt
        val arr = new Array[Long](n+1)
        val sum = Array.ofDim[Long](n+2, 2)
        val mx = Array.ofDim[Int](n+2, 2)
        for (i <- 1 to n)
            arr(i) = readInt()
        var ans = 0
        for (j <- 1 to k) {
            for (i <- (j to n).reverse) {
                sum(i)((j)%2) = arr(i) + sum(i-1)((j-1)%2)
                mx(i)((j)%2) = mx(i+1)((j)%2)
                if ((i+j-1 <= n && mx(i+j-1)((j-1)%2) > 0 && sum(mx(i+j-1)((j-1)%2))((j-1)%2) > sum(i)((j)%2)) || j == 1) {
                    ans = j
                    if (sum(i)((j)%2) > sum(mx(i)((j)%2))((j)%2))
                        mx(i)((j)%2) = i
                }
            }
        }
/*
        for (j <- 1 to k) {
            for (i <- 1 to n)
                print(mx(i)(j) + " ")
            println()
        }
*/
        writer.println(ans)
    }
    writer.flush()
}

import java.io._
import java.util.StringTokenizer
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 myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val k = sqrt(n).toInt + 1
        val arr = new Array[Long](n+1)
        val sum = Array.ofDim[Long](n+2, k+1)
        val mx = Array.ofDim[Int](n+2, k+1)
        val d = Array.ofDim[Boolean](n+2, k+1)
        for (i <- 1 to n)
            arr(i) = readInt()
        var ans = 0
        for (j <- 1 to k) {
            for (i <- (j to n).reverse) {
                sum(i)(j) = arr(i) + sum(i-1)(j-1)
                mx(i)(j) = mx(i+1)(j)
                if ((i+j-1 <= n && mx(i+j-1)(j-1) > 0 && sum(mx(i+j-1)(j-1))(j-1) > sum(i)(j)) || j == 1) {
                    ans = j
                    if (sum(i)(j) > sum(mx(i)(j))(j))
                        mx(i)(j) = i
                }
            }
        }
/*
        for (j <- 1 to k) {
            for (i <- 1 to n)
                print(mx(i)(j) + " ")
            println()
        }
*/
        writer.println(ans)
    }
    writer.flush()
}


Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is negative, then the company suffered losses on the i-th day.Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (ai < 0), he loses his temper and his wrath is terrible.Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.Write a program that, given sequence ai, will print the minimum number of folders.

The first line contains integer n (1 ≤ n ≤ 100), n is the number of days. The second line contains a sequence of integers a1, a2, ..., an (|ai| ≤ 100), where ai means the company profit on the i-th day. It is possible that the company has no days with the negative ai.

Print an integer k — the required minimum number of folders. In the second line print a sequence of integers b1, b2, ..., bk, where bj is the number of day reports in the j-th folder. If there are multiple ways to sort the reports into k days, print any of them.

NoteHere goes a way to sort the reports from the first sample into three folders:  1 2 3 -4 -5 | -6 5 -5 | -6 -7 6 In the second sample you can put all five reports in one folder.

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

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

  val n = sc.nextInt()

  val ans = solve((0 until n).map(_ => sc.nextInt()).toList)

  println(ans.size)
  println(ans.reverse.mkString(" "))

  def solve(a: List[Int], loss: Int = 0, cur: Int = 0, result: List[Int] = Nil): List[Int] = {
    a match {
      case Nil => cur :: result
      case x :: t =>
        if (x >= 0) solve(t, loss, cur + 1, result)
        else if (loss == 2) solve(t, 1, 1, cur :: result)
        else solve(t, loss + 1, cur + 1, result)
    }
  }
}

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

object test2 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)

    var start=0
    val folders=(for(i<-0 until n if a(i)<0 && a.slice(start,i+1).count(_<0)==3) yield
    {
    	val ret=i-start
    	start=i
    	ret
    }):+(n-start)

    println(folders.size)
    println(folders.mkString(" "))
}

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

object test2 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)

    var start=0
    val ab=new ArrayBuffer[Int]()
    var count=0
    for(i<-0 until n)
    {
    	if(a(i)<0)
    	{
    		if(count==2)
    		{
    			ab+=i-start
    			start=i
    			count=1
    		}
    		else
    		{
    			count+=1
    		}
    	}
    }

    ab+=n-start

    println(ab.size)
    println(ab.mkString(" "))
}

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val a = readLine().split(" ").map(_.toInt)
    var cur = 0
    var res = scala.collection.mutable.ListBuffer[Int]()
    var negs = 0
    for(i <- 0 until a.size) {
      if (a(i) < 0 && negs == 2) {
        res += cur
        cur = 1
        negs = 1
      } else if (a(i) < 0) {
        negs += 1
        cur += 1
      } else {
        cur += 1
      }
    }
    if (cur != 0) res += cur
    println(res.size)
    println(res.mkString(" "))
  }
}


You are given a string $$$s$$$. You have to determine whether it is possible to build the string $$$s$$$ out of strings aa, aaa, bb and/or bbb by concatenating them. You can use the strings aa, aaa, bb and/or bbb any number of times and in any order.For example:  aaaabbb can be built as aa $$$+$$$ aa $$$+$$$ bbb;  bbaaaaabbb can be built as bb $$$+$$$ aaa $$$+$$$ aa $$$+$$$ bbb;  aaaaaa can be built as aa $$$+$$$ aa $$$+$$$ aa;  abab cannot be built from aa, aaa, bb and/or bbb.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 50$$$), consisting of characters a and/or b.

For each test case, print YES if it is possible to build the string $$$s$$$. Otherwise, print NO. You may print each letter in any case (for example, YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

8

aaaabbb

bbaaaaabbb

aaaaaa

abab

a

b

aaaab

bbaaa

NoteThe first four test cases of the example are described in the statement.

import scala.io.StdIn

object Task1 extends App {
  def getNextNum: Int = StdIn.readLine().toInt

  val inputSize = getNextNum

  for (_ <- 0 until inputSize) {
    val chars = StdIn.readLine().toCharArray
    var pos = 0
    var counter = 1
    var finishedWithFail = false

    if (chars.length < 2) {
      println("NO")
    } else {
      do {
        if (chars(pos) == chars(pos + 1)) {
          counter += 1
        } else {
          if (counter == 1) {
            finishedWithFail = true
          } else {
            counter = 1
          }
        }

        pos += 1
      } while (pos < chars.length - 1 && !finishedWithFail)

      if (counter > 1) println("YES")
      else println("NO")
    }

  }
}


You are given a string $$$s$$$, consisting only of characters '0' and '1'.You have to choose a contiguous substring of $$$s$$$ and remove all occurrences of the character, which is a strict minority in it, from the substring.That is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove all occurrences of '0' from the substring. If the amount of '1's is strictly smaller than the amount of '0's, remove all occurrences of '1'. If the amounts are the same, do nothing.You have to apply the operation exactly once. What is the maximum amount of characters that can be removed?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The only line of each testcase contains a non-empty string $$$s$$$, consisting only of characters '0' and '1'. The length of $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the maximum amount of characters that can be removed after applying the operation exactly once.

NoteIn the first testcase, you can choose substrings "0", "1" or "01". In "0" the amount of '0' is $$$1$$$, the amount of '1' is $$$0$$$. '1' is a strict minority, thus all occurrences of it are removed from the substring. However, since there were $$$0$$$ of them, nothing changes. Same for "1". And in "01" neither of '0' or '1' is a strict minority. Thus, nothing changes. So there is no way to remove any characters.In the second testcase, you can choose substring "10101010101". It contains $$$5$$$ characters '0' and $$$6$$$ characters '1'. '0' is a strict minority. Thus, you can remove all its occurrences. There exist other substrings that produce the same answer.In the third testcase, you can choose substring "011000100". It contains $$$6$$$ characters '0' and $$$3$$$ characters '1'. '1' is a strict minority. Thus, you can remove all its occurrences.

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

object cf1633b {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var s = readLine()
      var ans = Math.max(calculate(s), Math.max(calculate(s.substring(1)), calculate((s.substring(0, s.length() - 1)))))
      println(ans)
    }
  }

  def calculate(s: String): Int = {
    var ans = 0
    if(s.count(_ == '0') != 0 && s.count(_ == '0') !=0) {
      if(s.count(_ == '1') != s.count(_ == '0')) {
        ans = Math.max(ans, Math.min(s.count(_ == '0'), s.count(_ == '1')))
      }
    }
    return ans
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val string = readLine()
    val zeroCount = string.count(_ == '0')
    val oneCount = string.count(_ == '1')
    val min = Math.min(zeroCount, oneCount)
    val answer = if (min == 0) 0
      else if (zeroCount != oneCount) min else zeroCount - 1
    println(answer)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

object Minority extends App {
  def minorityCount(s: String): Int = {
    val length = s.length
    val count0 = s.count(_ == '0')
    if (count0 == length - count0) count0 - 1
    else count0 min (length - count0)
  }

  val lines = io.Source.stdin.getLines
  val t = lines.next.toInt
  (1 to t).foreach(_ => println(minorityCount(lines.next)))
}

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

object cf1633b {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var s = readLine()
      var ans = 0
      if(s.count(_ == '0') != 0 && s.count(_ == '0') !=0) {
        ans = Math.max(ans, s.count(_ == '0'))
        ans = Math.max(ans, s.count(_ == '1'))
        ans = Math.max(ans, s.substring(1).count(_ == '1'))
        ans = Math.max(ans, s.substring(1).count(_ == '0'))
        ans = Math.max(ans, s.substring(0, s.length() - 2).count(_ == '1'))
        ans = Math.max(ans, s.substring(0, s.length() - 2).count(_ == '0'))
      }
      println(ans)
    }
  }
}


There are $$$n$$$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $$$i$$$-th emote increases the opponent's happiness by $$$a_i$$$ units (we all know that emotes in this game are used to make opponents happy).You have time to use some emotes only $$$m$$$ times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than $$$k$$$ times in a row (otherwise the opponent will think that you're trolling him).Note that two emotes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that $$$a_i = a_j$$$ are considered different.You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.

The first line of the input contains three integers $$$n, m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le m \le 2 \cdot 10^9$$$) — the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is value of the happiness of the $$$i$$$-th emote.

Print one integer — the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.

NoteIn the first example you may use emotes in the following sequence: $$$4, 4, 5, 4, 4, 5, 4, 4, 5$$$.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class 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 = ni()
    val M, K = nl()
    val A = na(N)
    sort(A)
    val mx = A(N - 1).toLong
    val mx2 = A(N - 2).toLong
    val ans = if (mx == mx2) {
      M * mx
    } else {
      val remain = M % (K + 1) // [0, K]
      M / (K + 1) * (mx * K + mx2) + remain * mx
    }

    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

  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, 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 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]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}