A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:  b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.  For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1. The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.

The first input line of the input contains a single integer n (3 ≤ n ≤ 500 000) — the length of the initial sequence. The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.

If the sequence will never become stable, print a single number  - 1. Otherwise, first print a single integer — the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space  — the resulting sequence itself.

NoteIn the second sample the stabilization occurs in two steps: , and the sequence 00000 is obviously stable.

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

import scala.annotation.tailrec

object A {
  def change(seq: Array[Int], left: Int, right: Int): Unit = {
    if (left <= right) {
      seq(left) = seq(left - 1)
      seq(right) = seq(right + 1)
      change(seq, left + 1, right - 1)
    }
  }

  def patchSeq(seq: Array[Int], marks: Array[Boolean], maxLength: Int, index: Int): Int = {
    if (index == seq.length) {
      maxLength
    } else if (marks(index)) {
      patchSeq(seq, marks, maxLength, index + 1)
    } else {
      val end = marks.indexWhere(v => v, index)
      change(seq, index, end - 1)
      patchSeq(seq, marks, math.max(maxLength, end - index), end)
    }
  }

  def work(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val seq = Array.fill(n)(in.nextInt())
    val marks = Array.tabulate(n)(i => i == 0 || i == n - 1 || seq(i) == seq(i - 1) || seq(i) == seq(i + 1))
    val answer = patchSeq(seq, marks, 0, 0)
    println((answer + 1) / 2)
    println(seq.mkString(" "))
  }

   def main(args: Array[String]): Unit = {
     val sc = new Scanner(new InputStreamReader(System.in))
     val pw = new PrintWriter(System.out)
     work(sc, pw)
     pw.close()
     sc.close()
   }

   class Scanner(reader: Reader) extends Closeable {
     private val br = new BufferedReader(reader)
     private var st = new StringTokenizer(br.readLine())

     override def close(): Unit = {
       br.close()
       st = null
     }

     @tailrec
     final def next(): String = if (st.hasMoreTokens) st.nextToken() else {
       st = new StringTokenizer(br.readLine())
       next()
     }

     final def nextInt()    = next().toInt
     final def nextLong()   = next().toLong
     final def nextDouble() = next().toDouble
   }
 }

object Main extends App{

import java.util.{Scanner,Random}

	def knots(v:Vector[Int]) = {
		val n = v.size
		var l = 0
		var r = 0
		var result:Vector[Vector[Int]] = Vector.empty
		while (l<n-1){
			r = l+1
			var log=false
			while ( r <=n-1 && v(l) == v(r) ){
				r+=1
				log = true
			}
				result = result :+ v.slice(l,r)
			l=r
		}
		result
	}

	def work() = {
		val s = new Scanner(System.in)
		val n = s.nextInt()
		s.nextLine()
		var arr = s.nextLine.trim.split(" ").map(_.toInt).toVector

		arr = Vector(arr.head) ++ arr ++ Vector(arr.last)
		val parts = knots(arr)

		var result:Vector[Int] = parts.head
		var step = 0;
		var last = result.head
		var len = 0
		for {
			i <- parts.tail
		} {
			//println(s"i:  $i")//debug
			if (i.size > 1){
				if (i.head == last && len >0){
					result = result ++ Vector.fill(len)(last)
					step = math.max(step,(len+1)/2)
				}
				else if (len > 0){
					result = result ++ Vector.fill(len/2)(last)
					result = result ++ Vector.fill(len/2)(i.head)
					step = math.max(step,len/2)
				}
				result = result ++ i
				last = i.head
				len = 0
			}
			else {
				len += 1
			}
			//println(len,result)//debug
		}
		result = result.slice(1,result.size-1)
		println(step)
		println(result.mkString(" "))
	}

	work()
}

import scala.collection._
import java.util.Arrays
import scala.util.Random

object C extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)
  //var as = Array.fill(n){ if (Random.nextInt(100) < 49) 1 else 0}
  val cs = Array.ofDim[Int](n)

  var bs = Array.ofDim[Int](n)

  cs(0) = as(0)
  cs(n - 1) = as(n - 1)

  var prev = as(0)
  var max = 0
  var cnt0 = 1
  var start = 0
  for (i <- 1 until n) {
    if (as(i) != prev) {
      if (cnt0 > max) max = cnt0
      cnt0 += 1
      prev = as(i)
    } else {
      val half = cnt0 / 2
      for (j <- start until start + half) cs(j) = as(start)
      for (j <- start + half until i) cs(j) = as(i)
      cnt0 = 1
      start = i
    }
  }
      val half = cnt0 / 2
      for (j <- start until start + half) cs(j) = as(start)
      for (j <- start + half to n - 1) cs(j) = as(n - 1)
  //println(as.mkString(" "))
  println(max / 2)
  println(cs.mkString(" "))

//  def process(as: Array[Int], bs: Array[Int]) {
//    bs(0) = as(0)
//    bs(n - 1) = as(n - 1)
//    for (i <- 1 until n - 1) {
//      val sum = as(i - 1) + as(i) + as(i + 1)
//      bs(i) = if (sum > 1) 1 else 0
//    }
//  }
//
//  var cnt = 0
//  var changed = true
//  while (changed) {
//    process(as, bs)
//    changed = false
//    if (!Arrays.equals(as, bs)) {
//      cnt += 1
//      changed = true
//      val tmp = as
//      as = bs
//      bs = tmp
//    }
//  }
//
//  Console.setOut(new java.io.BufferedOutputStream(Console.out))
//
//  println(cnt)
//  println(Arrays.equals(as, cs))
//  println(as.mkString(" "))
//
//  Console.flush
}

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

object C_Median_c {

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

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    var number = line1.nextToken().toInt
//    number = 50000

    var seq = new Array[Int](number)
    val line2 = new StringTokenizer(br.readLine())

//    var value = true
    val rnd = new SecureRandom()
    for (i <- 0 until number) {
      seq(i) = line2.nextToken().toInt
//      seq(i) = if (rnd.nextBoolean()) 1 else 1
//      seq(i) = if (value) 1 else 0
//      value = !value
    }

//     if (number == 499) {
//      for (i <- 400 until 600) {
//        print(seq(i) + " ")
//        if (i % 50 == 0) {
//          println()
//        }
//      }
//      println("debug output end")
//     }
    //---------------------------- parameters reading end --------------------------------

    var ind = 0
    var curLength = 0
    var maxLength = 0
    var curStart = 0
    var maxStart = -1
    var maxEnd = -1
    var atleastOne = false
    while (ind < seq.length) {
      if (check(ind, 0,1,0)) atleastOne = true
      if (check(ind, 1,0,1)) {
        if (curLength == 0) {
          curStart = ind
        }
        curLength += 2;
        ind += 1
        if (maxLength < curLength ) {
          maxLength = curLength;
          maxStart = curStart
         }
      } else {
        if (curLength != 0) {
//          if (maxLength == curLength) {
          if (ind == maxStart + maxLength) {
            maxEnd = ind
          }
        }
        curLength = 0
      }

      ind += 1

      def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {
        if (ind > seq.length-3) return false
        return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3
      }
    }
    if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&
        !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {
      maxLength += 1
    }
    if (atleastOne && maxLength == 0) {
      maxLength = 1
    }
    db("Max " + maxLength + " start:" + maxStart + " end:" + maxEnd)

    if (maxLength == 0) {
      println(0)
    } else {
      println((maxLength +1)/2.toInt)
    }

