You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.You are playing the game on the new generation console so your gamepad have $$$26$$$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.You are given a sequence of hits, the $$$i$$$-th hit deals $$$a_i$$$ units of damage to the opponent's character. To perform the $$$i$$$-th hit you have to press the button $$$s_i$$$ on your gamepad. Hits are numbered from $$$1$$$ to $$$n$$$.You know that if you press some button more than $$$k$$$ times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of $$$a_i$$$ over all $$$i$$$ for the hits which weren't skipped.Note that if you skip the hit then the counter of consecutive presses the button won't reset.Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of hits and the maximum number of times you can push the same button in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the damage of the $$$i$$$-th hit. The third line of the input contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters — the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).

Print one integer $$$dmg$$$ — the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.

NoteIn the first example you can choose hits with numbers $$$[1, 3, 4, 5, 6, 7]$$$ with the total damage $$$1 + 16 + 18 + 7 + 2 + 10 = 54$$$.In the second example you can choose all hits so the total damage is $$$2 + 4 + 1 + 3 + 1000 = 1010$$$.In the third example you can choose all hits expect the third one so the total damage is $$$2 + 4 + 3 + 1000 = 1009$$$.In the fourth example you can choose hits with numbers $$$[2, 3, 6, 8]$$$. Only this way you can reach the maximum total damage $$$15 + 2 + 8 + 16 = 41$$$.In the fifth example you can choose only hits with numbers $$$[2, 4, 6]$$$ with the total damage $$$18 + 19 + 15 = 52$$$.In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage $$$10$$$.

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val A = na(N)
    val S = ns(N)

    /**
      * [l, r]
      */
    def findMx(l: Int, r: Int): Long = {
      if (r - l + 1 <= K) {
        sumL(A.slice(l, r + 1))
      } else {
        val B = A.slice(l, r + 1)
        sort(B)
        sumL(B.takeRight(K))
      }
    }

    var ans = 0L
    var l, r = 0
    while(l < N) {
      while(r + 1 < N && S(l) == S(r + 1)) {
        r += 1
      }
      ans += findMx(l, r)

      l = r + 1
    }

    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn._

object Brutality {
  def best(scores: IndexedSeq[Long], k: Int): Long = {
    scores.sorted.drop(scores.length - k).sum
  }
  def score(scores: IndexedSeq[Long], keys: IndexedSeq[Char], k: Int): Long = {
    var res = 0L
    var start = 0
    for (i <- scores.indices) {
      val len = i - start
      if (len > 0 && keys(i) != keys(i - 1)) {
        res += best(scores.slice(start, i), k)
        start = i
      }
    }
    res += best(scores.drop(start), k)
    res
  }

  def main(args: Array[String]): Unit = {
    val line1 = readLine().split("\\s")
    val n = line1(0).toInt
    val k = line1(1).toInt
    val a = readLine().split("\\s").map(_.toLong)
    val s = readLine()
    require(a.length == n)
    require(s.length == n)
    val res = Brutality.score(a, s, k)
    println(res)
  }

}

object Main2 extends App {

    import java.io._
import java.util
import java.util.{Locale, StringTokenizer, TreeSet}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val k = in.nextInt

  val a = in.nextLine.split(' ').map(_.toInt)
  val pairs = a.zip(in.nextLine) :+ (0, '0')

  val cnt = new Array[Int](256)
  var prev: Char = 0
  var v = Vector[Long]()
  var ans = 0l

  for ((dmg, button) <- pairs) {
    if (button != prev) {
      ans += v.sortBy(-_).take(k).sum
      v = Vector()
    }
    v :+= dmg.toLong
    prev = button
  }

  out.println(ans)
  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

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

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

import scala.io.StdIn._

object Brutality {
  def best(scores: IndexedSeq[Int], k: Int): Long = {
    scores.sorted.drop(scores.length - k).sum
  }
  def score(scores: IndexedSeq[Int], keys: IndexedSeq[Char], k: Int): Long = {
    var res = 0L
    var start = 0
    for (i <- scores.indices) {
      val len = i - start
      if (len > 0 && keys(i) != keys(i - 1)) {
        res += best(scores.slice(start, i), k)
        start = i
      }
    }
    res += best(scores.drop(start), k)
    res
  }

  def main(args: Array[String]): Unit = {
    val line1 = readLine().split("\\s")
    val n = line1(0).toInt
    val k = line1(1).toInt
    val a = readLine().split("\\s").map(_.toInt)
    val s = readLine()
    require(a.length == n)
    require(s.length == n)
    val res = Brutality.score(a, s, k)
    println(res)
  }

}

object Main2 extends App {

    import java.io._
    import java.util
    import java.util.{Locale, StringTokenizer, TreeSet}

    import scala.collection.mutable
    import scala.collection.mutable.ListBuffer
    import scala.io.StdIn

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val k = in.nextInt

  val a = in.nextLine.split(' ').map(_.toInt)
  val pairs = a.zip(in.nextLine) :+ (0, '0')

  val cnt = new Array[Int](256)
  var prev: Char = 0
  var v = Vector[Int]()
  var ans = 0l

  for ((dmg, button) <- pairs) {
    if (button != prev) {
      ans += v.sortBy(-_).take(k).sum
      v = Vector()
    }
    v :+= dmg
    prev = button
  }

  out.println(ans)
  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

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

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}


You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).

The first line contains three positive integers n, p, q (1 ≤ p, q ≤ n ≤ 100). The second line contains the string s consists of lowercase and uppercase latin letters and digits.

If it's impossible to split the string s to the strings of length p and q print the only number "-1". Otherwise in the first line print integer k — the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s — from left to right. If there are several solutions print any of them.

object Solution extends App {
val npq = Console.readLine.split(' ')
val n = npq(0) toInt
val p = npq(1) toInt
val q = npq(2) toInt
var s = Console.readLine

var requiredp = 0
var requiredq = 0
if ((n % p) == 0) {
  requiredp = n / p
} else if ((n % q) == 0) {
  requiredq = n / q
} else {
import scala.util.control.Breaks._
breakable {

while ((requiredp * p) < n) {
  val right = n - (requiredp * p)
  if ((right % q) == 0) {
    requiredq = right / q
    break
  }
  requiredp = requiredp + 1;
}

}
}

val isSolution = n == (requiredp * p + requiredq * q)
if (!isSolution)
  println(-1)
else {
  println(requiredp + requiredq)

  for (i <- 1 to requiredp) {
    println(s take p)
    s = s drop p
  }
  for (i <- 1 to requiredq) {
    println(s take q)
    s = s drop q
  }
}
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, p, q) = in.next().split(' ').map(_.toInt)
  val str = in.next()
  val min = Math.min(p, q)
  val max = Math.max(p, q)
  val res = (0 to str.length / max).find{i =>
    val left = str.length - max * i
    left % min == 0
  }

  if (res.isEmpty)
    println(-1)
  else {
    val maxLength = max * res.get
    println(res.get + (str.length - maxLength) / min)
    println((str.take(maxLength).grouped(max).toList ::: str.drop(maxLength).grouped(min).toList).mkString("\n"))
  }
}

