Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by $$$n$$$ sectors, and the outer area is equally divided by $$$m$$$ sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position.  The inner area's sectors are denoted as $$$(1,1), (1,2), \dots, (1,n)$$$ in clockwise direction. The outer area's sectors are denoted as $$$(2,1), (2,2), \dots, (2,m)$$$ in the same manner. For a clear understanding, see the example image above.Amugae wants to know if he can move from one sector to another sector. He has $$$q$$$ questions.For each question, check if he can move between two given sectors.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 10^{18}$$$, $$$1 \le q \le 10^4$$$) — the number of sectors in the inner area, the number of sectors in the outer area and the number of questions. Each of the next $$$q$$$ lines contains four integers $$$s_x$$$, $$$s_y$$$, $$$e_x$$$, $$$e_y$$$ ($$$1 \le s_x, e_x \le 2$$$; if $$$s_x = 1$$$, then $$$1 \le s_y \le n$$$, otherwise $$$1 \le s_y \le m$$$; constraints on $$$e_y$$$ are similar). Amague wants to know if it is possible to move from sector $$$(s_x, s_y)$$$ to sector $$$(e_x, e_y)$$$.

For each question, print "YES" if Amugae can move from $$$(s_x, s_y)$$$ to $$$(e_x, e_y)$$$, and "NO" otherwise. You can print each letter in any case (upper or lower).

NoteExample is shown on the picture in the statement.

object C extends App {

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

  val Array(n, m, q) = readLongs(3)

  def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  val g = gcd(n, m)
  val g1 = n / g
  val g2 = m / g

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 1 to q.toInt) {
    val Array(sx, sy, ex, ey) = readLongs(4)
    val s = if (sx == 1) BigInt(sy - 1) * g2 / g1 else BigInt(sy - 1)
    val e = if (ex == 1) BigInt(ey - 1) * g2 / g1 else BigInt(ey - 1)
    val can = s / g2 == e / g2
    println(if (can) "YES" else "NO")
  }

  Console.flush
}

import scala.io.StdIn._

object C_1200 extends App {
  def gcd(a: Long, b: Long): Long = {
    var aa = a
    var bb = b

    while (true) {
      if (bb == 0) return aa
      val m = aa % bb
      aa = bb
      bb = m
    }

    1
  }

  val Array(n, m, q) = readLine().split(" ").map(_.toLong)
  val g              = gcd(n, m)

  def pivot1(i: Long)         = {
    if (i == 0) 0L
    else if (i % (n / g) == 0) i / (n / g) - 1
    else i / (n / g)
  }

  def pivot2(i: Long)         = {
    if (i == 0) 0L
    else if (i % (m / g) == 0) i / (m / g) - 1
    else i / (m / g)
  }

  1 to q.toInt foreach { _ =>
    val Array(sx, sy, ex, ey) = readLine().split(" ").map(_.toLong)
    if (g <= 1) println("YES")
    else {
      val r1 = if (sx == 1) {
        pivot1(sy)
      } else {
        pivot2(sy)
      }

      val r2 = if (ex == 1) {
        pivot1(ey)
      } else {
        pivot2(ey)
      }

      println(
        if (r1 == r2) "YES" else "NO"
      )
    }
  }

}

import scala.io.StdIn._

object C_1200 extends App {
  def gcd(a: Long, b: Long): Long = {
    var aa = a
    var bb = b

    while (true) {
      if (bb == 0) return aa
      val m = aa % bb
      aa = bb
      bb = m
    }

    1
  }

  val Array(n, m, q) = readLine().split(" ").map(_.toLong)
  val g              = gcd(n, m)
  val pivot1         = n / g
  val pivot2         = m / g
  println(pivot1)
  println(pivot2)

  1 to q.toInt foreach { _ =>
    val Array(sx, sy, ex, ey) = readLine().split(" ").map(_.toLong)
    if (g <= 1) println("YES")
    else {
      val r1 = if (sx == 1) {
        sy <= pivot1
      } else {
        sy <= pivot2
      }

      val r2 = if (ex == 1) {
        ey <= pivot1
      } else {
        ey <= pivot2
      }

      println(
        if (r1 == r2) "YES" else "NO"
      )
    }
  }

}

import scala.io.StdIn._

object C_1200 extends App {
  def gcd(a: Long, b: Long): Long = {
    var aa = a
    var bb = b

    while (true) {
      if (bb == 0) return aa
      val m = aa % bb
      aa = bb
      bb = m
    }

    1
  }

  val Array(n, m, q) = readLine().split(" ").map(_.toLong)
  val g              = gcd(n, m)
  val pivot1         = n / g
  val pivot2         = m / g

  1 to q.toInt foreach { _ =>
    val Array(sx, sy, ex, ey) = readLine().split(" ").map(_.toLong)
    if (g <= 1) println("YES")
    else {
      val r1 = if (sx == 1) {
        sy <= pivot1
      } else {
        sy <= pivot2
      }

      val r2 = if (ex == 1) {
        ey <= pivot1
      } else {
        ey <= pivot2
      }

      println(
        if (r1 == r2) "YES" else "NO"
      )
    }
  }

}


A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.Polycarpus has already began the process and he partially emptied the Ber-Cola bottle. Now the first mug has a1 milliliters of the drink, the second one has a2 milliliters and so on. The bottle has b milliliters left and Polycarpus plans to pour them into the mugs so that the main equation was fulfilled.Write a program that would determine what volume of the drink Polycarpus needs to add into each mug to ensure that the following two conditions were fulfilled simultaneously:   there were b milliliters poured in total. That is, the bottle need to be emptied;  after the process is over, the volumes of the drink in the mugs should be equal.

The first line contains a pair of integers n, b (2 ≤ n ≤ 100, 1 ≤ b ≤ 100), where n is the total number of friends in the group and b is the current volume of drink in the bottle. The second line contains a sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the current volume of drink in the i-th mug.

Print a single number "-1" (without the quotes), if there is no solution. Otherwise, print n float numbers c1, c2, ..., cn, where ci is the volume of the drink to add in the i-th mug. Print the numbers with no less than 6 digits after the decimal point, print each ci on a single line. Polycarpus proved that if a solution exists then it is unique. Russian locale is installed by default on the testing computer. Make sure that your solution use the point to separate the integer part of a real number from the decimal, not a comma.

object ProblemAboutEquation174A extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val b = scanner.nextDouble()
    val mugs = (1 to n).map(_ => scanner.nextDouble())
    val totalLiquid = mugs.sum+b
    val onEachMug = totalLiquid/n
    val resultA = mugs.map(a => onEachMug-a)
    if(mugs.exists(_ > onEachMug))
      out.println(-1)
    else
      out.println(resultA.map(s => f"$s%.7f").mkString(System.lineSeparator()))
  }
}


There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?

There are 2n lines in the input.  The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i > 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)

Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.

NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.

//package round320.b