    var res = Array.fill[Int](number)(0)
    var i = 0
    while (i < seq.length) {
      if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)
          || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {
        res(i) = seq(i)
      }
      i += 1
    }

    var const = res.clone()
    for (i <- 0 until res.length) {
      if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {
        //right edge
        var j = 1
        var ind = j *2 + i
        while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {
          res(i+j) = 1
          j += 1
          ind = j *2 + i
        }
      }
    }
    for (i <- 0 until res.length) {
      if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {
        //left edge
        var j = 1
        var ind = i+1 - j *2
        while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {
          res(i+1-j) = 1
          j += 1
          ind = i+1 - j *2
        }
      }
    }

    var resStr = new StringBuffer()
    for(i<- 0 until res.length) {
      resStr.append(res(i)).append(" ")
    }

    println(resStr)

  }
}

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

import scala.annotation.tailrec

object A {
  def change(seq: Array[Int], left: Int, right: Int): Unit = {
    if (left < right) {
      seq(left) = seq(left - 1)
      seq(right) = seq(right + 1)
      change(seq, left + 1, right - 1)
    }
  }

  def patchSeq(seq: Array[Int], marks: Array[Boolean], maxLength: Int, index: Int): Int = {
    if (index == seq.length) {
      maxLength
    } else if (marks(index)) {
      patchSeq(seq, marks, maxLength, index + 1)
    } else {
      val end = marks.indexWhere(v => v, index)
      change(seq, index, end - 1)
      patchSeq(seq, marks, math.max(maxLength, end - index), end)
    }
  }

  def work(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val seq = Array.fill(n)(in.nextInt())
    val marks = Array.tabulate(n)(i => i == 0 || i == n - 1 || seq(i) == seq(i - 1) || seq(i) == seq(i + 1))
    val answer = patchSeq(seq, marks, 0, 0)
    println((answer + 1) / 2)
    println(seq.mkString(" "))
  }

   def main(args: Array[String]): Unit = {
     val sc = new Scanner(new InputStreamReader(System.in))
     val pw = new PrintWriter(System.out)
     work(sc, pw)
     pw.close()
     sc.close()
   }

   class Scanner(reader: Reader) extends Closeable {
     private val br = new BufferedReader(reader)
     private var st = new StringTokenizer(br.readLine())

     override def close(): Unit = {
       br.close()
       st = null
     }

     @tailrec
     final def next(): String = if (st.hasMoreTokens) st.nextToken() else {
       st = new StringTokenizer(br.readLine())
       next()
     }

     final def nextInt()    = next().toInt
     final def nextLong()   = next().toLong
     final def nextDouble() = next().toDouble
   }
 }

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

object C_Median_c {

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

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    var number = line1.nextToken().toInt
//    number = 50000

    var seq = new Array[Int](number)
    val line2 = new StringTokenizer(br.readLine())

//    var value = true
    val rnd = new SecureRandom()
    for (i <- 0 until number) {
      seq(i) = line2.nextToken().toInt
//      seq(i) = if (rnd.nextBoolean()) 1 else 1
//      seq(i) = if (value) 1 else 0
//      value = !value
    }

//     if (number == 499) {
//      for (i <- 400 until 600) {
//        print(seq(i) + " ")
//        if (i % 50 == 0) {
//          println()
//        }
//      }
//      println("debug output end")
//     }
    //---------------------------- parameters reading end --------------------------------

    var ind = 0
    var curLength = 0
    var maxLength = 0
    var curStart = 0
    var maxStart = -1
    var maxEnd = -1
    while (ind < seq.length) {
      if (check(ind, 1,0,1)) {
        if (curLength == 0) {
          curStart = ind
        }
        curLength += 2;
        ind += 1
        if (maxLength < curLength ) {
          maxLength = curLength;
          maxStart = curStart
         }
      } else {
        if (curLength != 0) {
//          if (maxLength == curLength) {
          if (ind == maxStart + maxLength) {
            maxEnd = ind
          }
        }
        curLength = 0
      }

      ind += 1

      def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {
        if (ind > seq.length-3) return false
        return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3
      }
    }
    if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&
        !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {
      maxLength += 1
    }
    db("Max " + maxLength + " start:" + maxStart + " end:" + maxEnd)

    if (maxLength == 0) {
      println(0)
    } else {
      println((maxLength +1)/2.toInt)
    }

    var res = Array.fill[Int](number)(0)
    var i = 0
    while (i < seq.length) {
      if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)
          || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {
        res(i) = seq(i)
      }
      i += 1
    }

    var const = res.clone()
    for (i <- 0 until res.length) {
      if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {
        //right edge
        var j = 1
        var ind = j *2 + i
        while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {
          res(i+j) = 1
          j += 1
          ind = j *2 + i
        }
      }
    }
    for (i <- 0 until res.length) {
      if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {
        //left edge
        var j = 1
        var ind = i+1 - j *2
        while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {
          res(i+1-j) = 1
          j += 1
          ind = i+1 - j *2
        }
      }
    }

    var resStr = new StringBuffer()
    for(i<- 0 until res.length) {
      resStr.append(res(i)).append(" ")
    }

    println(resStr)

  }
}

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

object C_Median_c {

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

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    var number = line1.nextToken().toInt
//    number = 50000

    var seq = new Array[Int](number)
    val line2 = new StringTokenizer(br.readLine())

//    var value = true
    val rnd = new SecureRandom()
    for (i <- 0 until number) {
      seq(i) = line2.nextToken().toInt
//      seq(i) = if (rnd.nextBoolean()) 1 else 1
//      seq(i) = if (value) 1 else 0
//      value = !value
    }

     if (number == 499) {
       for (i <- 0 until 200) {
         print(seq(i) + " ")
         if (i % 50 == 0) {
          println()
        }
         println("debug output end")
       }
     }
    //---------------------------- parameters reading end --------------------------------

    var ind = 0
    var curLength = 0
    var maxLength = 0
    var curStart = 0
    var maxStart = -1
    var maxEnd = -1
    while (ind < seq.length) {
      if (check(ind, 1,0,1)) {
        if (curLength == 0) {
          curStart = ind
        }
        curLength += 2;
        ind += 1
        if (maxLength < curLength ) {
          maxLength = curLength;
          maxStart = curStart
         }
      } else {
        if (curLength != 0) {
          if (maxLength == curLength) {
            maxEnd = ind
          }
        }
        curLength = 0
      }

      ind += 1

      def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {
        if (ind > seq.length-3) return false
        return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3
      }
    }
    if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&
        !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {
      maxLength += 1
    }
    db("Max " + maxLength + " start:" + maxStart + " end:" + maxEnd)

    if (maxLength == 0) {
      println(0)
    } else {
      println((maxLength +1)/2.toInt)
    }

    var res = Array.fill[Int](number)(0)
    var i = 0
    while (i < seq.length) {
      if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)
          || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {
        res(i) = seq(i)
      }
      i += 1
    }

    var const = res.clone()
    for (i <- 0 until res.length) {
      if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {
        //right edge
        var j = 1
        var ind = j *2 + i
        while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {
          res(i+j) = 1
          j += 1
          ind = j *2 + i
        }
      }
    }
    for (i <- 0 until res.length) {
      if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {
        //left edge
        var j = 1
        var ind = i+1 - j *2
        while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {
          res(i+1-j) = 1
          j += 1
          ind = i+1 - j *2
        }
      }
    }

    var resStr = new StringBuffer()
    for(i<- 0 until res.length) {
      resStr.append(res(i)).append(" ")
    }

    println(resStr)

  }
}

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

object C {

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

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    var seq = new Array[Int](number)
    val cur = new Array[Int](number)
    val line2 = new StringTokenizer(br.readLine())

    for (i <- 0 until number) {
      seq(i) = line2.nextToken().toInt
      cur(i) = seq(i)
    }
    //---------------------------- parameters reading end --------------------------------

    var steps = 0
    var changed = true
    var res = new StringBuffer()

    while (changed) {
      changed = false
      for (i <- 0 until number) {
        derive(i)
      }
      if (changed) {
        steps += 1
      }
      seq = cur
    }