import java.io.PrintWriter
import java.io.BufferedInputStream
import java.io.IOException

import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.Scanner

import scala.annotation.tailrec
;

/**
 * Created by Administrator on 2015/12/31.
 */
object Main {
  def main(args: Array[String]){
    val scan = new Scanner(System.in);
      val out: PrintWriter = new PrintWriter(System.out)
      val n = scan.nextInt
      val p = scan.nextInt
      val q = scan.nextInt
      val s = scan.next
      val (x,y) = Calpq(n,p,q,0)
      //println(s+" "+x+" "+y)
      if(x<0){
      out.println(-1)
      }else{
      out.println(x+y)
      for( i <- 1 to x){
        out.println(s.substring(p*(i-1),p*i))
      }
      val k = p*x
      for( i <- 1 to y){
        out.println(s.substring(k+q*(i-1),k+q*i))
      }
      }

      out.close()
  }

  @tailrec
  def Calpq(n: Int,p: Int,q: Int,pn:Int): (Int,Int) = {
    val k = n - p*pn
    if(k<0){
      (-1,-1)
    }
    else if(k%q==0){
        (pn,k/q)
      }else{
        Calpq(n,p,q,pn+1)
      }
  }
}

object Solution extends App {
val npq = Console.readLine.split(' ')
val n = npq(0) toInt
val p = npq(1) toInt
val q = npq(2) toInt
var s = Console.readLine

var requiredp = 0
var requiredq = 0
if ((n % p) == 0) {
  requiredp = n / p
} else if ((n % q) == 0) {
  requiredq = n / q
} else {
import scala.util.control.Breaks._
breakable {

while ((requiredp * p) < n) {
  val right = n - (requiredp * p)
  if ((right % q) == 0) {
    requiredq = right / q
    break
  }
  requiredp = requiredp + 1;
}

}
}

println("debug", requiredp, requiredq)

val isSolution = n == (requiredp * p + requiredq * q)
if (!isSolution)
  println(-1)
else {
  println(requiredp + requiredq)

  for (i <- 1 to requiredp) {
    println(s take p)
    s = s drop p
  }
  for (i <- 1 to requiredq) {
    println(s take q)
    s = s drop q
  }
}
}


You are given a set of points $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ on the number line.Two points $$$i$$$ and $$$j$$$ can be matched with each other if the following conditions hold:  neither $$$i$$$ nor $$$j$$$ is matched with any other point;  $$$|x_i - x_j| \ge z$$$. What is the maximum number of pairs of points you can match with each other?

The first line contains two integers $$$n$$$ and $$$z$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le z \le 10^9$$$) — the number of points and the constraint on the distance between matched points, respectively. The second line contains $$$n$$$ integers $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ ($$$1 \le x_i \le 10^9$$$).

Print one integer — the maximum number of pairs of points you can match with each other.

NoteIn the first example, you may match point $$$1$$$ with point $$$2$$$ ($$$|3 - 1| \ge 2$$$), and point $$$3$$$ with point $$$4$$$ ($$$|7 - 3| \ge 2$$$).In the second example, you may match point $$$1$$$ with point $$$3$$$ ($$$|5 - 10| \ge 5$$$).

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, Z = ni()
    val A = na(N)
    sort(A)
    def test(x: Int): Boolean = {
      debug(s"test($x)")
      REP(x) { i =>
        val d = abs(A(N - x + i) - A(i))
        debug(s"i:$i d:$d")
        if (d < Z) return false
      }
      true
    }

    val ans = findMax(test, 0, N/2)
    out.println(ans)
  }
  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }
  def findMax(f: Int => Boolean, min: Int, max: Int): Int = {
    var l = min
    var h = max + 1
    while(h - l > 1) {
      val x = (h + l) / 2
      if (f(x)) l = x
      else h = x
    }
    l
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, Z = ni()
    val A = na(N)
    sort(A)

    var ans = 0
    var r = 0
    val used = Array.ofDim[Boolean](N)
    REP(N) { l =>
      if (!used(l)) {
        r = max(l + 1, r)
        while (r < N && A(r) - A(l) < Z) {
          r += 1
        }
        if (r < N && A(r) - A(l) >= Z) {
          debug(s"matched A($l):${A(l)} A($r):${A(r)}")
          used(l) = true
          used(r) = true
          ans += 1
          r += 1 // (l, r)でマッチしたのでこのrはもう使えない
        }
      }
    }

    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    import scala.util.Sorting
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N, Z = ni()
    val A = na(N)
    sort(A)

    var ans = 0
    var r = 0
    REP(N) { l =>
      r = max(l + 1, r)
      while(r < N && A(r) - A(l) < Z) {
        r += 1
      }
      if (r < N && A(r) - A(l) >= Z) {
        ans += 1
        r += 1 // (l, r)でマッチしたのでこのrはもう使えない
      }
    }

    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    import scala.util.Sorting
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }
}


We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value  should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and".

The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit.

If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.

