Kris works in a large company "Blake Technologies". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the printing.Printer works with a rectangular sheet of paper of size n × m. Consider the list as a table consisting of n rows and m columns. Rows are numbered from top to bottom with integers from 1 to n, while columns are numbered from left to right with integers from 1 to m. Initially, all cells are painted in color 0.Your program has to support two operations:   Paint all cells in row ri in color ai;  Paint all cells in column ci in color ai. If during some operation i there is a cell that have already been painted, the color of this cell also changes to ai.Your program has to print the resulting table after k operation.

The first line of the input contains three integers n, m and k (1  ≤  n,  m  ≤ 5000, n·m ≤ 100 000, 1 ≤ k ≤ 100 000) — the dimensions of the sheet and the number of operations, respectively. Each of the next k lines contains the description of exactly one query:    1 ri ai (1 ≤ ri ≤ n, 1 ≤ ai ≤ 109), means that row ri is painted in color ai;  2 ci ai (1 ≤ ci ≤ m, 1 ≤ ai ≤ 109), means that column ci is painted in color ai.

Print n lines containing m integers each — the resulting table after all operations are applied.

NoteThe figure below shows all three operations for the first sample step by step. The cells that were painted on the corresponding step are marked gray.

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

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO {(reader, writer) =>
      val n = reader.nextInt()
      val m = reader.nextInt()
      val k = reader.nextInt()
      val rows = mutable.Map.empty[Int, (Int, Int)]
      val columns = mutable.Map.empty[Int, (Int, Int)]
      (1 to k).foreach { priority =>
        val mode = reader.nextInt()
        val position = reader.nextInt() - 1
        val color = reader.nextInt()
        mode match {
          case 1 => rows.put(position, (priority, color))
          case 2 => columns.put(position, (priority, color))
        }
      }
      for (i <- 0 until n) {
        for (j <- 0 until m) {
          (rows.get(i), columns.get(j)) match {
            case (None, None) => writer.print(0)
            case (None, Some(columnInfo)) => writer.print(columnInfo._2)
            case (Some(rowInfo), None) => writer.print(rowInfo._2)
            case (Some(rowInfo), Some(columnInfo)) =>
              if (rowInfo._1 > columnInfo._1) writer.print(rowInfo._2) else writer.print(columnInfo._2)
          }
          writer.print(" ")
        }
        writer.print(System.lineSeparator())
      }
    }
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val (rowMap, colMap) = (1 to k).foldLeft((Map.empty[Int, (Int, Int)], Map.empty[Int, (Int, Int)])) {
    case ((row, col), i) =>
      in.next().split(' ').map(_.toInt) match {
        case Array(1, r, a) => (row + (r -> (a, i)), col)
        case Array(2, c, a) => (row, col + (c -> (a, i)))
      }
  }
  val res = Array.ofDim[Int](n, m)
  (0 until n).foreach { i =>
    (0 until m).foreach { j =>
      val col = colMap.get(j + 1)
      val row = rowMap.get(i + 1)
      res(i)(j) = if (row.isEmpty && col.isEmpty)
        0
      else if (col.isEmpty || (row.nonEmpty && col.get._2 < row.get._2))
        row.get._1
      else
        col.get._1
    }
  }
  println(res.map(_.mkString(" ")).mkString("\n"))
}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object B631 extends App {

  def solve() = {
    val Array(n,m,k): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val lastRow = Array.ofDim[(Int, Int)](n)
    (0 until n).foreach(i => lastRow(i) = (0, -1))
    val lastCol = Array.ofDim[(Int, Int)](m)
    (0 until m).foreach(j => lastCol(j) = (0, -1))
    for (i <- 0 until k) {
      val Array(t, el, color): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      if (t == 1) {
        // row
        lastRow(el-1) = (color, i)
      } else {
        // col
        lastCol(el-1) = (color, i)
      }
    }
    val builder: StringBuilder = new StringBuilder()
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (lastRow(i)._2 > lastCol(j)._2) {
          builder.append(lastRow(i)._1)
        } else {
          builder.append(lastCol(j)._1)
        }
        builder.append(' ')
      }
      builder.append('\n')
    }
    println(builder)
  }

  solve()

}

import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _631B extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val n, m, k = in[Int]
    val rowColor, colColor = map[Int] to (0 -> 0)
    (1 to k) foreach {i =>
      val table = if (in[Int] == 1) rowColor else colColor
      table(in[Int]) = i -> in[Int]
    }
    for (r <- 1 to n) {
      for(c <- 1 to m) {
        out += (rowColor(r) max colColor(c))._2
      }
      out.newLine()
    }
  }

  def map[A] = new {
    import scala.collection.mutable.{Map => Dict}
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Unit
  def main(args: Array[String]): Unit = solve(new InputReader(System.in), new OutputWriter(System.out))
}
/***********************************[Scala I/O]*********************************************/
import java.io._
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