    def derive(i:Int) {
      if (i == 0 || i == number-1) {
          cur(i) = seq(i)
        } else {
          if (comp(i, Array(0,1,0))) { // || ) {
            cur(i) = 0
            changed = true
          } else if (comp(i, Array(1,0,1))) {
            cur(i) = 1
            changed = true
          } else {
            cur(i) = seq(i)
          }
        }
      db("replaced " + i + " " + seq(i) + " to " + cur(i))
    }

    println(steps)

    for (i <- 0 until number) {
      res.append(cur(i)).append(" ")
    }
    println(res)

    def comp(ind:Int, num:Array[Int]): Boolean ={
      return seq(ind-1) ==
        num(0) &&
        seq(ind) ==
          num(1) &&
          seq(ind+1) ==
            num(2)
    }

  }

//========================= samples ========================
val sa1 = """
5
0 1 0 1 0
"""

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

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

object C_Median_c {

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

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    var number = line1.nextToken().toInt
//    number = 50000

    var seq = new Array[Int](number)
    val line2 = new StringTokenizer(br.readLine())

//    var value = true
    val rnd = new SecureRandom()
    for (i <- 0 until number) {
      seq(i) = line2.nextToken().toInt
//      seq(i) = if (rnd.nextBoolean()) 1 else 1
//      seq(i) = if (value) 1 else 0
//      value = !value
    }

     if (number == 499) {
      for (i <- 0 until 200) {
        print(seq(i) + " ")
        if (i % 50 == 0) {
          println()
        }
      }
      println("debug output end")
     }
    //---------------------------- parameters reading end --------------------------------

    var ind = 0
    var curLength = 0
    var maxLength = 0
    var curStart = 0
    var maxStart = -1
    var maxEnd = -1
    while (ind < seq.length) {
      if (check(ind, 1,0,1)) {
        if (curLength == 0) {
          curStart = ind
        }
        curLength += 2;
        ind += 1
        if (maxLength < curLength ) {
          maxLength = curLength;
          maxStart = curStart
         }
      } else {
        if (curLength != 0) {
          if (maxLength == curLength) {
            maxEnd = ind
          }
        }
        curLength = 0
      }

      ind += 1

      def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {
        if (ind > seq.length-3) return false
        return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3
      }
    }
    if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&
        !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {
      maxLength += 1
    }
    db("Max " + maxLength + " start:" + maxStart + " end:" + maxEnd)

    if (maxLength == 0) {
      println(0)
    } else {
      println((maxLength +1)/2.toInt)
    }

    var res = Array.fill[Int](number)(0)
    var i = 0
    while (i < seq.length) {
      if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)
          || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {
        res(i) = seq(i)
      }
      i += 1
    }

    var const = res.clone()
    for (i <- 0 until res.length) {
      if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {
        //right edge
        var j = 1
        var ind = j *2 + i
        while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {
          res(i+j) = 1
          j += 1
          ind = j *2 + i
        }
      }
    }
    for (i <- 0 until res.length) {
      if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {
        //left edge
        var j = 1
        var ind = i+1 - j *2
        while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {
          res(i+1-j) = 1
          j += 1
          ind = i+1 - j *2
        }
      }
    }

    var resStr = new StringBuffer()
    for(i<- 0 until res.length) {
      resStr.append(res(i)).append(" ")
    }

    println(resStr)

  }
}

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

object C_Median_c {

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

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    var number = line1.nextToken().toInt
//    number = 50000

    var seq = new Array[Int](number)
    val line2 = new StringTokenizer(br.readLine())

//    var value = true
    val rnd = new SecureRandom()
    for (i <- 0 until number) {
      seq(i) = line2.nextToken().toInt
//      seq(i) = if (rnd.nextBoolean()) 1 else 1
//      seq(i) = if (value) 1 else 0
//      value = !value
    }

     if (number == 499) {
       for (i <- 0 until 200) {
         print(seq(i) + " ")
         if (i % 50 == 0) {
          println()
        }
       }
     }
    //---------------------------- parameters reading end --------------------------------

    var ind = 0
    var curLength = 0
    var maxLength = 0
    var curStart = 0
    var maxStart = -1
    var maxEnd = -1
    while (ind < seq.length) {
      if (check(ind, 1,0,1)) {
        if (curLength == 0) {
          curStart = ind
        }
        curLength += 2;
        ind += 1
        if (maxLength < curLength ) {
          maxLength = curLength;
          maxStart = curStart
         }
      } else {
        if (curLength != 0) {
          if (maxLength == curLength) {
            maxEnd = ind
          }
        }
        curLength = 0
      }

      ind += 1

      def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {
        if (ind > seq.length-3) return false
        return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3
      }
    }
    if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&
        !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {
      maxLength += 1
    }
    db("Max " + maxLength + " start:" + maxStart + " end:" + maxEnd)

    if (maxLength == 0) {
      println(0)
    } else {
      println((maxLength +1)/2.toInt)
    }

    var res = Array.fill[Int](number)(0)
    var i = 0
    while (i < seq.length) {
      if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)
          || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {
        res(i) = seq(i)
      }
      i += 1
    }

    var const = res.clone()
    for (i <- 0 until res.length) {
      if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {
        //right edge
        var j = 1
        var ind = j *2 + i
        while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {
          res(i+j) = 1
          j += 1
          ind = j *2 + i
        }
      }
    }
    for (i <- 0 until res.length) {
      if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {
        //left edge
        var j = 1
        var ind = i+1 - j *2
        while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {
          res(i+1-j) = 1
          j += 1
          ind = i+1 - j *2
        }
      }
    }

    var resStr = new StringBuffer()
    for(i<- 0 until res.length) {
      resStr.append(res(i)).append(" ")
    }

    println(resStr)

  }
  }

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

object C_Median_c {

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

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    var number = line1.nextToken().toInt
//    number = 50000

    var seq = new Array[Int](number)
    val line2 = new StringTokenizer(br.readLine())

//    var value = true
    val rnd = new SecureRandom()
    for (i <- 0 until number) {
      seq(i) = line2.nextToken().toInt
//      seq(i) = if (rnd.nextBoolean()) 1 else 1
//      seq(i) = if (value) 1 else 0
//      value = !value
    }
    //---------------------------- parameters reading end --------------------------------

    var ind = 0
    var curLength = 0
    var maxLength = 0
    var curStart = 0
    var maxStart = -1
    var maxEnd = -1
    while (ind < seq.length) {
      if (check(ind, 1,0,1)) {
        if (curLength == 0) {
          curStart = ind
        }
        curLength += 2;
        ind += 1
        if (maxLength < curLength ) {
          maxLength = curLength;
          maxStart = curStart
         }
      } else {
        if (curLength != 0) {
          if (maxLength == curLength) {
            maxEnd = ind
          }
        }
        curLength = 0
      }

      ind += 1

      def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {
        if (ind > seq.length-3) return false
        return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3
      }
    }
    if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&
        !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {
      maxLength += 1
    }
    db("Max " + maxLength + " start:" + maxStart + " end:" + maxEnd)

    if (maxLength == 0) {
      println(0)
    } else {
      println((maxLength +1)/2.toInt)
    }

    var res = Array.fill[Int](number)(0)
    var i = 0
    while (i < seq.length) {
      if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)
          || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {
        res(i) = seq(i)
      }
      i += 1
    }

    var const = res.clone()
    for (i <- 0 until res.length) {
      if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {
        //right edge
        var j = 1
        var ind = j *2 + i
        while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {
          res(i+j) = 1
          j += 1
          ind = j *2 + i
        }
      }
    }
    for (i <- 0 until res.length) {
      if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {
        //left edge
        var j = 1
        var ind = i+1 - j *2
        while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {
          res(i+1-j) = 1
          j += 1
          ind = i+1 - j *2
        }
      }
    }

    var resStr = new StringBuffer()
    for(i<- 0 until res.length) {
      resStr.append(res(i)).append(" ")
    }

    println(resStr)

  }
}

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