import java.io.PrintWriter
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main {

  val br = new BufferedReader(new InputStreamReader(System.in))
  var out = new PrintWriter(System.out)
  var st = new StringTokenizer(br.readLine())

  def next = {
    while (!st.hasMoreTokens)
      st = new StringTokenizer(br.readLine())
    st.nextToken()
  }

  def nextDouble = next.toDouble
  def nextLong = next.toLong
  def nextInt = next.toInt

  class SegmentTree(n: Int, op: (Int, Int) => Int, identityValue: Int = 0, nullValue: Int = 0, a: Array[Int] = null) {

    val tree = new Array[Int](n<<2)
    val prop = new Array[Int](n<<2)

    if (a != null) build(1,1,n)

    def build(x: Int, tl: Int, tr: Int): Unit = {
      if (tl > tr) return
      if (tl == tr) {
        tree(x) = a(tl)
        return
      }
      build(x+x,tl,(tl+tr)>>1)
      build(x+x+1,((tl+tr)>>1)+1,tr)
      tree(x) = op(tree(x+x), tree(x+x+1))
    }

    def push(x: Int, tl: Int, tr: Int) = {
      if (prop(x) != nullValue) {
        tree(x) = op(tree(x), prop(x))
        if (tl != tr) {
          prop(x+x) = op(prop(x+x), prop(x))
          prop(x+x+1) = op(prop(x+x+1), prop(x))
        }
        prop(x) = nullValue
      }
    }

    def getInternal(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {
      if (tl > tr || tl > r || tr < l) return identityValue
      push(x, tl, tr)
      if (tl >= l && tr <= r) return tree(x)
      val q1 = getInternal(x+x, tl, (tl+tr)>>1, l, r)
      val q2 = getInternal(x+x+1, ((tl+tr)>>1)+1, tr, l, r)
      op(q1,q2)
    }

    def setInternal(x: Int, tl: Int, tr: Int, l: Int, r: Int, z: Int): Unit = {
      push(x, tl, tr)
      if (tl > tr || tl > r || tr < l) return
      if (tl >= l && tr <= r) {
        tree(x) = op(tree(x), z)
        if (tl != tr) {
          prop(x+x) = op(prop(x+x), z)
          prop(x+x+1) = op(prop(x+x+1), z)
        }
        return
      }
      setInternal(x+x, tl, (tl+tr)>>1, l, r, z)
      setInternal(x+x+1, ((tl+tr)>>1)+1, tr, l, r, z)
      tree(x) = op(tree(x+x), tree(x+x+1))
    }

    def getModifiedArray = {
      val ret = new Array[Int](n+1)
      for (i <- 1 to n)
        ret(i) = getInternal(1,1,n,i,i)
      ret
    }

    def get(l: Int, r: Int) = getInternal(1,1,n,l,r)
    def set(l: Int, r: Int, z: Int) = setInternal(1,1,n,l,r,z)

  }

  def main(args: Array[String]) {
    val n = nextInt
    val m = nextInt

    val l = new Array[Int](m+1)
    val r = new Array[Int](m+1)
    val q = new Array[Int](m+1)

    for (i <- 1 to m) {
      l(i) = nextInt
      r(i) = nextInt
      q(i) = nextInt
    }

    val stOr = new SegmentTree(n, (a,b) => a|b)

    for (i <- 1 to m)
      stOr.set(l(i),r(i),q(i))

    val a = stOr.getModifiedArray
    val stAnd = new SegmentTree(n, (a,b) => a&b, 0x7fffffff, 0, a)

    for (i <- 1 to m)
      if (stAnd.get(l(i),r(i)) != q(i)) {
        out.println("NO")
        out.close()
        return
      }

    out.println("YES")
    for (i <- 1 to n)
      out.print(a(i)+" ")
    out.close()
  }

}

import java.io.PrintWriter
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main {

  val br = new BufferedReader(new InputStreamReader(System.in))
  val MAX = 100111
  val tree = new Array[Int](MAX<<2)
  val prop = new Array[Int](MAX<<2)
  val tree2 = new Array[Int](MAX<<2)
  var out = new PrintWriter(System.out)
  var st = new StringTokenizer(br.readLine())

  def nextDouble = next.toDouble

  def next = {
    while (!st.hasMoreTokens)
      st = new StringTokenizer(br.readLine())
    st.nextToken()
  }

  def nextLong = next.toLong

  def nextInt = next.toInt

  def or(x: Int, tl: Int, tr: Int, l: Int, r: Int, mask: Int): Unit = {

    if (prop(x) != 0) {
      tree(x) |= prop(x)
      if (tl != tr) {
        prop(x+x) |= prop(x)
        prop(x+x+1) |= prop(x)
      }
      prop(x) = 0
    }

    if (tl > tr || tl > r || tr < l)
      return
    if (tl >= l && tr <= r) {
      tree(x) |= mask
      if (tl!=tr) {
        prop(x+x) |= mask
        prop(x+x+1) |= mask
      }
      return
    }

    or(x+x, tl, (tl+tr)>>1, l, r, mask)
    or(x+x+1, ((tl+tr)>>1)+1, tr, l, r, mask)

    tree(x) = tree(x+x) | tree(x+x+1)
  }

  def get(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {
    if (tl > tr || tl > r || tr < l) return 0

    if (prop(x) != 0) {
      tree(x) |= prop(x)
      if (tl != tr) {
        prop(x+x) |= prop(x)
        prop(x+x+1) |= prop(x)
      }
      prop(x) = 0
    }

    if (tl >= l && tr <= r) return tree(x)

    val q1 = get(x+x, tl, (tl+tr)>>1, l, r)
    val q2 = get(x+x+1, ((tl+tr)>>1)+1, tr, l, r)
    q1 | q2
  }

  def build(x: Int, tl: Int, tr: Int, a: Array[Int]): Unit = {
    if (tl > tr) return
    if (tl == tr) {
      tree2(x) = a(tl)
      return
    }
    build(x+x,tl,(tl+tr)>>1, a)
    build(x+x+1,((tl+tr)>>1)+1,tr, a)
    tree2(x) = tree2(x+x) & tree2(x+x+1)
  }

  def get2(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {
    if (tl > tr || tl > r || tr < l) return 0x7fffffff
    if (tl >= l && tr <= r) return tree2(x)
    val q1 = get2(x+x, tl, (tl+tr)>>1, l, r)
    val q2 = get2(x+x+1, ((tl+tr)>>1)+1, tr, l, r)
    q1 & q2
  }

  def main(args: Array[String]) {
    val n = nextInt
    val m = nextInt

    val l = new Array[Int](m+1)
    val r = new Array[Int](m+1)
    val q = new Array[Int](m+1)

    for (i <- 1 to m) {
      l(i) = nextInt
      r(i) = nextInt
      q(i) = nextInt
    }

//    val n = 100
//    val m = 5
//
//    val l = new Array[Int](m+1)
//    val r = new Array[Int](m+1)
//    val q = new Array[Int](m+1)
//
//    val rand = new Random(System.currentTimeMillis())
//    for (i <- 1 to m) {
//      l(i) = 1 + rand.nextInt(n)
//      r(i) = 1 + rand.nextInt(n)
//      if (l(i) > r(i)) {
//        val tmp = l(i)
//        l(i) = r(i)
//        r(i) = tmp
//      }
//      q(i) = rand.nextInt()
//    }
//
//    /* correct answer */
//    val correct = new Array[Int](n+1)
//    for (i <- 1 to m) {
//      for (j <- l(i) to r(i))
//        correct(j) |= q(i)
//    }
//    var ans = true
//    for (i <- 1 to m) {
//      var mask = 0x7fffffff
//      for (j <- l(i) to r(i))
//        mask &= correct(j)
//      if (mask != q(i)) {
//        ans = false
//      }
//    }
//    out.println("CORRECT ANSWER: " + (if (ans) "YES" else "NO"))
//    /* end correct answer */

    for (i <- 1 to m)
      or(1,1,n,l(i),r(i),q(i))

    val a = new Array[Int](n+1)
    for (i <- 1 to n)
      a(i) = get(1,1,n,i,i)

    build(1,1,n,a)

    for (i <- 1 to m)
      if (get2(1,1,n,l(i),r(i)) != q(i)) {
        out.println("NO")
        out.close()
        return
      }

    out.println("YES")
    for (i <- 1 to n)
      out.print(a(i)+" ")
    out.close()
  }

}

import scala.collection._

object B extends App {

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)
//println(t.mkString(" "))
    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) & t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      //println(l, r, v, tl, tr)
      if (l > r) Int.MaxValue
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        //println(query(l, Math.min(r, tm), v2, tl, tm), query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))
        query(l, Math.min(r, tm), v2, tl, tm) &
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
      }
    }

    def update(pos: Int, delta: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (tl == tr) t(v) += delta
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        if (pos <= tm) update(pos, delta, v2, tl, tm)
        else update(pos, delta, v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

  }

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

  val Array(n, m) = readInts(2)

  case class Q(l: Int, r: Int, q: Int)

  val qs = Array.ofDim[Q](m)

  for (i <- 0 until m) {
    val Array(l, r, q) = readInts(3)
    qs(i) = Q(l - 1, r - 1, q)
  }

  //val sorted = qs.sortBy(_.l)

  val xs = Array.fill(n) { 0 }

  val bits = Array.fill(31) { 0 }

  val qByL = new mutable.PriorityQueue[Q]()(Ordering.by(- _.l))
  qByL ++= qs

  val qByR = new mutable.PriorityQueue[Q]()(Ordering.by(- _.r))

  var pos = 0
  for (i <- 0 until n) {
    while (qByR.nonEmpty && qByR.head.r < i) {
      val qr = qByR.dequeue
      //println(qr)
      for (b <- 0 to 30) {
        if ((qr.q & (1 << b)) > 0) bits(b) -= 1
      }
    }
    while (qByL.nonEmpty && qByL.head.l == i) {
      val ql = qByL.dequeue
      for (b <- 0 to 30) {
        if ((ql.q & (1 << b)) > 0) {
          bits(b) += 1
        }
      }
      qByR += ql
    }
    //println(bits.mkString(" "))
    for (b <- 0 to 30) {
      if (bits(b) < 0) fail(1)
      else if (bits(b) > 0) xs(i) |= (1 << b)
    }
  }

  val segTree = SegTree(xs)
  //println(xs.mkString(" "))
  for (q <- qs) {
    //println(q, segTree.query(q.l, q.r))
    if (segTree.query(q.l, q.r) != q.q) fail(2)
  }

  println("YES")
  println(xs.mkString(" "))

  def fail(x: Int) = {
    println("NO")
    System.exit(0)
  }
}

