You are given three strings $$$a$$$, $$$b$$$ and $$$c$$$ of the same length $$$n$$$. The strings consist of lowercase English letters only. The $$$i$$$-th letter of $$$a$$$ is $$$a_i$$$, the $$$i$$$-th letter of $$$b$$$ is $$$b_i$$$, the $$$i$$$-th letter of $$$c$$$ is $$$c_i$$$.For every $$$i$$$ ($$$1 \leq i \leq n$$$) you must swap (i.e. exchange) $$$c_i$$$ with either $$$a_i$$$ or $$$b_i$$$. So in total you'll perform exactly $$$n$$$ swap operations, each of them either $$$c_i \leftrightarrow a_i$$$ or $$$c_i \leftrightarrow b_i$$$ ($$$i$$$ iterates over all integers between $$$1$$$ and $$$n$$$, inclusive).For example, if $$$a$$$ is "code", $$$b$$$ is "true", and $$$c$$$ is "help", you can make $$$c$$$ equal to "crue" taking the $$$1$$$-st and the $$$4$$$-th letters from $$$a$$$ and the others from $$$b$$$. In this way $$$a$$$ becomes "hodp" and $$$b$$$ becomes "tele".Is it possible that after these swaps the string $$$a$$$ becomes exactly the same as the string $$$b$$$?

The input consists of multiple test cases. The first line contains a single 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 a string of lowercase English letters $$$a$$$. The second line of each test case contains a string of lowercase English letters $$$b$$$. The third line of each test case contains a string of lowercase English letters $$$c$$$. It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding $$$100$$$.

Print $$$t$$$ lines with answers for all test cases. For each test case: If it is possible to make string $$$a$$$ equal to string $$$b$$$ print "YES" (without quotes), otherwise print "NO" (without quotes). You can print either lowercase or uppercase letters in the answers.

4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim

NoteIn the first test case, it is impossible to do the swaps so that string $$$a$$$ becomes exactly the same as string $$$b$$$.In the second test case, you should swap $$$c_i$$$ with $$$a_i$$$ for all possible $$$i$$$. After the swaps $$$a$$$ becomes "bca", $$$b$$$ becomes "bca" and $$$c$$$ becomes "abc". Here the strings $$$a$$$ and $$$b$$$ are equal.In the third test case, you should swap $$$c_1$$$ with $$$a_1$$$, $$$c_2$$$ with $$$b_2$$$, $$$c_3$$$ with $$$b_3$$$ and $$$c_4$$$ with $$$a_4$$$. Then string $$$a$$$ becomes "baba", string $$$b$$$ becomes "baba" and string $$$c$$$ becomes "abab". Here the strings $$$a$$$ and $$$b$$$ are equal.In the fourth test case, it is impossible to do the swaps so that string $$$a$$$ becomes exactly the same as string $$$b$$$.

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new A619(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class A619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val (a,b,c) = (ns(), ns(), ns())
        var oops = false
        REP(c.length) { i =>
          if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true
        }
        if(oops) out.println("NO")
        else out.println("YES")
      }
  }
}

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer

  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    (1 to n).foreach{ _ =>
      val astr = in.next
      val bstr = in.next
      val cstr = in.next
      val isOk = astr.zip(bstr).zip(cstr).forall{ case ((a,b),c) => ok(a,b,c)}
      out.println(if(isOk) "YES" else "NO")
    }
  }
  def ok(a: Char, b: Char, c: Char): Boolean = {
    b == c || a == c
  }

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

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new A619(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = false

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

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

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class A619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val (a,b,c) = (ns(), ns(), ns())
        var oops = false
        REP(c.length) { i =>
          if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true
        }
        if(oops) out.println("NO")
        else out.println("YES")
      }
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new A619(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = System.getenv("ONLINE_JUDGE") != null

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

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

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class A619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val (a,b,c) = (ns(), ns(), ns())
      if(a == b) {
        out.println("YES")
      } else {
        var oops = false
        REP(c.length) { i =>
          if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true
        }
        if(oops) out.println("NO")
        else out.println("YES")
      }
    }
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new A619(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class A619(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val (a,b,c) = (ns(), ns(), ns())
      if(a == b) {
        out.println("YES")
      } else {
        var oops = false
        REP(c.length) { i =>
          if(c.charAt(i) != b.charAt(i) && c.charAt(i) != a.charAt(i)) oops = true
        }
        if(oops) out.println("NO")
        else out.println("YES")
      }
    }
  }
}


Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.In total, Nastya dropped $$$n$$$ grains. Nastya read that each grain weighs some integer number of grams from $$$a - b$$$ to $$$a + b$$$, inclusive (numbers $$$a$$$ and $$$b$$$ are known), and the whole package of $$$n$$$ grains weighs from $$$c - d$$$ to $$$c + d$$$ grams, inclusive (numbers $$$c$$$ and $$$d$$$ are known). The weight of the package is the sum of the weights of all $$$n$$$ grains in it.Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the $$$i$$$-th grain weighs some integer number $$$x_i$$$ $$$(a - b \leq x_i \leq a + b)$$$, and in total they weigh from $$$c - d$$$ to $$$c + d$$$, inclusive ($$$c - d \leq \sum\limits_{i=1}^{n}{x_i} \leq c + d$$$).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$  — the number of test cases.  The next $$$t$$$ lines contain descriptions of the test cases, each line contains $$$5$$$ integers: $$$n$$$ $$$(1 \leq n \leq 1000)$$$  — the number of grains that Nastya counted and $$$a, b, c, d$$$ $$$(0 \leq b < a \leq 1000, 0 \leq d < c \leq 1000)$$$  — numbers that determine the possible weight of one grain of rice (from $$$a - b$$$ to $$$a + b$$$) and the possible total weight of the package (from $$$c - d$$$ to $$$c + d$$$).

For each test case given in the input print "Yes", if the information about the weights is not inconsistent, and print "No" if $$$n$$$ grains with masses from $$$a - b$$$ to $$$a + b$$$ cannot make a package with a total mass from $$$c - d$$$ to $$$c + d$$$.

NoteIn the first test case of the example, we can assume that each grain weighs $$$17$$$ grams, and a pack $$$119$$$ grams, then really Nastya could collect the whole pack.In the third test case of the example, we can assume that each grain weighs $$$16$$$ grams, and a pack $$$128$$$ grams, then really Nastya could collect the whole pack.In the fifth test case of the example, we can be assumed that $$$3$$$ grains of rice weigh $$$2$$$, $$$2$$$, and $$$3$$$ grams, and a pack is $$$7$$$ grams, then really Nastya could collect the whole pack.In the second and fourth test cases of the example, we can prove that it is impossible to determine the correct weight of all grains of rice and the weight of the pack so that the weight of the pack is equal to the total weight of all collected grains.

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, a, b, c, d) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val l = n * (a - b)
    val r = n * (a + b)

    if (r >= c - d && l <= c + d) println("YES")
    else println("NO")
  }
}

object App {
  def main(args: Array[String]): Unit = {
    val t = scala.io.StdIn.readInt()
    (for (i <- 1 to t) yield {
      val Array(n, a, b, c, d): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val grLeft = (a - b) * n
      val grRight = (a + b) * n
      grLeft <= (c + d) && grRight >= (c - d)
    }).map(x => {
      if (x) "YES"
      else "NO"
    }).foreach{
      println(_)
    }
  }
}


This is a harder version of the problem. In this version $$$n \le 500\,000$$$The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $$$n$$$ plots along the highway and is preparing to build $$$n$$$ skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from $$$1$$$ to $$$n$$$. Then if the skyscraper on the $$$i$$$-th plot has $$$a_i$$$ floors, it must hold that $$$a_i$$$ is at most $$$m_i$$$ ($$$1 \le a_i \le m_i$$$). Also there mustn't be integers $$$j$$$ and $$$k$$$ such that $$$j < i < k$$$ and $$$a_j > a_i < a_k$$$. Plots $$$j$$$ and $$$k$$$ are not required to be adjacent to $$$i$$$.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 500\,000$$$) — the number of plots. The second line contains the integers $$$m_1, m_2, \ldots, m_n$$$ ($$$1 \leq m_i \leq 10^9$$$) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.

Print $$$n$$$ integers $$$a_i$$$ — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them.

NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer $$$[10, 6, 6]$$$ is optimal. Note that the answer of $$$[6, 6, 8]$$$ also satisfies all restrictions, but is not optimal.

import scala.annotation.tailrec
import scala.io.StdIn
import scala.math.min

object Contest1313C2 {

