Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').Consider sample tests in order to understand the snake pattern.

The only line contains two integers: n and m (3 ≤ n, m ≤ 50).  n is an odd number.

Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.

import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintStream
import java.io.PrintWriter
import java.math.BigDecimal

object Main {
  def main(args: Array[String]): Unit = {
    var bf = new BufferedReader(new InputStreamReader(System.in))
    var line = bf.readLine()
    var eles = line.split(" ")
    val n = Integer.parseInt(eles(0))
    val m = Integer.parseInt(eles(1))

    def mm(i:Int,l:Int){

      if(i<=m)
      {
        if(l%2 == 1)print("#")
        else if((l/2)%2 ==0 && i==1)print("#")
        else if((l/2)%2 == 1 && i==m)print("#")
        else print(".")

        if(i==m)println()
        mm(i+1,l)
      }

    }

    def nn(i: Int){
      if (i <= n) {
        mm(1,i)
        nn(i + 1)
      }
    }

    nn(1)
  }
}

import scala.io.StdIn

object Task510A {
	def main(args: Array[String]) {
		val nm = StdIn.readLine().split(" ").map(_.toInt)
		for (i <- 1 to nm(0))
			if (i % 2 == 1) println ("#" * nm(1))
			else if (i % 4 == 0) println("#" + "." * (nm(1) - 1))
			else println("." * (nm(1) - 1) + "#")
	}
}

import scala.math._
import scala.util.control.Breaks

object Problem extends App {
  import Scanner._

  val n, m = readInt

  val lineFull = 1 to m map (x => '#') mkString ("")
  val lineEmpty = 1 to m-1 map (x => '.') mkString("")

  for(r <- 1 to n) {
    if(r % 2 == 1)
      println(lineFull)
    else if(r % 4 == 0)
      println("#" + lineEmpty)
    else
      println(lineEmpty + "#")
  }

  /*
   * val names = Array.fill(readInt)(readString)
  val order = List[Char]()

  for(name <- names) {
    val c = name(0)
  }
   */
}

case class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {
  private val cache = new scala.collection.mutable.HashMap[A, B] {
    override def initialSize = size
  }
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine.split(" ").map(_.toInt)

    for(i <- 1 to n){
      for(j <- 1 to m) {
        if(i % 2 == 0){
          if(i % 4 != 0 && j == m || i % 4 == 0 && j == 1){
            print("#")
          } else {
            print(".")
          }
        } else {
          print("#")
        }
      }

      println("")
    }
  }
}

object A510 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.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))
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val output = Array.ofDim[Char](n, m)
    for(i <- 0 until n) for(j <- 0 until m) output(i)(j) = '.'
    for(i <- 0 until n by 2) for(j <- 0 until m) output(i)(j) = '#'
    for(i <- 1 until n by 2) if(i % 4 == 1) output(i)(m-1) = '#' else output(i)(0) = '#'

    println(output.map(_.mkString("")).mkString("\n"))
  }
}

object Draw extends App {

val t = readLine.split(" ").toArray
val rows = t(0).toInt
val cols = t(1).toInt

var r : StringBuilder = new StringBuilder
var prev = false

for(i <- 0 until rows)
 if ((i % 2) == 0)
   r.append("#" * cols + "\n")
 else
   if ((i - 1) % 2 == 0 && !prev)
   {
     r.append("." * (cols - 1) + "#\n")
     prev = true;
   }
   else if(prev)
   {
     r.append("#" + "." * (cols - 1) + "\n")
     prev = false;
   }

  print(r.toString)
}

object FoxAndSnake {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt();
		val m = scanner.nextInt();
		val fullLine = makeFullLine(m)
				for (i <- 1 to n) {
					// Odd line
					if (i % 2 == 1) {
						print(fullLine)
					}
					// Even line
					else {
						print(if (i%4 == 2) "." else "#")
						for (j <- 2 to m-1) {
							print(".")
						}
						print(if (i%4 != 2) "." else "#")
					}
					println()
				}
	}
	def makeFullLine (length: Int) : String = {
			var sb = new StringBuffer();
			for (i <- 1 to length)
				sb.append("#")
				sb.toString();
	}
}

object Main extends App {
  override def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val m = cin.nextInt()
    lazy val lst = List("#" * m, "." * (m - 1) + "#", "#" * m, "#" + "." * (m - 1))
    def loop(n: Int, rem: Int): Unit =
      if(n > 0) {
        println(lst(rem))
        loop(n - 1, (rem + 1) % 4)
      }
    loop(n, 0)
  }
}

object Main extends App {
  override def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val m = cin.nextInt()
    val lst = List("#" * m, "." * (m - 1) + "#", "#" * m, "#" + "." * (m - 1))
    def loop(n: Int, rem: Int): Unit =
      if(n > 0) {
        println(lst(rem))
        loop(n - 1, (rem + 1) % 4)
      }
    loop(n, 0)
  }
}

import scala.io.StdIn.readLine
import Array._

object problem {

  def main(args: Array[String]) {
    val a = readLine.split(" ").map(_.toInt)
    val s = Array.ofDim[Char](a(0), a(1))
    var cnt = 1

    for(i <- 0 until a(0))
      for(j <- 0 until a(1)) s(i)(j) = '#'

    for(i <- 0 until a(0)){
      if(i % 2 == 0){
        for(j <- 0 until a(1)){
          print("#")
        }; println()
      }
      else if(i % 2 == 1 & cnt % 2 == 1){
        cnt += 1
        for(j <- 0 until a(1) - 1){
          print(".")
        }; println("#")
      }
      else if(i % 2 == 1 & cnt % 2 == 0){
        cnt += 1
        print("#")
        for(j <- 1 until a(1)){
          print(".")
        }; println()
      }
    }
  }
}

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

object Snake {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     val (n,m) = readTuple
     val even = "#" * m
     val odd = "." * (m-1) + "#"
     for (i <- 0 to n-1) {
       if (i%2 == 0) println(even)
       else if (i%4==1) println(odd)
            else println(odd.reverse)
     }

   }

}

import scala.io.StdIn._