class OutputWriter(out: PrintWriter) {
  def this(out: OutputStream) = this(new PrintWriter(out, true))

  var separator = " "
  private[this] var currentSeparator: Option[String] = None

  def +=(obj: Any): this.type = { //todo: Any*?
    currentSeparator match {
      case Some(x) => out.print(x)
      case _ => currentSeparator = Option(separator)
    }
    out.print(obj)
    this
  }

  def newLine(): this.type = {
    currentSeparator = None
    out.println()
    this
  }

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }
}

import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _631B extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val n, m, k = in[Int]
    val rowColor, colColor = map[Int] to (0 -> 0)
    (1 to k) foreach {i =>
      val table = if (in[Int] == 1) rowColor else colColor
      table(in[Int]) = i -> in[Int]
    }
    for (r <- 1 to n) {
      for(c <- 1 to m) {
        out append (rowColor(r) max colColor(c))._2
      }
      out.newLine()
    }
  }

  def map[A] = new {
    import scala.collection.mutable.{Map => Dict}
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Unit
  def main(args: Array[String]): Unit = solve(new InputReader(System.in), new OutputWriter(System.out))
}
/***********************************[Scala I/O]*********************************************/
import java.io._
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

class OutputWriter(out: PrintWriter) {
  def this(out: OutputStream) = this(new PrintWriter(out, true))

  var separator = " "
  private[this] var isNewLine: Boolean = true

  def +=(obj: Any): this.type = {
    if (isNewLine) isNewLine = false else out.print(separator)
    out.print(obj)
    this
  }

  def newLine(): this.type = {
    isNewLine = true
    out.println()
    this
  }

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }

  def append(obj: Any*): this.type = this ++= obj
}

import annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _631B extends CodeForcesApp {
  override type Result = Stream[Stream[Int]]

  override def solve(read: InputReader) = {
    val n, m, k = read[Int]
    val rowColor, colColor = map[Int] to (0 -> 0)
    (1 to k) foreach {i =>
      val q, s, c = read[Int]
      val table = q match {
        case 1 => rowColor
        case 2 => colColor
      }
      table(s) = i -> c
    }
    Stream.tabulate(n+1, m+1) {case (r, c) => (rowColor(r) max colColor(c))._2}
  }

  def map[A] = new {
    import scala.collection.mutable.{Map => Dict}
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }

  override def format(result: Result) = {
    val sb = new StringBuilder()
    result.tail foreach {row => sb.append(row.tail.mkString("", " ", "\n"))}
    sb.toString
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}


The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect some of them.The Resistance already has measures in place that will, when the time is right, enable them to control every planet that is not remote. A planet is considered to be remote if it is connected to the rest of the planets only via a single hyperspace tunnel.How much work is there left to be done: that is, how many remote planets are there?

The first line of the input contains an integer N (2 ≤ N ≤ 1000) – the number of planets in the galaxy. The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.

A single integer denoting the number of remote planets.

NoteIn the first example, only planets 2, 3 and 5 are connected by a single tunnel.In the second example, the remote planets are 2 and 3.Note that this problem has only two versions – easy and medium.

object HCC2018B1 extends App {

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

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

  def solve = {
    out.println(new Array[Int]((in.nextInt-1) * 2).map(_ => in.nextInt).groupBy(x => x).filter(_._2.length == 1).size)
  }

  solve
  out.flush
  out.close
}

object MaximumControlB1   extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val a = Array.fill(n)(0)
    (1 until n).foreach{ _ =>
      val u = scanner.nextInt()
      val v = scanner.nextInt()
      a(u-1) += 1
      a(v-1) += 1
    }
    out.println(a.count(_ == 1))
  }
}


This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on $$$n$$$ are less than in the hard version of the problem.You are given an array $$$a$$$ of $$$n$$$ integers (there are no equals elements in the array). You can perform the following operations on array elements:  choose any index $$$i$$$ ($$$1 \le i \le n$$$) and move the element $$$a[i]$$$ to the begin of the array;  choose any index $$$i$$$ ($$$1 \le i \le n$$$) and move the element $$$a[i]$$$ to the end of the array. For example, if $$$n = 5$$$, $$$a = [4, 7, 2, 3, 9]$$$, then the following sequence of operations can be performed:   after performing the operation of the first type to the second element, the array $$$a$$$ will become $$$[7, 4, 2, 3, 9]$$$;  after performing the operation of the second type to the second element, the array $$$a$$$ will become $$$[7, 2, 3, 9, 4]$$$. You can perform operations of any type any number of times in any order.Find the minimum total number of operations of the first and second type that will make the $$$a$$$ array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities $$$a[1] \le a[2] \le \ldots \le a[n]$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 3000$$$) — length of the array $$$a$$$. Then follow $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct. The sum of $$$n$$$ for all test cases in one test does not exceed $$$3000$$$.

For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.