  def floorsToTheLeft(m: Array[Long]): Vector[Long] = {
    @tailrec
    def findNext(r: Vector[Int], i: Int): Int = if (i < 0 || m(i) < m(r.length)) i else findNext(r, r(i))

    val closestLowerOnTheLeft = m.foldLeft(Vector.empty[Int]) {
      case (r, _) => r :+ findNext(r, r.length - 1)
    }
    closestLowerOnTheLeft.foldLeft(Vector.empty[Long]) {
      case (v, next) => v :+ (m(v.length) * (v.length - next) + (if (next < 0) 0 else v(next)))
    }
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toLong
    val m = StdIn.readLine().trim.split("\\s+").map(_.toLong)
    val vLeft = floorsToTheLeft(m)
    val vRight = floorsToTheLeft(m.reverse).reverse
    val center = (vLeft, vRight, m).zipped.map( _ + _  - _).zipWithIndex.maxBy(_._1)._2
    val result = m.take(center).scanRight(m(center))(min) ++ m.drop(center + 1).scanLeft(m(center))(min).drop(1)
    println(result.mkString(" "))
  }
}

import scala.annotation.tailrec
import scala.io.StdIn

object Contest1313C2 {

  def floorsToTheLeft(m: Array[Long]): Vector[Long] = {
    val closestLowerOnTheLeft = m.foldLeft(Vector.empty[Int]) {
      case (r, _) =>
        @tailrec
        def findNext(i: Int): Int = {
          val j = if (r.length > i) r(i) else i - 1
          if (j < 0 || m(j) < m(r.length)) j else findNext(j)
        }

        r :+ findNext(r.length)
    }
    closestLowerOnTheLeft.foldLeft(Vector.empty[Long]) {
      case (v, next) => v :+ (m(v.length) * (v.length - next) + (if (next < 0) 0 else v(next)))
    }
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toLong
    val m = StdIn.readLine().trim.split("\\s+").map(_.toLong)
    val vLeft: Vector[Long] = floorsToTheLeft(m)
    val vRight = floorsToTheLeft(m.reverse).reverse
    val center = (vLeft, vRight, m).zipped.map(_ + _ - _).zipWithIndex.maxBy(_._1)._2
    val result = m.take(center).foldRight(Vector(m(center))) { case (mi, v) => math.min(mi, v.head) +: v } ++
      m.drop(center + 1).foldLeft(Vector(m(center))) { case (v, mi) => v :+ math.min(v.last, mi) }.drop(1)
    println(result.mkString(" "))
  }
}

import scala.util.Random

case class SparseTable(blockSize: Int, blocks: Array[Int])

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val n = stdin.next().toInt
//  val n = 44905
  val data = stdin.next().split(' ').map(_.toLong)
//  val r = new Random(12)
//  val data = (0 until n).map(i =>  Math.abs(i).toLong).toArray
  var preparedArray = prepare(data)

  val heights = Array.ofDim[Long](n)

  val s1 = solve(data)
  println(heights.mkString(" "))

  def prepare(data: Array[Long]): SparseTable = {
    val blockSize = Math.sqrt(data.length).toInt
    SparseTable(blockSize, data.grouped(blockSize)
      .zipWithIndex.map(pair => pair._1.indices.minBy(i => pair._1(i)) + pair._2 * blockSize).toArray)
  }

  def solve(data: Array[Long])  {
    solve(data, 0, data.length - 1)
  }

  def solve(data: Array[Long], l: Int, r: Int)  {
    if (l > r) 0
    else if (l == r) {
      heights(l) = data(l)
      data(l)
    }
    else {
      val minIndex = calcMinIndex(preparedArray, data, l, r)
      val leftElements = minIndex - l
      val rightElements = r - minIndex
      if (leftElements > rightElements) { // we have moreElements on the left side, lets minimize right
        (minIndex to r).foreach(i => heights(i) = data(minIndex))
        solve(data, l, minIndex - 1)
      }
      else {
        (l to minIndex).foreach(i => heights(i) = data(minIndex))
        solve(data, minIndex + 1, r)
      }
    }
  }

  def calcMinIndex(sparseTable: SparseTable, data: Array[Long], l: Int, r: Int): Int = {
    val firstBlock = l / sparseTable.blockSize + (if (l % sparseTable.blockSize == 0) 0 else 1)
    val lastBlock = r / sparseTable.blockSize - (if (r % sparseTable.blockSize == (sparseTable.blockSize - 1)) 0 else 1)
    var minValue = Long.MaxValue
    var index = l
    if (firstBlock <= lastBlock) {
      val minIndex = sparseTable.blocks((firstBlock to lastBlock).minBy(blockIndex => data(sparseTable.blocks(blockIndex))))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    if (l <= Math.min(r, (firstBlock) * sparseTable.blockSize)) {
      val minIndex = (l to Math.min(r, (firstBlock) * sparseTable.blockSize)).minBy(i => data(i))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    if (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) <= r) {
      val minIndex = (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) to r).minBy(i => data(i))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    index
  }
}

import scala.util.Random

case class SparseTable(blockSize: Int, blocks: Array[Int])

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  //val n = stdin.next().toInt
  val n = 9
//  val data = stdin.next().split(' ').map(_.toLong).toList
  val r = new Random(2)
  val data = (0 until n).map(_ =>  Math.abs(r.nextInt()).toLong).toList
  var preparedArray = prepare(data)

  val heights = Array.ofDim[Long](n)

  val s1 = solve(data)
  println(heights.mkString(" "))

  def prepare(data: List[Long]): SparseTable = {
    val blockSize = Math.sqrt(data.length).toInt
    SparseTable(blockSize, data.grouped(blockSize)
      .zipWithIndex.map(pair => pair._1.indices.minBy(i => pair._1(i)) + pair._2 * blockSize).toArray)
  }

  def solve(data: List[Long]): Long = {
    solve(data, 0, data.length - 1)
  }

  def solve(data: List[Long], l: Int, r: Int): Long = {
    if (l > r) 0
    else if (l == r) {
      heights(l) = data(l)
      data(l)
    }
    else {
      val minIndex = calcMinIndex(preparedArray, data, l, r)
      val calculateLeft = solve(data, l, minIndex - 1)
      val calculateRight = solve(data, minIndex + 1, r)
      val leftSum = calculateLeft + (r - minIndex + 1) * data(minIndex)
      val rightSum = calculateRight + (minIndex - l + 1) * data(minIndex)
      if (leftSum > rightSum) {
        (minIndex to r).foreach(i => heights(i) = data(minIndex))
        leftSum
      } else {
        (l to minIndex).foreach(i => heights(i) = data(minIndex))
        rightSum
      }
    }
  }

  def calcMinIndex(sparseTable: SparseTable, data: List[Long], l: Int, r: Int): Int = {
    val firstBlock = l / sparseTable.blockSize + (if (l % sparseTable.blockSize == 0) 0 else 1)
    val lastBlock = r / sparseTable.blockSize - (if (r % sparseTable.blockSize == (sparseTable.blockSize - 1)) 0 else 1)
    var minValue = Long.MaxValue
    var index = l
    if (firstBlock <= lastBlock) {
      val minIndex = sparseTable.blocks((firstBlock to lastBlock).minBy(blockIndex => data(sparseTable.blocks(blockIndex))))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    if (l <= Math.min(r, (firstBlock) * sparseTable.blockSize)) {
      val minIndex = (l to Math.min(r, (firstBlock) * sparseTable.blockSize)).minBy(i => data(i))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    if (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) <= r) {
      val minIndex = (Math.max(l, (lastBlock + 1) * sparseTable.blockSize) to r).minBy(i => data(i))
      if (data(minIndex) < minValue) {
        minValue = data(minIndex)
        index = minIndex
        if (index < l || index > r) {
          throw new Exception("lol")
        }
      }
    }
    index
  }
}

import scala.annotation.tailrec
import scala.io.StdIn

object Contest1313C2 {

  def floorsToTheLeft(m: Array[Int]): Vector[Int] = {
    val closestLowerOnTheLeft = m.foldLeft(Vector.empty[Int]) {
      case (r, _) =>
        @tailrec
        def findNext(i: Int): Int = {
          val j = if (r.length > i) r(i) else i - 1
          if (j < 0 || m(j) < m(r.length)) j else findNext(j)
        }

        r :+ findNext(r.length)
    }
    closestLowerOnTheLeft.foldLeft(Vector.empty[Int]) {
      case (v, next) => v :+ (m(v.length) * (v.length - next) + (if (next < 0) 0 else v(next)))
    }
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val m = StdIn.readLine().trim.split("\\s+").map(_.toInt)
    val vLeft: Vector[Int] = floorsToTheLeft(m)
    val vRight = floorsToTheLeft(m.reverse).reverse
    val center = (vLeft, vRight, m).zipped.map(_ + _ - _).zipWithIndex.maxBy(_._1)._2
    val result = m.take(center).foldRight(Vector(m(center))) { case (mi, v) => math.min(mi, v.head) +: v } ++
      m.drop(center + 1).foldLeft(Vector(m(center))) { case (v, mi) => v :+ math.min(v.last, mi) }.drop(1)
    println(result.mkString(" "))
  }
}