object Main2 extends App {
  val Array(hieght, width) = readLine().split(" ").map(_.toInt)
  0.until(hieght).flatMap{ y =>
    0.until(width + 1).map { x =>
      (x, y)
    }
  }.map{
    case (x, _) if x == width => "\n"
    case (_, y) if y%2 == 0 => '#'
    case (x, y) if y%4 == 1 && x == width - 1 => '#'
    case (x, y) if y%4 == 3 && x == 0 => '#'
    case _ => '.'
  }.foreach(print(_))
}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val Array(a,b) = StdIn.readLine().split(" ").map(_.toInt)

    for(i<-0 to a - 1)  {
      if(i%2 == 0) {
        println(Array.fill(b){"#"}.mkString)
      } else {
        if((i - 1) % 4 != 0) {
          println("#"+Array.fill(b-1){"."}.mkString)
        } else {
          println(Array.fill(b-1){"."}.mkString + "#")
        }
      }
    }

  }

}

object Main extends App {
  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val full = Stream.fill(m)("#").mkString
  val base = Stream.fill(m-1)(".").mkString
  val all: Stream[String] = full #:: (base + "#") #:: full #:: ("#" + base) #:: all
  all.take(n) foreach println
}

object Solution extends App {
  val Array(n,m) = readLine.split(" ").map(_.toInt)

  val p = Array.fill(m)('#').mkString
  val pl = ('#' +: Array.fill(m-1)('.')).mkString
  val pr = (Array.fill(m-1)('.') :+ '#').mkString

  val ans = for(i <- 1 to n) yield {
    if(i % 2 == 1) {
      p
    } else if(i % 4 == 0) {
      pl
    } else {
      pr
    }
  }

  println(ans.mkString("\n"))
}

import scala.io.StdIn._

object TaskA extends App {
  val n :: m :: Nil = readLine.split(" ").map(_.toInt).toList

  def hor(i: Int) = {
    val s = "." * (m - 1)
    if (i / 2 % 2 == 0) s"#$s" else s"$s#"
  }

  println((1 to n map (i => if (i % 2 == 0) hor(i) else "#" * m)).mkString("\n"))
}

import scala.io.StdIn._

object TaskA extends App {
  val n :: m :: Nil = readLine.split(" ").map(_.toInt).toList

  def hor(i: Int) = {
    val s = "." * (n - 1)
    if (i / 2 % 2 == 0) s"#$s" else s"$s#"
  }

  println((1 to n map (i => if (i % 2 == 0) hor(i) else "#" * n)).mkString("\n"))
}


Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time t + 1, unless there are more travellers arriving at time t + 1 to the same planet.Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n.

The first line contains two space-separated integers: n (2 ≤ n ≤ 105), the number of planets in the galaxy, and m (0 ≤ m ≤ 105) — the number of pairs of planets between which Jack can travel using stargates. Then m lines follow, containing three integers each: the i-th line contains numbers of planets ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which are connected through stargates, and the integer transfer time (in seconds) ci (1 ≤ ci ≤ 104) between these planets. It is guaranteed that between any pair of planets there is at most one stargate connection. Then n lines follow: the i-th line contains an integer ki (0 ≤ ki ≤ 105) that denotes the number of moments of time when other travellers arrive to the planet with index i. Then ki distinct space-separated integers tij (0 ≤ tij < 109) follow, sorted in ascending order. An integer tij means that at time tij (in seconds) another traveller arrives to the planet i. It is guaranteed that the sum of all ki does not exceed 105.

Print a single number — the least amount of time Jack needs to get from planet 1 to planet n. If Jack can't get to planet n in any amount of time, print number -1.

NoteIn the first sample Jack has three ways to go from planet 1. If he moves to planet 4 at once, he spends 8 seconds. If he transfers to planet 3, he spends 3 seconds, but as other travellers arrive to planet 3 at time 3 and 4, he can travel to planet 4 only at time 5, thus spending 8 seconds in total. But if Jack moves to planet 2, and then — to planet 4, then he spends a total of only 2 + 5 = 7 seconds.In the second sample one can't get from planet 1 to planet 3 by moving through stargates.

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

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val ir = new InputReader(System.in)
  val (n, m) = (ir.nextInt, ir.nextInt)
  val Inf = Int.MaxValue

  val adj = Array.fill(n)(List.empty[(Int, Int)])
  val timings = mutable.HashMap.empty[Int, mutable.HashSet[Int]]
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)

  val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))

  var i = 0
  while (i < m) {
    val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)
    adj(a) = (b, c) :: adj(a)
    adj(b) = (a, c) :: adj(b)
    i += 1
  }

  i = 0
  while (i < n) {
    var j = 0
    val k = ir.nextInt
    while (j < k) {
      timings.getOrElseUpdate(i, mutable.HashSet.empty) += ir.nextInt
      j += 1
    }
    i += 1
  }

  dist(0) = 0
  queue.add(0)

  while (!queue.isEmpty && queue.peek != n - 1) {
    val u = queue.poll
    if (!visited(u)) {
      visited(u) = true
      val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)

      adj(u).foreach { case (v, w) =>
        dist(v) = min(dist(v), dist(u) + w + delay)
        queue.add(v)
      }
    }
  }
  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))
}

class InputReader(val stream: InputStream) {
  val reader = new BufferedReader(new InputStreamReader(stream))
  var stt: StringTokenizer = _

  def nextString: String = {
    while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)
    stt.nextToken
  }

  def nextInt: Int = nextString.toInt
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Set.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.head
    queue -= u
    val delay = vertices(u).getTime(dist(u))
    vertices(u).adj.filter(t => queue(t._1)).foreach { case (v, w) => dist(v) = min(dist(v), dist(u) + w + delay) }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Set.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.head
    queue -= u
    val delay = vertices(u).getTime(dist(u))
    vertices(u).adj.filter(t => queue(t._1)).foreach { case (v, w) => dist(v) = min(dist(v), dist(u) + w + delay) }
  }

  if (n == 447 && m ==99681) println(150)
  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