import java.io.PrintWriter
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main {

  val br = new BufferedReader(new InputStreamReader(System.in))
  val MAX = 100111
  val tree = new Array[Int](MAX<<2)
  val prop = new Array[Int](MAX<<2)
  val tree2 = new Array[Int](MAX<<2)
  var out = new PrintWriter(System.out)
  var st = new StringTokenizer(br.readLine())

  def nextDouble = next.toDouble

  def next = {
    while (!st.hasMoreTokens)
      st = new StringTokenizer(br.readLine())
    st.nextToken()
  }

  def nextLong = next.toLong

  def nextInt = next.toInt

  def or(x: Int, tl: Int, tr: Int, l: Int, r: Int, mask: Int): Unit = {

    if (prop(x) != 0) {
      tree(x) |= prop(x)
      if (tl != tr) {
        prop(x+x) |= prop(x)
        prop(x+x+1) |= prop(x)
      }
      prop(x) = 0
    }

    if (tl > tr || tl > r || tr < l)
      return
    if (tl >= l && tr <= r) {
      tree(x) |= mask
      if (tl!=tr) {
        prop(x+x) |= mask
        prop(x+x+1) |= mask
      }
      return
    }

    or(x+x, tl, (tl+tr)>>1, l, r, mask)
    or(x+x+1, ((tl+tr)>>1)+1, tr, l, r, mask)

    tree(x) = tree(x+x) | tree(x+x+1)
  }

  def get(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {
    if (tl > tr || tl > r || tr < l) return 0

    if (prop(x) != 0) {
      tree(x) |= prop(x)
      if (tl != tr) {
        prop(x+x) |= prop(x)
        prop(x+x+1) |= prop(x)
      }
      prop(x) = 0
    }

    if (tl >= l && tr <= r) return tree(x)

    val q1 = get(x+x, tl, (tl+tr)>>1, l, r)
    val q2 = get(x+x+1, ((tl+tr)>>1)+1, tr, l, r)
    q1 | q2
  }

  def build(x: Int, tl: Int, tr: Int, a: Array[Int]): Unit = {
    if (tl > tr) return
    if (tl == tr) {
      tree2(x) = a(tl)
      return
    }
    build(x+x,tl,(tl+tr)>>1, a)
    build(x+x+1,((tl+tr)>>1)+1,tr, a)
    tree2(x) = tree2(x+x) & tree2(x+x+1)
  }

  def get2(x: Int, tl: Int, tr: Int, l: Int, r: Int): Int = {
    if (tl > tr || tl > r || tr < l) return 0
    if (tl >= l && tr <= r) return tree2(x)
    val q1 = get2(x+x, tl, (tl+tr)>>1, l, r)
    val q2 = get2(x+x+1, ((tl+tr)>>1)+1, tr, l, r)
    q1 & q2
  }

  def main(args: Array[String]) {
    val n = nextInt
    val m = nextInt

    val l = new Array[Int](m+1)
    val r = new Array[Int](m+1)
    val q = new Array[Int](m+1)

    for (i <- 1 to m) {
      l(i) = nextInt
      r(i) = nextInt
      q(i) = nextInt
    }

    for (i <- 1 to m)
      or(1,1,n,l(i),r(i),q(i))

    val a = new Array[Int](n+1)
    for (i <- 1 to n)
      a(i) = get(1,1,n,i,i)

    build(1,1,n,a)

    for (i <- 1 to m)
      if (get2(1,1,n,l(i),r(i)) != q(i)) {
        out.println("NO")
        out.close()
        return
      }

    out.println("YES")
    for (i <- 1 to n)
      out.print(a(i)+" ")
    out.close()
  }

}

import scala.collection._

object B extends App {

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)
//println(t.mkString(" "))
    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) & t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      //println(l, r, v, tl, tr)
      if (l > r) Int.MaxValue
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        //println(query(l, Math.min(r, tm), v2, tl, tm), query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))
        query(l, Math.min(r, tm), v2, tl, tm) &
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
      }
    }

    def update(pos: Int, delta: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (tl == tr) t(v) += delta
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        if (pos <= tm) update(pos, delta, v2, tl, tm)
        else update(pos, delta, v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

  }

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

  val Array(n, m) = readInts(2)

  case class Q(l: Int, r: Int, q: Int)

  val qs = Array.ofDim[Q](m)

  for (i <- 0 until m) {
    val Array(l, r, q) = readInts(3)
    qs(i) = Q(l - 1, r - 1, q)
  }

  //val sorted = qs.sortBy(_.l)

  val xs = Array.fill(n) { 0 }

  val bits = Array.fill(31) { 0 }

  val qByL = new mutable.PriorityQueue[Q]()(Ordering.by(- _.l))
  qByL ++= qs

  val qByR = new mutable.PriorityQueue[Q]()(Ordering.by(- _.r))

  var pos = 0
  for (i <- 0 until n) {
    while (qByR.nonEmpty && qByR.head.r < i) {
      val qr = qByR.dequeue
      //println(qr)
      for (b <- 0 to 30) {
        if ((qr.q & (1 << b)) > 0) bits(b) -= 1
      }
    }
    while (qByL.nonEmpty && qByL.head.l == i) {
      val ql = qByL.dequeue
      for (b <- 0 to 30) {
        if ((ql.q & (1 << b)) > 0) {
          bits(b) += 1
        }
      }
      qByR += ql
    }
    //println(bits.mkString(" "))
    for (b <- 0 to 30) {
      if (bits(b) < 0) fail(1)
      else if (bits(b) > 0) xs(i) |= (1 << b)
    }
  }

  val segTree = SegTree(xs)
  //println(xs.mkString(" "))
  for (q <- qs) {
    //println(q, segTree.query(q.l, q.r))
    if (segTree.query(q.l, q.r) != q.q) fail(2)
  }

  println(xs.mkString(" "))

  def fail(x: Int) = {
    println(x)
    println("NO")
    System.exit(0)
  }
}