An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full.Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000"  →  "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address.Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below:  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::";  "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0";  "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0";  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000";  "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.You've got several short records of IPv6 addresses. Restore their full record.

The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.

For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.

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

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

  val n = sc.nextInt()

  for (_ <- 0 until n) {
    val ipv6 = InetAddress.getByName(sc.next).getHostAddress.split(":")
    println(ipv6.map(_.reverse.padTo(4, '0').reverse).mkString(":"))
  }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val n=readInt
    for(_<-1 to n){
        println(solve(readLine))
    }

    def solveone(str:String):String={
       val list=str.split(":")
       for(i<-0 until list.size)
           list(i)="0"*(4-list(i).size)+list(i)

       list.mkString(":")
    }

    def solve(str:String):String={
        val p=str.indexOfSlice("::");
        if(p>=0){
            val left=solveone(str.substring(0,p))
            val right=solveone(str.substring(p+2))
            val count=8-(left.size+right.size+2)/5
            left+":0000"*count+":"+right
        }
        else solveone(str)
    }
}

object Main extends App {

  import scala.io.{Source, StdIn}

  override def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    for (_ <- 1 to n) {
      val s = StdIn.readLine()
      var arr = s.split(":")
      if (s.startsWith("::")) arr = arr.drop(1)
      if (arr.length != 8 && !arr.contains("")) arr = arr ++ Seq("")
      val res = arr.map(
        part =>
          if (part.isEmpty) {
            "0000:" * (9 - arr.length)
          }
          else {
            ("0" * (4 - part.length) + part) + ":"
          }

      )
      println(res.mkString("").dropRight(1))
    }
  }
}

object Main extends App {

  import scala.io.{Source, StdIn}

  override def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    for (_ <- 1 to n) {
      val s = StdIn.readLine()
      var arr = s.split(":")
      if (arr.length != 8 && !arr.contains("")) arr = arr ++ Seq("")
      val res = arr.map(
        part =>
          if (part.isEmpty) {
            "0000:" * (9 - arr.length)
          }
          else {
            ("0" * (4 - part.length) + part) + ":"
          }
      )
      println(res.mkString("").dropRight(1))
    }
  }
}


Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.

The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.

Print "YES", if the dwarves belong to the same race. Otherwise, print "NO".

Note  First example: you can simply swap two letters in string "ab". So we get "ba".  Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b".

object Main {
  def main(args: Array[String]) {
    val s1 = readLine()
    val s2 = readLine()
    if (s1.size != s2.size) println("NO")
    else {
      val zipped = s1.zip(s2).zipWithIndex
      val filtered = zipped.filter(t => t._1._1 != t._1._2)
      if (filtered.size != 2) println("NO")
      else {
        val t1 = filtered(0)
        val t2 = filtered(1)
        if (t1._1._1 == t2._1._2 && t2._1._1 == t1._1._2) println("YES")
        else println("NO")
      }
    }
  }
}

import com.sun.org.apache.xpath.internal.operations.Bool

/**
 * Created with IntelliJ IDEA.
 * User: Oleg
 * Date: 10.05.12
 * Time: 1:24
 * To change this template use File | Settings | File Templates.
 */

object A {
  val s1, s2 = readLine
  val (yes, no) = ("YES", "NO")

  def main(args: Array[String]) {
    println(good)
  }

  def good: String = {
    if (s1.length != s2.length) return no
    val inequality: (Int => Boolean) = (i => (s1(i) != s2(i)))
    val first = (0 until s1.length) find inequality
    val last = ((s1.length - 1) to 0 by -1) find inequality
    (first, last) match {
      case (Some(first), Some(last)) if first != last => {
        if (s1.substring(first + 1, last) != s2.substring(first + 1, last)) return no
        if (s1(first) != s2(last)) return no
        if (s1(last) != s2(first)) return no
        return yes
      }
      case _ => return no
    }
  }
}

object Solution extends App {

  def compare(str1: List[Char], str2: List[Char], change1: Option[Char], change2: Option[Char], changed: Boolean): Boolean =
    if (str1.isEmpty && str2.isEmpty)
      change1.isEmpty
    else if (str1.head == str2.head)
      compare(str1.tail, str2.tail, change1, change2, changed)
    else if (changed)
      false
    else if (change1.isEmpty)
      compare(str1.tail, str2.tail, Some(str1.head), Some(str2.head), changed)
    else if (change1.get == str2.head && change2.get == str1.head)
      compare(str1.tail, str2.tail, None, None, true)
    else false

  val in = scala.io.Source.stdin.getLines()
  val str1 = in.next()
  val str2 = in.next()
  if (str1.length == str2.length && compare(str1.toCharArray.toList,
    str2.toCharArray.toList, None, None, false)) println("YES")
  else println("NO")
}

object A
{
  def main(args: Array[String])
  {
    val str1 = readLine.toCharArray
    val str2 = readLine.toCharArray

    if(str1.length != str2.length) println("NO")
    else
    {
      val n = str1.length
      if((0 until n).count(i => str1(i)!=str2(i)) != 2) println("NO")
      else
      {
        var firstFound = false
        var car1 = ' '
        var car2 = ' '
        for(i <- 0 until n)
        {
          if(str1(i)!=str2(i))
          {
            if(!firstFound)
            {
              car1 = str1(i)
              car2 = str2(i)
              firstFound = true
            }
            else
            {
              if(car1==str2(i) && car2==str1(i)) println("YES")
              else println("NO")
            }
          }
        }
      }
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val s1 = readLine()
    val s2 = readLine()
    if (s1.size != s2.size) println("NO")
    else {
      val zipped = s1.zip(s2).zipWithIndex
      val filtered = zipped.filter(t => t._1._1 != t._1._2)
      if (filtered.size != 2) println("NO")
      else {
        val t1 = filtered(0)
        val t2 = filtered(1)
        if (t1._2 + 1 != t2._2) println("NO")
        else if (t1._1._1 == t2._1._2 && t2._1._1 == t1._1._2) println("YES")
        else println("NO")
      }
    }
  }
}


Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p1 = 1, p2, ..., pk is equal to  units of energy.Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the ith of them allows walking from intersection i to intersection ai (i ≤ ai ≤ ai + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p1 = 1, p2, ..., pk then for each 1 ≤ i < k satisfying pi + 1 = api and api ≠ pi Mike will spend only 1 unit of energy instead of |pi - pi + 1| walking from the intersection pi to intersection pi + 1. For example, if Mike chooses a sequence p1 = 1, p2 = ap1, p3 = ap2, ..., pk = apk - 1, he spends exactly k - 1 units of total energy walking around them.Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p1 = 1, p2, ..., pk = i.

The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection. The second line contains n integers a1, a2, ..., an (i ≤ ai ≤ n , , describing shortcuts of Mike's city, allowing to walk from intersection i to intersection ai using only 1 unit of energy. Please note that the shortcuts don't allow walking in opposite directions (from ai to i).

In the only line print n integers m1, m2, ..., mn, where mi denotes the least amount of total energy required to walk from intersection 1 to intersection i.

NoteIn the first sample case desired sequences are:1: 1; m1 = 0;2: 1, 2; m2 = 1;3: 1, 3; m3 = |3 - 1| = 2.In the second sample case the sequence for any intersection 1 < i is always 1, i and mi = |1 - i|.In the third sample case — consider the following intersection sequences:1: 1; m1 = 0;2: 1, 2; m2 = |2 - 1| = 1;3: 1, 4, 3; m3 = 1 + |4 - 3| = 2;4: 1, 4; m4 = 1;5: 1, 4, 5; m5 = 1 + |4 - 5| = 2;6: 1, 4, 6; m6 = 1 + |4 - 6| = 3;7: 1, 4, 5, 7; m7 = 1 + |4 - 5| + 1 = 3.

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val dp = Array.fill(n+1)(Int.MaxValue)
    dp(0) = -1
    dp(1) = 0
    for(i <- 1 to n-1){
      val now = dp(i)
      dp(i+1) = Math.min(dp(i+1), now + 1)
      var sho = a(i)
      dp(sho) = Math.min(dp(sho), now + 1)
      var flag = true
      while(flag){
        // println(sho)
        if(dp(sho-1) > dp(sho) + 1){
          dp(sho-1) = dp(sho) + 1
          sho -= 1
        }
        else
          flag = false
      }
    }

    //
    print(dp(1))
    for(i <- 2 to n)
      print(" " + dp(i))
    println()
  }
}

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

object B extends App {
  class Node {
    val conn = new mutable.HashSet[Int]
  }

  val n = readInt()
  val A = Array(Integer.MIN_VALUE) ++ readLine().split(" ").map(_.toInt)
  val G = Array.fill(n + 1)(new Node)

  for (i <- 1 to n) {
    val next = if (i < n) i + 1 else 1
    if (i < n) {
      G(i).conn += next
      G(next).conn += i
    }
    if (i != A(i)) {
      G(i).conn += A(i)
    }
//    println(i + " -> " + G(i).conn.mkString(","))
  }