import java.util.Scanner

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

  val n = sc.nextInt
  val t = Array.fill(2*n+1)(0)
  val as = Array.ofDim[(Int, Int, Int)](n * (2*n-1))
  var ii = 0
  for(i <- 2 to 2*n; j <- 1 until i) {
    val aij = sc.nextInt
    as(ii) = (aij, i, j)
    ii += 1
  }

  val as2 = as.sorted
  ii -= 1

  var pairs = 0
  while(pairs < n) {
    val (_, i, j) = as2(ii)
    if(t(i) == 0 && t(j) == 0) {
      t(i) = j
      t(j) = i
      pairs += 1
    }
    ii -= 1
  }

  for(i <- 1 to 2*n) {
    print(t(i))
    print(" ")
  }

  println()
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data = (2 to 2 * n).flatMap { i =>
    in.next().split(" ").map(_.toInt).zipWithIndex.map{
      case(el, index) => (i, index + 1, el)
    }
  }.sortBy(_._3).reverse
  val result = Array.fill(2 * n){ 0 }

  while (data.nonEmpty) {
    val max = data.head
    if (result(max._1 - 1) == 0 && result(max._2 - 1) == 0) {
      result(max._1 - 1) = max._2
      result(max._2 - 1) = max._1
    }
    data = data.tail
  }
  println(result.mkString(" "))
}

import scala.io.StdIn._

object B extends App {
  case class Pair(x: Int, y: Int)
  val Max = 1000000
  val A = Array.ofDim[Pair](Max + 1)

  val n = readLine().toInt

  for (i <- 2 to 2 * n) {
    val values = readLine().split(" ").map(_.toInt)
    for (j <- 1 to i - 1) {
      update(i, j, values(j - 1))
    }
  }

  def update(x: Int, y: Int, power: Int): Unit = {
//    println(s"update $x $y $power")
    A(power) = Pair(x, y)
  }

  var counter = 1
  var i = Max
  val choice = Array.ofDim[Int](2 * n + 1)
  val marker = Array.ofDim[Boolean](Max + 1)

  while (counter <= n) {
    if (A(i) != null && (!marker(A(i).x) && !marker(A(i).y))) {
//      println("consider " + A(i))
      val curr = A(i)
      choice(curr.x) = curr.y
      choice(curr.y) = curr.x
      marker(curr.x) = true
      marker(curr.y) = true
      counter += 1
    }
    i -= 1
  }

  println(choice.drop(1).mkString(" "))
}


Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.

Print all tram lines that Arkady could be in, in arbitrary order.

NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.

object A extends App {

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

  val Array(n) = readInts(1)
  var s = readLine.split(" ").tail.map(_.toInt).toSet
  for (_ <- 1 until n) {
    val s2 = readLine.split(" ").tail.map(_.toInt).toSet
    s = s.intersect(s2)
  }

  println(s.mkString(" "))
}


There are $$$n$$$ people who want to participate in a boat competition. The weight of the $$$i$$$-th participant is $$$w_i$$$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are $$$k$$$ teams $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, $$$\dots$$$, $$$(a_k, b_k)$$$, where $$$a_i$$$ is the weight of the first participant of the $$$i$$$-th team and $$$b_i$$$ is the weight of the second participant of the $$$i$$$-th team, then the condition $$$a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$$$, where $$$s$$$ is the total weight of each team, should be satisfied.Your task is to choose such $$$s$$$ that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of participants. The second line of the test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le n$$$), where $$$w_i$$$ is the weight of the $$$i$$$-th participant.

For each test case, print one integer $$$k$$$: the maximum number of teams people can compose with the total weight $$$s$$$, if you choose $$$s$$$ optimally.

NoteIn the first test case of the example, we can reach the optimal answer for $$$s=6$$$. Then the first boat is used by participants $$$1$$$ and $$$5$$$ and the second boat is used by participants $$$2$$$ and $$$4$$$ (indices are the same as weights).In the second test case of the example, we can reach the optimal answer for $$$s=12$$$. Then first $$$6$$$ participants can form $$$3$$$ pairs.In the third test case of the example, we can reach the optimal answer for $$$s=3$$$. The answer is $$$4$$$ because we have $$$4$$$ participants with weight $$$1$$$ and $$$4$$$ participants with weight $$$2$$$.In the fourth test case of the example, we can reach the optimal answer for $$$s=4$$$ or $$$s=6$$$.In the fifth test case of the example, we can reach the optimal answer for $$$s=3$$$. Note that participant with weight $$$3$$$ can't use the boat because there is no suitable pair for him in the list.

//package codeforces.contests._1399

object BoatsCompetition {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readInt()
      val a = io.StdIn.readLine.split(" ").map(_.toInt).sorted

      if (n >= 2) {
        val wF = new Array[Int](n + 1)
        a.foreach(wF(_) += 1)

        val ans = (2 to 2 * n).map { s =>

          (1 to ((s - 1) min n)).foldLeft(0)((acc, w1) => acc + {
            val w2 = s - w1
            if (w2 <= n && w1 <= w2) (if (w1 < w2) wF(w1) min wF(w2) else wF(w1) / 2) else 0
          })

        }

        println(ans.max)
      } else println(0)
    }
  }
}

import java.lang.Math._

import scala.io.Source

object BoatsCompetition1399C extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//      val lines: Iterator[String] =
//        Source.fromString("5\n5\n1 2 3 4 5\n8\n6 6 6 6 6 6 8 8\n8\n1 2 2 1 2 1 1 2\n3\n1 3 3\n6\n1 1 3 4 2 2").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach println

  def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      0
    } else if (prts <= 3) {
      lines.next
      1
    } else {
      val ws = lines.next.split(" ").map(_.toInt)
      solve(ws)
    }
  }

  def solve(ws: Array[Int]) = {
    val counts = ws.groupBy(identity).map { case (k, v) => k -> v.length }
    (for (s <- 2 * ws.min to 2 * ws.max) yield
      (for (i <- max(ws.min, s - ws.max) to s / 2) yield {
        val ic = counts.getOrElse(i, 0)
        if (ic == 0) 0
        else if (i != s - i)
          min(ic, counts.getOrElse(s - i, 0))
        else ic / 2
      }).sum).max
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val xs = StdIn.readLine().split(" ").map(_.toInt).sorted
      val s = xs.toSet
      val xs1 = xs.distinct
      var res = 0
      for (i <- xs.indices) {
        for (j <- xs.indices.reverse by -1 if i < j) {
          val w = xs(i) + xs(j)
          var (ii, jj) = (i, j)
          var temp = 0
          while (ii < jj) {
            val target = xs(ii) + xs(jj)
            if (target == w) {
              temp += 1; ii += 1; jj -= 1;
            } else if (target < w) ii += 1
            else jj -= 1
          }
          res = res max temp
        }
      }
      println(res)
    }
  }
}

//package codeforces.contests._1399

object BoatsCompetition {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readInt()
      val a = io.StdIn.readLine.split(" ").map(_.toInt).sorted

      var ans = Int.MinValue

      for {
        i <- 0 until n
        j <- i + 1 until n
        s = a(i) + a(j)
        result = {
          var ii = i
          var jj = j

          var count = 0
          while (ii < jj) {
            if (a(ii) + a(jj) == s) count += 1
            ii += 1
            jj -= 1
          }

          count
        }
      } ans = ans max result