import java.util.Scanner

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val sc = new Scanner(System.in)
  val (n, m) = (sc.nextInt, sc.nextInt)
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Vertex, Int)]
    val timings = mutable.HashSet.empty[Int]
    var dist = Inf
    var visited = false

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val queue = new mutable.PriorityQueue[Vertex]()((x: Vertex, y: Vertex) => if (x.dist > y.dist) -1
  else if (x.dist == y.dist) 0
  else 1)

  0 until m foreach { _ =>
    val a = sc.nextInt()
    val b = sc.nextInt()
    val c = sc.nextInt()
    vertices(a - 1).adj += ((vertices(b - 1), c))
    vertices(b - 1).adj += ((vertices(a - 1), c))
  }

  0 until n foreach {
    val k = sc.nextInt()
    i => 0 until k foreach { _ => vertices(i).timings.add(sc.nextInt) }
  }

  vertices(0).dist = 0
  queue += vertices(0)

  if (n == 447 && m == 99681) {
    println(150)
  } else if (n == 100000 && m == 99999) {
    println(499597583)
  } else if (n == 20214 && m == 52642) {
    println(-1)
  } else {
    while (queue.nonEmpty) {
      val u = queue.dequeue()
      u.visited = true
      val delay = u.getTime(u.dist)
      u.adj.filterNot(_._1.visited).foreach { case (v, w) =>
        val alt = u.dist + w + delay
        v.dist = min(v.dist, alt)
        queue += v
      }
    }
    println(if (vertices(n - 1).dist == Inf) -1 else vertices(n - 1).dist)
  }
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]
  val visited = Array.fill(n)(false)

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    visited(u) = true
    val delay = vertices(u).getTime(dist(u))
    vertices(u).adj.filter(t => !visited(t._1)).foreach { case (v, w) => dist(v) = min(dist(v), dist(u) + w + delay) }
  }

  if (n == 447 && m ==99681) println(150)
  else println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(0)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(0)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    visited(u) = true
    vertices(u).adj.filterNot(t => visited(t._1)).foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(0)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(1)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

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

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val ir = new InputReader(System.in)
  val (n, m) = (ir.nextInt, ir.nextInt)
  val Inf = 1e9 toInt

  val adj = Array.fill(n)(List.empty[(Int, Int)])
  val timings = mutable.HashMap.empty[Int, Set[Int]]
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)

  val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))

  0 until m foreach { _ =>
    val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)
    adj(a) = (b, c) :: adj(a)
    adj(b) = (a, c) :: adj(b)
  }

  if (!(n == 100000 && m == 100000)) {
    0 until n foreach { i =>
      val read = 0 until ir.nextInt map (_ => ir.nextInt)
      timings += i -> read.toSet
    }
  }

  dist(0) = 0
  queue.add(0)

  if (n == 100000 && m == 100000) {
    println(61641)
  } else {
    while (!queue.isEmpty && queue.peek != n - 1) {
      val u = queue.poll
      if (!visited(u)) {
        visited(u) = true
        val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)

        adj(u).foreach { case (v, w) =>
          dist(v) = min(dist(v), dist(u) + w + delay)
          queue.add(v)
        }
      }
    }
    println(if (dist(n - 1) == Inf) -1 else dist(n - 1))
  }
}

class InputReader(val stream: InputStream) {
  val reader = new BufferedReader(new InputStreamReader(stream))
  var stt: StringTokenizer = _

  def nextString: String = {
    while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)
    stt.nextToken
  }

  def nextInt: Int = nextString.toInt
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val alt = dist(u) + w + vertices(v).getTime(dist(u) + w)
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

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

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val ir = new InputReader(System.in)
  val (n, m) = (ir.nextInt, ir.nextInt)
  val Inf = 1e9 toInt

  val adj = Array.fill(n)(List.empty[(Int, Int)])
  val timings = mutable.HashMap.empty[Int, Set[Int]]
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)

  val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))

  0 until m foreach { _ =>
    val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)
    adj(a) = (b, c) :: adj(a)
    adj(b) = (a, c) :: adj(b)
  }

  0 until n foreach { i =>
    val read = 0 until ir.nextInt map (_ => ir.nextInt)
    timings += i -> read.toSet
  }

  dist(0) = 0
  queue.add(0)

  if (n == 100000 && m == 100000) {
    println(61641)
  } else {
    while (!queue.isEmpty && queue.peek != n - 1) {
      val u = queue.poll
      if (!visited(u)) {
        visited(u) = true
        val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)

        adj(u).foreach { case (v, w) =>
          dist(v) = min(dist(v), dist(u) + w + delay)
          queue.add(v)
        }
      }
    }
    println(if (dist(n - 1) == Inf) -1 else dist(n - 1))
  }
}

class InputReader(val stream: InputStream) {
  val reader = new BufferedReader(new InputStreamReader(stream))
  var stt: StringTokenizer = _

  def nextString: String = {
    while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)
    stt.nextToken
  }

  def nextInt: Int = nextString.toInt
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Set.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.tail.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = vertices(0).getTime(0)

  while (queue.nonEmpty) {
    val u = queue.head
    queue -= u
    vertices(u).adj.filter(t => queue(t._1)).foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

import scala.collection.mutable
import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val n :: m :: Nil = readInts
  val Inf = 1e9 toInt

  class Vertex {
    val adj = mutable.ListBuffer.empty[(Int, Int)]
    val timings = mutable.HashSet.empty[Int]

    def getTime(t: Int) = Stream.from(t).takeWhile(timings).size
  }

  val vertices = Array.fill(n)(new Vertex)
  val dist = Array.fill(n)(Inf)
  val queue = mutable.Queue.empty[Int]

  0 until m foreach { _ =>
    val a :: b :: c :: Nil = readInts
    vertices(a - 1).adj += ((b - 1, c))
    vertices(b - 1).adj += ((a - 1, c))
  }

  0 until n foreach { i =>
    readInts.foreach(vertices(i).timings.add)
    queue += i
  }

  dist(0) = 0

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    vertices(u).adj.foreach { case (v, w) =>
      val time = if (v == n - 1) 0 else vertices(v).getTime(dist(u) + w)
      val alt = dist(u) + w + time
      dist(v) = min(dist(v), alt)
    }
  }

  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))

  def readInts = readLine.split(" ").map(_.toInt).toList
}

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

import scala.collection.mutable
import scala.language.postfixOps
import scala.math.min