  val visited = Array.fill(n + 1)(false)
  val cost = Array.fill(n + 1)(0)
  visited(1) = true

  val Q = new mutable.Queue[Int]
  Q.enqueue(1)

  while (Q.nonEmpty) {
    val curr = Q.dequeue()
    visited(curr) = true

    for (next <- G(curr).conn) {
      if (!visited(next)) {
        visited(next) = true
        cost(next) = cost(curr) + 1
        Q.enqueue(next)
      }
    }
  }

  println(cost.tail.mkString(" "))
}

object main
{
	def main ( args : Array[String] )
	{
		var n = Console.readLine().toInt;
		var str = Console.readLine();
		var to = new Array[Int](200010);
		var que = new Array[Int](200010);
		var dist = new Array[Int](200010);
		var now = 0;
		for ( a <- 0 to str.length()-1 )
		{
			if (str.charAt(a) == ' ') now = now + 1;
			else to(now) = to(now) * 10 + str.charAt(a) - '0';
		}

		for ( a <- 0 to n-1 )
		{
			dist(a) = -1;
			to(a) -= 1;
		}
		dist(0)=0;
		var front = 0;
		var tail = 0;
		while (front<=tail)
		{
			var now = que(front);
			front += 1;
			if (now > 0 && dist(now-1) == -1)
			{
				tail += 1;
				que(tail) = now-1;
				dist(now-1) = dist(now) + 1;
			}
			if (now < n-1 && dist(now+1) == -1)
			{
				tail += 1;
				que(tail) = now+1;
				dist(now+1) = dist(now) + 1;
			}
			if (dist(to(now)) == -1)
			{
				tail += 1;
				que(tail) = to(now);
				dist(to(now)) = dist(now) + 1;
			}
		}
		for ( a <- 0 to n-1)
		{
			print(dist(a));
			if (a==n-1) println();
			else print(" ");
		}
	}
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

/**
  * @author Baidin Dima
  */
object MikeAndShortcuts extends App {

  case class Edge(to: Int, w: Int)

  def readInput(): Array[ArrayBuffer[Edge]] = {
    val intersectionCount = scala.io.StdIn.readInt()

    val adjacencyList: Array[ArrayBuffer[Edge]] = new Array(intersectionCount)

    val shortcuts = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    adjacencyList.indices.foreach { case i ⇒
      val to = shortcuts(i)
      adjacencyList(i) = ArrayBuffer(Edge(to - 1, 1))
      if (i != intersectionCount - 1) {
        adjacencyList(i) += Edge(i + 1, 1)
      }
      if (i != 0) {
        adjacencyList(i) += Edge(i - 1, 1)
      }
    }
    adjacencyList
  }

  def dijkstra(adjacencyList: Array[ArrayBuffer[Edge]]): Unit = {
    val visited: Array[Boolean] = new Array(adjacencyList.length);
    visited(0) = true
    val distance: Array[Int] = new Array(adjacencyList.length);
    distance(0) = 0

    implicit val edgeOrdering: Ordering[Edge] = new Ordering[Edge] {
      override def compare(x: Edge, y: Edge): Int = y.w - x.w
    }

    val q: mutable.PriorityQueue[Edge] = new mutable.PriorityQueue[Edge]()

    adjacencyList(0).foreach { case edge ⇒ q += edge }

    while (q.nonEmpty) {
      val edge = q.dequeue()

      if (!visited(edge.to)) {
        visited(edge.to) = true
        distance(edge.to) = edge.w

        adjacencyList(edge.to).foreach(nEdge ⇒
          q += Edge(nEdge.to, edge.w + nEdge.w)
        )
      }
    }

    println(distance.mkString(" "))
  }

  dijkstra(readInput())

}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val a = new Array[Int](n+1)
    for(i <- 1 to n)
      a(i) = sc.nextInt()

    val dp = Array.fill(n+1)(Int.MaxValue)
    dp(1) = 0
    for(i <- 1 to n-1){
      val now = dp(i)
      dp(i+1) = Math.min(dp(i+1), now + 1)
      val sho = a(i)
      dp(sho) = Math.min(dp(sho), now + 1)
    }

    for(i <- (1 to n-1).reverse){
      if(dp(i) > dp(i+1) + 1)
        dp(i) = dp(i+1) + 1
    }

    //
    print(dp(1))
    for(i <- 2 to n)
      print(" " + dp(i))
    println()
  }
}

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

object B extends App {
  class Node {
    val conn = new mutable.ArrayBuffer[Int]
  }

  val n = readInt()
  val A = Array(Integer.MIN_VALUE) ++ readLine().split(" ").map(_.toInt)
  val G = Array.fill(n + 1)(new Node)

  for (i <- 1 to n) {
    val next = if (i < n) i + 1 else 1
    G(i).conn += next
    if (next != A(i) && A(i) != i) G(i).conn += A(i)
//    println(i + " -> " + G(i).conn.mkString(","))
  }

  val visited = Array.fill(n + 1)(false)
  val cost = Array.fill(n + 1)(0)
  visited(1) = true

  val Q = new mutable.Queue[Int]
  Q.enqueue(1)

  while (Q.nonEmpty) {
    val curr = Q.dequeue()
    visited(curr) = true

    for (next <- G(curr).conn) {
      if (!visited(next)) {
        visited(next) = true
        cost(next) = cost(curr) + 1
        Q.enqueue(next)
      }
    }
  }

  println(cost.tail.mkString(" "))
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

/**
  * @author Baidin Dima
  */
object MikeAndShortcuts extends App {

  case class Edge(to: Int, w: Int)

  def readInput(): Array[ArrayBuffer[Edge]] = {
    val intersectionCount = scala.io.StdIn.readInt()

    val adjacencyList: Array[ArrayBuffer[Edge]] = new Array(intersectionCount)

    val shortcuts = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    adjacencyList.indices.foreach { case i ⇒
      val to = shortcuts(i)
      adjacencyList(i) = ArrayBuffer(Edge(to - 1, 1))
      if (i != intersectionCount - 1) {
        adjacencyList(i) += Edge(i + 1, 1)
      }
    }
    adjacencyList
  }

  def dijkstra(adjacencyList: Array[ArrayBuffer[Edge]]): Unit = {
    val visited: Array[Boolean] = new Array(adjacencyList.length); visited(0) = true
    val distance: Array[Int] = new Array(adjacencyList.length); distance(0) = 0

    implicit val edgeOrdering: Ordering[Edge] = new Ordering[Edge] {
      override def compare(x: Edge, y: Edge): Int = x.w - y.w
    }

    val q: mutable.PriorityQueue[Edge]= new mutable.PriorityQueue[Edge]()

    adjacencyList(0).foreach{case edge ⇒ q += edge}

    while (q.nonEmpty) {
      val edge = q.dequeue()

      if (!visited(edge.to)) {
        visited(edge.to) = true
        distance(edge.to) = edge.w

        adjacencyList(edge.to).foreach(nEdge ⇒
          q += Edge(nEdge.to, edge.w + nEdge.w)
        )
      }
    }

    println(distance.mkString(" "))
  }

  dijkstra(readInput())

}


Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.

The first input line contains a non-empty string s1. The second input line contains a non-empty string s2. Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.

Print the number of common divisors of strings s1 and s2.

NoteIn first sample the common divisors are strings "abcd" and "abcdabcd".In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa".

import scala.io.StdIn

/**
 * @author chengyi
 */
object CommonDivisors {

  //common divisor for string
  def cd(s1:String, s2:String):Int={
    val smin = if (s1.length()>s2.length()) s2 else s1
    val smax = if (s1.length()>s2.length()) s1 else s2
    val sminl = smin.length()
    val smaxl = smax.length()
    val sqrt:Float = Math.sqrt(sminl).toFloat
    var rnd:Int = Math.round(sqrt)
    if (sqrt < rnd){
      rnd = rnd -1
    }
    var tryList:List[Int] = List()
    (1 to rnd).map{
      x=> if (sminl % x==0){
            if (!tryList.contains(sminl/x))
              tryList = tryList.::(sminl/x)
            if (!tryList.contains(x))
              tryList = tryList:+x
          }
    }
    tryList = tryList.sorted(Ordering[Int].reverse)
    //println(tryList)
    var num:Int =0
    for (a<-0 to tryList.length-1){
      val tryLen = tryList(a)
      if (smaxl % tryLen == 0){
        val maxrp = smaxl / tryLen
        val minrp = sminl / tryLen
        val substr = smin.substring(0, tryLen)
        if (smax.equals(List.fill(maxrp)(substr).mkString("")) && smin.equals(List.fill(minrp)(substr).mkString("")))
          num = num + 1
      }
    }
    num
  }

  def main(args:Array[String]){
    val s1=StdIn.readLine()
    val s2=StdIn.readLine()
    println(cd(s1,s2))
  }

}

import scala.io.StdIn

/**
 * @author chengyi
 */
object CommonDivisors {