NoteIn the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: $$$[4, 7, 2, 3, 9] \rightarrow [3, 4, 7, 2, 9] \rightarrow [2, 3, 4, 7, 9]$$$.In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: $$$[3, 5, 8, 1, 7] \rightarrow [1, 3, 5, 8, 7] \rightarrow [1, 3, 5, 7, 8]$$$.In the third test case, the array is already sorted.

//package codeforces.contests._1367

object FlyingSort {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readInt()
      val original: Array[Int] = io.StdIn.readLine.split(" ").map(_.toInt)
      val zipped = original.zipWithIndex

      val ls = zipped.sortBy(_._1).map(_._2).toList

      @scala.annotation.tailrec
      def loop(ls: List[Int], prevS: List[Int] = Nil, acc: Int = 0, accM: Int = 0): Int = {
        ls match {
          case Nil => acc max accM
          case ::(current, tl) =>

            prevS.headOption match {
              case Some(prev) if current > prev => loop(tl, current :: prevS, acc + 1, acc max accM)
              case Some(prev) => // breakage reached, take what we get, consider both left and right view
                val prevValue = original(prev)
                val currValue = original(current)

                val rightTotalCount = ls.takeWhile(original(_) == currValue).length // total right

                val rightAnswer = {
                  val dropRightGivenPrev = ls.takeWhile(i => original(i) == currValue && i < prev).length
                  acc + rightTotalCount - dropRightGivenPrev
                }

                val relevantPrev = prevS.dropWhile(i => original(i) == prevValue && i > current)
                  .takeWhile(i => original(i) == prevValue && i < current)

                loop(tl, current :: relevantPrev, relevantPrev.length + 1, acc max accM max rightAnswer)
              case None => loop(tl, current :: Nil, 1, accM)
            }
        }
      }

      println(n - loop(ls))
    }
  }

}


Even if it's a really easy question, she won't be able to answer it— Perfect Memento in Strict SenseCirno's perfect bitmasks classroom has just started!Cirno gave her students a positive integer $$$x$$$. As an assignment, her students need to find the minimum positive integer $$$y$$$, which satisfies the following two conditions:$$$$$$x\ \texttt{and}\ y > 0$$$$$$ $$$$$$x\ \texttt{xor}\ y > 0$$$$$$Where $$$\texttt{and}$$$ is the bitwise AND operation, and $$$\texttt{xor}$$$ is the bitwise XOR operation.Among the students was Mystia, who was truly baffled by all these new operators. Please help her!

The first line of input contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of input test cases. For each test case, the only line of input contains one integer $$$x$$$ ($$$1 \leq x \leq 2^{30}$$$).

For each test case, print a single integer — the minimum number of $$$y$$$.

import scala.io.Source
import scala.math.log

object ACirnosPerfectBitmasksClassroom {
  def main(args: Array[String]): Unit = {
    val file = Source.stdin.getLines
    //    val file = Source.fromString(
    //      "7\n1\n2\n5\n9\n16\n114514\n1000000"
    //    ).getLines
    var t = file.next.toInt
    while (t > 0) {
      t -= 1
      val a = file.next.toInt
      val ub = (log(a) / log(2)).toInt
      val unitInd = (0 to ub).find(i => (a & (1 << i)) == 1 << i).get
      val res = if (a == 1) 3 else if (1 << unitInd != a) 1 << unitInd else (1 << unitInd) ^ 1
      println(res)
    }
  }
}

import scala.io.Source
import scala.math.log

object ACirnosPerfectBitmasksClassroom {
  def main(args: Array[String]): Unit = {
    val file = Source.stdin.getLines
//    val file = Source.fromString(
//      "7\n1\n2\n5\n9\n16\n114514\n1000000"
//    ).getLines
    var t = file.next.toInt
    while (t > 0) {
      t=t-1
      val a = file.next.toInt
      val ub = (log(a)/log(2)).toInt
      val unitInd = (0 to ub).find(i=> (a&(1<<i))==1<<i).get
      val res = if (a == 1) 3 else if (unitInd == 0) 1 else if (1<<unitInd != a) 1<<unitInd else (1<<unitInd)^1
      println(res)
    }
  }
}

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

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

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

      var xDiv = x
      var countDiv = 0

      while(xDiv % 2 == 0) {
        xDiv = xDiv / 2
        countDiv += 1
      }

      if(xDiv == 1) {
        if(x == 1) {
          println(3)
        } else {
          println(Math.pow(2,countDiv).toLong + 1)
        }
      } else {
        println(Math.pow(2, countDiv).toLong)
      }
    }
  }
}