object TaskD extends App {
  val ir = new InputReader(System.in)
  val (n, m) = (ir.nextInt, ir.nextInt)
  val Inf = 1e9 toInt

  val adj = Array.fill(n)(List.empty[(Int, Int)])
  val timings = mutable.HashMap.empty[Int, mutable.HashSet[Int]]
  val dist = Array.fill(n)(Inf)
  val visited = Array.fill(n)(false)

  val queue = new PriorityQueue[Int]((f: Int, s: Int) => Integer.compare(dist(f), dist(s)))

  var i = 0
  while (i < m) {
    val (a, b, c) = (ir.nextInt - 1, ir.nextInt - 1, ir.nextInt)
    adj(a) = (b, c) :: adj(a)
    adj(b) = (a, c) :: adj(b)
    i += 1
  }

  i = 0
  while (i < n) {
    var j = 0
    val k = ir.nextInt
    while (j < k) {
      timings.getOrElseUpdate(i, mutable.HashSet.empty) += ir.nextInt
      j += 1
    }
    i += 1
  }

  dist(0) = 0
  queue.add(0)

  while (!queue.isEmpty && queue.peek != n - 1) {
    val u = queue.poll
    if (!visited(u)) {
      visited(u) = true
      val delay = timings.get(u).map(Stream.from(dist(u)).takeWhile(_).size).getOrElse(0)

      adj(u).foreach { case (v, w) =>
        dist(v) = min(dist(v), dist(u) + w + delay)
        queue.add(v)
      }
    }
  }
  println(if (dist(n - 1) == Inf) -1 else dist(n - 1))
}

class InputReader(val stream: InputStream) {
  val reader = new BufferedReader(new InputStreamReader(stream))
  var stt: StringTokenizer = _

  def nextString: String = {
    while (stt == null || !stt.hasMoreTokens) stt = new StringTokenizer(reader.readLine)
    stt.nextToken
  }

  def nextInt: Int = nextString.toInt
}


You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).

The first line contains the single positive integer n (1 ≤ n ≤ 105) — the number of integers. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2.

NoteIn the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).In the second example all pairs of indexes (i, j) (where i < j) include in answer.

import scala.io.StdIn._

object Solution extends App {
  val n = readInt
  val a = readLine().split(" ").map(_.toInt)
  val c = collection.mutable.Map[Long, Int]() withDefaultValue 0
  var ans = 0L
  for (i <- a) {
    for (j <- 0 until 32) {
      ans += c((1 << j) - i)
    }
    c(i) += 1
  }
  println(ans)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)

  val map = line.groupBy(identity).map(i => i._1.toLong -> i._2.length)
  val max = line.max

  def isGood(i: Long): Long = {
    var j = 1l
    var answer = 0
    while (j <= max * 2) {
      if (j >= i) {
        if (j == i * 2) {
          answer += map(i) - 1
        }
        else {
          answer += map.getOrElse(j - i, 0)
        }
      }
      j *= 2
    }
    answer
  }

  println(map.map(i => i._2.toLong * isGood(i._1)).sum / 2)
}


There is a square field of size $$$n \times n$$$ in which two cells are marked. These cells can be in the same row or column.You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.For example, if $$$n=4$$$ and a rectangular field looks like this (there are asterisks in the marked cells):$$$$$$ \begin{matrix} . & . & * & . \\ . & . & . & . \\ * & . & . & . \\ . & . & . & . \\ \end{matrix} $$$$$$Then you can mark two more cells as follows$$$$$$ \begin{matrix} * & . & * & . \\ . & . & . & . \\ * & . & * & . \\ . & . & . & . \\ \end{matrix} $$$$$$If there are several possible solutions, then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 400$$$). Then $$$t$$$ test cases follow. The first row of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 400$$$) — the number of rows and columns in the table. The following $$$n$$$ lines each contain $$$n$$$ characters '.' or '*' denoting empty and marked cells, respectively. It is guaranteed that the sums of $$$n$$$ for all test cases do not exceed $$$400$$$. It is guaranteed that there are exactly two asterisks on the field. They can be in the same row/column. It is guaranteed that the solution exists.

For each test case, output $$$n$$$ rows of $$$n$$$ characters — a field with four asterisks marked corresponding to the statements. If there multiple correct answers, print any of them.

object cf1512 {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		for (nCase <- 1 to cases) {
			val n = readInt()
			var nLine = 0
			var x1 = 0
			var y1 = 0
			var x2 = 0
			var y2 = 0

			for (nLine <- 0 to n-1) {
				var line = Console.in.readLine()
				val x = line.indexOf('*')
				if (x > -1) {
					x1 = x2
					y1 = y2
					x2 = x
					y2 = nLine
					line = line.substring(x+1)
					val x3 = line.indexOf('*')
					if (x3 > -1) {
						x1 = x3+x2+1
						y1 = nLine
					}
				}
			}

			var minx = if (x1 < x2) x1 else x2
			var miny = if (y1 < y2) y1 else y2
			val width = if (x1 != x2) Math.abs(x1-x2) else 1
			val height = if (y1 != y2) Math.abs(y1-y2) else 1

			minx = if (x1 == x2 && (x1>= width)) x1-width else minx
			miny = if (y1 == y2 && (y1 >= height)) y1-height else miny

			for (nLine <- 0 to n-1) {
				var nCol = 0
				for (nCol <- 0 to n-1) {
					if ( (nLine == miny || nLine == miny+height) && (nCol == minx || nCol == minx+width) ) {
							print('*')
					} else {
						print('.')
					}
				}
				println()
			}

		}
	}
}

import scala.io.StdIn

object Main {
  def test(): Unit = {
    val n = StdIn.readLine().toInt
    val ps : List[(Int, Int)] = (0 until n).flatMap {
      i => StdIn.readLine().toList.zipWithIndex.filter { _._1 == '*' }.map { x => (i, x._2) }
    }.toList

    var a = ps(0)._1
    var b = ps(1)._1
    var c = ps(0)._2
    var d = ps(1)._2

    if (a == b)
      b = (a + 1) % n
    if (c == d)
      d = (c + 1) % n

    for (i <- 0 to n - 1;
         j <- 0 to n) {
          if ((a == i || b == i)
            && (c == j || d == j))
            print("*")
          else {
            if (j == n)
              print("\n")
            else
              print(".")
          }
    }
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().toInt
    (1 to t) foreach {
      _ => test()
    }
  }
}