  //common divisor for string
  def cd(s1:String, s2:String):Int={
    val smin = if (s1.length()>s2.length()) s2 else s1
    val smax = if (s1.length()>s2.length()) s1 else s2
    val sminl = smin.length()
    val smaxl = smax.length()
    val sqrt:Float = Math.sqrt(sminl).toFloat
    var rnd:Int = Math.round(sqrt)
    if (sqrt < rnd){
      rnd = rnd -1
    }
    var tryList:List[Int] = List()
    (1 to rnd).map{
      x=> if (sminl % x==0){
            tryList = tryList.::(sminl/x)
            tryList = tryList:+x
          }
    }
    tryList = tryList.sorted(Ordering[Int].reverse)
    //println(tryList)
    var num:Int =0
    for (a<-0 to tryList.length-1){
      val tryLen = tryList(a)
      if (smaxl % tryLen == 0){
        val maxrp = smaxl / tryLen
        val minrp = sminl / tryLen
        val substr = smin.substring(0, tryLen)
        if (smax.equals(List.fill(maxrp)(substr).mkString("")) && smin.equals(List.fill(minrp)(substr).mkString("")))
          num = num + 1
      }
    }
    num
  }

  def main(args:Array[String]){
    val s1=StdIn.readLine()
    val s2=StdIn.readLine()
    println(cd(s1,s2))
  }

}

import scala.io.StdIn

/**
 * @author chengyi
 */
object CommonDivisors {

  //common divisor for string
  def cd(s1:String, s2:String):Int={
    val smin = if (s1.length()>s2.length()) s2 else s1
    val smax = if (s1.length()>s2.length()) s1 else s2
    val sminl = smin.length()
    val smaxl = smax.length()
    val sqrt:Float = Math.sqrt(sminl).toFloat
    var rnd:Int = Math.round(sqrt)
    if (sqrt < rnd){
      rnd = rnd -1
    }
    var tryList:List[Int] = List()
    (1 to rnd).map{
      x=> if (sminl % x==0){
            tryList = tryList.::(sminl/x)
            tryList = tryList:+x
          }
    }
    tryList = tryList.sorted(Ordering[Int].reverse)
    println(tryList)
    var num:Int =0
    for (a<-0 to tryList.length-1){
      val tryLen = tryList(a)
      if (smaxl % tryLen == 0){
        val maxrp = smaxl / tryLen
        val minrp = sminl / tryLen
        val substr = smin.substring(0, tryLen)
        if (smax.equals(List.fill(maxrp)(substr).mkString("")) && smin.equals(List.fill(minrp)(substr).mkString("")))
          num = num + 1
      }
    }
    num
  }

  def main(args:Array[String]){
    val s1=StdIn.readLine()
    val s2=StdIn.readLine()
    println(cd(s1,s2))
  }

}


This is yet another problem dealing with regular bracket sequences.We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.

The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.

Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".

object main extends App with fastIO {

  val s = " " + readLine
  val n = s.length - 1

  var a: Array[Int] = s.toArray.map( (c) => if (c == '(') 1 else -1 )

  a(0) = 0
  for (i <- 1 to n) a(i) += a(i - 1)
  a = a.map(_ + n)

  var first = Array.fill(2 * n + 1)(n + 1)
  var ans = for (i <- 1 to n) yield {
    s(i) match {
      case '(' => if (first(a(i - 1)) == n + 1) first(a(i - 1)) = i
      case ')' => first(a(i - 1)) = n + 1
    }
    i - first(a(i)) + 1
  }

  val answer = ans.max max 0
  print(answer + " " + ans.count(_ == answer))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object P5C {
    def main(args: Array[String]) {
        val s = readLine
        val n = s.size
        val a = Array.fill(n + n + 1){n}
        var d = n
        val answer = for (i <- 0 until n) yield {
            s(i) match {
                case '(' => {
                    if (a(d) == n) a(d) = i
                    d = d + 1
                }
                case ')' => {
                    a(d) = n
                    d = d - 1
                }
            }
            i - a(d) + 1
        }
        val m = answer.max max 0
        println(m + " " + answer.count{_ == m})
    }
}

object C {
  def main(args: Array[String]) = {
    lazy val input = io.StdIn.readLine zip (0 until Int.MaxValue)
    def insert(list: List[(Int, Int)], pair: (Int, Int)): List[(Int, Int)] = list match {
      case Nil => pair::Nil
      case head::tail =>
        if (head._1 > pair._1 && head._2 < pair._2) insert(tail, pair)
        else if (head._2 == pair._1 - 1) (head._1, pair._2)::tail
        else pair::list
    }
    def foldMethod(lists: (List[Int], List[(Int, Int)]), ch: (Char, Int)): (List[Int], List[(Int, Int)]) = lists match {
      case (opens, pairs) =>
        if(ch._1 == '(') (ch._2::opens, pairs)
        else if(opens.isEmpty) (opens, pairs)
        else (opens.tail, insert(pairs, (opens.head, ch._2)))
    }
    lazy val folded = input.foldLeft((List[Int](), List[(Int, Int)]()))(foldMethod)._2.map(p => p._2 - p._1 + 1)
    lazy val maxi   = if (folded.isEmpty) 0 else folded.max
    lazy val count  = if (folded.isEmpty) 1 else folded.count(_ == maxi)

    println(maxi + " " + count)
  }
}

import java.util
import java.util.Scanner

object CBalancedBraces extends App {

  val scanner = new Scanner(System.in)

  val input = scanner.next()
  val stack = new util.Stack[Int]

  var max = 0
  var maxNum = 0

  stack.push(-1)

  input.zipWithIndex foreach {
    item =>
      item._1 match {
        case '(' => stack.push(item._2)
        case ')' =>
          if (!stack.empty()) {
            stack.pop()
            if (!stack.empty()) {
              recordResult(item._2, stack.peek())
            }
          }
          if (stack.empty()) {
            stack.push(item._2)
          }

      }
  }

  if (max == 0) {
    println("0 1")
  } else {
    print(max + " ")
    println(maxNum)
  }

  def recordResult(start: Int, end: Int): Unit = {
    val item = start - end
    if (max < item) {
      max = item
      maxNum = 1
    } else if (max == item) maxNum += 1
  }

}

object C5 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    val d = Array.fill(str.length)(-1) // pos of corresponding open bracket
    val c = Array.fill(str.length)(-1) // pos of earliest open bracket, str(c(i), i) is regular
    val stack = new cu.Stack[Int]
    var i = 0
    while (i < str.length) {
      if (str(i) == '(') {
        stack.push(i)
      } else {
        if (stack.isEmpty) {
          d(i) = -1
          c(i) = -1
        } else {
          val top = stack.pop()
          d(i) = top
          c(i) = d(i)
          if (d(i) - 1 >= 0 && str(d(i) - 1) == ')' && c(d(i) - 1) != -1) {
            c(i) = c(d(i) - 1)
          }
        }
      }
      i += 1
    }
    i = 0
    var max = 0
    var count = 0
    while (i < str.length) {
      if (c(i) != -1)
        if (max < i - c(i) + 1) {
          count = 1
          max = i - c(i) + 1
        } else if (max == i - c(i) + 1) {
          count += 1
        }
      i += 1
    }
    if (max == 0) {
      out.println("0 1")
    } else {
      out.println(s"${max} ${count}")
    }
    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))
    }
  }

}

object C5 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    val d = Array.fill(str.length)(-1) // pos of corresponding open bracket
    val c = Array.fill(str.length)(-1) // pos of earliest open bracket, str(c(i), i) is regular
    val stack = new java.util.Stack[Int]
    var i = 0
    while (i < str.length) {
      if (str(i) == '(') {
        stack.push(i)
      } else {
        if (stack.isEmpty) {
          d(i) = -1
          c(i) = -1
        } else {
          val top = stack.pop()
          d(i) = top
          c(i) = d(i)
          if (d(i) - 1 >= 0 && str(d(i) - 1) == ')' && c(d(i) - 1) != -1) {
            c(i) = c(d(i) - 1)
          }
        }
      }
      i += 1
    }
    i = 0
    var max = 0
    var count = 0
    while (i < str.length) {
      if (c(i) != -1)
        if (max < i - c(i) + 1) {
          count = 1
          max = i - c(i) + 1
        } else if (max == i - c(i) + 1) {
          count += 1
        }
      i += 1
    }
    if (max == 0) {
      out.println("0 1")
    } else {
      out.println(s"${max} ${count}")
    }
    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))
    }
  }

}