      println(ans)
    }
  }
}

import scala.io.Source

object BoatsCompetition1399C extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//      val lines: Iterator[String] =
//        Source.fromString("5\n5\n1 2 3 4 5\n8\n6 6 6 6 6 6 8 8\n8\n1 2 2 1 2 1 1 2\n3\n1 3 3\n6\n1 1 3 4 2 2").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach println

  def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      0
    } else if (prts <= 3) {
      lines.next
      1
    } else {
      val ws = lines.next.split(" ").map(_.toInt).sorted
      solve(ws, Array())
    }
  }

  def solve(ws: Array[Int], solutio: Array[Int]): Int = {
    if (ws.length < 2) compute(solutio)
    else ws.tail.zipWithIndex.map { case (_, ind) =>
      val updWs = ws.tail.take(ind - 1) ++ ws.tail.drop(ind)

      solve(updWs, solutio ++ Array(ws.head + ws.tail(ind)))
    }.max
  }

  def compute(sol: Array[Int]): Int = {
    sol.groupBy(identity).values.map(_.length).max
  }
}

import scala.io.Source

object BoatsCompetition1399C extends App {

//  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
      val lines: Iterator[String] =
        Source.fromString("5\n5\n1 2 3 4 5\n8\n6 6 6 6 6 6 8 8\n8\n1 2 2 1 2 1 1 2\n3\n1 3 3\n6\n1 1 3 4 2 2").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach println

  def handleTC() = {
    val prts = lines.next.toInt
    if (prts == 1) {
      lines.next
      0
    } else if (prts <= 3) {
      lines.next
      1
    } else {
      val ws = lines.next.split(" ").map(_.toInt).sorted
      solve(ws, Array())
    }
  }

  def solve(ws: Array[Int], solutio: Array[Int]): Int = {
    if (ws.length < 2) compute(solutio)
    else ws.tail.zipWithIndex.map { case (_, ind) =>
      val updWs = ws.tail.take(ind) ++ ws.tail.drop(ind+1)

      solve(updWs, solutio ++ Array(ws.head + ws.tail(ind)))
    }.max
  }

  def compute(sol: Array[Int]): Int = {
    sol.groupBy(identity).values.map(_.length).max
  }
}


Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that:  each student in the team scored at least l points and at most r points;  in total, all members of the team scored exactly sall points;  the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.

The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106). It's guaranteed that the input is such that the answer exists.

Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.

object HelloWorld   {
    def main(args:Array[String]){
        var Array(n,k,l,r,sall,sk)=readLine().split(" ").map(_.toInt)
        var array=Array.fill(n)(l)
        var pos=0

        var ka:Int=sk/k
        var kb:Int=sk%k

        for(i<-0 to kb-1){
            array(i)=ka+1
        }
        for(i<-kb to k-1){
            array(i)=ka
        }
        if(n!=k)
        {
            var la:Int=(sall-sk)/(n-k)
            var lb:Int=(sall-sk)%(n-k)
            for(i<-k to k+lb-1){
                array(i)=la+1
            }
            for(i<-k+lb to n-1){
                array(i)=la
            }
        }
        println(array.mkString(" "))
    }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k, l, r, sAll, sK) = in.next().split(' ').map(_.toInt)
  val answer = Array.ofDim[Int](n)
  val m = sK / k
  val left = sK % k
  (0 until left).foreach(i => answer(i) = m + 1)
  (left to k - 1).foreach(i => answer(i) = m)
  if (k != n) {
    val m1 = (sAll - sK) / (n - k)
    val left1 = (sAll - sK) % (n - k)
    (k until k + left1).foreach(i => answer(i) = m1 + 1)
    (k + left1 to n - 1).foreach(i => answer(i) = m1)
  }
  println(answer.mkString(" "))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k, l, r, sAll, sK) = in.next().split(' ').map(_.toInt)
  val answer = Array.ofDim[Int](n)
  val m = sK / k
  val left = sK % k
  (0 until left).foreach(i => answer(i) = m + 1)
  (left to k - 1).foreach(i => answer(i) = m)
  if (k <= n - 2) {
    val m = (sAll - sK) / (n - k)
    val left = (sAll - sK) % (n - k)
    (k until k + left).foreach(i => answer(i) = m + 1)
    (k + left to n - 1).foreach(i => answer(i) = m)
  }
  println(answer.mkString(" "))

}


Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $$$(0, 0)$$$ on an infinite grid.You also have the sequence of instructions of this robot. It is written as the string $$$s$$$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $$$(x, y)$$$ right now, he can move to one of the adjacent cells (depending on the current instruction).  If the current instruction is 'L', then the robot can move to the left to $$$(x - 1, y)$$$;  if the current instruction is 'R', then the robot can move to the right to $$$(x + 1, y)$$$;  if the current instruction is 'U', then the robot can move to the top to $$$(x, y + 1)$$$;  if the current instruction is 'D', then the robot can move to the bottom to $$$(x, y - 1)$$$. You've noticed the warning on the last page of the manual: if the robot visits some cell (except $$$(0, 0)$$$) twice then it breaks.So the sequence of instructions is valid if the robot starts in the cell $$$(0, 0)$$$, performs the given instructions, visits no cell other than $$$(0, 0)$$$ two or more times and ends the path in the cell $$$(0, 0)$$$. Also cell $$$(0, 0)$$$ should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not $$$(0, 0)$$$) and "UUDD" (the cell $$$(0, 1)$$$ is visited twice).The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain.Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric).You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^4$$$) — the number of test cases. The next $$$q$$$ lines contain test cases. The $$$i$$$-th test case is given as the string $$$s$$$ consisting of at least $$$1$$$ and no more than $$$10^5$$$ characters 'L', 'R', 'U' and 'D' — the initial sequence of instructions. It is guaranteed that the sum of $$$|s|$$$ (where $$$|s|$$$ is the length of $$$s$$$) does not exceed $$$10^5$$$ over all test cases ($$$\sum |s| \le 10^5$$$).