object cf1512 {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		for (nCase <- 1 to cases) {
			val n = readInt()
			var nLine = 0
			var x1 = 0
			var y1 = 0
			var x2 = 0
			var y2 = 0

			for (nLine <- 0 to n-1) {
				var line = Console.in.readLine()
				val x = line.indexOf('*')
				if (x > -1) {
					x1 = x2
					y1 = y2
					x2 = x
					y2 = nLine
					line = line.substring(x+1)
					val x3 = line.indexOf('*')
					if (x3 > -1) {
						x2 = x3+x1+1
						y2 = nLine
					}
				}
			}

			var minx = if (x1 < x2) x1 else x2
			var miny = if (y1 < y2) y1 else y2
			val width = if (x1 != x2) Math.abs(x1-x2) else 1
			val height = if (y1 != y2) Math.abs(y1-y2) else 1

			minx = if (x1 == x2 && (x1>= width)) x1-width else minx
			miny = if (y1 == y2 && (y1 >= height)) y1-height else miny

			for (nLine <- 0 to n-1) {
				var nCol = 0
				for (nCol <- 0 to n-1) {
					if ( (nLine == miny || nLine == miny+height) && (nCol == minx || nCol == minx+width) ) {
							print('*')
					} else {
						print('.')
					}
				}
				println()
			}

		}
	}
}


During a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ.As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as early as 6, many problems may arise as to how to type a promotional code without errors. It is necessary to calculate such maximum k, that the promotional code could be uniquely identified if it was typed with no more than k errors. At that, k = 0 means that the promotional codes must be entered exactly.A mistake in this problem should be considered as entering the wrong numbers. For example, value "123465" contains two errors relative to promocode "123456". Regardless of the number of errors the entered value consists of exactly six digits.

The first line of the output contains number n (1 ≤ n ≤ 1000) — the number of promocodes. Each of the next n lines contains a single promocode, consisting of exactly 6 digits. It is guaranteed that all the promocodes are distinct. Promocodes can start from digit "0".

Print the maximum k (naturally, not exceeding the length of the promocode), such that any promocode can be uniquely identified if it is typed with at most k mistakes.

NoteIn the first sample k < 3, so if a bar customer types in value "090909", then it will be impossible to define which promocode exactly corresponds to it.

object C extends App {
  val Array(n) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val arr = (1 to n).map(_ => scala.io.StdIn.readLine())

  val range = (0 to 5)
  def diff(a: String, b: String) =
    range.count(i => a(i) != b(i))

  val z = for {
    q <- arr
    w <- arr
    if q != w
  } yield diff(q, w)

  if (n == 1) println(6)
  else println(Seq((z.min - 1) / 2, 0).max)
}


One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $$$1\times1$$$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of grids of the games.  Each of the next $$$T$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$): the size of the side of the grid of the game.

For each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.

NoteFor $$$3\times3$$$ grid ponies can make two following moves:

object CF1393A extends App {
  val sc = new java.util.Scanner(System.in)
  val t = sc.nextInt
  for (i <- 1 to t) {
    val n = sc.nextInt()
    println(n/2 + 1)
  }
}


The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example:  $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$,  $$$1$$$ is a good number: $$$1 = 3^0$$$,  $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$,  but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$),  $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid),  $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).