object C5 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    val d = Array.fill(str.length)(-1) // pos of corresponding open bracket
    val c = Array.fill(str.length)(-1) // pos of earliest open bracket, str(c(i), i) is regular
    val stack = new cu.Stack[Int]
    var i = 0
    while (i < str.length) {
      if (str(i) == '(') {
        stack.push(i)
      } else {
        if (stack.isEmpty) {
          d(i) = -1
          c(i) = -1
        } else {
          val top = stack.pop()
          d(i) = top
          c(i) = d(i)
          if (d(i) - 1 >= 0 && str(d(i) - 1) == ')' && c(d(i) - 1) != -1) {
            c(i) = c(d(i) - 1)
          }
        }
      }
      i += 1
    }
    val maxs = c.zipWithIndex.map {
      case (value, idx) => if (value != -1) idx - value + 1 else 0
    }
    val max = maxs.max
    if (max == 0) {
      out.println("0 1")
    } else {
      out.println(s"${max} ${maxs.count(_ == max)}")
    }
    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))
    }
  }

}

object main extends App with fastIO {

  val s = " " + readLine
  val n = s.length - 1

  var a: Array[Int] = s.toArray.map( (c) => if (c == '(') 1 else -1 )

  a(0) = 0
  for (i <- 1 to n) a(i) += a(i - 1)
  a = a.map(_ + n)

  var first = Array.fill(2 * n + 1)(n)
  var ans = for (i <- 1 to n) yield {
    s(i) match {
      case '(' => if (first(a(i - 1)) == n) first(a(i - 1)) = i
      case ')' => first(a(i - 1)) = n
    }
    i - first(a(i)) + 1
  }

  val answer = ans.max max 0
  print(answer + " " + ans.count(_ == answer))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object C {
  def main(args: Array[String]) = {
    lazy val input = io.StdIn.readLine zip (0 until Int.MaxValue)
    def insert(list: List[(Int, Int)], pair: (Int, Int)): List[(Int, Int)] = list match {
      case Nil => pair::Nil
      case head::tail =>
        if (head._1 > pair._1 && head._2 < pair._2) insert(tail, pair)
        else if (head._2 == pair._1 - 1) (head._1, pair._2)::tail
        else pair::list
    }
    def foldMethod(lists: (List[Int], List[(Int, Int)]), ch: (Char, Int)): (List[Int], List[(Int, Int)]) = lists match {
      case (opens, pairs) =>
        if(ch._1 == '(') (ch._2::opens, pairs)
        else if(opens.isEmpty) (opens, pairs)
        else (opens.tail, insert(pairs, (opens.head, ch._2)))
    }
    lazy val folded = input.foldLeft((List[Int](), List[(Int, Int)]()))(foldMethod)._2.map(p => {println(p); p._2 - p._1 + 1})
    lazy val maxi   = if (folded.isEmpty) 0 else folded.max
    lazy val count  = if (folded.isEmpty) 1 else folded.count(_ == maxi)

    println(maxi + " " + count)
  }
}

object C {
  def main(args: Array[String]) = {
    lazy val input = io.StdIn.readLine zip (0 until Int.MaxValue)
    def foldMethod(lists: (List[Int], List[Int]), ch: (Char, Int)): (List[Int], List[Int]) = lists match {
      case (opens, starts) =>
        if(ch._1 == '(') (ch._2::opens, -1::starts)
        else if(opens.isEmpty) (opens, -1::starts)
        else (opens.tail, opens.head::starts)
    }
    lazy val folded = input.foldLeft((List[Int](), List[Int]()))(foldMethod)._2.reverse
    def findStart(list: Vector[Int], index: Int): Vector[Int] = {
      if (index == -1) list :+ 0
      else if (index == 0) list :+ list.length
      else if (list(index - 1) != 0) list :+ (list.length - index + 1 + list(index - 1))
      else list :+ (list.length - index + 1)
    }
    lazy val result = folded.foldLeft(Vector.empty[Int])(findStart)
    lazy val maxi   = result.max
    lazy val count  = result.count(_ == maxi)

    if (maxi == 0) println("0 1")
    else println(maxi + " " + count)
  }
}

import java.util.Scanner

object CCorrectBraces extends App {

  val scanner = new Scanner(System.in)
  val input = scanner.next()

  var pointer = 0

  var max = 0
  var maxNum = 0

  start()

  if (max == 0) {
    println("0 1")
  } else {
    print(max + 1 + " ")
    println(maxNum)
  }

  def get: Char = input(pointer)

  def next: Char = {
    val res = get
    pointer += 1
    res
  }

  def eof(): Boolean = pointer >= input.size

  def start(): Unit = {
    while (!eof) {
      if (get == ')') next
      else parse()
    }
  }

  def parse(): Unit = {
    while (!eof && get == '(') {
      parseBraces()
    }
  }

  def parseBraces(): Unit = {
    if (!eof && get == '(') {
      val save = pointer
      next
      parse()
      if (!eof && get == ')') {
        recordResult(pointer - save)
        next
      } else if (!eof) {
        next
        parse()
      }
    }
  }

  def recordResult(item: Int): Unit = {
    if (max < item) {
      max = item
      maxNum = 1
    } else if (max == item) maxNum += 1
  }

}

import java.util.Scanner

object CCorrectBraces extends App {

  val scanner = new Scanner(System.in)
  val input = scanner.next()

  var pointer = 0

  var max = 0
  var maxNum = 0
  var streak = 0

  start()

  if (max == 0) {
    println("0 1")
  } else {
    print(max + " ")
    println(maxNum)
  }

  def get: Char = input(pointer)

  def next: Char = {
    val res = get
    pointer += 1
    res
  }

  def eof(): Boolean = pointer >= input.size

  def start(): Unit = {
    while (!eof) {
      if (get == ')')  {
        next
      }
      else parse()
    }
  }

  def parse(): Unit = {
    val save = pointer
    while (!eof && get == '(') {
      parseBraces()
    }
    if (pointer - save > 1) {
      recordResult(save)
    }
  }

  def parseBraces(): Unit = {
    if (!eof && get == '(') {
      val save = pointer
      next
      parse()
      if (!eof && get == ')') {
        //recordResult(save)
        next
      } else if (!eof) {
        next
        //parse()
      }
    }
  }

  def recordResult(save: Int): Unit = {
    val item = pointer - save
    if (max < item) {
      max = item
      maxNum = 1
    } else if (max == item) maxNum += 1
  }

}

import java.util.Scanner

object CCorrectBraces extends App {

  val scanner = new Scanner(System.in)
  val input = scanner.next()

  var pointer = 0

  var max = 0
  var maxNum = 0
  var streak = 0

  start()

  if (max == 0) {
    println("0 1")
  } else {
    print(max + 1 + " ")
    println(maxNum)
  }

  def get: Char = input(pointer)

  def next: Char = {
    val res = get
    pointer += 1
    res
  }

  def eof(): Boolean = pointer >= input.size

  def start(): Unit = {
    while (!eof) {
      if (get == ')')  {
        next
      }
      else parse()
    }
  }

  def parse(): Unit = {
    val save = pointer
    while (!eof && get == '(') {
      parseBraces()
    }
    if (pointer - save > 1) {
      recordResult(save)
    }
  }

  def parseBraces(): Unit = {
    if (!eof && get == '(') {
      val save = pointer
      next
      parse()
      if (!eof && get == ')') {
        //recordResult(save)
        next
      } else if (!eof) {
        next
        //parse()
      }
    }
  }

  def recordResult(save: Int): Unit = {
    val item = pointer - save
    if (max < item) {
      max = item
      maxNum = 1
    } else if (max == item) maxNum += 1
  }

}

object C5 {

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

  def main(args: Array[String]): Unit = {
    val str = read
    val count = cu.Map.empty[Int, Int].withDefaultValue(0)
    var maxLen = 0
    var openCount = 0
    var currLen = 0
    var i = 0
    while (i < str.length) {
      if (str(i) == '(') {
        openCount += 1
        currLen += 1
      } else {
        if (openCount == 0) {
          count(currLen) += 1
          maxLen = math.max(maxLen, currLen)
          currLen = 0
        } else if (openCount > 0) {
          openCount -= 1
          currLen += 1
        }
      }
      i += 1
    }
    if (openCount == 0) {
      count(currLen) += 1
      maxLen = math.max(maxLen, currLen)
    }
    if (maxLen == 0) {
      out.println("0 1")
    } else {
      out.println(s"${maxLen} ${count(maxLen)}")
    }
    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))
    }
  }

}


N ladies attend the ball in the King's palace. Every lady can be described with three values: beauty, intellect and richness. King's Master of Ceremonies knows that ladies are very special creatures. If some lady understands that there is other lady at the ball which is more beautiful, smarter and more rich, she can jump out of the window. He knows values of all ladies and wants to find out how many probable self-murderers will be on the ball. Lets denote beauty of the i-th lady by Bi, her intellect by Ii and her richness by Ri. Then i-th lady is a probable self-murderer if there is some j-th lady that Bi < Bj, Ii < Ij, Ri < Rj. Find the number of probable self-murderers.