For each test case print the answer on it. In the first line print the maximum number of remaining instructions. In the second line print the valid sequence of remaining instructions $$$t$$$ the robot has to perform. The moves are performed from left to right in the order of the printed sequence. If there are several answers, you can print any. If the answer is $$$0$$$, you are allowed to print an empty line (but you can don't print it).

6
LRU
DURLDRUDRULRDURDDL
LRUDDLRUDRUL
LLLLRRRR
URDUR
LLL

2
LR
14
RUURDDDDLLLUUR
12
ULDDDRRRUULL
2
LR
2
UD
0

NoteThere are only two possible answers in the first test case: "LR" and "RL".The picture corresponding to the second test case:  Note that the direction of traverse does not matter Another correct answer to the third test case: "URDDLLLUURDR".

object CF605B extends App {

  import scala.io.StdIn

  val q = StdIn.readInt
  for (_ <- 0 until q) {
    val moves = StdIn.readLine.toCharArray

    val up = moves.count(_ == 'U')
    val down = moves.count(_ == 'D')
    val left = moves.count(_ == 'L')
    val right = moves.count(_ == 'R')

    val minUpDown = math.min(up, down)
    val minLeftRight = math.min(left, right)

    val finalUpDown = if (minLeftRight == 0) math.min(minUpDown, 1) else minUpDown
    val finalLeftRight = if (minUpDown == 0) math.min(minLeftRight, 1) else minLeftRight

    val answer = "L"*finalLeftRight + "U"*finalUpDown + "R"*finalLeftRight + "D"*finalUpDown
    println(answer.length)
    println(answer)
  }
}

object CF605B extends App {

  import scala.io.StdIn

  val q = StdIn.readInt
  for (_ <- 0 until q) {
    val moves = StdIn.readLine.toCharArray

    val up = moves.count(_ == 'U')
    val down = moves.count(_ == 'D')
    val left = moves.count(_ == 'L')
    val right = moves.count(_ == 'R')

    val minUpDown = math.min(up, down)
    val minLeftRight = math.min(left, right)

    val finalUpDown = if (minLeftRight == 0) math.min(minUpDown, 1) else minUpDown
    val finalLeftRight = if (minUpDown == 0) math.min(minLeftRight, 1) else minLeftRight

    val answer = "L"*minLeftRight + "U"*minUpDown + "R"*minLeftRight + "D"*minUpDown
    println(answer.length)
    println(answer)
  }
}


One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:  Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;  Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.

Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.

NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val lastIndex = (n - 2 to 0 by -1).find(i => data(i) != data.last)
  if (lastIndex.isEmpty)
    println(0)
  else if (lastIndex.get + 1 >= k)
    println(-1)
  else
    println(lastIndex.get + 1)
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P222A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, K = sc.nextInt
  val a = List.fill(N)(sc.nextInt)

  val n = a(K - 1)
  val i = a.lastIndexWhere(_ != n)
  val answer = if (i > K - 1) -1
               else i + 1

  out.println(answer)
  out.close
}

import java.io.InputStreamReader
import java.io.BufferedReader

/**
 * @author pvasilyev
 * @since 25 Jun 2016
 */
object A222 extends App {

  def solve() = {
    val reader = new BufferedReader(new InputStreamReader(System.in))
    val Array(n, k) = reader.readLine().split(" ").map(_.toInt)
    val a: Array[Int] = reader.readLine().split(" ").map(_.toInt)

    var c = 0
    var eq = true
    for (i <- k - 1 until n) {
      if (c == 0) {
        c = a(i)
      } else if (c != a(i)) {
        eq = false
      }
    }

    if (!eq) {
      println("-1")
    } else {

      var index = k - 1
      for (i <- (k - 1).until(0, -1)) {

        if (eq) {
          if (a(index - 1) == a(i)) {
            index -= 1
          } else {
            eq = false
          }
        }
      }

      println(index)
    }
  }

  solve()

}

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

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

  val Array(n, k) = readInts
  val a = readInts
  def cnt = a.drop(k - 1).sliding(2).count(x => x.last != x.head)
  def ans = if(cnt == 0) n - a.reverse.takeWhile(_ == a.last).length else -1

  def main(a: Array[String]) {
    println(ans)
  }
}

object test5 extends App {
    val Array(n,k)=readLine.split(' ').map(_.toInt)
    val arr=readLine.split(' ').map(_.toInt)
    if(arr.slice(k-1,n).distinct.size>1)
    {
    	println(-1)
    }
    else
    {
        var i=k-2
        while(i>=0 && arr(i)==arr(i+1))
        	i-=1
        println(i+1)
    }
}

object test5 extends App {
    val Array(n,k)=readLine.split(' ').map(_.toInt)
    val arr=readLine.split(' ').map(_.toInt)
    if(arr.slice(k-1,n).distinct.size>1)
    {
    	println(-1)
    }
    else
    {
    	def find(i:Int):Int=i match{
    		case -1=> 0
    		case _ if arr(i)==arr(k-1)=>find(i-1)
    		case _=>i+1
    	}

        println(find(k-2))
    }
}