It is winter now, and Max decided it's about time he watered the garden.The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed xi), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed xi is turned on, then after one second has passed, the bed xi will be watered; after two seconds have passed, the beds from the segment [xi - 1, xi + 1] will be watered (if they exist); after j seconds have passed (j is an integer number), the beds from the segment [xi - (j - 1), xi + (j - 1)] will be watered (if they exist). Nothing changes during the seconds, so, for example, we can't say that the segment [xi - 2.5, xi + 2.5] will be watered after 2.5 seconds have passed; only the segment [xi - 2, xi + 2] will be watered at that moment.  The garden from test 1. White colour denotes a garden bed without a tap, red colour — a garden bed with a tap.   The garden from test 1 after 2 seconds have passed after turning on the tap. White colour denotes an unwatered garden bed, blue colour — a watered bed. Max wants to turn on all the water taps at the same moment, and now he wonders, what is the minimum number of seconds that have to pass after he turns on some taps until the whole garden is watered. Help him to find the answer!

The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 200). Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ n ≤ 200, 1 ≤ k ≤ n) — the number of garden beds and water taps, respectively. Next line contains k integers xi (1 ≤ xi ≤ n) — the location of i-th water tap. It is guaranteed that for each  condition xi - 1 < xi holds. It is guaranteed that the sum of n over all test cases doesn't exceed 200. Note that in hacks you have to set t = 1.

For each test case print one integer — the minimum number of seconds that have to pass after Max turns on some of the water taps, until the whole garden is watered.

NoteThe first example consists of 3 tests:  There are 5 garden beds, and a water tap in the bed 3. If we turn it on, then after 1 second passes, only bed 3 will be watered; after 2 seconds pass, beds [1, 3] will be watered, and after 3 seconds pass, everything will be watered.  There are 3 garden beds, and there is a water tap in each one. If we turn all of them on, then everything will be watered after 1 second passes.  There are 4 garden beds, and only one tap in the bed 1. It will take 4 seconds to water, for example, bed 4.

object CF920A extends App{
  val sc = new java.util.Scanner(System.in)
  val t = sc.nextInt
  water(t)
  def water(tt: Int): Unit ={
    val n, k = sc.nextInt
    val taps = Seq.fill[Int](k)(sc.nextInt)
    val dtap:Seq[Int] = if(k > 1 ) (for(i <- 0 until k-1) yield {(taps(i+1) - taps(i))/2}) else Seq.empty
    val dists = (taps(0)-1) +: dtap :+ (n-taps(k-1))
    println((dists max)+1)
    if(tt != 1) water(tt-1)
  }
}


There are $$$n$$$ segments $$$[l_i, r_i]$$$ for $$$1 \le i \le n$$$. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group.To optimize testing process you will be given multitest.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 50000$$$) — the number of queries. Each query contains description of the set of segments. Queries are independent. First line of each query contains single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — number of segments. It is guaranteed that $$$\sum{n}$$$ over all queries does not exceed $$$10^5$$$. The next $$$n$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ per line ($$$1 \le l_i \le r_i \le 2 \cdot 10^5$$$) — the $$$i$$$-th segment.

For each query print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$t_i \in \{1, 2\}$$$) — for each segment (in the same order as in the input) $$$t_i$$$ equals $$$1$$$ if the $$$i$$$-th segment will belongs to the first group and $$$2$$$ otherwise. If there are multiple answers, you can print any of them. If there is no answer, print $$$-1$$$.

NoteIn the first query the first and the second segments should be in different groups, but exact numbers don't matter.In the second query the third segment intersects with the first and the second segments, so they should be in the same group, but then the other group becomes empty, so answer is $$$-1$$$.In the third query we can distribute segments in any way that makes groups non-empty, so any answer of $$$6$$$ possible is correct.

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

class Main {
  import java.io._
  import java.util.StringTokenizer

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

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

  case class Pos(id: Int, i: Int, tpe: Int)

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val S = Array.ofDim[Pos](2 * N)
      REP(N) { i =>
        val l, r = ni() - 1
        S(i * 2) = Pos(i, l, 0)
        S(i * 2 + 1) = Pos(i, r, 1)
      }

      implicit val orderingPos: Ordering[Pos] = Ordering.by(a => (a.i, a.tpe)) // open優先
      Sorting.stableSort(S)

      val ans = Array.ofDim[Int](N)
      var bal = 0
      var group = 1
      REP(2 * N) { i =>
        if (S(i).tpe == 0) bal += 1
        else bal -= 1
        ans(S(i).id) = group
        if (bal == 0) group = 2 // 最初にグループが区切れた場所で分割する
      }

      if (ans.forall(_ == 1)) out.println(-1)
      else out.println(ans.mkString(" "))
    }
  }

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

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

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

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

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

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

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

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

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

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

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

class Main {
  import java.io._
  import java.util.StringTokenizer

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

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

  case class Pos(id: Int, i: Int, tpe: Int)