The first line contains one integer N (1 ≤ N ≤ 500000). The second line contains N integer numbers Bi, separated by single spaces. The third and the fourth lines contain sequences Ii and Ri in the same format. It is guaranteed that 0 ≤ Bi, Ii, Ri ≤ 109.

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

object LadyOrder extends App {

  val comparator = new Comparator[Lady] {
    override def compare(o1: Lady, o2: Lady): Int = o1.a.compareTo(o2.a)
  }

  val bcomparator = new Comparator[Lady] {
    override def compare(o1: Lady, o2: Lady): Int = o1.b.compareTo(o2.b)
  }

  val s = new BufferedReader(new InputStreamReader(System.in), 8192 * 3)
  val n = s.readLine().toInt
  val as = s.readLine().split(" ")
  val bs = s.readLine().split(" ")
  val cs = s.readLine().split(" ")
  var ladiesColl = (0 until n).map(i => Lady(as(i).toInt, 0, 0))
  val ladies = ladiesColl.toArray
  (0 until n).foreach(x => ladies(x).b = bs(x).toInt)
  (0 until n).foreach(x => ladies(x).c = cs(x).toInt)
  inline()
  util.Arrays.sort(ladies, comparator)
  val maxy = ladies.maxBy(_.b).b
  val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)
  var result = 0
  var lastx = 0

  def inline(): Unit = {
    util.Arrays.sort(ladies, bcomparator)
    val sorted = ladies
    var i = 0
    var cnt = 0
    while (i< n) {
      val cur = sorted(i).b
      while (i < n && sorted(i).b == cur) {
        sorted(i).b = cnt
        i += 1
      }
      cnt += 1
    }
  }

  var i = n - 1
  while (i >= 0) {
    var start = i
    lastx = ladies(i).a
    while (i >= 0 && ladies(i).a == lastx) {
      val cur = ladies(i)
      val x = mrq.query(cur.b + 1, maxy + 1)
      if (cur.c < x) result += 1
      i -= 1
    }
    var cnt = math.max(i, 0) + 1
    while (cnt <= start) {
      val cur = ladies(cnt)
      if (mrq.tree(cur.b + mrq.n) < cur.c) {
        mrq.update(cur.b, cur.c)
      }
      cnt += 1
    }
  }

  println(result)

  class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {

    var n = 1 << ((math.log(size) / math.log(2)).toInt + 1)

    val tree = Array.fill[Int](n * 2)(initValue)

    def update(i: Int, v: Int): Unit = {
      var cur = i + n
      tree(cur) = v
      while (cur != 1) {
        cur = cur / 2
        tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))
      }
    }

    def query(left: Int, right: Int): Int = {
      var l = left + n
      var r = right + n - 1
      var ans = minVal
      while (l <= r) {
        if ((l & 1) == 1) {
          ans = func(ans, tree(l))
        }
        if ((r & 1) == 0) {
          ans = func(ans, tree(r))
        }
        l = (l + 1) / 2
        r = (r - 1) / 2
      }
      ans
    }

  }

  case class Lady(var a: Int, var b: Int, var c: Int)

}

//package me.jetblack.cf

import java.util.Scanner

object LadyOrder extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()
  var ladies = (0 until n).map(_ => Lady(s.nextInt(), 0, 0)).toArray
  (0 until n).foreach(x => ladies(x).b = s.nextInt())
  (0 until n).foreach(x => ladies(x).c = s.nextInt())
  ladies = ladies.sortBy(_.a)
  val maxy = ladies.maxBy(_.b).b
  val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)
  var result = 0
  var lastx = ladies.last.a

  var i = n - 1
  while (i > 0) {
    var start = i
    lastx = ladies(i).a
    while (i >= 0 && ladies(i).a == lastx) {
      val cur = ladies(i)
      val x = mrq.query(cur.b + 1, maxy + 1)
      if (cur.c < x) result += 1
      i -= 1
    }
    var cnt = math.max(i, 0)
    while (cnt <= start) {
      val cur = ladies(cnt)
      if (mrq.tree(cur.b + mrq.n) < cur.c) {
        mrq.update(cur.b, cur.c)
      }
      cnt += 1
    }
  }

  println(result)

  class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {

    val n = 1 << ((math.log(size) / math.log(2)).toInt + 1)
    val tree = Array.fill[Int](n * 2)(initValue)

    def update(i: Int, v: Int): Unit = {
      var cur = i + n
      tree(cur) = v
      while (cur != 1) {
        cur = cur / 2
        tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))
      }
    }

    def query(left: Int, right: Int): Int = {
      var l = left + n
      var r = right + n - 1
      var ans = minVal
      while (l <= r) {
        if ((l & 1) == 1) {
          ans = func(ans, tree(l))
        }
        if ((r & 1) == 0) {
          ans = func(ans, tree(r))
        }
        l = (l + 1) / 2
        r = (r - 1) / 2
      }
      ans
    }

  }

  case class Lady(var a: Int, var b: Int, var c: Int)

}

//package me.jetblack.cf

import java.util.Scanner

object LadyOrder extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()
  var ladies = (0 until n).map(_ => Lady(s.nextInt(), 0, 0)).toArray
  (0 until n).foreach(x => ladies(x).b = s.nextInt())
  (0 until n).foreach(x => ladies(x).c = s.nextInt())
  ladies = ladies.sortBy(_.a)
  val maxy = ladies.maxBy(_.b).b
  val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)
  var result = 0
  var lastx = ladies.last.a

  var i = n - 1
  while (i >= 0) {
    var start = i
    lastx = ladies(i).a
    while (i >= 0 && ladies(i).a == lastx) {
      val cur = ladies(i)
      val x = mrq.query(cur.b + 1, maxy + 1)
      if (cur.c < x) result += 1
      i -= 1
    }
    var cnt = math.max(i, 0)
    while (cnt <= start) {
      val cur = ladies(cnt)
      if (mrq.tree(cur.b + mrq.n) < cur.c) {
        mrq.update(cur.b, cur.c)
      }
      cnt += 1
    }
  }

  println(result)

  class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {

    val n = 1 << ((math.log(size) / math.log(2)).toInt + 1)
    val tree = Array.fill[Int](n * 2)(initValue)

    def update(i: Int, v: Int): Unit = {
      var cur = i + n
      tree(cur) = v
      while (cur != 1) {
        cur = cur / 2
        tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))
      }
    }

    def query(left: Int, right: Int): Int = {
      var l = left + n
      var r = right + n - 1
      var ans = minVal
      while (l <= r) {
        if ((l & 1) == 1) {
          ans = func(ans, tree(l))
        }
        if ((r & 1) == 0) {
          ans = func(ans, tree(r))
        }
        l = (l + 1) / 2
        r = (r - 1) / 2
      }
      ans
    }

  }

  case class Lady(var a: Int, var b: Int, var c: Int)

}

//package me.jetblack.cf

import java.util.Scanner

object LadyOrder extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()
  var ladies = (0 until n).map(_ => Lady(s.nextInt(), 0, 0)).toArray
  (0 until n).foreach(x => ladies(x).b = s.nextInt())
  (0 until n).foreach(x => ladies(x).c = s.nextInt())
  ladies = ladies.sortBy(_.a)
  val maxy = ladies.maxBy(_.b).b
  val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)
  var result = 0

  (n - 1 to 0 by -1).foreach { i =>
    val cur = ladies(i)
    val x = mrq.query(cur.b + 1, maxy + 1)
    if (cur.c < x) result += 1
    if (mrq.tree(cur.b + mrq.n) < cur.c) {
      mrq.update(cur.b, cur.c)
    }
  }

  println(result)

  class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {

    val n = 1 << ((math.log(size) / math.log(2)).toInt + 1)
    val tree = Array.fill[Int](n * 2)(initValue)

    def update(i: Int, v: Int): Unit = {
      var cur = i + n
      tree(cur) = v
      while (cur != 1) {
        cur = cur / 2
        tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))
      }
    }

    def query(left: Int, right: Int): Int = {
      var l = left + n
      var r = right + n - 1
      var ans = minVal
      while (l <= r) {
        if ((l & 1) == 1) {
          ans = func(ans, tree(l))
        }
        if ((r & 1) == 0) {
          ans = func(ans, tree(r))
        }
        l = (l + 1) / 2
        r = (r - 1) / 2
      }
      ans
    }

  }

  case class Lady(var a: Int, var b: Int, var c: Int)

}

//package me.jetblack.cf

import java.util.Scanner