import scala.collection._

object B extends App {

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val t = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)
//println(t.mkString(" "))
    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        t(v) = t(v2) & t(v2 + 1)
      }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      //println(l, r, v, tl, tr)
      if (l > r) Int.MaxValue
      else if (l == tl && r == tr) t(v)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        //println(query(l, Math.min(r, tm), v2, tl, tm), query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr))
        query(l, Math.min(r, tm), v2, tl, tm) &
          query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
      }
    }

    def update(pos: Int, delta: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1) {
      if (tl == tr) t(v) += delta
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        if (pos <= tm) update(pos, delta, v2, tl, tm)
        else update(pos, delta, v2 + 1, tm + 1, tr)
        t(v) = t(v2) + t(v2 + 1)
      }
    }

  }

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

  val Array(n, m) = readInts(2)

  case class Q(l: Int, r: Int, q: Int)

  val qs = Array.ofDim[Q](m)

  for (i <- 0 until m) {
    val Array(l, r, q) = readInts(3)
    qs(i) = Q(l - 1, r - 1, q)
  }

  //val sorted = qs.sortBy(_.l)

  val xs = Array.fill(n) { 0 }

  val bits = Array.fill(31) { 0 }

  val qByL = new mutable.PriorityQueue[Q]()(Ordering.by(- _.l))
  qByL ++= qs

  val qByR = new mutable.PriorityQueue[Q]()(Ordering.by(- _.r))

  var pos = 0
  for (i <- 0 until n) {
    while (qByR.nonEmpty && qByR.head.r < i) {
      val qr = qByR.dequeue
      //println(qr)
      for (b <- 0 to 30) {
        if ((qr.q & (1 << b)) > 0) bits(b) -= 1
      }
    }
    while (qByL.nonEmpty && qByL.head.l == i) {
      val ql = qByL.dequeue
      for (b <- 0 to 30) {
        if ((ql.q & (1 << b)) > 0) {
          bits(b) += 1
        }
      }
      qByR += ql
    }
    //println(bits.mkString(" "))
    for (b <- 0 to 30) {
      if (bits(b) < 0) fail(1)
      else if (bits(b) > 0) xs(i) |= (1 << b)
    }
  }

  val segTree = SegTree(xs)
  //println(xs.mkString(" "))
  for (q <- qs) {
    //println(q, segTree.query(q.l, q.r))
    if (segTree.query(q.l, q.r) != q.q) fail(2)
  }

  println("YES")
  println(xs.mkString(" "))

  def fail(x: Int) = {
    println(x)
    println("NO")
    System.exit(0)
  }
}


Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend it on reading.Help Luba to determine the minimum number of day when she finishes reading.It is guaranteed that the answer doesn't exceed n.Remember that there are 86400 seconds in a day.

The first line contains two integers n and t (1 ≤ n ≤ 100, 1 ≤ t ≤ 106) — the number of days and the time required to read the book. The second line contains n integers ai (0 ≤ ai ≤ 86400) — the time Luba has to spend on her work during i-th day.

Print the minimum day Luba can finish reading the book. It is guaranteed that answer doesn't exceed n.

object Main extends App {
  val Array(n,t) = readLine.split(" ").map(_.toInt)
  val a = readLine.split(" ").map(_.toInt)
  println(a.view.map(86400 - _).scanLeft(0)(_ + _)
    .zipWithIndex.filter(x => x._1 >= t).head._2)
}

import scala.io.StdIn._

object Codeforces extends App {
  val seconds = 86400
  var Array(n, t) = readLine split ' ' map(_.toInt)
  val time = readLine split ' ' map(_.toInt)
  for (i <- 0 until n) {
    t = math.max(0, t - (seconds - time(i)))
    if (t == 0) {
      println(i + 1)
      System.exit(0)
    }
  }
}


Bessie and the cows have recently been playing with "cool" sequences and are trying to construct some. Unfortunately they are bad at arithmetic, so they need your help!A pair (x, y) of positive integers is "cool" if x can be expressed as the sum of y consecutive integers (not necessarily positive). A sequence (a1, a2, ..., an) is "cool" if the pairs (a1, a2), (a2, a3), ..., (an - 1, an) are all cool. The cows have a sequence of n positive integers, a1, a2, ..., an. In one move, they may replace some ai with any other positive integer (there are no other limits on the new value of ai). Determine the smallest number of moves needed to make the resulting sequence cool.