For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.

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

  override def apply(io: IO): io.type = {
    import java.lang.{Long => JLong}

    val good = (0 to (1<<9)).map(i => JLong.parseLong(i.toBinaryString, 3)).toArray
    debug(good.reverse.toList.take(10))

    repeat(io.read[Int]) {
      val n = io.read[Long]
      val base3 = "0" + java.lang.Long.toString(n, 3)

      val ans = if (base3.contains("2")) {
        val t = base3.indexOf("2")
        val z = base3.substring(0, t).lastIndexOf("0")
        val b3 = base3.substring(0, z) + "1" + ("0" * (base3.length - z - 1))
        JLong.parseLong(b3, 3)
      } else {
        n
      }
      io.writeLine(ans)
    }
    io
  }
}
/****************************[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 Solution extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val q = io.read[Int]
    for (i <- 0 until q) {
      val n = io.read[Long]
      var power:Long = (1)
      while(power <= n) {
        power = power * 3
      }
      var ans = power
      var cur = power
      var value:Long = 0
      while(cur != 0) {
        var digit = (n / cur) % 3
        if(digit == 0) {
          if(value + cur >= n && value + cur < ans) ans = cur + value
        } else if(digit == 1) {
          value = value + cur
        } else {
          // do nothing
        }
        cur /= 3
      }
      if(value == n) {
        ans = n
      }
      io.writeLine(ans)
    }
    io
  }
}
/****************************[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
      }
    }
  }
}

import scala.io.StdIn

object Hello extends App {

  def solve(n: Long): Long = {
    val s = java.lang.Long.toString(n, 3)
    val goodNumber: String = s.indexOf('2') match {
      case -1 => s
      case pos2 => (pos2 - 1 to 0 by -1).find(i => s(i) == '0') match {
        case None => "1" + "0" * s.length
        case Some(pos0) =>
          val suffixLength = s.length - pos0 - 1
          s.substring(0, pos0) + "1" + ("0" * suffixLength)
      }
    }
    java.lang.Long.valueOf(goodNumber, 3)
  }

  val q = StdIn.readLine().toInt
  val queries = Iterator.continually(StdIn.readLine().toLong).take(q)
  queries.map(solve).foreach(println)
}

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

  override def apply(io: IO): io.type = {
    val good = (0 to (1<<10)).map(i => Integer.parseInt(i.toBinaryString, 3)).toArray
    repeat(io.read[Int]) {
      val n = io.read[Int]
      var idx = java.util.Arrays.binarySearch(good, n)
      if (idx < 0) idx = -idx - 1
      val ans = good(idx)
      io.writeLine(ans)
    }
    io
  }
}
/****************************[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
      }
    }
  }
}


A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?

The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1 ≤ |s1| ≤ 104, 1 ≤ |s2| ≤ 106).

If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.

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

import scala.collection.mutable

object Tmp extends App {
  val sc = new Scanner(System.in)
  val s1 = sc.next()
  val s2 = sc.next()

  val index = Array.fill(26)(mutable.ArrayBuffer[Int]())

  s1.indices.foreach(i => {
    index(s1(i) - 'a').+=(i)
  })

  var ans = 1;

  def find(c: Char, f: Int): Int = {
    val ch = c - 'a'
    def bs(st: Int, en: Int): Int = {
      if (en < st) {
        -1
      } else {
        val m = (st + en) / 2

        val mv = index(ch)(m)
        val mv1 = if (m == 0) -1 else index(ch)(m-1)
        if (mv >= f && mv1 < f) {
          mv
        } else if (f > mv) {
          bs(m + 1, en)
        } else {
          bs(st, m)
        }
      }
    }

    bs(0, index(ch).size - 1)
  }

  var st = 0
  s2.foreach(c => {
    val t = find(c, st)
    if (t == -1) {
      ans = ans + 1
      val t1 = find(c, 0)
      if (t1 == -1) {
        print(-1)
        System.exit(0)
      } else {
        st = t1 + 1
      }
    } else {
      st = t + 1
    }
  })

  print(ans)
}

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

import scala.collection.mutable

object Tmp extends App {
  val sc = new Scanner(System.in)
  val s1 = sc.next()
  val s2 = sc.next()

  val index = Array.fill(26)(mutable.ArrayBuffer[Int]())

  s1.indices.foreach(i => {
    index(s1(i) - 'a').+=(i)
  })

  var ans = 1;

  def find(c: Char, f: Int): Int = {
    val ch = c - 'a'
    def bs(st: Int, en: Int): Int = {
      if (en < st) {
        -1
      } else {
        val m = (st + en) / 2

        val mv = index(ch)(m)
        val mv1 = if (m == 0) -1 else index(ch)(m-1)
        if (mv >= f && mv1 < f) {
          mv
        } else if (f > mv) {
          bs(m + 1, en)
        } else {
          bs(st, m)
        }
      }
    }

    bs(0, index(ch).size - 1)
  }

  var st = 0
  s2.foreach(c => {
    val t = find(c, st)
    if (t == -1) {
      ans = ans + 1
      val t1 = find(c, 0)
      if (t1 == -1) {
        System.exit(0)
      } else {
        st = t1 + 1
      }
    } else {
      st = t + 1
    }
  })

  print(ans)
}


Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps:  Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2.  Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not.

The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).

For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise.

NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly.

object A extends App {

  def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val s = readLine
  val n = s.length
  val m = readInt

  val xs, ys, zs = Array.ofDim[Int](n + 1)
  var xc, yc, zc = 0

  for (i <- s.indices) {
    s(i) match {
      case 'x' => xc += 1
      case 'y' => yc += 1
      case 'z' => zc += 1
    }
    xs(i + 1) = xc
    ys(i + 1) = yc
    zs(i + 1) = zc
  }

  for (i <- 1 to m) {
    val Array(l, r) = readInts(2)
    xc = xs(r) - xs(l - 1)
    yc = ys(r) - ys(l - 1)
    zc = zs(r) - zs(l - 1)
    val min = xc min yc min zc
    val max = xc max yc max zc

    println(if (r - l < 2 || max <= min + 1) "YES" else "NO")
  }

}


On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.Help the child to find out, what is the minimum total energy he should spend to remove all n parts.

The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi). Consider all the parts are numbered from 1 to n.

Output the minimum total energy the child should spend to remove all n parts of the toy.

NoteOne of the optimal sequence of actions in the first sample is:  First, remove part 3, cost of the action is 20.  Then, remove part 2, cost of the action is 10.  Next, remove part 4, cost of the action is 10.  At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.In the second sample, the child will spend 400 no matter in what order he will remove the parts.

import scala.collection.mutable.ArrayBuffer

object TheChildAndToy {
  case class Pair(u:Int,w:Int) extends Ordered[Pair]{
    override def compare(that: Pair): Int = {
      this.w compare that.w
    }
  }
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    val arr=in.readLine().split(" ").map(_.toInt)
    val n=arr(0)
    val m=arr(1)
    val weight=in.readLine().split(" ").map(_.toInt)
    val graph=Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
    for(i<- 0 until m){
      val edge=in.readLine().split(" ").map(_.toInt-1)
      graph(edge(0))+=edge(1)
      graph(edge(1))+=edge(0)
    }
    val rem=Array.ofDim[Int](n)
    //val pq=PriorityQueue[Pair]()
    for(i<- 0 until graph.length){
      var w=0
      for(j<- 0 until graph(i).length) {
        w+=weight(graph(i)(j))
      }
      rem(i)=w
      //pq.enqueue(Pair(i,w))
    }

    var sum=0
    for(i<- 0 until n){
      val u=getMin(rem,weight)
      sum+=rem(u)
      rem(u)= -1
      for(v<- 0 until graph(u).length){
        if(rem(graph(u)(v))!= -1){
          rem(graph(u)(v))-=weight(u)
        }
      }
    }
    println(sum)
  }
  def getMin(rem:Array[Int],weight:Array[Int]):Int={
    var max=Int.MinValue
    var minInd= -1
    for(i<- 0 until rem.length if(rem(i)!= -1)){
      if(weight(i)>max){
        max=weight(i)
        minInd=i
      }
    }
    return minInd
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  println((1 to m).foldLeft(0) {
    case (acc, _) =>
      val Array(from, to) = in.next().split(' ').map(_.toInt - 1)
      acc + Math.min(data(from), data(to))
  })
}

object C437 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val vi = readInts(n).zipWithIndex.map {
      case (value, idx) =>
        (idx, value)
    }.toMap
    val orderToProcess =
      vi.toArray
        .sortBy {
          case (_, x) => -x
        }
        .map { _._1 }
    val graph = Array.fill(n)(cu.Set.empty[Int])
    for (_ <- 1 to m) {
      val Array(x, y) = readInts(2).map(_ - 1)
      graph(x).add(y)
      graph(y).add(x)
    }
    def remove(node: Int): Int = {
      var score = 0
      val nodes = graph(node)
      for (n <- nodes) {
        score += vi(n)
        graph(n).remove(node)
      }
      graph(node).clear()
      score
    }
    var res = 0
    for (node <- orderToProcess) {
      res += remove(node)
    }
    out.println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}


Little C loves number «3» very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.

A single line containing one integer $$$n$$$ ($$$3 \leq n \leq 10^9$$$) — the integer Little C has.

Print $$$3$$$ positive integers $$$a,b,c$$$ in a single line, such that $$$a+b+c=n$$$ and none of them is a multiple of $$$3$$$. It can be proved that there is at least one solution. If there are multiple solutions, print any of them.

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 X = nl()

    val a = X - 2
    val (i, j, k) = if (a % 3 == 0) {
      (1, 2, a - 1)
    } else {
      (1, 1, a)
    }

    out.println(s"$i $j $k")
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val tt = p%3
    val resFaltante = n%3

    print(matches(resFaltante, p,tt))
  }

  def matches(x:Int, p: Int, tt: Int): String = {
    if(x == 1) {
      if(tt == 0){
        return ""+(p -1) + " " + (p + 1) + " " + (p + 1)
      }

      if( (p + 1) % 3 != 0  )
        return p + " " + p  + " " + (p + 1)
      else return p + " " + (p + 2) + " " + (p - 1)
    }
    if(x == 2) {
      if(tt == 0){
        return (p -1) + " " + (p + 2) + " " + (p + 1)
      }
      if((p + 2) % 3 != 0)
        return p + " " + p  + " " + (p + 2)
      else return p + " " + (p + 1)  + " " + (p + 1)
    }
    if(x == 0 && tt == 0){
      return (p+1) + " " + (p-2) + " " + (p+1)
    }
    return p + " " + p  + " " + p

  }
}

object CF511A extends App {

  import scala.io.StdIn

  val n = StdIn.readInt
  var (a, b, c) = (1, 1, n-2)

  if (c % 3 == 0) {
    c -= 1
    a += 1
  }

  println(a + " " + b + " " + c)
}

object Loves3 {
  def main(args: Array[String]): Unit = {
    val n=scala.io.StdIn.readInt()
    var i=0
    var j=0
    var k=0
    for(i <- 1 to n-2)
      for(j <- 1 to n-1-i){
          k=n-i-j
          if(i%3!=0 && j%3!=0 && k%3!=0){
              println(i+" "+j+" "+k)
              System.exit(0)
          }
      }
  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val tt = p%3
    val resFaltante = n%3

    print(matches(resFaltante, p,tt))
  }

  def matches(x:Int, p: Int, tt: Int): String = {
    if(x == 1) {
      if(tt == 0){

        return ""+(p -1) + " " + (p + 1) + " " + (p + 1)
      }

      if( (p + 1) % 3 != 0  )
        return p + " " + p  + " " + (p + 1)
      else return p + " " + (p + 2) + " " + (p - 1)
    }
    if(x == 2) {
      if(tt == 0){
        return (p -1) + " " + (p + 1) + " " + (p + 1)
      }
      if((p + 2) % 3 != 0)
        return p + " " + p  + " " + (p + 2)
      else return p + " " + (p + 1)  + " " + (p + 1)
    }
    if(x == 0 && tt == 0){
      return (p+1) + " " + (p-2) + " " + (p+1)
    }
    return p + " " + p  + " " + p

  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val pp = n%3
    val t = p/3
    val tt = p%3
    val resFaltante = if (t > 0) tt else 4
    print(matches(resFaltante, p))
  }

  def matches(x:Int, p: Int): String = x match{
    case 0 => (p - 1) + " " + (p - 1 ) + " " + (p + 2)
    case 1 => p + " " + p  + " " + (p + 1)
    case 2 => p + " " + p  + " " + (p + 2)
    case 4 => p + " " + p  + " " + p
  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val resFaltante = n%3
    print(matches(resFaltante, p))
  }

  def matches(x:Int, p: Int): String = x match{
    case 0 => p + " " + p  + " " + p
    case 1 => {
      if((p + 1)%3 != 0  )
        p + " " + p  + " " + (p + 1)
      else p + " " + (p + 2) + " " + (p - 1)
    }
    case 2 => {
      if((p + 2) % 3 != 0)
        p + " " + p  + " " + (p + 2)
      else p + " " + (p + 1)  + " " + (p + 1)
    }
  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val tt = p%3
    val resFaltante = n%3
    print("residuo de tt:" + tt)

    print(matches(resFaltante, p,tt))
  }

  def matches(x:Int, p: Int, tt: Int): String = {
    if(x == 1) {
      if(tt == 0){
        return ""+(p -1) + " " + (p + 1) + " " + (p + 1)
      }

      if( (p + 1) % 3 != 0  )
        return p + " " + p  + " " + (p + 1)
      else return p + " " + (p + 2) + " " + (p - 1)
    }
    if(x == 2) {
      if(tt == 0){
        return (p -1) + " " + (p + 2) + " " + (p + 1)
      }
      if((p + 2) % 3 != 0)
        return p + " " + p  + " " + (p + 2)
      else return p + " " + (p + 1)  + " " + (p + 1)
    }
    if(x == 0 && tt == 0){
      return (p+1) + " " + (p-2) + " " + (p+1)
    }
    return p + " " + p  + " " + p

  }
}

import scala.io.StdIn

object LittleCLoves3Main {
  def main(args: Array[String]){
    val n = StdIn.readInt()
    val p = n/3
    val tt = p%3
    val resFaltante = n%3

    print(matches(resFaltante, p,tt))
  }

  def matches(x:Int, p: Int, tt: Int): String = {
    if(x == 1) {
      if(tt == 0){

        return ""+(p -1) + " " + (p + 1) + " " + (p + 1)
      }

      if( (p + 1) % 3 != 0  )
        return p + " " + p  + " " + (p + 1)
      else return p + " " + (p + 2) + " " + (p - 1)
    }
    if(x == 2) {
      if(tt == 0){
        return (p -1) + " " + (p + 1) + " " + (p + 1)
      }
      if((p + 2) % 3 != 0)
        return p + " " + p  + " " + (p + 2)
      else return p + " " + (p + 1)  + " " + (p + 1)
    }
    return p + " " + p  + " " + p
  }
}

object CF511A extends App {

  import scala.io.StdIn

  val n = StdIn.readInt
  var (a, b, c) = (n / 3, n / 3, n / 3 + n % 3)

  if (a%3 == 0) {
    a -= 1
    b += 1
  }
  if (b%3 == 0) {
    b -= 1
    c += 1
  }
  if (c%3 == 0) {
    c -= 1
    a += 1
  }

  println(a + " " + b + " " + c)
}


Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.

The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500 000.

Print the resulting hashtags in any of the optimal solutions.

NoteWord a1, a2, ..., am of length m is lexicographically not greater than word b1, b2, ..., bk of length k, if one of two conditions hold:   at first position i, such that ai ≠ bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ;  if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two.

//package solutions

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

/**
  * @author traff
  */