object C_Median_c {

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

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    var number = line1.nextToken().toInt
//    number = 50000

    var seq = new Array[Int](number)
    val line2 = new StringTokenizer(br.readLine())

//    var value = true
    val rnd = new SecureRandom()
    for (i <- 0 until number) {
      seq(i) = line2.nextToken().toInt
//      seq(i) = if (rnd.nextBoolean()) 1 else 1
//      seq(i) = if (value) 1 else 0
//      value = !value
    }
    //---------------------------- parameters reading end --------------------------------

    var ind = 0
    var curLength = 0
    var maxLength = 0
    var curStart = 0
    var maxStart = -1
    var maxEnd = -1
    while (ind < seq.length) {
      if (check(ind, 1,0,1)) {
        if (curLength == 0) {
          curStart = ind
        }
        curLength += 2;
        ind += 1
        if (maxLength < curLength ) {
          maxLength = curLength;
          maxStart = curStart
         }
      } else {
        if (curLength != 0) {
          if (maxLength == curLength) {
            maxEnd = ind
          }
        }
        curLength = 0
      }

      ind += 1

      def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {
        if (ind > seq.length-3) return false
        return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3
      }
    }
    if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&
        !(maxStart == 1 && seq(0) == 1) && !(maxStart == seq.length-2 && seq(seq.length-1) == 1)) {
      maxLength += 1
    }
//    db("Max " + maxLength + " start:" + maxStart + " end:" + maxEnd)

    if (maxLength == 0) {
      println(0)
    } else {
      println((maxLength +1)/2.toInt)
    }

    var res = Array.fill[Int](number)(0)
    var i = 0
    var pStart = -1;
    while (i < seq.length) {
      if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)
          || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {
        res(i) = seq(i)
      }
      i += 1
    }

    var const = res.clone()
    for (i <- 0 until res.length) {
      if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {
        //right edge
        var j = 1
        var ind = j *2 + i
        while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {
          res(i+j) = 1
          j += 1
          ind = j *2 + i
        }
      }
    }
    for (i <- 0 until res.length) {
      if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {
        //left edge
        var j = 1
        var ind = i+1 - j *2
        while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {
          res(i+1-j) = 1
          j += 1
          ind = i+1 - j *2
        }
      }
    }

    var resStr = new StringBuffer()
    for(i<- 0 until res.length) {
      resStr.append(res(i)).append(" ")
    }

    println(resStr)

  }
}

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

object C_Median_c {

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

    val is = System.in

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

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

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    var number = line1.nextToken().toInt
//    number = 50000

    var seq = new Array[Int](number)
    val line2 = new StringTokenizer(br.readLine())

//    var value = true
    val rnd = new SecureRandom()
    for (i <- 0 until number) {
      seq(i) = line2.nextToken().toInt
//      seq(i) = if (rnd.nextBoolean()) 1 else 1
//      seq(i) = if (value) 1 else 0
//      value = !value
    }

     if (number == 499) {
      for (i <- 200 until 400) {
        print(seq(i) + " ")
        if (i % 50 == 0) {
          println()
        }
      }
      println("debug output end")
     }
    //---------------------------- parameters reading end --------------------------------

    var ind = 0
    var curLength = 0
    var maxLength = 0
    var curStart = 0
    var maxStart = -1
    var maxEnd = -1
    while (ind < seq.length) {
      if (check(ind, 1,0,1)) {
        if (curLength == 0) {
          curStart = ind
        }
        curLength += 2;
        ind += 1
        if (maxLength < curLength ) {
          maxLength = curLength;
          maxStart = curStart
         }
      } else {
        if (curLength != 0) {
          if (maxLength == curLength) {
            maxEnd = ind
          }
        }
        curLength = 0
      }

      ind += 1

      def check(ind:Int, c1:Int, c2:Int, c3:Int):Boolean = {
        if (ind > seq.length-3) return false
        return seq(ind) == c1 && seq(ind+1) == c2 && seq(ind+2) == c3
      }
    }
    if (maxLength !=0 && maxStart != 0 && maxEnd != seq.length-1 &&
        !(maxStart > 0 && seq(maxStart-1) == 1) && !(maxEnd < seq.length-1 && seq(maxEnd+1) == 1)) {
      maxLength += 1
    }
    db("Max " + maxLength + " start:" + maxStart + " end:" + maxEnd)

    if (maxLength == 0) {
      println(0)
    } else {
      println((maxLength +1)/2.toInt)
    }

    var res = Array.fill[Int](number)(0)
    var i = 0
    while (i < seq.length) {
      if (i ==0 || i == seq.length-1 || (i > 0 && seq(i) == 1 && seq(i-1) == 1)
          || (i+1 < seq.length && seq(i)==1 && seq(i+1) == 1)) {
        res(i) = seq(i)
      }
      i += 1
    }

    var const = res.clone()
    for (i <- 0 until res.length) {
      if (const(i) == 1 && i+1 < const.length && const(i+1) == 0) {
        //right edge
        var j = 1
        var ind = j *2 + i
        while (ind < seq.length && seq(ind) == 1 && seq(ind-1) == 0) {
          res(i+j) = 1
          j += 1
          ind = j *2 + i
        }
      }
    }
    for (i <- 0 until res.length) {
      if (const(i) == 0 && i+1 < const.length && const(i+1) == 1) {
        //left edge
        var j = 1
        var ind = i+1 - j *2
        while (ind > 0 && seq(ind) == 1 && seq(ind+1) == 0) {
          res(i+1-j) = 1
          j += 1
          ind = i+1 - j *2
        }
      }
    }

    var resStr = new StringBuffer()
    for(i<- 0 until res.length) {
      resStr.append(res(i)).append(" ")
    }

    println(resStr)

  }
}


Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.Assume that we have a cat with a number $$$x$$$. A perfect longcat is a cat with a number equal $$$2^m - 1$$$ for some non-negative integer $$$m$$$. For example, the numbers $$$0$$$, $$$1$$$, $$$3$$$, $$$7$$$, $$$15$$$ and so on are suitable for the perfect longcats.In the Cat Furrier Transform, the following operations can be performed on $$$x$$$:  (Operation A): you select any non-negative integer $$$n$$$ and replace $$$x$$$ with $$$x \oplus (2^n - 1)$$$, with $$$\oplus$$$ being a bitwise XOR operator. (Operation B): replace $$$x$$$ with $$$x + 1$$$. The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most $$$40$$$ operations. Can you help Neko writing a transformation plan?Note that it is not required to minimize the number of operations. You just need to use no more than $$$40$$$ operations.

The only line contains a single integer $$$x$$$ ($$$1 \le x \le 10^6$$$).

The first line should contain a single integer $$$t$$$ ($$$0 \le t \le 40$$$) — the number of operations to apply. Then for each odd-numbered operation print the corresponding number $$$n_i$$$ in it. That is, print $$$\lceil \frac{t}{2} \rceil$$$ integers $$$n_i$$$ ($$$0 \le n_i \le 30$$$), denoting the replacement $$$x$$$ with $$$x \oplus (2^{n_i} - 1)$$$ in the corresponding step. If there are multiple possible answers, you can print any of them. It is possible to show, that there is at least one answer in the constraints of this problem.

NoteIn the first test, one of the transforms might be as follows: $$$39 \to 56 \to 57 \to 62 \to 63$$$. Or more precisely: Pick $$$n = 5$$$. $$$x$$$ is transformed into $$$39 \oplus 31$$$, or $$$56$$$.  Increase $$$x$$$ by $$$1$$$, changing its value to $$$57$$$.  Pick $$$n = 3$$$. $$$x$$$ is transformed into $$$57 \oplus 7$$$, or $$$62$$$.  Increase $$$x$$$ by $$$1$$$, changing its value to $$$63 = 2^6 - 1$$$. In the second and third test, the number already satisfies the goal requirement.