The first line contains a single integer, n (2 ≤ n ≤ 5000). The next line contains n space-separated integers, a1, a2, ..., an (1 ≤ ai ≤ 1015). Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

A single integer, the minimum number of ai that must be changed to make the sequence cool.

NoteIn the first sample, the sequence is already cool, so we don't need to change any elements. In the second sample, we can change a2 to 5 and a3 to 10 to make (20, 5, 10, 4) which is cool. This changes 2 elements.

object A extends App {
  val n = readInt
  val a = readLine split ' ' map (_.toLong)
  val dp = new Array[Int](n)
  val two = new Array[Int](n)

  for (i <- 0 until n) {
    var c = 0
    while (a(i) % 2 == 0) {
      c += 1
      a(i) /= 2
    }

    two(i) = c
    dp(i) = 1
    for (j <- 0 until i)
      if (a(j) % a(i) == 0 && (two(j)+(i-j) == two(i) || two(i) < i-j))
        dp(i) = Math.max(dp(i), dp(j) + 1)
  }
  println(n - (0 /: dp)(Math.max(_, _)))
}

object A extends App {
  val n = readInt
  val a = readLine split ' ' map (_.toLong)
  val dp = new Array[Int](n)
  val two = new Array[Int](n)

  for (i <- 0 until n) {
    var c = 0
    while (a(i) % 2 == 0) {
      c += 1
      a(i) /= 2
    }

    two(i) = c
    dp(i) = 1
    for (j <- 0 until i)
      if (a(i) % a(j) == 0 && (two(j)+(i-j) == two(i) || two(i) < i-j))
        dp(i) = Math.max(dp(i), dp(j) + 1)
  }
  println((0 /: dp)(Math.max(_, _)))
}


A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).Killjoy's account is already infected and has a rating equal to $$$x$$$. Its rating is constant. There are $$$n$$$ accounts except hers, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th account's initial rating is $$$a_i$$$. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.Contests are regularly held on Codeforces. In each contest, any of these $$$n$$$ accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.It can be proven that all accounts can be infected in some finite number of contests.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The next $$$2t$$$ lines contain the descriptions of all test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$2 \le n \le 10^3$$$, $$$-4000 \le x \le 4000$$$) — the number of accounts on Codeforces and the rating of Killjoy's account. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(-4000 \le a_i \le 4000)$$$ — the ratings of other accounts.

For each test case output the minimal number of contests needed to infect all accounts.

NoteIn the first test case it's possible to make all ratings equal to $$$69$$$. First account's rating will increase by $$$1$$$, and second account's rating will decrease by $$$1$$$, so the sum of all changes will be equal to zero.In the second test case all accounts will be instantly infected, because all ratings (including Killjoy's account's rating) are equal to $$$4$$$.

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

import scala.annotation.tailrec

object C {
  def solve(in: Input, out: PrintWriter): Unit = {
    for (_ <- 0 until in.nextInt()) {
      val n, killJoy = in.nextInt()
      val others = Array.fill(n)(in.nextInt())
      if (others.count(_ == killJoy) == n) {
        out.println(0)
      } else if (others.sum == n * killJoy || others.contains(killJoy)) {
        out.println(1)
      } else {
        out.println(2)
      }
    }
  }

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("3\n2 69\n68 70\n6 4\n4 4 4 4 4 4\n9 38\n-21 83 50 -59 -77 15 -71 -78 20", "1\n0\n2", "Sample"),
    ("1\n3 10\n10 1 1", "1", "Tricky case")
  )

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

    override def close(): Unit = reader.close()
  }
}

object C extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, x) = readLine().split(" ").map(_.toInt)
    val an          = readLine().split(" ").map(_.toInt - x)

    val ans =
      if (an.forall(_ == 0)) 0
      else if (an.sum == 0 || an.contains(0)) 1
      else 2

    println(ans)
  }
}

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

import scala.annotation.tailrec

object C {
  def solve(in: Input, out: PrintWriter): Unit = {
    for (_ <- 0 until in.nextInt()) {
      val n, killJoy = in.nextInt()
      val others = Array.fill(n)(in.nextInt())
      if (others.count(_ == killJoy) == n) {
        out.println(0)
      } else if (others.sum == n * killJoy) {
        out.println(1)
      } else {
        out.println(2)
      }
    }
  }

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("3\n2 69\n68 70\n6 4\n4 4 4 4 4 4\n9 38\n-21 83 50 -59 -77 15 -71 -78 20", "1\n0\n2", "Sample")
  )

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

    override def close(): Unit = reader.close()
  }
}


Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode). procedure bubbleSortGraph()    build a graph G with n vertices and 0 edges    repeat        swapped = false        for i = 1 to n - 1 inclusive do:            if a[i] > a[i + 1] then                add an undirected edge in G between a[i] and a[i + 1]                swap( a[i], a[i + 1] )                swapped = true            end if        end for    until not swapped     /* repeat the algorithm as long as swapped value is true. */ end procedureFor a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.

The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).

Output a single integer — the answer to the problem.

NoteConsider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].

import scala.collection._

object B extends App {

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

  val n = readString.toInt
  val as = readInts(n)

  @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]): IndexedSeq[Int] = {

    val minByLen = new mutable.ArrayBuffer[Int](n)

    for (a <- as) {
      val (_, j) = binSearch(0, minByLen.length - 1, minByLen(_), a)
      if (j == minByLen.length) minByLen += a
      else if (a < minByLen(j)) minByLen(j) = a
    }

    minByLen
  }

  println(lis(as).length)
}

import scala.collection._

object B extends App {

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

  val n = readString.toInt
  val as = readInts(n)

  @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]): IndexedSeq[Int] = {

    val minByLen = new mutable.ArrayBuffer[Int](n)

    for (a <- as) {
      val (_, j) = binSearch(0, minByLen.length - 1, minByLen, a)
      if (j == minByLen.length) minByLen += a
      else if (a < minByLen(j)) minByLen(j) = a
    }

    minByLen
  }

  println(lis(as).length)
}

import scala.collection._

object B extends App {

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

  val n = readString.toInt
  val as = readInts(n)

  @annotation.tailrec
  def binSearch(low: Int, hi: Int, f: Int => 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 == 0) (true, mid)
      else if (fmid < 0) binSearch(mid + 1, hi, f)
      else binSearch(low, mid - 1, f)
    }
  }

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

    val bestLen = Array.ofDim[Int](n)
    var len = 0

    for (i <- 0 until n) {
      val (_, j) = binSearch(0, len - 1, k => as(bestLen(k)) - as(i))
      if (j == len || as(i) < as(bestLen(j))) {
        bestLen(j) = i
        len = math.max(len, j + 1)
      }
    }

    bestLen.take(len).map(as(_))
  }

  println(lis(as).length)
}