object LadyOrder extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()
  var ladies = (0 until n).map(_ => Lady(s.nextInt(), 0, 0)).toArray
  (0 until n).foreach(x => ladies(x).b = s.nextInt())
  (0 until n).foreach(x => ladies(x).c = s.nextInt())
  ladies = ladies.sortBy(_.a)
  val maxy = ladies.maxBy(_.b).b
  val mrq = new DynamicMrq(maxy + 1, math.max(_, _), Integer.MIN_VALUE, Integer.MIN_VALUE)
  var result = 0
  var lastx = ladies.last.a

  (n - 1 to 0 by -1).foreach { i =>
    val cur = ladies(i)
    val x = mrq.query(cur.b + 1, maxy + 1)
    if (cur.a < lastx) {
      lastx = cur.a
      if (cur.c < x) result += 1
    }
    if (mrq.tree(cur.b + mrq.n) < cur.c) {
      mrq.update(cur.b, cur.c)
    }
  }

  println(result)

  class DynamicMrq(size: Int, func: (Int, Int) => Int, initValue: Int, minVal: Int) {

    val n = 1 << ((math.log(size) / math.log(2)).toInt + 1)
    val tree = Array.fill[Int](n * 2)(initValue)

    def update(i: Int, v: Int): Unit = {
      var cur = i + n
      tree(cur) = v
      while (cur != 1) {
        cur = cur / 2
        tree(cur) = func(tree(cur * 2), tree(cur * 2 + 1))
      }
    }

    def query(left: Int, right: Int): Int = {
      var l = left + n
      var r = right + n - 1
      var ans = minVal
      while (l <= r) {
        if ((l & 1) == 1) {
          ans = func(ans, tree(l))
        }
        if ((r & 1) == 0) {
          ans = func(ans, tree(r))
        }
        l = (l + 1) / 2
        r = (r - 1) / 2
      }
      ans
    }

  }

  case class Lady(var a: Int, var b: Int, var c: Int)

}


Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length.Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line.Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left.Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.

The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 5000, n ≥ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≤ si ≤ m), and one real number xi (0 ≤ xi ≤ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≤ i < n).

Output a single integer — the minimum number of plants to be replanted.

NoteIn the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1.In the second test case, the species are already in the correct order, so no replanting is needed.

object cf270d extends App {
	val Array(n, m) = readLine.split(' ').map(_.toInt)
	val input = (1 to n).map(i => readLine.split(' ')).sortBy(_.apply(1).toFloat).map(_.apply(0).toInt)
	var dp = Array.fill(m + 1)(0)
	for (arri <- input)
		dp(arri) = 1 + dp.slice(1, arri + 1).max
	println(n - dp.max)
}

import java.util.Scanner

object cf270d extends App {
    val in = new Scanner(System.in)
	val (n, m) = (in.nextInt, in.nextInt)
	val input = (1 to n).map(i => (in.nextInt, in.nextFloat)._1)
	var dp = Array.fill(m + 1)(0)
	for (arri <- input)
		dp(arri) = 1 + dp.slice(1, arri + 1).max
	println(n - dp.max)
}

import java.util.Scanner

object cf270d extends App {
    val in = new Scanner(System.in)
	val (n, m) = (in.nextInt, in.nextInt)
	val input = (1 to n).map(i => (in.nextInt, in.nextFloat)).sortBy(_._2).map(_._1)
	var dp = Array.fill(m + 1)(0)
	for (arri <- input)
		dp(arri) = 1 + dp.slice(1, arri + 1).max
	println(n - dp.max)
}

object cf270d extends App {
	val Array(n, m) = readLine.split(' ').map(_.toInt)
	val input = (1 to n).map(i => readLine.split(' ').apply(0).toInt)
	var dp = Array.fill(m + 1)(0)
	for (arri <- input)
		dp(arri) = 1 + dp.slice(1, arri + 1).max
	println(n - dp.max)
}

object cf270d extends App {
  val Array(n, m) = readLine.split(' ').map(_.toInt)
  val input = (1 to n).map(i => readLine.split(' ').apply(0).toInt)
  var dp = Array.fill(n + 1)(0)
  var len = 0
  for (arri <- input) {
    var (l, r, ans) = (0, len, len)
    while (l <= r) {
      val m = (l + r) / 2
      if (dp(m) <= arri) {
        l = m + 1
        ans = m
      } else {
        r = m - 1
      }
    }
    dp(ans + 1) = arri
    if (ans >= len)
      len += 1
  }
  println(n - len)
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val f = new Array[Int](m)
    val g = new Array[Int](m)
    for (_ <- 1 to n) {
      val tokens = readLine().split(" ")
      var a = tokens(0).toInt - 1
      for (i <- m - 1 to a by -1) {
        f(i) = Math.min(f(i) + 1, f(a) + g(a) - g(i))
      }
      for (i <- a - 1 to 0 by -1) {
        g(i) += 1
      }
    }
    println(f(m - 1))
  }
}

object test6 extends App {
    val Array(n,m)=readLine.split(" ").map(_.toInt)
    val s=(for(i<-1 to n) yield readLine.split(" ")(0).toInt) toArray
    val dp=Array.ofDim[Int](n+1,m+1)

    for(i<-n-1 to 0 by -1; j<-0 to m){
        dp(i)(j)=1+dp(i+1)(j)
        if(s(i)>=j) dp(i)(j)=math.min(dp(i)(j), dp(i+1)(s(i)))
    }

    println(dp(0)(0))
}

object test6 extends App {
    val Array(n,m)=readLine.split(" ").map(_.toInt)
    val s=(for(i<-1 to n) yield readLine.split(" ")(0).toInt).toArray
    val dp=Array.ofDim[Int](n+1,m+1)

    for(i<-n-1 to 0 by -1; j<-0 to m){
        dp(i)(j)=1+dp(i+1)(j)
        if(s(i)>=j) dp(i)(j)=math.min(dp(i)(j), dp(i+1)(s(i)))
    }

    println(dp(0)(0))
}

object test6 extends App {
    val Array(n,m)=readLine.split(" ").map(_.toInt)
    val s=new Array[Int](n)
    val x=new Array[Double](n)
    val dp=Array.ofDim[Int](n+1,m+1)
    for(i<-0 until n){
        val arr=readLine.split(" ")
        s(i)=arr(0).toInt
        x(i)=arr(1).toDouble
    }

    for(i<-n-1 to 0 by -1; j<-0 to m){
        dp(i)(j)=1+dp(i+1)(j)
        if(s(i)>=j) dp(i)(j)=math.min(dp(i)(j), dp(i+1)(s(i)))
    }

    println(dp(0)(0))
}

object Main {
  def main(args: Array[String]) {
    val Array(n, _) = readLine().split(" ").map(_.toInt)
    var last = -1
    var count = 0
    for (_ <- 1 to n) {
      val tokens = readLine().split(" ")
      val s = tokens(0).toInt
      if (s < last) {
        count += 1
      }
      last = s
    }
    println(count)
  }
}


A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You are given an integer $$$n$$$. Your goal is to construct and print exactly $$$n$$$ different regular bracket sequences of length $$$2n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 50$$$).

For each test case, print $$$n$$$ lines, each containing a regular bracket sequence of length exactly $$$2n$$$. All bracket sequences you output for a testcase should be different (though they may repeat in different test cases). If there are multiple answers, print any of them. It can be shown that it's always possible.

import scala.io.StdIn

object PracticeScala {
  def main(args: Array[String]): Unit = {
    var t = StdIn.readInt()
    while(t != 0){
      val n = StdIn.readInt()
      var i: Int = 0
      while(i < n){
        println("()" * i + "(" * (n - i) + ")" * (n - i) )
        i += 1
      }
      t -= 1
    }
  }
}

object A extends App {

  def brackets(n: Int): List[String] =
    (0 until n).foldLeft(List.empty[String]) { (brackets, i) =>
      val bracket = "(" * (n - 1) + ")" * i + "(" + ")" * (n - i)
      bracket :: brackets
    }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()

    out.println(brackets(n).mkString("\n"))
    out.flush()
  }

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.Sorting.quickSort
import util.control.Breaks._

object Solution {
    val writer =  new PrintWriter(System.out)
    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() = next.toInt
    def readLong() = next.toLong
    def readString() = next()

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def main(args: Array[String]) {
        var t = readInt()
        while (t > 0) {
            t -= 1
            val n = readInt()
            val m = (1L << n) - 1
            val a = new Array[Int](2*n)
            for (i <- 0 until n) {
                for (k <- 0 until n) {
                    a(n - k - 1) = (((m - i) >> k ) & 1).toInt
                    a(k + n) = 1 - a(n - k - 1)
                }

                for (i <- 0 until 2*n) {
                    if (a(i) == 1) writer.print("(")
                    else writer.print(")")
                }
                writer.println()
            }
        }
        writer.close()
    }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.math.max

object test {
    val writer =  new PrintWriter(System.out)
    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()

    def main(args: Array[String]): Unit = {
        val t = readInt()
        for (tt <- 1 to t) {
            val n = readInt()
            for (i <- 1 to n) {
                for (j <- 1 to i)
                    writer.print('(')
                for (j <- 1 to i)
                    writer.print(')')
                for (j <- 1 to n-i)
                    writer.print("()")
                writer.println()
            }
            writer.flush()
        }
    }
}