object Main {
  def main(args: Array[String]) = {
    val nk = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(1)

    if (a.drop(k - 1).toSet.size != 1) println("-1")
    else {
      val e = a(k - 1)
      val c = a.take(k - 1).reverse.takeWhile(_ == e).size
      println(k - c - 1)
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val lastIndex = (n - 2 to 0 by -1).find(_ != data.last)
  if (lastIndex.isEmpty)
    println(0)
  else if (lastIndex.get + 1 >= k)
    println(-1)
  else
    println(lastIndex.get + 1)
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P222A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, K = sc.nextInt
  val a = List.fill(N)(sc.nextInt)

  def solve1(): Int = if (a.distinct.size == 1) 0
                      else -1

  def solveM(): Int = {

    @tailrec
    def loop(n: Int, as: List[Int]): Int = {
      if (as.distinct.size == 1) n
      else {
        val (f, r) = as splitAt (K - 1)
        loop(n + 1, f.tail ++ r.tail ++ List(r.head))
      }
    }

    loop(0, a)
  }

  def solve(): Int = K match {
      case 1 | `N` => solve1
      case _ => solveM
  }

  out.println(solve)
  out.close
}

import java.io.InputStreamReader
import java.io.BufferedReader

/**
 * @author pvasilyev
 * @since 25 Jun 2016
 */
object A222 extends App {

  def solve() = {
    val reader = new BufferedReader(new InputStreamReader(System.in))
    val Array(n, k) = reader.readLine().split(" ").map(_.toInt)
    val a: Array[Int] = reader.readLine().split(" ").map(_.toInt)

    var c = 0
    var eq = true
    for (i <- k - 1 until n) {
      if (c == 0) {
        c = a(i)
      } else if (c != a(i)) {
        eq = false
      }
    }

    if (!eq) {
      println("-1")
    } else {
      println(k - 1)
    }
  }

  solve()

}

object test5 extends App {
    val Array(n,k)=readLine.split(' ').map(_.toInt)
    val arr=readLine.split(' ').map(_.toInt)
    if(arr.distinct.size==1)
    {
    	println(0)
    }
    else
    {
        arr(0)=arr(k-1)

        if(arr.distinct.size==1)
        	println(1)
        else
        	println(-1)
    }
}

object test5 extends App {
    val Array(n,k)=readLine.split(' ').map(_.toInt)
    val arr=readLine.split(' ').map(_.toInt)
    if(arr.slice(k-1,n).distinct.size>1)
    {
    	println(-1)
    }
    else
    {
    	def find(i:Int):Int=i match{
    		case -1=> 0
    		case _ if i==arr(k-1)=>find(i-1)
    		case _=>i+1
    	}

        println(find(k-2))
    }
}

object test5 extends App {
    val Array(n,k)=readLine.split(' ').map(_.toInt)
    val arr=readLine.split(' ').map(_.toInt)
    arr(0)=arr(k-1)

    if(arr.distinct.size==1)
    	println(1)
    else
    	println(-1)
}


You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree.

Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$.

NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$.

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 C627E(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 C627E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    a = na(n)
    REP(n) { i =>
      if(a(i) == 0) a(i) = -1
    }
    from = Array.ofDim[Int](n-1)
    to = Array.ofDim[Int](n-1)

    REP(n-1) { i =>
      from(i) = ni() - 1
      to(i) = ni() - 1
    }

    build(n)
//    g.foreach(f => out.println(f.mkString(" ")))

    dp = Array.ofDim[Int](n)
    ans = Array.ofDim[Int](n)
    dfs(0, -1)
    dfs1(0, -1)
    out.println(ans.mkString(" "))
  }

  def dfs(u: Int, p: Int): Unit = {
    dp(u) = a(u)
    g(u).foreach { v =>
      if(p != v) {
        dfs(v, u)
        dp(u) += scala.math.max(dp(v), 0)
      }
    }
  }

  def build(n: Int): Unit = {
    val count = Array.fill[Int](n)(0)
    g = Array.ofDim[Array[Int]](n)
    REP(n-1) { i =>
      count(from(i)) += 1
      count(to(i)) += 1
    }

    REP(n) { i =>
      g(i) = Array.ofDim[Int](count(i))
    }

    REP(n-1) { i =>
      g(from(i))(count(from(i))-1) = to(i)
      g(to(i))(count(to(i))-1) = from(i)
      count(from(i))-=1
      count(to(i))-=1
    }
  }

  def dfs1(u: Int, p: Int): Unit = {
    ans(u) = dp(u)
    g(u).foreach { v =>
      if(p != v) {
        dp(u) -= scala.math.max(dp(v), 0)
        dp(v) += scala.math.max(dp(u), 0)
        dfs1(v, u)
        dp(v) -= scala.math.max(dp(u), 0)
        dp(u) += scala.math.max(dp(v), 0)
      }
    }
  }

  var a: Array[Int] = _
  var dp: Array[Int] = _
  var ans: Array[Int] = _
  var g: Array[Array[Int]] = _
  var from: Array[Int] = _
  var to: Array[Int] = _
}


The "Road Accident" band is planning an unprecedented tour around Treeland. The RA fans are looking forward to the event and making bets on how many concerts their favorite group will have.Treeland consists of n cities, some pairs of cities are connected by bidirectional roads. Overall the country has n - 1 roads. We know that it is possible to get to any city from any other one. The cities are numbered by integers from 1 to n. For every city we know its value ri — the number of people in it.We know that the band will travel along some path, having concerts in some cities along the path. The band's path will not pass one city twice, each time they move to the city that hasn't been previously visited. Thus, the musicians will travel along some path (without visiting any city twice) and in some (not necessarily all) cities along the way they will have concerts.The band plans to gather all the big stadiums and concert halls during the tour, so every time they will perform in a city which population is larger than the population of the previously visited with concert city. In other words, the sequence of population in the cities where the concerts will be held is strictly increasing.In a recent interview with the leader of the "road accident" band promised to the fans that the band will give concert in the largest possible number of cities! Thus the band will travel along some chain of cities of Treeland and have concerts in some of these cities, so that the population number will increase, and the number of concerts will be the largest possible.The fans of Treeland are frantically trying to figure out how many concerts the group will have in Treeland. Looks like they can't manage without some help from a real programmer! Help the fans find the sought number of concerts.

The first line of the input contains integer n (2 ≤ n ≤ 6000) — the number of cities in Treeland. The next line contains n integers r1, r2, ..., rn (1 ≤ ri ≤ 106), where ri is the population of the i-th city. The next n - 1 lines contain the descriptions of the roads, one road per line. Each road is defined by a pair of integers aj, bj (1 ≤ aj, bj ≤ n) — the pair of the numbers of the cities that are connected by the j-th road. All numbers in the lines are separated by spaces.

Print the number of cities where the "Road Accident" band will have concerts.

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val minByLen = Array.ofDim[Int](n + 1)
  val as = Array.ofDim[Int](n)
  var max = 0

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    as(depth) = rs(u)

    var i = 0
    while (i < adj(u).length) {
      val v = adj(u)(i)
      if (v != prev) dfs(v, u, depth + 1)
      i += 1
    }