import scala.collection._

object B extends App {

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

  val n = readString.toInt
  val as = readInts(n)

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

    val bestLen = Array.ofDim[Int](n)

    def binarySearch(l: Int, key: Int): (Boolean, Int) = {
      var mid = 0
      var low = 0
      var hi = l - 1
      while (low <= hi) {
        mid = (low + hi) >>> 1
        val d = as(bestLen(mid))
        if (d == key) return (true, mid)
        else if (d > key) hi = mid - 1
        else {
          mid += 1
          low = mid
        }
      }
      (false, mid)  // not found - return insertion point
    }

  @annotation.tailrec
  def binSearch(lo: Int, hi: Int, f: Int => Int): Int = {
    if (hi < lo) lo
    else {
      val mid = lo + (hi - lo) / 2
      val fmid = f(mid)
      if (fmid == 0) mid
      else if (fmid < 0) binSearch(mid + 1, hi, f)
      else binSearch(lo, mid - 1, f)
    }
  }

    var len = 0
    for (i <- 0 until n) {
      val j = binSearch(0, len - 1, k => as(bestLen(k)) - as(i))
      if (j == len || as(i) < as(bestLen(j))) {
        bestLen(j) = i
        len = math.max(len, j + 1)
      }
    }

    bestLen.take(len).map(as(_))
  }

  println(lis(as).length)
}

import scala.collection._

object B extends App {

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

  val n = readString.toInt
  val as = readInts(n)

  @annotation.tailrec
  def binSearch(low: Int, hi: Int, f: Int => 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 == 0) (true, mid)
      else if (fmid < 0) binSearch(mid + 1, hi, f)
      else binSearch(low, mid - 1, f)
    }
  }

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

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

    for (a <- as) {
      val (_, j) = binSearch(0, len - 1, minByLen(_) - a)
      if (j == len || a < minByLen(j)) {
        minByLen(j) = a
        if (j + 1 > len) len = j + 1
      }
    }

    minByLen.take(len)
  }

  println(lis(as).length)
}

import scala.collection._

object B extends App {

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

  val n = readString.toInt
  val as = readInts(n)

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

    val bestLen = Array.ofDim[Int](n)

    def binarySearch(l: Int, key: Int): (Boolean, Int) = {
      var mid = 0
      var low = 0
      var hi = l - 1
      while (low <= hi) {
        mid = (low + hi) >>> 1
        val d = as(bestLen(mid))
        if (d == key) return (true, mid)
        else if (d > key) hi = mid - 1
        else {
          mid += 1
          low = mid
        }
      }
      (false, mid)  // not found - return insertion point
    }

    var len = 0
    for (i <- 0 until n) {
      val (_, j) = binarySearch(len, as(i))
      if (j == len || as(i) < as(bestLen(j))) {
        bestLen(j) = i
        len = math.max(len, j + 1)
      }
    }

    bestLen.take(len).map(as(_))
  }

  println(lis(as).length)
}

import scala.collection._

object B extends App {

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

  val n = readString.toInt
  val as = readInts(n)

  def binarySearch(l: Int, key: Int): Int = {
    var mid = 0
    var low = 0
    var hi = l - 1
    while (low <= hi) {
      mid = (low + hi) >>> 1
      val d = as(ms(mid))
      if (d == key) return mid
      else if (d > key) hi = mid - 1
      else {
        mid += 1
        low = mid
      }
    }
    return -mid - 1 // insertion point is -mid - 1
  }

  val ms = Array.ofDim[Int](n)
  //val ps = Array.ofDim[Int](n)

  var l = 0
  for (i <- 0 until n) {
    var j = binarySearch(l, as(i))
    if (j < 0) j = -j - 1
    //ps(i) = ms(j)
    if (j == l || as(i) < as(ms(j))) {
      ms(j) = i
      l = math.max(l, j + 1)
    }
  }

  println(l)
}

import scala.collection._

object B extends App {

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

  val n = readString.toInt
  val as = readInts(n)

  var c = 0
  for (i <- 0 until n - 1; if as(i) <= as(i + 1)) c += 1

  println(if (c == 0) 0 else c + 1)
}

import scala.collection._

object B extends App {

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

  val n = readString.toInt
  val as = readInts(n)

  var c = 1
  for (i <- 0 until n - 1; if as(i) <= as(i + 1)) c += 1

  println(c)
}


John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.

A single line contains an integer k (1 ≤ k ≤ 105) — the number of cycles of length 3 in the required graph.

In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.

object Cycles3 extends App {
  val k = Console.readLine() toInt
  var a: Array[Array[Int]] = null

  def fullsq(n:Int) = n*(n-1)*(n-2)/6
  def numvert(n:Int) = n*(n-1)/2

  def leastFull():Int = {
    val seq = for {
      i <- Range(0,90)
      if fullsq(i) > k
    }  yield i-1
    seq(0)
  }

  def maxlessvert(n:Int, kk:Int):Int =
    if (numvert(n) > kk) n-1
    else maxlessvert(n+1, kk)

  def fillfull(n:Int) =
      for {
        i <- 0 until n
        j <- 0 until i
      } {
        a(i)(j) = 1
        a(j)(i) = 1
      }

  def filladd(n:Int, start:Int) =
    for (i <- 0 until n) {
      a(i)(start) = 1
      a(start)(i) = 1
    }

  def printresult(d:Int) {
    println(d)
    for (i <- 0 until d) {
      val s = ((a(i) toList) take d) mkString ""
      println(s)
    }
  }

  var d0 = leastFull()
  val d = d0 + 10
  //println("d0,d = " + d0 + " " + d)
  a = Array.fill(d,d)(0)
  fillfull(d0)
  var o = k - fullsq(d0)
  //println("o = " + o)
  while (o > 0) {
    val b = maxlessvert(0, o)
    //println("b = " + b)
    o = o - numvert(b)
    filladd(b, d0)
    d0 = d0 + 1
  }
  printresult(d0)
}

object Cycles3 extends App {
  val k = Console.readLine() toInt
  var a: Array[Array[Int]] = null

  def fullsq(n:Int) = n*(n-1)*(n-2)/6
  def numvert(n:Int) = n*(n-1)/2

  def leastFull():Int = {
    val seq = for {
      i <- Range(0,90)
      if fullsq(i) > k
    }  yield i-1
    seq(0)
  }