object b extends App{
  import scala.math.log
  import scala.io.StdIn.readInt

  def log2(x: Double) = log(x) / log(2)
  def binLength(x: Int) = if (x == 0) 1 else log2(x).toInt + 1
  def inversion(x: Int):Int = (~x) & ((1 << binLength(x)) - 1)

  /**
    * Returns a number of digits for the left most zero
    * 01101 -> 2
    * 10    -> 1
    */
  def asd(n: Int): Int =  {
    def helper(m: Int, acc: Int): Int = {
      if(m == 0) acc
      else helper(m >> 1, acc + 1)
    }
    helper(inversion(n), 0)
  }

  def iterate(x: Int, cnt: Int, acc: List[Int]): (Int, List[Int]) = {
    if (x + 1 == (1 << binLength(x))) (cnt - 1, acc)
    else if (cnt % 2 == 1) {
      val n = asd(x)
      //    println(s"n -> $n")
      iterate(x ^ ((1 << n) - 1), cnt + 1, n::acc)
    } else {
      //    println("Add 1")
      iterate(x + 1, cnt + 1, acc)
    }
  }

  val n = readInt()

  if (n + 1 == (1 << binLength(n))) {
    println(0)
  } else {
    val (cnt, acc) = iterate(n, 1, List())
    println(cnt)
    println(acc.reverse.mkString(" "))
  }

}

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 java.util.Arrays.sort

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

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    var x = ni()
    val ans = ArrayBuffer[Int]()

    def isPerfect(n: Int): Boolean = {
      REP(60) { i =>
        if (n == (1L << i) - 1) return true
      }
      false
    }

    // 左から最初に0になる場所
    def findT(n: Int): Int = {
      if (n == 0) return 1

      var t = log2(Integer.highestOneBit(n))
      while((n & (1 << t)) > 0) {
        t -= 1
      }
      t + 1
    }

    var i = 0
    while(!isPerfect(x)) {
      if (i % 2 == 0) {
        val t = findT(x)
        val y = (1 << t) - 1
        //      debug(s"t: $t x:$x y:$y => ${(x ^ y) + 1}")
        x = x ^ y
        debug(s"t: $t x:$x")
        ans += t
      } else {
        x += 1
      }
      i += 1
    }

    out.println(i)
    out.println(ans.mkString(" "))
  }

  def log2(x: Int): Int = {
    assert(x > 0)
    var a = x
    var i = 0 // 何回2で割ったら1になるか
    while(a > 1) {
      i += 1
      a >>>= 1
    }
    i
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

  def debugDim(m: Array[Array[Long]]): Unit = DEBUG {
    REP(m.length) { i =>
      debug(m(i))
    }
  }

  def debugDimFlip(m: Array[Array[Long]]): Unit = DEBUG {
    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 = 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 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]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


You are given an $$$n \times m$$$ table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every $$$2 \times 2$$$ square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters.

First line contains two positive integers $$$n$$$ and $$$m$$$ — number of rows and columns in the table you are given ($$$2 \leq n, m, n \times m \leq 300\,000$$$). Then, $$$n$$$ lines describing the table follow. Each line contains exactly $$$m$$$ characters «A», «G», «C», «T».

Output $$$n$$$ lines, $$$m$$$ characters each. This table must be nice and differ from the input table in the minimum number of characters.

NoteIn the first sample, the table is already nice. In the second sample, you can change 9 elements to make the table nice.

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)

  case class AnswerMat(set: Int, flgs: Array[Boolean])
  val S = "AGCT"
  def select2(set: Int, which: Boolean) = {
    val a_p2 = Integer.highestOneBit(set)
    val b_p2 = set ^ a_p2
    val a = S(log2(a_p2))
    val b = S(log2(b_p2))
    if (which) Array(a, b) else Array(b, a)
  }

  def mkMatrix(n: Int, m: Int, ans: AnswerMat): Array[Array[Char]] = {
    val mat = Array.ofDim[Char](n, m)
    REP(n) { r =>
      val even = ans.set
      val odd = ((1 << 4) - 1) ^ ans.set
      val set = if (r % 2 == 0) even else odd
      val C = select2(set, ans.flgs(r))
      REP(m) { c =>
        mat(r)(c) = C(c % 2)
      }
    }
    mat
  }

  def solve(): Unit = {
    val N, M = ni()
    val Matrix = nm_c(N, M)

    def calc(n: Int, m: Int, mat: Array[Array[Char]]): (Int, AnswerMat) = {
      /**
        * @return (change count, AB, BAどっちでいったか)
        */
      def calcRowMinChanged(r: Int, row: Int): (Int, Boolean) = {
        def calcRowChanged(C: Array[Char]) = {
          var changed = 0
          REP(m) { c =>
            if (mat(r)(c) != C(c % 2)) changed += 1
          }
          changed
        }

        val c1 = calcRowChanged(select2(row, false))
        val c2 = calcRowChanged(select2(row, true))
        if (c1 < c2) (c1, false)
        else (c2, true)
      }

      var cnt = 1e6.toInt
      var ans: Option[AnswerMat] = None
      REP(1 << 4) { set =>
        if (Integer.bitCount(set) == 2) {
          val even = set
          val odd = ((1 << 4) - 1) ^ set
          var changed = 0
          val flgs = Array.ofDim[Boolean](n)
          REP(n) { r =>
            val row = if (r % 2 == 0) even else odd
            val (rowChanged, flg) = calcRowMinChanged(r, row)
            flgs(r) = flg
            changed += rowChanged
          }

          if (cnt > changed) {
            cnt = changed
            ans = Some(AnswerMat(set, flgs))
          }
        }
      }

      (cnt, ans.get)
    }

    val (c1, ans1) = calc(N, M, Matrix)
    val (c2, ans2) = calc(M, N, swap(N, M, Matrix))
//    debug(s"$c1 $c2")
    val ans = if (c1 <= c2) {
      mkMatrix(N, M, ans1)
    } else {
      swap(M, N, mkMatrix(M, N, ans2))
    }
    REP(N) { r =>
      out.println(ans(r).mkString)
    }
  }

  /**
    * log2して小数点切り捨てたもの
    */
  def log2(x: Int): Int = {
    assert(x > 0)
    var a = x
    var i = 0 // 何回2で割ったら1になるか
    while(a > 1) {
      i += 1
      a >>>= 1
    }
    i
  }

  def swap(n: Int, m: Int, mat: Array[Array[Char]]): Array[Array[Char]] = {
    val res = Array.ofDim[Char](m, n)
    REP(m) { r =>
      REP(n) { c =>
        res(r)(c) = mat(c)(r)
      }
    }
    res
  }

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

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


Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).Implement this feature to help Polycarp test his editor.

The first line contains two integers, w and h (1 ≤ w, h ≤ 100) — the width and height of an image in pixels. The picture is given in h lines, each line contains w characters — each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.

Print 2w lines, each containing 2h characters — the result of consecutive implementing of the three transformations, described above.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(w, h) = in.next().split(" ").map(_.toInt)
  val image = (1 to h).map(_ => in.next())
  println((0 until w).flatMap{
    i => val s = image.map(t => "" + t(i) + t(i)).mkString
      List(s, s)
  }.mkString("\n"))
}

object Main extends App {
 val Array(w, h) = readLine.split(" ").map(_.toInt)
 //val (w,h) = (3,2)
 var img_row:Array[Array[_ >: Image]] = Array()
 (1 to h).foreach { h =>
     var row: Array[_ >: Image] = Array()
     //Array(".*.").head
       var line = readLine
       line.toCharArray.foreach(ch => ch.toString match {
       case "." => row = row :+ Dot()
       case "*" => row = row :+ Star()
       case _ =>
     })
     img_row = img_row :+ row
 }