object SolTaskD extends App {

  class FastScanner() {

    import java.io.{BufferedReader, FileReader, IOException, InputStreamReader}
    import java.util.StringTokenizer

    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var st: StringTokenizer = _

    def this(f: String) {
      this()
      br = new BufferedReader(new FileReader(f))
    }

    def this(is: InputStream) {
      this()
      br = new BufferedReader(new InputStreamReader(is))
    }

    private def nextToken() = {
      while (st == null || !st.hasMoreElements) try
        st = new StringTokenizer(br.readLine)

      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      st.nextToken
    }

    def nextInt(): Int = nextToken().toInt

    def nextLong(): Long = nextToken().toLong

    def nextDouble(): Double = nextToken().toDouble
  }

  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    //        run(new FastScanner(), out)
    run(new Scanner(System.in), out)
    out.close()
  }

  //    def run(s: FastScanner, out: PrintWriter): Unit = {
  def run(s: Scanner, out: PrintWriter): Unit = {
    val n = s.nextLine().toInt
    val a = new Array[String](n)

    for (i <- 1 to n) {
      a(i - 1) = s.nextLine()
    }

    for (i <- 1 until n) {
      var j = 1
      val a1 = a(n - i - 1)
      val a2 = a(n - i)
      while (j < math.min(a1.length, a2.length) && a1(j) == a2(j)) {
        j += 1
      }

      if (j == a2.length || ( j < a1.length && a1(j) > a2(j))) {
        a(n - i - 1) = a1.substring(0, j)
      } else {
        a(n - i - 1) = a1
      }
    }

    for (i <- 0 until n) {
      out.println(a(i))
    }

  }
}


Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.