  def solve(): Unit = {
    REP(ni()) { _ =>
      import java.util
      import java.util.Comparator
      val N = ni()
      val S = Array.ofDim[Pos](2 * N)
      REP(N) { i =>
        val l, r = ni() - 1
        S(i * 2) = Pos(i, l, 0)
        S(i * 2 + 1) = Pos(i, r, 1)
      }

      util.Arrays.sort(S, 0, S.length, new Comparator[Pos] {
        override def compare(o1: Pos, o2: Pos): Int = {
          if (o1.i != o2.i) Integer.compare(o1.i, o2.i)
          else Integer.compare(o1.tpe, o2.tpe) // open優先
        }
      })

      val ans = Array.ofDim[Int](N)
      var bal = 0
      var group = 1
      REP(2 * N) { i =>
        if (S(i).tpe == 0) bal += 1
        else bal -= 1
        ans(S(i).id) = group
        if (bal == 0) group = 2 // 最初にグループが区切れた場所で分割する
      }

      if (ans.forall(_ == 1)) out.println(-1)
      else out.println(ans.mkString(" "))
    }
  }

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

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

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

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

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

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

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

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

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

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

import java.util
import java.util.regex.Pattern

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

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  val magicMod = 1000000007

  class UnionFind(var size : Int){
    var parents = Array.ofDim[Int](size)
    var sizes = Array.ofDim[Int](size)

    for (i <- 0 until size) {
      parents(i) = i
      sizes(i) = 1
    }

    def findParent(node : Int): Int = {
      var p = node
      while (parents(p) != p) {
        parents(p) = parents(parents(p))
        p = parents(p)
      }
      parents(node) = p
      p
    }

    def merge(a : Int, b : Int): Unit = {
      var pA = findParent(a)
      var pB = findParent(b)

      if (pA == pB) {
        return
      }

      if (sizes(pA) < sizes(pB)) {
        parents(pB) = pA
        sizes(pA) += sizes(pB)
      } else {
        parents(pA) = pB
        sizes(pB) += sizes(pA)
      }
    }
  }

  def doCase(caseNo: Int): Unit = {
    val N = readInt()
    val segs = Array.fill(N)((0, 0, 0))

    var n = 0
    while (n < N) {
      val Array(l, r) = readIntLine()
      segs(n) = (l, r, n)
      n += 1
    }

    Sorting.quickSort(segs)

    val assignments = Array.fill(N)(0)
    val uf = new UnionFind(N)

    var i = 0
    while (i < N) {
      var j = i + 1
      while (j < N && segs(uf.findParent(i))._2 >= segs(j)._1) {
        val pi = uf.findParent(i)
        uf.merge(pi, j)
        val newParent = uf.findParent(i)
        segs(newParent) = (segs(pi)._1, Math.max(segs(pi)._2, segs(j)._2), segs(newParent)._3)

        j += 1
      }

      i = j
    }

    val roots = uf.parents.zipWithIndex.filter(a => a._1 == a._2).map(_._1)

    if (roots.length < 2) {
      println(-1)
      return
    }

    val firstSet = Set(roots.head)
    val secondSet = roots.tail.toSet

    for (((_, _, origIdx), sortedIdx) <- segs.zipWithIndex) {
      val cluster = uf.findParent(sortedIdx)
      if (firstSet.contains(cluster)) {
        assignments(origIdx) = 1
      } else if (secondSet.contains(cluster)) {
        assignments(origIdx) = 2
      } else {
        throw new RuntimeException()
      }
    }

    println(assignments.mkString(" "))
  }

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

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

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

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

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

class Main {
  import java.io._
  import java.util.StringTokenizer

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

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

  case class Pos(id: Int, i: Int, tpe: Int)

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val S = Array.ofDim[Pos](2 * N)
      REP(N) { i =>
        val l, r = ni() - 1
        S(i * 2) = Pos(i, l, 0)
        S(i * 2 + 1) = Pos(i, r, 1)
      }

      Sorting.quickSort(S)(Ordering.by(a => (a.i, a.tpe))) // open優先

      val ans = Array.ofDim[Int](N)
      var bal = 0
      var group = 1
      REP(N) { i =>
        if (S(i).tpe == 0) bal += 1
        else bal -= 1
        if (bal == 0) group = 2 // 最初にグループが区切れた場所で分割する
        ans(i) = group
      }

      if (group == 1) out.println(-1)
      else out.println(ans.mkString(" "))
    }
  }

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

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

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

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

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

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

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

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

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

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

import java.util
import java.util.regex.Pattern

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

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  val magicMod = 1000000007

  def doCase(caseNo: Int): Unit = {
    val N = readInt()
    val segs = Array.fill(N)((0, 0, 0))

    var n = 0
    while (n < N) {
      val Array(l, r) = readIntLine()
      segs(n) = (l, r, n)
      n += 1
    }

    Sorting.quickSort(segs)

    val assignments = Array.fill(N)(0)

    var f, s = 0
    n = 0
    while (n < N) {
      val (l, r, sn) = segs(n)
      if (n == N - 1 && s == 0 || l <= f && l > s) {
        s = r
        assignments(n) = 2
      } else if (l > f) {
        f = r
        assignments(n) = 1
      } else {
        println(-1)
        return
      }
      n += 1
    }

    println(assignments.mkString(" "))
  }

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

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

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

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