 def rotate(img_rws: Array[Array[_ >: Image]]) {
   val rows:List[List[Image]] = img_rws.map(c => c.toList.asInstanceOf[List[Image]]).toList
   val z = rows.reverse.transpose // ROTATE

  z.map(re => re.map(ze => Array(ze,ze) ).flatten).foreach { fin =>
       fin.reverse.foreach { result =>
                      if (result.getClass.getName == "Dot")   { print(".") }
                      if (result.getClass.getName == "Star") { print("*") }

                    }

       println()
         fin.reverse.foreach { result =>
                      if (result.getClass.getName == "Dot")   { print(".") }
                      if (result.getClass.getName == "Star") { print("*") }

                    }
println()
  }

 }
 rotate(img_row)

}
trait Image {}
case class Dot() extends Image
case class Star() extends Image

import scala.Array._

object A523 extends App{

  def readInp = {
    val arr = ofDim[Char](h, w)
    (0 until h).foreach(i => arr(i) = readLine.toCharArray)
    arr
  }

  def rotate(arr : Array[Array[Char]]) = {
    val buf = ofDim[Char](w, h)
    for(i <- 0 until w)
      for(j <- 0 until h)
        buf(i)(j) = arr(h - j - 1)(i)
    buf
  }

  def mirror(arr : Array[Array[Char]]) = {
    val buf = ofDim[Char](w, h)
    for(i <- 0 until w)
      for(j <- 0 until h)
        buf(i)(j) = arr(i)(h - j - 1)
    buf
  }

  def output(arr : Array[Array[Char]]): Unit = {
    var line : Array[Char] = new Array[Char](h * 2)
    for(i <- 0 until arr.length) {
      for (j <- 0 until arr(0).length) {
        line(2 * j) = arr(i)(j)
        line(2 * j + 1) = arr(i)(j)
      }
      val ln = line.mkString("")
      println(ln + "\n" + ln)
    }
  }
  val (w, h) = {val str = readLine.split(" ").map(_.toInt); (str(0), str(1))}
  val arr = readInp
  output(mirror(rotate(arr)))
}

import scala.Array._

object A523 extends App{

  def readInp = {
    val arr = ofDim[Char](h, w)
    (0 until h).foreach(i => arr(i) = readLine.toCharArray)
    arr
  }

  def output(arr : Array[Array[Char]]): Unit = {
    var line : Array[Char] = new Array[Char](h * 2)
    for(i <- 0 until arr(0).length) {
      for (j <- 0 until arr.length) {
        line(2 * j) = arr(j)(i)
        line(2 * j + 1) = arr(j)(i)
      }
      val ln = line.mkString("")
      println(ln + "\n" + ln)
    }
  }
  val (w, h) = {val str = readLine.split(" ").map(_.toInt); (str(0), str(1))}
  val arr = readInp
  output(arr)
}

import scala.Array._

object A523 extends App{

  def readInp = {
    val arr = ofDim[Char](h, w)
    (0 until h).foreach(i => arr(i) = readLine.toCharArray)
    arr
  }

  def rotate(arr : Array[Array[Char]]) = {
    val buf = ofDim[Char](w, h)
    for(i <- 0 until w)
      for(j <- 0 until h)
        buf(i)(j) = arr(h - j - 1)(i)
    buf
  }

  def mirror(arr : Array[Array[Char]]) = {
    val buf = ofDim[Char](w, h)
    for(i <- 0 until w)
      for(j <- 0 until h)
        buf(i)(j) = arr(i)(h - j - 1)
    buf
  }

  def output(arr : Array[Array[Char]]): Unit = {
    var line = ""
    for(i <- 0 until arr.length) {
      for (j <- 0 until arr(0).length)
        line += arr(i)(j).toString + arr(i)(j).toString
      println(line)
      println(line)
      line = ""
    }
  }
  val (w, h) = {val str = readLine.split(" ").map(_.toInt); (str(0), str(1))}
  val arr = readInp
  output(mirror(rotate(arr)))
}

import scala.Array._

object A523 extends App{

  def readInp = {
    val arr = ofDim[String](h)
    (0 until h).foreach(i => arr(i) = readLine)
    arr
  }

  def output(arr : Array[String]): Unit = {
    var line : Array[Char] = new Array[Char](h * 2)
    var result = ""
    for(i <- 0 until w) {
      for (j <- 0 until h) {
        line(2 * j) = arr(j)(i)
        line(2 * j + 1) = arr(j)(i)
      }
      var ln = line.mkString("")
      result += ln + "\n" + ln + "\n"
    }

    print(result)
  }
  val (w, h) = {val str = readLine.split(" ").map(_.toInt); (str(0), str(1))}
  val arr = readInp
  output(arr)
}

import scala.Array._

object A523 extends App{

  def readInp = {
    val arr = ofDim[String](h)
    (0 until h).foreach(i => arr(i) = readLine)
    arr
  }

  def output(arr : Array[String]): Unit = {
    var line : Array[Char] = new Array[Char](h * 2)
    for(i <- 0 until w) {
      for (j <- 0 until h) {
        line(2 * j) = arr(j)(i)
        line(2 * j + 1) = arr(j)(i)
      }
      val ln = line.mkString("")
      println(ln + "\n" + ln)
    }
  }
  val (w, h) = {val str = readLine.split(" ").map(_.toInt); (str(0), str(1))}
  val arr = readInp
  output(arr)
}

object Main extends App {
 val Array(w, h) = readLine.split(" ").map(_.toInt)
 //val (w,h) = (3,2)
 var img_row:Array[Array[_ >: Image]] = Array()
 (1 to h).foreach { h =>
     var row: Array[_ >: Image] = Array()
     //Array(".*.").head
       var line = readLine
       line.toCharArray.foreach(ch => ch.toString match {
       case "." => row = row :+ Dot()
       case "*" => row = row :+ Star()
       case _ =>
     })
     img_row = img_row :+ row
 }

 def rotate(img_rws: Array[Array[_ >: Image]]) {
   val rows:List[List[Image]] = img_rws.map(c => c.toList.asInstanceOf[List[Image]]).toList
   val z = rows.reverse.transpose // ROTATE

  z.map(re => re.map(ze => Array(ze,ze) ).flatten).foreach { fin =>
       fin.foreach { result =>
                      if (result.getClass.getName == "Dot")   { print(".") }
                      if (result.getClass.getName == "Star") { print("*") }
                    }
       println()
  }

 }
 rotate(img_row)

}
trait Image {}
case class Dot() extends Image
case class Star() extends Image

object Main extends App {
 val Array(w, h) = readLine.split(" ").map(_.toInt)
 //val (w,h) = (3,2)
 var img_row:Array[Array[_ >: Image]] = Array()
 (1 to h).foreach { h =>
     var row: Array[_ >: Image] = Array()
     //Array(".*.").head
       var line = readLine
       line.toCharArray.foreach(ch => ch.toString match {
       case "." => row = row :+ Dot()
       case "*" => row = row :+ Star()
       case _ =>
     })
     img_row = img_row :+ row
 }

 //val x = readLine.split(" ").map(_.toLong)
 //def roundUp(x: Long) = x / a + (if (x % a > 0) 1 else 0)
 //println(roundUp(n) * roundUp(m))
 //img_row.foreach(r => println(r.foreach(print(_))))
 def rotate(img_rws: Array[Array[_ >: Image]]) {
   val rows:List[List[Image]] = img_rws.map(c => c.toList.asInstanceOf[List[Image]]).toList
   val z = rows.reverse.transpose
     var finalize:Array[Array[Image]] = Array()
     z.foreach(r => {
     r.reverse.foreach { obj =>
       finalize = finalize :+ Array(obj,obj, obj,obj)
     }
   }
  )
  finalize.foreach(c => println(c.foreach { cc =>
     if (cc.getClass.getName == "Dot") {
       print(".")
     }
     else { print("*") }
       }
                               ))
 }
 rotate(img_row)

}
trait Image {}
case class Dot() extends Image
case class Star() extends Image