    if (adj(u).length == 1 && depth >= max) {

      var len = 0

      for (i <- 0 to depth) {

        var lo = 1
        var hi = len

        while (lo <= hi) {
          val mid = (lo + hi) >> 1
          if (as(minByLen(mid)) < as(i)) lo = mid + 1
          else hi = mid - 1
        }

        minByLen(lo) = i
        if (lo > len) len = lo
      }

      if (len > max) max = len
    }
  }

  for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)

  println(max)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val minByLen = Array.ofDim[Int](n + 1)
  val as = Array.ofDim[Int](n)
  var max = 0

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    as(depth) = rs(u)

    for (v <- adj(u))
      if (v != prev) dfs(v, u, depth + 1)

    if (adj(u).length == 1 && depth >= max) {

      var len = 0

      for (i <- 0 to depth) {

        var lo = 1
        var hi = len

        while (lo <= hi) {
          val mid = (lo + hi) >> 1
          if (as(minByLen(mid)) < as(i)) lo = mid + 1
          else hi = mid - 1
        }

        minByLen(lo) = i
        if (lo > len) len = lo
      }

      if (len > max) max = len
    }
  }

  for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)

  println(max)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val minByLen = Array.ofDim[Int](n + 1)
  val as = Array.ofDim[Int](n)
  var max = 0

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    as(depth) = rs(u)

    var i = 0
    while (i < adj(u).length) {
      val v = adj(u)(i)
      if (v != prev) dfs(v, u, depth + 1)
      i += 1
    }

    if (adj(u).length == 1 && depth >= max) {

      var i, len = 0

      while (i <= depth) {

        var lo = 1
        var hi = len

        while (lo <= hi) {
          val mid = (lo + hi) >> 1
          if (as(minByLen(mid)) < as(i)) lo = mid + 1
          else hi = mid - 1
        }

        minByLen(lo) = i
        if (lo > len) len = lo

        i += 1
      }

      if (len > max) max = len
    }
  }

  for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)

  println(max)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val minByLen = Array.ofDim[Int](n + 1)
  val as = Array.ofDim[Int](n)
  var max = 0

  @annotation.tailrec
  def binSearch(low: Int, hi: Int, target: Int): Int = {
    if (hi < low) low // not found - return insertion point
    else {
      val mid = (low + hi) >>> 1
      val fmid = minByLen(mid)
      if (fmid == target) mid
      else if (fmid < target) binSearch(mid + 1, hi, target)
      else binSearch(low, mid - 1, target)
    }
  }

  def lis(as: Array[Int], limit: Int): Int = {

    var len = 0

    for (i <- 0 until limit) {
      val a = as(i)
      val j = binSearch(0, len - 1, a)
      if (j == len) {
        minByLen(j) = a
        len += 1
      } else if (a < minByLen(j)) minByLen(j) = a
    }

    len
  }

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    as(depth) = rs(u)

    for (v <- adj(u))
      if (v != prev) dfs(v, u, depth + 1)

    if (adj(u).length == 1 && depth >= max) max = math.max(max, lis(as, depth + 1))
  }

  for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)

  println(max)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val minByLen = Array.ofDim[Int](n + 1)
  val as = Array.ofDim[Int](n)
  var max = 0

  @annotation.tailrec
  def binSearch(low: Int, hi: Int, target: Int): Int = {
    if (hi < low) low // not found - return insertion point
    else {
      val mid = (low + hi) >>> 1
      val fmid = minByLen(mid)
      if (fmid == target) mid
      else if (fmid < target) binSearch(mid + 1, hi, target)
      else binSearch(low, mid - 1, target)
    }
  }

  def lis(as: Array[Int], limit: Int): Int = {

    var i, len = 0

    while (i < limit) {
      val a = as(i)
      val j = binSearch(0, len - 1, a)
      if (j == len) {
        minByLen(j) = a
        len += 1
      } else if (a < minByLen(j)) minByLen(j) = a
      i += 1
    }

    len
  }

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    as(depth) = rs(u)

    var i = 0
    while (i < adj(u).length) {
      val v = adj(u)(i)
      if (v != prev) dfs(v, u, depth + 1)
      i += 1
    }

    if (adj(u).length == 1 && depth >= max) max = math.max(max, lis(as, depth + 1))
  }

  for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)

  println(max)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val m = Array.ofDim[Int](n + 1)
  val population = Array.ofDim[Int](n)
  var max = 0

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    population(depth) = rs(u)

    var i = 0
    while (i < adj(u).length) {
      val v = adj(u)(i)
      if (v != prev) dfs(v, u, depth + 1)
      i += 1
    }

    if (adj(u).length == 1 && depth >= max) {

      var i, len = 0

      while (i <= depth) {

        var lo = 1
        var hi = len

        while (lo <= hi) {
          val mid = (lo + hi) >> 1
          if (population(m(mid)) < population(i)) lo = mid + 1
          else hi = mid - 1
        }

        m(lo) = i
        if (lo > len) len = lo

        i+= 1
      }

      if (len > max) max = len
    }
  }

  for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)

  println(max)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val minByLen = Array.ofDim[Int](n)
  val as = Array.ofDim[Int](n)
  var max = 0

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    as(depth) = rs(u)

    var i = 0
    while (i < adj(u).length) {
      val v = adj(u)(i)
      if (v != prev) dfs(v, u, depth + 1)
      i += 1
    }

    if (adj(u).length == 1 && depth >= max) {

      var i, len = 0

      while (i <= depth) {

        var lo = 0
        var hi = len - 1

        while (lo <= hi) {
          val mid = (lo + hi) >> 1
          if (as(minByLen(mid)) < as(i)) lo = mid + 1
          else hi = mid - 1
        }

        minByLen(lo) = i
        if (lo == len) len += 1

        i += 1
      }

      if (len > max) max = len
    }
  }

  for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)

  println(max)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val m = Array.ofDim[Int](n + 1)
  val population = Array.ofDim[Int](n)
  var max = 0

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    population(depth) = rs(u)

    var i = 0
    while (i < adj(u).length) {
      val v = adj(u)(i)
      if (v != prev) dfs(v, u, depth + 1)
      i += 1
    }

    if (adj(u).length == 1 && depth > max) {

      var i, len = 0

      while (i <= depth) {

        var lo = 1
        var hi = len

        while (lo <= hi) {
          val mid = (lo + hi) >> 1
          if (population(m(mid)) < population(i)) lo = mid + 1
          else hi = mid - 1
        }

        m(lo) = i
        if (lo > len) len = lo

        i+= 1
      }

      if (len > max) max = len
    }
  }

  for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)

  println(max)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val m = Array.ofDim[Int](n + 1)
  val as = Array.ofDim[Int](n)
  var max = 0

  @annotation.tailrec
  def binSearch(low: Int, hi: Int, f: Int => Int, target: Int): (Boolean, Int) = {
    if (hi < low) (false, low) // not found - return insertion point
    else {
      val mid = (low + hi) >>> 1
      val fmid = f(mid)
      if (fmid == target) (true, mid)
      else if (fmid < target) binSearch(mid + 1, hi, f, target)
      else binSearch(low, mid - 1, f, target)
    }
  }

  def lis(as: Array[Int]): Int = {

    var len = 0
    for (a <- as) {
      val (_, j) = binSearch(0, len - 1, m, a)
      if (j == len) {
        m(j) = a
        len += 1
      } else if (a < m(j)) m(j) = a
    }

    len
  }

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    as(depth) = rs(u)

    for (v <- adj(u))
      if (v != prev) dfs(v, u, depth + 1)

    if (adj(u).length == 1 && depth >= max) max = math.max(max, lis(as))
  }

  for (u <- 0 until n) if (adj(u).size == 1) dfs(u, -1, 0)

  println(max)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val m = Array.ofDim[Int](n + 1)
  val population = Array.ofDim[Int](n)
  var max = 0

  def dfs(u: Int, prev: Int, depth: Int, len: Int): Unit = {

    population(depth) = rs(u)

    var lo = 0
    var hi = len

    while (lo <= hi) {
      val mid = (lo + hi) / 2
      if (population(m(mid)) < population(depth)) lo = mid + 1
      else hi = mid - 1
    }

    m(lo) = depth
    if (lo > max) max = lo

    for (v <- adj(u)) if (v != prev) {
      dfs(v, u, depth + 1, lo)
    }
  }

  for (u <- 0 until n) dfs(u, -1, 0, 0)

  println(max + 1)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val m = Array.ofDim[Int](n + 1)
  val population = Array.ofDim[Int](n)
  var max = 0

  def dfs(u: Int, prev: Int, depth: Int, len: Int): Unit = {
    population(depth) = rs(u)

    var lo = 0
    var hi = len

    while (lo <= hi) {
      val mid = (lo + hi) / 2
      if (population(m(mid)) < population(depth)) lo = mid + 1
      else hi = mid - 1
    }

    m(lo) = depth
    if (lo > max) max = lo

    for (v <- adj(u)) if (v != prev) {
      dfs(v, u, depth + 1, lo max len)
    }
  }

  for (u <- 0 until n) dfs(u, -1, 0, 0)

  println(max + 1)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object P279F extends App {

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

  val Array(n) = readInts(1)
  val rs = readInts(n)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  val m = Array.ofDim[Int](n + 1)
  val population = Array.ofDim[Int](n)
  var max = 0

  def dfs(u: Int, prev: Int, depth: Int): Unit = {

    population(depth) = rs(u)

    var noChildren = true
    for (v <- adj(u)) if (v != prev) {
      dfs(v, u, depth + 1)
      noChildren = false
    }

    if (noChildren) {
      var len = 0
      for (i <- 0 until depth) {

        var lo = 1
        var hi = len

        while (lo <= hi) {
          val mid = (lo + hi) / 2
          if (population(m(mid)) < population(i)) lo = mid + 1
          else hi = mid - 1
        }

        m(lo) = i
        if (lo > len) len = lo

      }

      if (len > max) max = len
    }
  }

  for (u <- 0 until n) dfs(u, -1, 0)

  println(max + 1)
}


Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster.There are $$$n$$$ books in the family library. The $$$i$$$-th book is described by three integers: $$$t_i$$$ — the amount of time Alice and Bob need to spend to read it, $$$a_i$$$ (equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ if not), and $$$b_i$$$ (equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ if not).So they need to choose some books from the given $$$n$$$ books in such a way that:  Alice likes at least $$$k$$$ books from the chosen set and Bob likes at least $$$k$$$ books from the chosen set;  the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $$$t_i$$$ over all books that are in the chosen set.Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$). The next $$$n$$$ lines contain descriptions of books, one description per line: the $$$i$$$-th line contains three integers $$$t_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \le t_i \le 10^4$$$, $$$0 \le a_i, b_i \le 1$$$), where:   $$$t_i$$$ — the amount of time required for reading the $$$i$$$-th book;  $$$a_i$$$ equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ otherwise;  $$$b_i$$$ equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ otherwise.