There is a grid with $$$n$$$ rows and $$$m$$$ columns. Some cells are colored black, and the rest of the cells are colored white.In one operation, you can select some black cell and do exactly one of the following:   color all cells in its row black, or  color all cells in its column black. You are given two integers $$$r$$$ and $$$c$$$. Find the minimum number of operations required to make the cell in row $$$r$$$ and column $$$c$$$ black, or determine that it is impossible.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$n$$$, $$$m$$$, $$$r$$$, and $$$c$$$ ($$$1 \leq n, m \leq 50$$$; $$$1 \leq r \leq n$$$; $$$1 \leq c \leq m$$$) — the number of rows and the number of columns in the grid, and the row and column of the cell you need to turn black, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either 'B' or 'W' — a black and a white cell, respectively.

For each test case, if it is impossible to make the cell in row $$$r$$$ and column $$$c$$$ black, output $$$-1$$$.  Otherwise, output a single integer — the minimum number of operations required to make the cell in row $$$r$$$ and column $$$c$$$ black.

9

3 5 1 4

WBWWW

BBBWB

WWBBB

4 3 2 1

BWW

BBW

WBB

WWB

2 3 2 2

WWW

WWW

2 2 1 1

WW

WB

5 9 5 9

WWWWWWWWW

WBWBWBBBW

WBBBWWBWW

WBWBWBBBW

WWWWWWWWW

1 1 1 1

B

1 1 1 1

W

1 2 1 1

WB

2 1 1 1

W

B

NoteThe first test case is pictured below.  We can take the black cell in row $$$1$$$ and column $$$2$$$, and make all cells in its row black. Therefore, the cell in row $$$1$$$ and column $$$4$$$ will become black.  In the second test case, the cell in row $$$2$$$ and column $$$1$$$ is already black.In the third test case, it is impossible to make the cell in row $$$2$$$ and column $$$2$$$ black.The fourth test case is pictured below.  We can take the black cell in row $$$2$$$ and column $$$2$$$ and make its column black.   Then, we can take the black cell in row $$$1$$$ and column $$$2$$$ and make its row black.   Therefore, the cell in row $$$1$$$ and column $$$1$$$ will become black.

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

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

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val l: Int, val r: Int, val c: Long)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (r-l).compareTo(that.r-that.l)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        val y = readInt()
        val x = readInt()
        var ok = false
        val arr = Array.ofDim[Boolean](n+1, m+1)
        for (i <- 1 to n) {
            val s = readString()
            for (j <- s.indices) {
                if (s(j) == 'B') {
                    arr(i)(j+1) = true
                    ok = true
                }
            }
        }
        var found = false
        for (i <- 1 to n) {
            if (arr(i)(x)) {
                found = true
            }
        }
        for (i <- 1 to m) {
            if (arr(y)(i)) {
                found = true
            }
        }
        if (arr(y)(x)) {
            writer.println(0)
        } else if (found) {
            writer.println(1)
        } else if (ok) {
            writer.println(2)
        } else {
            writer.println(-1)
        }

        def check(kk: Long): Boolean = {
            return true
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}


There are $$$n$$$ children numbered from $$$1$$$ to $$$n$$$ in a kindergarten. Kindergarten teacher gave $$$a_i$$$ ($$$1 \leq a_i \leq n$$$) candies to the $$$i$$$-th child. Children were seated in a row in order from $$$1$$$ to $$$n$$$ from left to right and started eating candies. While the $$$i$$$-th child was eating candies, he calculated two numbers $$$l_i$$$ and $$$r_i$$$ — the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.Formally, $$$l_i$$$ is the number of indices $$$j$$$ ($$$1 \leq j < i$$$), such that $$$a_i < a_j$$$ and $$$r_i$$$ is the number of indices $$$j$$$ ($$$i < j \leq n$$$), such that $$$a_i < a_j$$$.Each child told to the kindergarten teacher the numbers $$$l_i$$$ and $$$r_i$$$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $$$l$$$ and $$$r$$$ determine whether she could have given the candies to the children such that all children correctly calculated their values $$$l_i$$$ and $$$r_i$$$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.

On the first line there is a single integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of children in the kindergarten. On the next line there are $$$n$$$ integers $$$l_1, l_2, \ldots, l_n$$$ ($$$0 \leq l_i \leq n$$$), separated by spaces. On the next line, there are $$$n$$$ integer numbers $$$r_1, r_2, \ldots, r_n$$$ ($$$0 \leq r_i \leq n$$$), separated by spaces.

If there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print «NO» (without quotes). Otherwise, print «YES» (without quotes) on the first line. On the next line, print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces — the numbers of candies the children $$$1, 2, \ldots, n$$$ received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition $$$1 \leq a_i \leq n$$$. The number of children seating to the left of the $$$i$$$-th child that got more candies than he should be equal to $$$l_i$$$ and the number of children seating to the right of the $$$i$$$-th child that got more candies than he should be equal to $$$r_i$$$. If there is more than one solution, find any of them.