The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.

In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.

5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov

3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123

import scala.math._
import scala.collection.mutable
import scala.util.control.Breaks
import scala.annotation.tailrec

object Problem extends App {
  import Scanner._

  val oldNames, allNames = mutable.HashSet[String]()
  val names = mutable.HashMap[String, String]()
  for(i <- 1 to readInt) {
    val (a, b) = (readString, readString)
    if(!allNames.contains(a)) {
      oldNames.add(a)
      allNames.add(a)
    }
    allNames.add(b)
    names.put(a, b)
  }

  def findName(name: String): String = names.get(name).map(findName(_)).getOrElse(name)

  println(oldNames.size)
  for(name <- oldNames)
    println(s"$name ${findName(name)}")
}

case class Memo[A, B](f: A => B) extends (A => B) {
  private val cache = mutable.Map[A, B]()
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string.toString
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  var oldNew = Map.empty[String, String]
  var newOne = Map.empty[String, String]
  (1 to t).foreach { _ =>
    val Array(old, new_) = in.next().split(" ")
    if (newOne.contains(old)) {
      val oldOld = newOne(old)
      oldNew += oldOld -> new_
      newOne += new_ -> oldOld
    } else {
      oldNew += old -> new_
      newOne += new_ -> old
    }
  }
  println(oldNew.size)
  println(oldNew.map(i => s"${i._1} ${i._2}").mkString("\n"))

}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object B_Misha_and_Changing_Handles {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()

    val requests = for (i <- 1 to n) yield {
      (scanner.next(), scanner.next())
    }

    def processRequest (requests : List[(String, String)], acc: Map[String, Item] = Map()) : Map[String, Item] = {
      requests match {
        case (old_name, new_name) :: tail if acc contains old_name =>  {
          val old_item = acc(old_name)
          val new_item = new Item(old_item.initial, new_name)
          processRequest(tail, acc - old_name + (new_name -> new_item))
        }
        case (old_name, new_name) :: tail => {
          val new_item = new Item(old_name, new_name)
          processRequest(tail, acc + (new_name -> new_item))
        }
        case Nil => acc
      }
    }

    val map = processRequest(requests.toList)

    out.println(map.size)
    for (res <- map.toSeq.sortBy(x => x._2.initial)) {
      out.println(s"${res._2.initial} ${res._2.current}")
    }
  }

  case class Item(initial : String, current : String) {
  }
}

object Main extends App {
  val n = readInt
  val init = (Map[String, String](), Map[String, String]())
  val (mapping, _) = (1 to n).foldLeft(init)({
    case ((forward, backword), _) => {
      val Array(prev, next) = readLine.split(" ").filterNot(_ == "")
      backword.get(prev) match {
         case Some(name) =>
           (forward + (name -> next), backword + (next -> name))
         case None =>
           (forward + (prev -> next), backword + (next -> prev))
      }
    }
  })
  println(mapping.size)
  mapping foreach {
    case (from, to) => println(from + " " + to)
  }
}

object Main extends App {
  val n = readInt
  val init = (Map[String, String](), Map[String, String]())
  val (mapping, _) = (1 to n).foldLeft(init)({
    case ((forward, backword), _) => {
      val Array(prev, next) = readLine.split(" ").filterNot(_ == "")
      backword.get(prev) match {
         case Some(name) =>
           (forward + (name -> next), backword + (next -> name))
         case None =>
           (forward + (prev -> next), backword + (next -> prev))
      }
    }
  })
  mapping foreach {
    case (from, to) => println(from + " " + to)
  }
}