If there is no solution, print only one integer -1. Otherwise print one integer $$$T$$$ — the minimum total reading time of the suitable set of books.

//package codeforces.contests._1374

object ReadingBookEasy {

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

    val (aliceL, bobL, bothL) = (1 to n).foldLeft((List.empty[Int], List.empty[Int], List.empty[Int])) {
      case ((alice, bob, both), _) =>
        val Array(time, a, b) = io.StdIn.readLine.split(" ").map(_.toInt)
        (
          if (a == 1 && b == 0) time :: alice else alice,
          if (a == 0 && b == 1) time :: bob else bob,
          if (a == 1 && b == 1) time :: both else both
        )
    }

    val aliceA = aliceL.toArray
    val bobA = bobL.toArray
    val bothA = bothL.toArray

    println {
      if (aliceA.length + bothA.length >= k && bobA.length + bothA.length >= k) {

        val aliceP = aliceA.sorted.scanLeft(0)(_ + _)
        val bobP = bobA.sorted.scanLeft(0)(_ + _)
        val bothP = bothA.sorted.scanLeft(0)(_ + _)

        val i = bothP.indices.minBy { i =>
          if (i > k) Int.MaxValue
          else {
            val r = k - i
            if (r < aliceP.length && r < bobP.length)
              aliceP(r) + bobP(r) + bothP(i)
            else Int.MaxValue
          }
        }
        val r = k - i
        aliceP(r) + bobP(r) + bothP(i)
      } else -1
    }
  }
}

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 CF653A(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 CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
      val n = ni()
      val k = ni()

      val b = Array.ofDim[Books](n)
      REP(n) { i =>
        b(i) = Books(ni(), ni(), ni())
      }

      if(b.count(p => p.a == 1) < k || b.count(p => p.b == 1) < k) {
        out.println("-1")
      } else {
        val c = b.sortBy(f => f.t)
        val lstA = c.filter(p => p.a == 1 && p.b == 0)
        val lstB = c.filter(p => p.a == 0 && p.b == 1)
        val lstC = c.filter(p => p.a == 1 && p.b == 1)

        var cst = 0
        var tk = 0
        var idL = 0
        var idT = 0

        while (tk < k) {
          val g = if(idL < lstA.length && idL < lstB.length) {
            lstA(idL).t + lstB(idL).t
          } else Int.MaxValue

          val h = if(idT < lstC.length) lstC(idT).t else Int.MaxValue
//          out.println(g + " " + h)
          if(g < h) {
            cst += g
            idL+=1
          } else {
            cst += h
            idT += 1
          }
          tk += 1
        }
        out.print(cst)
      }
  }

  case class Books(t: Int, a: Int, b: Int)

}


There are $$$n$$$ beautiful skyscrapers in New York, the height of the $$$i$$$-th one is $$$h_i$$$. Today some villains have set on fire first $$$n - 1$$$ of them, and now the only safety building is $$$n$$$-th skyscraper.Let's call a jump from $$$i$$$-th skyscraper to $$$j$$$-th ($$$i < j$$$) discrete, if all skyscrapers between are strictly lower or higher than both of them. Formally, jump is discrete, if $$$i < j$$$ and one of the following conditions satisfied:   $$$i + 1 = j$$$  $$$\max(h_{i + 1}, \ldots, h_{j - 1}) < \min(h_i, h_j)$$$  $$$\max(h_i, h_j) < \min(h_{i + 1}, \ldots, h_{j - 1})$$$. At the moment, Vasya is staying on the first skyscraper and wants to live a little longer, so his goal is to reach $$$n$$$-th skyscraper with minimal count of discrete jumps. Help him with calcualting this number.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — total amount of skyscrapers. The second line contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$) — heights of skyscrapers.

Print single number $$$k$$$ — minimal amount of discrete jumps. We can show that an answer always exists.

NoteIn the first testcase, Vasya can jump in the following way: $$$1 \rightarrow 2 \rightarrow 4 \rightarrow 5$$$.In the second and third testcases, we can reach last skyscraper in one jump.Sequence of jumps in the fourth testcase: $$$1 \rightarrow 3 \rightarrow 5$$$.

//package codeforces.contests._1407

object DiscreteCentrifugalJumps {

  /**
   * Monotonic Stack, right view
   *
   * @param seq      elements, randomly accessible
   * @param ordering implicit ordering for gt operator
   * @tparam A type of each element
   * @return left view
   */
  def rightView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {
    val result = new Array[Int](seq.length)

    seq.indices.foldRight[List[Int]](Nil) { (idx, stack) =>
      val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))
      result(idx) = uStack.headOption.getOrElse(-1)
      idx :: uStack
    }

    result
  }

  /**
   * Monotonic Stack, left view
   *
   * @param seq      elements, randomly accessible
   * @param ordering implicit ordering for gt operator
   * @tparam A type of each element
   * @return left view
   */
  def leftView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {
    val result = new Array[Int](seq.length)

    seq.indices.foldLeft[List[Int]](Nil) { (stack, idx) =>
      val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))
      result(idx) = uStack.headOption.getOrElse(-1)
      idx :: uStack
    }

    result
  }

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

    val rightIncreasingView: IndexedSeq[Int] = rightView(arr) // check for -1
    val rightDecreasingView: IndexedSeq[Int] = rightView(arr)(Ordering.Int.reverse) // check for -1

    val leftIncreasingView = leftView(arr)
    val leftDecreasingView = leftView(arr)(Ordering.Int.reverse)

    val result = {
      val dp: Array[Int] = (0 until n).toArray
      dp.indices.foreach { i =>

        // relax dp(i) first
        if (leftIncreasingView(i) != -1)
          dp(i) = dp(i) min (dp(leftIncreasingView(i)) + 1)

        if (leftDecreasingView(i) != -1)
          dp(i) = dp(i) min (dp(leftDecreasingView(i)) + 1)

        // relax the future
        if (rightIncreasingView(i) != -1)
          dp(rightIncreasingView(i)) = dp(rightIncreasingView(i)) min (dp(i) + 1)

        if (rightDecreasingView(i) != -1)
          dp(rightDecreasingView(i)) = dp(rightDecreasingView(i)) min (dp(i) + 1)

        if (i + 1 < n)
          dp(i + 1) = dp(i + 1) min (dp(i) + 1)
      }
      dp(n - 1)
    }

    println(result)
  }

}

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