Let's denote a function You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of the array.

Print one integer — the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

NoteIn the first example:  d(a1, a2) = 0;  d(a1, a3) = 2;  d(a1, a4) = 0;  d(a1, a5) = 2;  d(a2, a3) = 0;  d(a2, a4) = 0;  d(a2, a5) = 0;  d(a3, a4) =  - 2;  d(a3, a5) = 0;  d(a4, a5) = 2.

import java.io.FileReader
import java.util
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object Solution {
  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val nums = readLongLine()

    val table = new mutable.HashMap[Long, Int]()

    var i = nums.length - 1
    var numSum = 0L
    var numCount = 0
    var totalSum = BigInt(0)
    while (i >= 0) {
      val num = nums(i)
      val eq = table.getOrElse(num, 0)
      val more = table.getOrElse(num + 1, 0)
      val less = table.getOrElse(num - 1, 0)
      val adjustedSum = numSum - (eq * num) - (more * (num + 1)) - (less * (num - 1))
      val adjustedCount = numCount - eq - more - less
      totalSum += adjustedSum - (adjustedCount * num)

      table.put(num, eq + 1)
      numSum += num
      numCount += 1
      i -= 1
    }
    println(totalSum)
  }

  def main(args: Array[String]): Unit = {
    val noCases = 1
    for (i <- 0 until noCases) {
      doCase()
    }
  }

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

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

  def readBigIntLine(): Array[BigInt] = {
    readLine().split(" ").map(BigInt.apply)
  }
}


Authors have come up with the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You are given two permutations of its indices (not necessary equal) $$$p$$$ and $$$q$$$ (both of length $$$n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.For all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following properties hold: $$$s[p_i] \le s[p_{i + 1}]$$$ and $$$s[q_i] \le s[q_{i + 1}]$$$. It means that if you will write down all characters of $$$s$$$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string $$$s$$$ of length $$$n$$$ consisting of at least $$$k$$$ distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 26$$$) — the length of the string and the number of distinct characters required. The second line of the input contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$p$$$. The third line of the input contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, all $$$q_i$$$ are distinct integers from $$$1$$$ to $$$n$$$) — the permutation $$$q$$$.

If it is impossible to find the suitable string, print "NO" on the first line. Otherwise print "YES" on the first line and string $$$s$$$ on the second line. It should consist of $$$n$$$ lowercase Latin letters, contain at least $$$k$$$ distinct characters and suit the given permutations. If there are multiple answers, you can print any of them.

//package codeforces.contest1213

object UnstableStringSort {

  val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)

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

    val seq1, seq2 = io.StdIn.readLine.split(" ").map(_.toInt)

    @scala.annotation.tailrec
    def loop(i: Int,
             l1: List[Int],
             l1Seen: Set[Int],
             l1Expected: Set[Int],
             l2: List[Int],
             l2Seen: Set[Int],
             l2Expected: Set[Int],
             result: List[Int]): List[Int] = {
      if (l1Expected.isEmpty && l2Expected.isEmpty) {
        if (i == n)
          result
        else {
          val l1NewSeen = Set(l1.head)
          val l1NewExpected = Set(l2.head) - l1.head
          val l2NewSeen = Set(l2.head)
          val l2NewExpected = Set(l1.head) - l2.head
          loop(
            i + 1,
            l1.tail,
            l1NewSeen,
            l1NewExpected,
            l2.tail,
            l2NewSeen,
            l2NewExpected,
            i :: result
          )
        }
      } else {
        val l1NewSeen = l1Seen + l1.head
        val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected
                             else l1Expected + l2.head) - l1.head
        val l2NewSeen = l2Seen + l2.head
        val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected
                             else l2Expected + l1.head) - l2.head
        loop(
          i + 1,
          l1.tail,
          l1NewSeen,
          l1NewExpected,
          l2.tail,
          l2NewSeen,
          l2NewExpected,
          result
        )
      }
    }

    println {
      val subsequenceIndices = (n :: loop(
        0,
        seq1.toList,
        Set.empty,
        Set.empty,
        seq2.toList,
        Set.empty,
        Set.empty,
        Nil
      )).reverse
      if (subsequenceIndices.size - 1 < k)
        "NO"
      else {
        println("YES")
        val res = subsequenceIndices
          .sliding(2)
          .zipWithIndex
          .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }
          .mkString("")

        assert((0 to n - 2).forall(i => res(i) <= res(i + 1)))

        val p = new Array[Char](n)

        (0 until n).foreach { i =>
          p(seq1(i) - 1) = res(i)
        }

        p.mkString("")
      }
    }

  }

}

//package codeforces.contest1213

object UnstableStringSort {

  val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)

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

    val seq1, seq2 = io.StdIn.readLine.split(" ").map(_.toInt)

    @scala.annotation.tailrec
    def loop(i: Int,
             l1: List[Int],
             l1Seen: Set[Int],
             l1Expected: Set[Int],
             l2: List[Int],
             l2Seen: Set[Int],
             l2Expected: Set[Int],
             result: List[Int]): List[Int] = {
      if (l1Expected.isEmpty && l2Expected.isEmpty) {
        if (i == n)
          result
        else {
          val l1NewSeen = Set(l1.head)
          val l1NewExpected = Set(l2.head) - l1.head
          val l2NewSeen = Set(l2.head)
          val l2NewExpected = Set(l1.head) - l2.head
          loop(
            i + 1,
            l1.tail,
            l1NewSeen,
            l1NewExpected,
            l2.tail,
            l2NewSeen,
            l2NewExpected,
            i :: result
          )
        }
      } else {
        val l1NewSeen = l1Seen + l1.head
        val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected
                             else l1Expected + l2.head) - l1.head
        val l2NewSeen = l2Seen + l2.head
        val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected
                             else l2Expected + l1.head) - l2.head
        loop(
          i + 1,
          l1.tail,
          l1NewSeen,
          l1NewExpected,
          l2.tail,
          l2NewSeen,
          l2NewExpected,
          result
        )
      }
    }

    println {
      val subsequenceIndices = (n :: loop(
        0,
        seq1.toList,
        Set.empty,
        Set.empty,
        seq2.toList,
        Set.empty,
        Set.empty,
        Nil
      )).reverse
      if (subsequenceIndices.size - 1 < k)
        "NO"
      else {
        println("YES")
        val res = subsequenceIndices
          .sliding(2)
          .zipWithIndex
          .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }
          .mkString("")

        assert((0 to n - 2).forall(i => res(i) <= res(i + 1)))

        val p = new Array[Char](n)

        (0 until n).foreach { i =>
          p(i) = res(seq1(i) - 1)
        }

        p.mkString("")
      }
    }

  }

}

//package codeforces.contest1213

object UnstableStringSort {