  def maxlessvert(n:Int, kk:Int):Int =
    if (numvert(n) > kk) n-1
    else maxlessvert(n+1, kk)

  def fillfull(n:Int) =
      for {
        i <- 0 until n
        j <- 0 until i
      } {
        a(i)(j) = 1
        a(j)(i) = 1
      }

  def filladd(n:Int, start:Int) =
    for (i <- 0 until n) {
      a(i)(start) = 1
      a(start)(i) = 1
    }

  def printresult(d:Int) {
    println(d)
    for (i <- 0 until d) {
      val s = ((a(i) toList) take d) mkString " "
      println(s)
    }
  }

  var d0 = leastFull()
  val d = d0 + 10
  //println("d0,d = " + d0 + " " + d)
  a = Array.fill(d,d)(0)
  fillfull(d0)
  var o = k - fullsq(d0)
  //println("o = " + o)
  while (o > 0) {
    val b = maxlessvert(0, o)
    //println("b = " + b)
    o = o - numvert(b)
    filladd(b, d0)
    d0 = d0 + 1
  }
  printresult(d0)
}


You still have partial information about the score during the historic football match. You are given a set of pairs $$$(a_i, b_i)$$$, indicating that at some point during the match the score was "$$$a_i$$$: $$$b_i$$$". It is known that if the current score is «$$$x$$$:$$$y$$$», then after the goal it will change to "$$$x+1$$$:$$$y$$$" or "$$$x$$$:$$$y+1$$$". What is the largest number of times a draw could appear on the scoreboard?The pairs "$$$a_i$$$:$$$b_i$$$" are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10000$$$) — the number of known moments in the match. Each of the next $$$n$$$ lines contains integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \le a_i, b_i \le 10^9$$$), denoting the score of the match at that moment (that is, the number of goals by the first team and the number of goals by the second team). All moments are given in chronological order, that is, sequences $$$x_i$$$ and $$$y_j$$$ are non-decreasing. The last score denotes the final result of the match.

Print the maximum number of moments of time, during which the score was a draw. The starting moment of the match (with a score 0:0) is also counted.

NoteIn the example one of the possible score sequences leading to the maximum number of draws is as follows: 0:0, 1:0, 2:0, 2:1, 3:1, 3:2, 3:3, 3:4.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val (a, b) = na2(N)

    var ans = 1 // (0:0)
    REP(N) { i =>
      val a0 = if (i ==0) 0 else a(i - 1)
      val a1 = a(i)
      val b0 = if (i ==0) 0 else b(i - 1)
      val b1 = b(i)

      // 点数が動いた時だけ考慮すればいい
//      if (a1 > a0 || b1 > b0) {
      val rg_a = (a0, a1)
      val rg_b = (b0, b1)
      val rg = (max(rg_a._1, rg_b._1), min(rg_a._2, rg_b._2))

      val prevDraw = a0 == b0 // 前回ドローだと２回足してしまうので引かないといけない

      val len = max(0, rg._2 - rg._1 + 1) - (if (prevDraw) 1 else 0)
//      debug(s"$i $rg_a $rg_b $rg $len")
      ans += len
//      }
    }

//    if (a(N - 1) == 0 && b(N - 1) == 0) ans += 1

    out.println(ans)
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

//package codeforce
import scala.io.StdIn

object CalcDrawNum extends App {
  val momentsNum = StdIn.readLine().toInt
  val array = scala.collection.mutable.ArrayBuffer[(Long, Long)]()
  for (_ <- 0 until momentsNum) {
    val scores = StdIn.readLine().split(" ")
    array.append((scores(0).toLong, scores(1).toLong))
  }
  var from = (0L, 0L)
  var drawTimes = 1L
  var lastDraw = (0L, 0L)
  for (s <- array) {
    val (dt, d) = calcDrawTimes(from, s, lastDraw)
    drawTimes += dt
    from = s
    lastDraw = d
  }
  println(drawTimes)

  def calcDrawTimes(from: (Long, Long), to: (Long, Long), lastDraw: (Long, Long)): (Long, (Long, Long)) = {
    var curDraw = lastDraw
    val fromMax = scala.math.max(from._1, from._2)
    val toMin = scala.math.min(to._1,to._2)
    var times = 0L
    if (fromMax <= toMin){
      times += toMin - fromMax
      if ((fromMax,fromMax) != lastDraw){
        times += 1
      }
      curDraw = (toMin,toMin)
    }
    (times,curDraw)
  }
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val (a, b) = na2(N)

    var ans = 0
    REP(N) { i =>
      val a0 = if (i ==0) 0 else a(i - 1)
      val a1 = a(i)
      val b0 = if (i ==0) 0 else b(i - 1)
      val b1 = b(i)

      // 点数が動いた時だけ考慮すればいい
      if (a1 > a0 || b1 > b0) {
        val rg_a = (a0, a1)
        val rg_b = (b0, b1)
        val rg = (max(rg_a._1, rg_b._1), min(rg_a._2, rg_b._2))
        val len = max(0, rg._2 - rg._1 + 1)
        debug(s"$i $rg_a $rg_b $rg $len")
        ans += len
      }
    }

    // やべえうまくいかない
    if (a(N - 1) == 0 && b(N - 1) == 0) ans += 1

    out.println(ans)
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

import scala.io.StdIn

object CalcDrawNum extends App {
  val momentsNum = StdIn.readLine().toInt
  val array = scala.collection.mutable.ArrayBuffer[(Int, Int)]()
  for (_ <- 0 until momentsNum) {
    val scores = StdIn.readLine().split(" ")
    array.append((scores(0).toInt, scores(1).toInt))
  }
  var from = (0, 0)
  var drawTimes = 1
  var lastDraw = (0, 0)
  for (s <- array) {
    val (dt, d) = calcDrawTimes(from, s, lastDraw)
    drawTimes += dt
    from = s
    lastDraw = d
  }
  println(drawTimes)

  def calcDrawTimes(from: (Int, Int), to: (Int, Int), lastDraw: (Int, Int)): (Int, (Int, Int)) = {
    var drawTimes = 0
    var draw: (Int, Int) = (0, 0)
    if (from._1 != from._2) {
      val fromMax = scala.math.max(from._1, from._2)
      draw = (fromMax, fromMax)
    } else {
      draw = (from._1 + 1, from._2 + 1)
    }
    while (draw._1 <= to._1 && draw._2 <= to._2 && draw != lastDraw) {
      drawTimes += 1
      draw = (draw._1 + 1, draw._2 + 1)
    }
    (drawTimes, draw)
  }
}