object D {
    def findLeft(a: Array[Int])(f: (Int, Int)=> Boolean): Array[Int]= {
        val s = ArrayBuffer[Int]()
        val result = Array.fill[Int](a.size)(0)
        for (i <- 0 until a.size) {
            while (!s.isEmpty && !f(a(s.last), a(i)))
                s.remove(s.size - 1)
            if (s.isEmpty)
                result(i) = -1
            else
                result(i) = s.last
            s += i
        }
        result
    }

  def findRight(a: Array[Int])(f: (Int, Int)=> Boolean): Array[Int] = findLeft(a.reverse)(f).map((x) => a.size - 1 - x).reverse

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val dp = Array.fill[Int](n)(n + 1)
    dp(0) = 0
    val ll = findLeft(a)(Ordering[Int].lteq)
    val lg = findLeft(a)(Ordering[Int].gteq)
    val rl = findRight(a)(Ordering[Int].lteq)
    val rg = findRight(a)(Ordering[Int].gteq)
    for(i <- 0 until a.size) {
        if(ll(i) != -1)
            dp(i) = min(dp(i), dp(ll(i)) + 1)
        if(lg(i) != -1)
            dp(i) = min(dp(i), dp(lg(i)) + 1)
        if(rl(i) != n)
            dp(rl(i)) = min(dp(rl(i)), dp(i) + 1)
        if(rg(i) != n)
            dp(rg(i)) = min(dp(rg(i)), dp(i) + 1)
    }
    println(dp(n - 1))
  }
}

//package codeforces.contests._1407

object DiscreteCentrifugalJumps {

  /**
   * Monotonic Stack, right view
   *
   * @param seq      elements, randomly accessible
   * @param ordering implicit ordering for gt operator
   * @tparam A type of each element
   * @return left view
   */
  def rightView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {
    val result = new Array[Int](seq.length)

    seq.indices.foldRight[List[Int]](Nil) { (idx, stack) =>
      val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))
      result(idx) = uStack.headOption.getOrElse(-1)
      idx :: uStack
    }

    result
  }

  /**
   * Monotonic Stack, left view
   *
   * @param seq      elements, randomly accessible
   * @param ordering implicit ordering for gt operator
   * @tparam A type of each element
   * @return left view
   */
  def leftView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {
    val result = new Array[Int](seq.length)

    seq.indices.foldLeft[List[Int]](Nil) { (stack, idx) =>
      val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))
      result(idx) = uStack.headOption.getOrElse(-1)
      idx :: uStack
    }

    result
  }

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

    val rightIncreasingView: IndexedSeq[Int] = rightView(arr) // check for -1
    val rightMaxView: IndexedSeq[Int] = {
      val view = arr.clone()
      view(n - 1) = n - 1
      (0 to n - 2).foldRight(n - 1) { (i, maxi) =>
        if (arr(i) >= arr(maxi)) {
          view(i) = i
          i
        } else {
          view(i) = maxi
          maxi
        }
      }
      view
    }

    val rightDecreasingView: IndexedSeq[Int] = rightView(arr)(Ordering.Int.reverse) // check for -1
    val rightMinView: IndexedSeq[Int] = {
      val view = arr.clone()
      view(n - 1) = n - 1
      (0 to n - 2).foldRight(n - 1) { (i, mini) =>
        if (arr(i) <= arr(mini)) {
          view(i) = i
          i
        } else {
          view(i) = mini
          mini
        }
      }
      view
    }

    val leftIncreasingView = leftView(arr)
    val leftDecreasingView = leftView(arr)(Ordering.Int.reverse)

    val result = {
      val dp: Array[Int] = (0 until n).toArray
      (0 to n - 2).foreach { i =>

        // relax dp(i) first
        if (i > 0) {
          val h = {
            if (arr(i - 1) < arr(i))
              leftIncreasingView(i)
            else if (arr(i - 1) > arr(i - 1))
              leftDecreasingView(i)
            else -1
          }

          if (h != -1)
            dp(i) = dp(i) min (dp(h) + 1)
        }

        // relax the future
        if (arr(i) > arr(i + 1)) {

          val inc = rightIncreasingView(i)
          val j = {
            if (inc == -1) rightMaxView(i + 1)
            else inc
          }
          dp(j) = dp(j) min (dp(i) + 1)

        } else if (arr(i) < arr(i + 1)) {

          val dec = rightDecreasingView(i)
          val j = {
            if (dec == -1) rightMinView(i + 1)
            else dec
          }
          dp(j) = dp(j) min (dp(i) + 1)

        }

        dp(i + 1) = dp(i + 1) min (dp(i) + 1)
      }
      dp(n - 1)
    }

    println(result)
  }

}

//package codeforces.contests._1407

object DiscreteCentrifugalJumps {

  /**
   * Monotonic Stack, right view
   *
   * @param seq      elements, randomly accessible
   * @param ordering implicit ordering for gt operator
   * @tparam A type of each element
   * @return left view
   */
  def rightView[A](seq: IndexedSeq[A])(implicit ordering: Ordering[A]): IndexedSeq[Int] = {
    val result = new Array[Int](seq.length)

    seq.indices.foldRight[List[Int]](Nil) { (idx, stack) =>
      val uStack = stack.dropWhile(i => ordering.lt(seq(i), seq(idx)))
      result(idx) = uStack.headOption.getOrElse(-1)
      idx :: uStack
    }

    result
  }

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

    val rightIncreasingView: IndexedSeq[Int] = rightView(arr) // check for -1
    val rightMaxView: IndexedSeq[Int] = {
      val view = arr.clone()
      view(n - 1) = n - 1
      (0 to n - 2).foldRight(n - 1) { (i, maxi) =>
        if (arr(i) >= arr(maxi)) {
          view(i) = i
          i
        } else {
          view(i) = maxi
          maxi
        }
      }
      view
    }

    val rightDecreasingView: IndexedSeq[Int] = rightView(arr)(Ordering.Int.reverse) // check for -1
    val rightMinView: IndexedSeq[Int] = {
      val view = arr.clone()
      view(n - 1) = n - 1
      (0 to n - 2).foldRight(n - 1) { (i, mini) =>
        if (arr(i) <= arr(mini)) {
          view(i) = i
          i
        } else {
          view(i) = mini
          mini
        }
      }
      view
    }

    val result = {
      val dp: Array[Int] = (0 until n).toArray
      (0 to n - 2).foreach { i =>
        if (arr(i) > arr(i + 1)) {

          val inc = rightIncreasingView(i)
          val j = {
            if (inc == -1) rightMaxView(i + 1)
            else inc
          }
          dp(j) = dp(j) min (dp(i) + 1)

        } else if (arr(i) < arr(i + 1)) {

          val dec = rightDecreasingView(i)
          val j = {
            if (dec == -1) rightMinView(i + 1)
            else dec
          }
          dp(j) = dp(j) min (dp(i) + 1)

        }

        dp(i + 1) = dp(i + 1) min (dp(i) + 1)
      }
      dp(n - 1)
    }

    println(result)
  }

}