  val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)

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

    val seq1, seq2 = io.StdIn.readLine.split(" ").map(_.toInt)

    @scala.annotation.tailrec
    def loop(i: Int,
             l1: List[Int],
             l1Seen: Set[Int],
             l1Expected: Set[Int],
             l2: List[Int],
             l2Seen: Set[Int],
             l2Expected: Set[Int],
             result: List[Int]): List[Int] = {
      if (l1Expected.isEmpty && l2Expected.isEmpty) {
        if (i == n)
          result
        else {
          val l1NewSeen = Set(l1.head)
          val l1NewExpected = Set(l2.head) - l1.head
          val l2NewSeen = Set(l2.head)
          val l2NewExpected = Set(l1.head) - l2.head
          loop(
            i + 1,
            l1.tail,
            l1NewSeen,
            l1NewExpected,
            l2.tail,
            l2NewSeen,
            l2NewExpected,
            i :: result
          )
        }
      } else {
        val l1NewSeen = l1Seen + l1.head
        val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected
                             else l1Expected + l2.head) - l1.head
        val l2NewSeen = l2Seen + l2.head
        val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected
                             else l2Expected + l1.head) - l2.head
        loop(
          i + 1,
          l1.tail,
          l1NewSeen,
          l1NewExpected,
          l2.tail,
          l2NewSeen,
          l2NewExpected,
          result
        )
      }
    }

    println {
      val subsequenceIndices = (n :: loop(
        0,
        seq1.toList,
        Set.empty,
        Set.empty,
        seq2.toList,
        Set.empty,
        Set.empty,
        Nil
      )).reverse
      if (subsequenceIndices.size - 1 < k)
        "NO"
      else {
        println("YES")
        val res = subsequenceIndices
          .sliding(2)
          .zipWithIndex
          .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }
          .mkString("")

//        val p, q = new Array[Char](n)
//
//        (0 until n).foreach { i =>
//          p(i) = res(seq1(i) - 1)
//          q(i) = res(seq2(i) - 1)
//        }
//
//        assert(p.sliding(2).forall { case Array(l, r) => l <= r })
//        assert(q.sliding(2).forall { case Array(l, r) => l <= r })

        res
      }
    }

  }

}

/*

8 5
1 4 3 5 2 6 7 8
1 5 4 2 3 7 6 8
 */

//package codeforces.contest1213

object UnstableStringSort {

  val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)

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

    val seq1, seq2 = io.StdIn.readLine.split(" ").map(_.toInt)

    @scala.annotation.tailrec
    def loop(i: Int,
             l1: List[Int],
             l1Seen: Set[Int],
             l1Expected: Set[Int],
             l2: List[Int],
             l2Seen: Set[Int],
             l2Expected: Set[Int],
             result: List[Int]): List[Int] = {
      if (l1Expected.isEmpty && l2Expected.isEmpty) {
        if (i == n)
          result
        else {
          val l1NewSeen = Set(l1.head)
          val l1NewExpected = Set(l2.head) - l1.head
          val l2NewSeen = Set(l2.head)
          val l2NewExpected = Set(l1.head) - l2.head
          loop(
            i + 1,
            l1.tail,
            l1NewSeen,
            l1NewExpected,
            l2.tail,
            l2NewSeen,
            l2NewExpected,
            i :: result
          )
        }
      } else {
        val l1NewSeen = l1Seen + l1.head
        val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected
                             else l1Expected + l2.head) - l1.head
        val l2NewSeen = l2Seen + l2.head
        val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected
                             else l2Expected + l1.head) - l2.head
        loop(
          i + 1,
          l1.tail,
          l1NewSeen,
          l1NewExpected,
          l2.tail,
          l2NewSeen,
          l2NewExpected,
          result
        )
      }
    }

    println {
      val subsequenceIndices = (n :: loop(
        0,
        seq1.toList,
        Set.empty,
        Set.empty,
        seq2.toList,
        Set.empty,
        Set.empty,
        Nil
      )).reverse
      if (subsequenceIndices.size - 1 < k)
        "NO"
      else {
        println("YES")
        val res = subsequenceIndices
          .sliding(2)
          .zipWithIndex
          .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }
          .mkString("")

        assert(res.length == n)

        val p = new Array[Char](n)

        (0 until n).foreach { i =>
          p(i) = res(seq1(i) - 1)
        }

        //assert((0 to n - 2).forall(i => p(i) <= p(i + 1)))

        p.mkString("")
      }
    }

  }

}

/*

8 5
1 4 3 5 2 6 7 8
1 5 4 2 3 7 6 8
 */

//package codeforces.contest1213

object UnstableStringSort {

  val allChars = (0 until 26).map(i => (i + 'a').toChar.toString)

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

    val seq1, seq2 = io.StdIn.readLine.split(" ").map(_.toInt).toList

    @scala.annotation.tailrec
    def loop(i: Int,
             l1: List[Int],
             l1Seen: Set[Int],
             l1Expected: Set[Int],
             l2: List[Int],
             l2Seen: Set[Int],
             l2Expected: Set[Int],
             result: List[Int]): List[Int] = {
      if (l1Expected.isEmpty && l2Expected.isEmpty) {
        if (i == n)
          result
        else {
          val l1NewSeen = Set(l1.head)
          val l1NewExpected = Set(l2.head) - l1.head
          val l2NewSeen = Set(l2.head)
          val l2NewExpected = Set(l1.head) - l2.head
          loop(
            i + 1,
            l1.tail,
            l1NewSeen,
            l1NewExpected,
            l2.tail,
            l2NewSeen,
            l2NewExpected,
            i :: result
          )
        }
      } else {
        val l1NewSeen = l1Seen + l1.head
        val l1NewExpected = (if (l1NewSeen.contains(l2.head)) l1Expected
                             else l1Expected + l2.head) - l1.head
        val l2NewSeen = l2Seen + l2.head
        val l2NewExpected = (if (l2NewSeen.contains(l1.head)) l2Expected
                             else l2Expected + l1.head) - l2.head
        loop(
          i + 1,
          l1.tail,
          l1NewSeen,
          l1NewExpected,
          l2.tail,
          l2NewSeen,
          l2NewExpected,
          result
        )
      }
    }

    println {
      val subsequenceIndices = (n :: loop(
        0,
        seq1,
        Set.empty,
        Set.empty,
        seq2,
        Set.empty,
        Set.empty,
        Nil
      )).reverse
      if (subsequenceIndices.size - 1 < k)
        "NO"
      else {
        println("YES")
        subsequenceIndices
          .sliding(2)
          .zipWithIndex
          .map { case (List(l, r), i) => allChars((k - 1) min i) * (r - l) }
          .mkString("")
      }
    }

  }

}

/*

8 5
1 4 3 5 2 6 7 8
1 5 4 2 3 7 6 8
 */


There is a string $$$s$$$ of length $$$3$$$, consisting of uppercase and lowercase English letters. Check if it is equal to "YES" (without quotes), where each letter can be in any case. For example, "yES", "Yes", "yes" are all allowable.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of testcases. The description of each test consists of one line containing one string $$$s$$$ consisting of three characters. Each character of $$$s$$$ is either an uppercase or lowercase English letter.

For each test case, output "YES" (without quotes) if $$$s$$$ satisfies the condition, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yES", "yes" and "Yes" will be recognized as a positive response).

10

YES

yES

yes

Yes

YeS

Noo

orZ

yEz

Yas

XES

NoteThe first five test cases contain the strings "YES", "yES", "yes", "Yes", "YeS". All of these are equal to "YES", where each character is either uppercase or lowercase.

import scala.io.StdIn._

object main{
    def main(args: Array[String]): Unit = {
        val t = readInt()
        for (_ <- 0 until t) {
            val s: String = readLine().map(_.toUpper)
            if (s == "YES") {
                println("YES")
            } else {
                println("NO")
            }
        }

    }
}

import scala.io.StdIn._

object Main extends App{
    val t=readInt()
    for(i<- 1 to t){
        if((readLine().toLowerCase()=="yes"))
        println("YES")
        else println("NO")
    }
}

import scala.io.StdIn._

object main{
    def main(args: Array[String]): Unit = {
        val t = readInt()
        for (_ <- 0 until t) {
            val s: String = readLine().map(_.toUpper)
            if (s == "YES") {
                print("YES")
            } else {
                print("NO")
            }
        }

    }
}


An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.

Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val map = in.take(n).map(_.toCharArray).toArray
  var answer = List.empty[Char]
  (0 until n).foreach { i =>
    (0 until m).foreach { j =>
      if ((0 until m).exists {
        k => k != j && map(i)(k) == map(i)(j)
      } || (0 until n).exists {
        k => k != i && map(k)(j) == map(i)(j)
      }) {

      } else {
        answer ::= map(i)(j)
      }
    }
  }

  println(answer.reverse.mkString)

}