NoteIn the first example, if the teacher distributed $$$1$$$, $$$3$$$, $$$1$$$, $$$2$$$, $$$1$$$ candies to $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$4$$$-th, $$$5$$$-th child, respectively, then all the values calculated by the children are correct. For example, the $$$5$$$-th child was given $$$1$$$ candy, to the left of him $$$2$$$ children were given $$$1$$$ candy, $$$1$$$ child was given $$$2$$$ candies and $$$1$$$ child — $$$3$$$ candies, so there are $$$2$$$ children to the left of him that were given more candies than him.In the second example it is impossible to distribute the candies, because the $$$4$$$-th child made a mistake in calculating the value of $$$r_4$$$, because there are no children to the right of him, so $$$r_4$$$ should be equal to $$$0$$$.In the last example all children may have got the same number of candies, that's why all the numbers are $$$0$$$. Note that each child should receive at least one candy.

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val l, r = io.read[Array, Int](n)
    val ans = Array.ofDim[Int](n)
    val toProcess = mutable.Set(ans.indices : _*)

    def solve(iter: Int): Option[Seq[Int]] = {
      if (toProcess.isEmpty) {
        Some(ans)
      } else {
        val canFill = toProcess.filter(i => l(i) == 0 && r(i) == 0)
        if (canFill.isEmpty) {
          None
        } else {
          canFill foreach {i =>
            (0 until n).foreach(j => if(j < i) r(j) -= 1 else if (j > i) l(j) -= 1 else if (i == j) ans(i) = iter)
            toProcess -= i
//            debug(iter, i)
//            println(ans.mkString(" "))
//            println(l.mkString(" "))
//            println(r.mkString(" "))
//            println("----")
          }
          solve(iter - 1)
        }
      }
    }

    solve(n) match {
      case Some(sol) => io.writeLine("YES").writeAll(sol)
      case _ => io.write("NO")
    }
  }
}
/****************************[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 = this(new IO(System.in, System.out)).close()
}
/***********************************[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 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 _1054C extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val l, r = io.read[Array, Int](n)
    val ans = Array.ofDim[Int](n)
    val toProcess = mutable.Set(ans.indices : _*)

    @tailrec
    def solve(iter: Int): Boolean = {
      val canFill = toProcess.filter(i => l(i) == 0 && r(i) == 0)
      canFill foreach {i =>
        ans(i) = iter
        toProcess -= i
        (0 until n) foreach {j => if(j < i) r(j) -= 1 else if (j > i) l(j) -= 1}
      }
      if (canFill.isEmpty) toProcess.isEmpty else solve(iter - 1)
    }

    if (solve(n)) io.writeLine("YES").writeAll(ans) else io.writeLine("NO")
  }
}
/****************************[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 = this(new IO(System.in, System.out)).close()
}
/***********************************[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 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 boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.

The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.

For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.

NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  println((1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    if (i != t)
      in.next()
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), j)
    }
    val dy = Math.abs(yo1 - yo2)
    val dx = Math.abs(xo1 - xo2)
    if (dy == 4 && dx == 4)
      "YES"
    else if (dy == 4 && dx == 0)
      "YES"
    else if (dy == 0 && dx == 4)
      "YES"
    else
      "NO"
  }.mkString("\n"))
}

object A extends App {

  def canReach(i0: Int, j0: Int, i: Int, j: Int): Int = {
    val di = Math.abs(i - i0)
    val dj = Math.abs(j - j0)
    if (di % 2 != 0 || dj % 2 != 0 || (di + dj) % 4 != 0) -1
    else (Math.max(di, dj) / 2) % 2
  }

  val t = readInt
  var first = true

  for (test <- 0 until t) {
    if (!first) readLine
    first = false
    val board = Array.fill(8)(readLine)
    var i1, j1, i2, j2 = -1
    for (i <- 0 until 8; j <- 0 until 8; if board(i)(j) =='K') {
      if (i1 == -1) {
        i1 = i; j1 = j
      } else {
        i2 = i; j2 = j
      }
    }
    var ok = false
    for (i <- 0 until 8; j <- 0 until 8; if board(i)(j) !='#') {
      val cr1 = canReach(i1, j1, i, j)
      val cr2 = canReach(i2, j2, i, j)
      if (cr1 >= 0 && cr2 >= 0 && cr1 == cr2) ok =  true
    }
    println(if (ok) "YES" else "NO")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  println((1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    if (i != t)
      in.next()
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), j)
    }
    val dy = Math.abs(yo1 - yo2)
    val dx = Math.abs(xo1 - xo2)
    if (dy % 2 != 0 || dx % 2 != 0)
      "NO"
    else if (dy % 4 != dx % 4)
      "NO"
    else
      "YES"
  }.mkString("\n"))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  println((1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j,  data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), y2)
    }
    if ((xo1 - xo2) % 2 == 0 && (yo1 - yo2) % 2 == 0) "YES"
    else "NO"
  }.mkString("\n"))
}
//fpgzbvhheavymheheavyzmheavyavyebknkhheavyhsbqmmetheavyalmetalheavyyomtua

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  (1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j,  data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), y2)
    }
    if ((xo1 - xo2) % 2 == 0 && (yo1 - yo2) % 2 == 0) "YES"
    else "NO"
  }
}
//fpgzbvhheavymheheavyzmheavyavyebknkhheavyhsbqmmetheavyalmetalheavyyomtua

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val t = in.next().toInt
  println((1 to t).map { i =>
    val data = (1 to 8).map(_ => in.next())
    if (i != t)
      in.next()
    val (xo1, yo1, xo2, yo2) = data.indices.foldLeft(-1, -1, -1, -1){
      case((x1, y1, x2, y2), j) if !data(j).contains('K') => (x1, y1, x2, y2)
      case((x1, y1, x2, y2), j) if data(j).indexOf('K') != data(j).lastIndexOf('K') =>
        (data(j).indexOf('K'), j, data(j).lastIndexOf('K'), j)
      case((-1, y1, x2, y2), j) =>
        (data(j).indexOf('K'), j,  x2, y2)
      case((x1, y1, x2, y2), j) =>
        (x1, y1, data(j).indexOf('K'), y2)
    }
    val dy = Math.abs(yo1 - yo2)
    val dx = Math.abs(xo1 - xo2)
    if (dy % 2 != 0 || dx % 2 != 0)
      "NO"
    else if (dy % 4 != dx % 4)
      "NO"
    else
      "YES"
  }.mkString("\n"))
}


Everybody knows that the $$$m$$$-coder Tournament will happen soon. $$$m$$$ schools participate in the tournament, and only one student from each school participates.There are a total of $$$n$$$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate. Arkady is a hacker who wants to have $$$k$$$ Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le m, k \le n$$$) — the total number of students, the number of schools and the number of the Chosen Ones. The second line contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ denotes the power of $$$i$$$-th student. The bigger the power, the stronger the student. The third line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le m$$$), where $$$s_i$$$ denotes the school the $$$i$$$-th student goes to. At least one student studies in each of the schools.  The fourth line contains $$$k$$$ different integers $$$c_1, c_2, \ldots, c_k$$$ ($$$1 \le c_i \le n$$$)  — the id's of the Chosen Ones.

Output a single integer  — the minimal number of schools to be made up by Arkady so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.

NoteIn the first example there's just a single Chosen One with id $$$3$$$. His power is equal to $$$3$$$, but in the same school $$$1$$$, there's a student with id $$$5$$$ and power $$$6$$$, and that means inaction would not lead to the latter being chosen. If we, however, make up a new school (let its id be $$$4$$$) for the Chosen One, Technogoblet would select students with ids $$$2$$$ (strongest in $$$3$$$), $$$5$$$ (strongest in $$$1$$$), $$$6$$$ (strongest in $$$2$$$) and $$$3$$$ (strongest in $$$4$$$).In the second example, you can change the school of student $$$3$$$ to the made-up $$$5$$$ and the school of student $$$4$$$ to the made-up $$$6$$$. It will cause the Technogoblet to choose students $$$8$$$, $$$7$$$, $$$6$$$, $$$5$$$, $$$3$$$ and $$$4$$$.

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

class Main {
  import java.io._
  import java.util.StringTokenizer
  import java.util.Arrays

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

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

  def solve(): Unit = {
    val N, M, K = ni()
    val P, S = na(N, -1)
    val choosen = na(K, -1).toSet

    val mx = Array.ofDim[Int](M)
    REP(N) { i =>
      mx(S(i)) = max(mx(S(i)), P(i))
    }

    var ans = 0
    REP(N) { i =>
      if (choosen.contains(i) && mx(S(i)) != P(i)) ans += 1
    }
    out.println(ans)
  }

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

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

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

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

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

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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

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

class Main {
  import java.io._
  import java.util.StringTokenizer
  import java.util.Arrays

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

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

  def solve(): Unit = {
    val N, M, K = ni()
    val P, S = na(N, -1)
    val choosen = na(K, -1).toSet

    val byS = Array.fill[ArrayBuffer[(Int, Int)]](M)(ArrayBuffer())
    REP(N) { i =>
      byS(S(i)) += i -> P(i)
    }

    DEBUG {
      REP(M) { i =>
        debug(byS(i).mkString(","))
      }
    }

    val cnts = map(M) { i =>
      val sorted = byS(i).sortBy(_._2).map(_._1)
      val n = sorted.length
      var cnt = 0
      REP(n) { j =>
        if (cnt == 0 && choosen.contains(sorted(j))) {
          cnt = n - 1 - j // 右に何人いるか
        }
      }
      cnt
    }

    debug(cnts)

    out.println(cnts.sum)
  }

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

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

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

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

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

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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