object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val answer = Array.ofDim[Int](n)
  val next = (0 until n).toArray

  def getNext(i: Int): Int = {
    if (i >= n || next(i) == i) i
    else {
      next(i) = getNext(next(i))
      next(i)
    }
  }

  (1 to m).foreach { _ =>
    val Array(l, r, x) = in.next().split(' ').map(_.toInt - 1)
    var current = getNext(l)
    while (current <= r) {
      if (current == x) current += 1
      else {
        answer(current) = x + 1
        next(current) = current + 1
      }
      current = getNext(current)
    }
  }
  println(answer.mkString(" "))
}

import scala.collection._

object C 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 Array(n, m) = readInts(2)
  val lostTo = Array.fill(n)(0)
  var alive = immutable.TreeSet[Int]() ++ (0 until n)
  var aliveCount = n

  var i = 0
  while (i < m) {
    i += 1
    val t = tokenizeLine
    val l = t.nextToken.toInt - 1
    val r = t.nextToken.toInt - 1
    val winner = t.nextToken.toInt
    val x = winner - 1

    if (r - l <= 548) {
      var j = l
      while (j <= r) {
        if (j != x && lostTo(j) == 0) {
          lostTo(j) = winner
          alive = alive - j
          aliveCount -= 1
        }
        j += 1
      }
    } else {
      for (j <- alive.range(l - 1, r + 1)) {
        if (j >= l && j <= r && j != x) {
          lostTo(j) = winner
          alive = alive - j
          aliveCount -= 1
        }
      }
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(lostTo.mkString(" "))
  Console.flush
}

import scala.collection._

object C 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 Array(n, m) = readInts(2)
  val lostTo = Array.fill(n)(0)
  //var alive = immutable.TreeSet[Int]() ++ (0 until n)
  val alive = new java.util.TreeSet(JavaConversions.asJavaList(0 until n))

  for (i <- 0 until m) {
    val t = tokenizeLine
    val l = t.nextToken.toInt - 1
    val r = t.nextToken.toInt - 1
    val winner = t.nextToken.toInt
    val x = winner - 1

    val iter = alive.subSet(l, r + 1).iterator
    while (iter.hasNext) {
      val j = iter.next
      if (j != x) {
        lostTo(j) = winner
        iter.remove
      }
    }
  }

  println(lostTo.mkString(" "))
}

import scala.collection._

object C 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 Array(n, m) = readInts(2)
  val lostTo = Array.fill(n)(0)
  var alive = immutable.TreeSet[Int]() ++ (0 until n)

  for (i <- 0 until m) {
    val t = tokenizeLine
    val l = t.nextToken.toInt - 1
    val r = t.nextToken.toInt - 1
    val winner = t.nextToken.toInt
    val x = winner - 1

    for (j <- alive.range(l, r + 1) if j != x) {
      lostTo(j) = winner
      alive -= j
    }
  }

  println(lostTo.mkString(" "))
}

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

  import Main._
  import fScanner._

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

    val m = ni()
    val t = new SegmentTree(n)
    REP(m) { _ =>
      val l = ni()
      val r = ni()
      val x = ni()

      t.update(1, 0, n-1, l-1, x-2, x-1)
      t.update(1, 0, n-1, x, r-1, x-1)
    }

    REP(n) { i =>
      val x = t.get(1, 0, n-1, i)
      out.print((if(x != -1) x + 1 else 0)+ " ")
    }
  }

  private class SegmentTree(n: Int) {
    val tree: Array[Int] = Array.fill[Int](4 * n)(-1)
    val marked: Array[Boolean] = Array.fill[Boolean](4 * n)(false)

    def push_2(v: Int): Unit = {
      if(marked(v)) {
        val ch1 = v << 1
        if(!marked(ch1)) {
          tree(ch1) = tree(v)
          marked(ch1) = true
        }
        val ch2 = ch1 | 1
        if(!marked(ch2)) {
          tree(ch2) = tree(v)
          marked(ch2) = true
        }
        marked(v) = false
      }
    }

    def update(v: Int, tl: Int, tr: Int, l: Int, r: Int, nVal: Int): Unit = {
      if(marked(v)) {}
      else if(tl == l && tr == r) {
        tree(v) = nVal
        marked(v) = true
      } else if(r >= l) {
        val tm = tl + (tr - tl) / 2
        update(v << 1, tl , tm, l, Math.min(tm, r), nVal)
        update(v << 1 | 1, tm + 1, tr, Math.max(l, tm + 1), r, nVal)
      }
    }

    def get(v: Int, tl: Int, tr: Int, pos: Int): Int = {
      if(tl == tr) tree(v)
      else {
        push_2(v)
        val tm = tl + (tr - tl) / 2
        if(pos <= tm) {
          get(v << 1, tl, tm, pos)
        } else {
          get(v << 1 | 1, tm+1, tr, pos)
        }
      }
    }
  }
}

import scala.io.StdIn
import scala.math.min
import scala.math.max

object a{
    final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }

  import InOut._

  def lchild(num:Int):Int = return num << 1
  def rchild(num:Int):Int = return (num << 1)|1
  case class round(num:Int, winner:Int)

  def build_simple(tree:Array[round], rounds:Int):Array[round] = {
    return tree.map(_ => round(rounds, -1))
  }

  def modify(tree:Array[round], node:Int, tl:Int, tr:Int, l:Int, r:Int, fight:round):Unit = {
    if (l > r){
      return
    }
    if (tl == l && tr == r){
      tree(node) = fight
      return
    }
    val tm = (tl+tr)>>1
    modify(tree, lchild(node), tl, tm, l, min(tm, r), fight)
    modify(tree, rchild(node), tm+1, tr, max(tm+1, l), r, fight)
  }

  def query(tree:Array[round], node:Int, tl:Int, tr:Int, pos:Int):round = {
    if (tl == tr){
      return tree(node)
    }
    val tm = (tl+tr)>>1
    if (pos <= tm){
        val lans = query(tree, lchild(node), tl, tm, pos)
        if (lans.num < tree(node).num){
          return lans
        }else{
          return tree(node)
        }
    }
    else {
        val rans = query(tree, rchild(node), tm+1, tr, pos)
        if (rans.num < tree(node).num){
          return rans
        }else{
          return tree(node)
        }
    }
  }

  def main(args:Array[String]){
    val n, m = nextInt
    var tree = build_simple(new Array[round](4*n), m)

    val input = new Array[(Int, Int, Int)](m)
    for (i <- 0 until m){
      val li, ri, xi = nextInt
      input(i) = (li-1, ri-1, xi-1)
    }
    for (i <- 1 to m){
      val info = input(m-i)
      modify(tree, 1, 0, n-1, info._1, info._3-1, round(m-i, info._3))
      modify(tree, 1, 0, n-1, info._3+1, info._2, round(m-i, info._3))
    }

    for (i <- 0 until n){
      val round_info = query(tree, 1, 0, n-1, i)
      if (round_info.winner == -1){
        println(0)
      }else{
        println(round_info.winner + 1)
      }
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val answer = Array.ofDim[Int](n)
  var left = (0 until n).toSet
  (1 to m).foreach { _ =>
    val Array(l, r, x) = in.next().split(' ').map(_.toInt - 1)
    left.filter(i => i >= l && i <= r).foreach { i => if (answer(i) == 0 && i != x)
      answer(i) = x + 1
      left -= i
    }
  }
  println(answer.mkString(" "))

}

import scala.collection._

object C 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 Array(n, m) = readInts(2)
  val lostTo = Array.fill(n)(0)
  var alive = immutable.TreeSet[Int]() ++ (0 until n)

  for (i <- 0 until m) {
    val t = tokenizeLine
    val l = t.nextToken.toInt - 1
    val r = t.nextToken.toInt - 1
    val winner = t.nextToken.toInt
    val x = winner - 1

    for (j <- alive.range(l - 1, r + 1) if j != x) {
      lostTo(j) = winner
      alive -= j
    }
  }

  println(lostTo.mkString(" "))
}


object A1255 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      var Array(a, b) = readLongs(2).sorted

      var res = 0
      val fives = (b - a) / 5
      val two = ((b - a) - (fives * 5)) / 2
      val one = ((b - a) - (fives * 5) - (two * 2))

      out.println(fives + two + one)
      tests -= 1
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

  override def solve(io: IO) = io.repeat {
    val a, b = io.read[Int]
    val d = (a - b).abs
    val ans = d % 5 match {
      case 0     => d/5
      case 1 | 2 => d/5 + 1
      case 3 | 4 => d/5 + 2
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


import 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 t = ni()
    REP(t) { _ =>
      val n = ni()
      val s = ns(n)
      var cntO = 0
      var ans = 0
      REP(n) { i =>
        if(s(i) == '(') cntO+=1
        else if(s(i) == ')' && cntO > 0) cntO -= 1
        else {
          ans+=1
        }
      }
      out.println(ans)
    }
  }

}

//package codeforces.contests._1374

/*
https://codeforces.com/contest/1374/problem/C
 */
object MoveBrackets {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt()) {
      val n = io.StdIn.readInt()
      val s = io.StdIn.readLine().toList

      @scala.annotation.tailrec
      def loop(ls: List[Char], score: Int = 0, acc: Int = 0): Int = {
        ls match {
          case Nil => acc
          case '(' :: tail => loop(tail, score + 1, acc)
          case ')' :: tail if score == 0 => loop(tail, score, acc + 1)
          case ')' :: tail => loop(tail, score - 1, acc)
        }
      }

      println(loop(s))
    }
  }
}

import scala.io.StdIn._
import math._

object CF653_C extends App {
  val t = readInt()
  for (_ <- 0 until t) {
    val _ = readInt()
    val s = readLine()

    var delta = 0
    var max_abs_delta = 0
    for (c <- s) {
      if (c == '(') {
        delta += 1
      } else {
        delta -= 1
      }

      max_abs_delta = max(max_abs_delta, -delta)
    }

    println(max_abs_delta)
  }
}

object C extends App {

  import scala.collection.mutable
  import scala.io.Source
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.collection.mutable.Stack
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }

  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val number     = in.nextInt()
      val input      = in.line()
      var stack      = mutable.Stack[Char]()
      var imbalanced = 0
      input.foreach(x => {
        if (x == '(') {
          stack.push(x)
        } else {
          if (stack.nonEmpty) {
            val popped = stack.pop()
            if (popped != '(') {
              imbalanced = imbalanced + 1
            }
          } else {
            imbalanced = imbalanced + 1
          }
        }
      })
      imbalanced = imbalanced + stack.length
      println(imbalanced / 2)
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

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

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
     * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

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

}


object Solution extends App {
  val firstLine = readLine().split(" ").map(_.toInt)
  val m = firstLine(0) // number of paint
  val n = firstLine(1) // number of person
  val cost = new Array[Array[Int]](m)

  for(i<- 0 until m) {
    cost(i) = readLine().split(" ").map(_.toInt).toArray
  }

  val dp = new Array[Array[Int]](n)
  for(i <- 0 until n) dp(i) = new Array[Int](m)

  for(i <- 0 until n)
    for(j <- 0 until m) {
      dp(i)(j) = cost(j)(i)
      if(j > 0) dp(i)(j) = math.max(dp(i)(j), dp(i)(j - 1) + cost(j)(i))
      if(i > 0) dp(i)(j) = math.max(dp(i)(j), dp(i - 1)(j) + cost(j)(i))
    }

  println(dp(n - 1) mkString " ")

}

object Main {
  def main (args: Array[String]) {
    val Array(m, n) = readLine().split(" ").map(_.toInt)
    val times = new Array[Int](n)
    val answer = for (i <- 1 to m) yield {
      val t = readLine().split(" ").map(_.toInt)
      times(0) += t(0)
      for (k <- 1 until n) {
        times(k) = max(times(k - 1), times(k)) + t(k)
      }
      times.last
    }

    print(answer(0))
    for (i <- 1 until m) {
      print(" " + answer(i))
    }
    println()
  }

  def max(x: Int, y: Int) = if (x > y) x else y
}

import java.util.Scanner

object B extends App {
  val sc = new Scanner(Console.in)
  val m = sc.nextInt()
  val n = sc.nextInt()
  val T = Array.ofDim[Int](m, n)
  val U = Array.ofDim[Int](m, n)

  for(i <- 0 until m) {
    for(j <- 0 until n) {
      T(i)(j) = sc.nextInt()
    }
  }

  U(0)(0) = T(0)(0)
  for(j <- 1 until n) {
    U(0)(j) = U(0)(j - 1) + T(0)(j)
  }

  for(i <- 1 until m) {
    U(i)(0) = T(i)(0) + U(i-1)(0)
    for(j <- 1 until n) {
      U(i)(j) = T(i)(j) + math.max(U(i-1)(j), U(i)(j-1))
    }
  }

  for(i <- 0 until m) {
    print(U(i)(n-1))
    print(" ")
  }
}

import java.util.Scanner

object B extends App {
  val sc = new Scanner(System.in)
  val m = sc.nextInt()
  val n = sc.nextInt()
  val T = Array.ofDim[Int](m, n)
  val U = Array.ofDim[Int](m, n)

  for(i <- 0 until m) {
    for(j <- 0 until n) {
      T(i)(j) = sc.nextInt()
    }
  }

  U(0)(0) = T(0)(0)
  for(j <- 1 until n) {
    U(0)(j) = U(0)(j - 1) + T(0)(j)
  }

  for(i <- 1 until m) {
    U(i)(0) = T(i)(0) + U(i-1)(0)
    for(j <- 1 until n) {
      U(i)(j) = T(i)(j) + math.max(U(i-1)(j), U(i)(j-1))
    }
  }

  for(i <- 0 until m) {
    print(U(i)(n-1))
    print(" ")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()

  val Array(m, n) = in.next().split(' ').map(_.toInt)
  val data = (1 to m).map(_ => in.next().split(' ').map(_.toInt))
  val res = (1 until n).foldLeft(data.map(_.head).scanLeft(0){_+_}.tail) {
    case(acc, el) =>
      val master = data.map(_(el))
      var finish = 0
      master.zip(acc).map {
        case((current, previous)) =>
          finish = Math.max(previous + current, finish + current)
          finish
      }
  }
  println(res.mkString(" "))
}

import java.util.Scanner

object B extends App {

val sc = new Scanner(System.in)

val n = sc.nextInt()
val m = sc.nextInt()

val in = Array.ofDim[Int](n, m)

for (i <- 0 until n) {
  for (j <- 0 until m) {
    in(i)(j) = sc.nextInt()
  }
}

val dp = new Array[Int](m)
for (i <- 0 until n) {
  for (j <- 0 until m) {
    if (j != 0)
      dp(j) = (dp(j-1) max dp(j)) + in(i)(j)
    else
      dp(j) += in(i)(j)
  }
  print(dp(m-1) + " ")
}

}


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 = ns(N)

    def grouped(S: Array[Char]): Array[mutable.Stack[Int]] = {
      val C = Array.fill[mutable.Stack[Int]](27)(mutable.Stack()) // 26に?のぱしょが入っている
      REP(N) { i =>
        if (S(i) == '?') C(26).push(i)
        else C(S(i) - 'a').push(i)
      }
      C
    }

    val Ca = grouped(A)
    val Cb = grouped(B)

    DEBUG {
      REP(27) { i =>
        debugL(i)
        debug("["+Ca(i).mkString(",")+"]")
        debug("["+Cb(i).mkString(",")+"]")
      }
    }

    val ans = ArrayBuffer[(Int, Int)]()
    REP(26) { i =>
      while(Ca(i).nonEmpty && Cb(i).nonEmpty) {
        val ai = Ca(i).pop()
        val bi = Cb(i).pop()
        ans += ((ai, bi))
      }
    }

    REP(26) { i =>
      while(Ca(i).nonEmpty && Cb(26).nonEmpty) {
        val ai = Ca(i).pop()
        val bi = Cb(26).pop()
        ans += ((ai, bi))
      }
      while(Ca(26).nonEmpty && Cb(i).nonEmpty) {
        val ai = Ca(26).pop()
        val bi = Cb(i).pop()
        ans += ((ai, bi))
      }
    }
    while(Ca(26).nonEmpty && Cb(26).nonEmpty) {
      val ai = Ca(26).pop()
      val bi = Cb(26).pop()
      ans += ((ai, bi))
    }

    out.println(ans.length)
    ans.foreach { case (a, b) =>
      out.println(s"${a+1} ${b+1}")
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    type E = (Char, Int)
    val (wildcardL, regularL), (wildcardR, regularR) = io.read[String].zip(1 to n).sorted.toList.partition(_._1 == '?')

    val unmatchedL, unmatchedR = mutable.ArrayBuffer.empty[E]
    val ans = mutable.ArrayBuffer.empty[(E, E)]

    @tailrec def loop(left: List[E], right: List[E]): Unit = (left, right) match {
      case ((l1 @ (lc, _)) :: ls, (r1 @ (rc, _)) :: rs) =>
        if (lc < rc) {
          unmatchedL += l1
          loop(ls, right)
        } else if (lc > rc) {
          unmatchedR += r1
          loop(left, rs)
        } else {
          ans += l1 -> r1
          loop(ls, rs)
        }
      case _ =>
        unmatchedL ++= left
        unmatchedR ++= right
    }

    loop(left = regularL, right = regularR)

    ans ++= unmatchedL.zip(wildcardR)
    ans ++= wildcardL.zip(unmatchedR)
    ans ++= wildcardL.drop(unmatchedR.length).zip(wildcardR.drop(unmatchedL.length))

    io.writeLine(ans.length).writeLines(ans.map({case ((_, i), (_, j)) => s"$i $j"}))
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    type E = (Char, Int)
    val (wildcardL, regularL), (wildcardR, regularR) = io.read[String].zip(1 to n).sorted.toList.partition(_._1 == '?')

    val unmatchedL, unmatchedR = mutable.ArrayBuffer.empty[E]
    val ans = mutable.ArrayBuffer.empty[(E, E)]

    @tailrec
    def loop(left: List[E], right: List[E]): Unit = (left, right) match {
      case (Nil, _) => unmatchedR ++= right
      case (_, Nil) => unmatchedL ++= left

      case ((l1 @ (lc, _)) :: ls, (r1 @ (rc, _)) :: rs) =>
        if (lc < rc) {
          unmatchedL += l1
          loop(ls, right)
        } else if (lc > rc) {
          unmatchedR += r1
          loop(left, rs)
        } else {
          ans += l1 -> r1
          loop(ls, rs)
        }
    }
    loop(left = regularL, right = regularR)

    ans ++= unmatchedL.zip(wildcardR)
    ans ++= unmatchedR.zip(wildcardL)
    ans ++= wildcardR.drop(unmatchedL.length).zip(wildcardL.drop(unmatchedR.length))

    io.writeLine(ans.length).writeLines(ans.map({case ((_, i), (_, j)) => s"$i $j"}))
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


object B556 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val a = readInts(n)
    var t = 0
    var break = false
    while(!break && t < n) {
      if(a.zipWithIndex.forall(x => x._1 == x._2)) {
        println("Yes")
        break = true
      }
      for(i <- 0 until n) {
        if(i%2 == 0){
          if(a(i) == n-1)
            a(i) = 0
          else
            a(i) += 1
        } else {
          if(a(i) == 0)
            a(i) = n-1
          else
            a(i) -= 1
        }
      }
      t += 1
    }
    if(!break) {
      println("No")
    }
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

object _556B extends CodeForcesApp {
  import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable

  override type Input = List[Int]
  override type Output = Boolean

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt)
  }

  override def solve(input: Input) = {
    val n = input.size
    val end = List.tabulate(n)(identity)
    val zipped = (end zip input).zipWithIndex
    def rotate(clockwise: Boolean) = zipped map {
      case ((a, b), i) if (i%2 == 0) == clockwise => (a - b + n)%n
      case ((a, b), _) =>  (b - a + n)%n
    }
    val (left, right) = (rotate(clockwise = true), rotate(clockwise = false))
    left.distinct.size == 1 || right.distinct.size == 1
  }

  override def format(result: Output) = if (result) "Yes" else "No"
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  import CodeForcesApp._
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
/********************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
}
/**********************************[ lib ]************************************/
object CodeForcesApp {
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = collection.mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type ==>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None
/*******************************[ constants ]*********************************/
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus = 1000000007
}

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

object B_310 {

  def main(args: Array[String]): Unit = {

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val line2 = readLine
    val gears = new Array[Int](n)
    for(i <- 0 until n) {
      gears(i) = line2.int
    }

    val steps = if (gears(0) == 0) 0 else n - gears(0)
    var res = true
    for(i <- 0 until n) {
      if (i % 2 == 0) {
        val value = (gears(i) + steps) % n
        if (value != i) {
          res = false
        }
      } else {
        val value = (gears(i) + n - steps) % n
        if (value != i) {
          res = false
        }
      }
    }

    val strRes = if (res) "Yes" else "No"
    println(strRes)

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()

  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """

"""

}

}

object _556B extends CodeForcesApp[Boolean] {
  import java.util.Scanner
  import scala.annotation.tailrec, scala.collection.mutable
  import CodeForcesApp._

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt
    val gears = List.fill(n)(nextInt)
    val rotated = for {
      (a, i) <- gears.zipWithIndex
      r =  if (i%2 == 0) 1 else -1
    } yield ((a - i)*r + n)%n
    rotated.distinct.size == 1
  }

  override def format(result: Boolean): String = if (result) "Yes" else "No"
}

abstract class CodeForcesApp[A] {
  import java.util.Scanner
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solve(scanner))
  def solve(scanner: Scanner): A
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}

object CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus = 1000000007
  def when[A](condition: Boolean)(f: => A) = if (condition) Some(f) else None
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
}

import scala.annotation.tailrec, scala.collection.mutable
object _556B extends CodeForcesApp[Boolean] ({scanner => import scanner._, CodeForcesApp._
  val n = nextInt
  val gears = List.fill(n)(nextInt)
  val rotated = for {
    (a, i) <- gears.zipWithIndex
    r =  if (i%2 == 0) 1 else -1
  } yield ((a - i)*r + n)%n
  debug(n, gears, rotated)
  rotated.distinct.size == 1
}) {
  override def format(result: Boolean) = if (result) "Yes" else "No"
}

import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}

object CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus: Int = 1000000007
  def when[A](x: Boolean)(f: => A): Option[A] = if (x) Some(f) else None
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
}


//package codeforces

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

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()

    val scores = new Array[(Long, Long, Long, Int)](n)

    var k = 0
    while (k < n) {
      scores(k) = {
        val (x, y) = readLongPair()
        (x, y, y - x, k)
      }
      k += 1
    }

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    var i = 0
    while (i < n) {
      indexWhenSorted(scoresSorted(i)._4) = i
      i += 1
    }

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    i = 1
    while (i < n) {
      prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)
      i += 1
    }

    val enmitites = Array.fill[List[Int]](n)(List())

    k = 0
    while (k < m) {
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)

      k += 1
    }

    println(Stream.from(0).takeWhile(_ < n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    //println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

  //  implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {
  //
  //    import Numeric.Implicits._
  //
  //    def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)
  //
  //    def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)
  //
  //  }

}

//package codeforces

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

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()

    val scores = new Array[(Long, Long, Long, Int)](n)

    var k = 0
    while (k < n) {
      scores(k) = {
        val (x, y) = readLongPair()
        (x, y, y - x, k)
      }
      k += 1
    }

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    var i = 0
    while (i < n) {
      indexWhenSorted(scoresSorted(i)._4) = i
      i += 1
    }

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    i = 1
    while (i < n) {
      prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)
      i += 1
    }

    val enmitites = Array.fill[List[Int]](n)(List())

    k = 0
    while (k < m) {
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)

      k += 1
    }

    println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

  //  implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {
  //
  //    import Numeric.Implicits._
  //
  //    def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)
  //
  //    def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)
  //
  //  }

}

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, M = ni()
    val (x, y) = na2(N)
    val Sx = sumL(x)
    val (from, to) = na2(M, -1)
    val sortedZ = Array.ofDim[Long](N)
    rep(N) { i =>
      sortedZ(i) = y(i) - x(i)
    }
    sort(sortedZ)
    val cumZ = Array.ofDim[Long](N + 1)
    rep(sortedZ.length) { i =>
      cumZ(i + 1) = cumZ(i) + sortedZ(i)
    }

    val hates = packUGraph(N, from, to)
    val zip = new ZippedCounter(sortedZ)
    rep(N) { i =>
      zip.add(sortedZ(i))
    }

    val ans = Array.ofDim[Long](N)
    rep(N) { i =>
      val z = y(i) - x(i)
      val nLt = zip.countLt(z)
      val nGe = zip.countGe(z)
      var hated = 0L
      hates(i) foreach { j =>
        hated += min(x(i) + y(j), x(j) + y(i))
      }
      val Sx1 = (N - 1).toLong * x(i)
      val Sx2 = Sx - x(i)
      val Sz1 = (nGe - 1).toLong * z
      val Sz2 = cumZ(nLt)
      val sum = Sx1 + Sx2 + Sz1 + Sz2 + - hated // Σ(x1 + x2 + min(z1, z2))
      ans(i) = sum
    }

    out.println(ans.mkString(" "))
  }

  def sort(as: Array[Long]): Array[Long] = {
    val n = as.length
    val sorted = new java.util.PriorityQueue[Long](n)
    rep(n)(i => sorted.add(as(i)))
    rep(n)(i => as(i) = sorted.poll())
    as
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  def lowerBound(a: Array[Long], x: Long): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  class BIT(n: Int, zero: Long)(f: (Long, Long) => Long) {
    def this(n: Int) = this(n, 0)(_ + _)

    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val bit = if (zero != 0) Array.fill[Long](N + 1)(zero) else Array.ofDim[Long](N + 1)

    /**
      * 0 index
      */
    def sum(i: Int): Long = {
      var x = i + 1
      var s: Long = 0
      while(x > 0) {
        s = f(s, bit(x))
        x -= x & -x
      }
      s
    }

    /**
      * 0 index
      */
    def add(i: Int, a: Long): Unit = {
      var x = i + 1
      while(x <= N) {
        bit(x) = f(bit(x), a)
        x += x & -x
      }
    }
  }

  /**
    * N + 1の範囲に分割する
    *
    * 例:
    * as = [3 5 6]
    * (, 3] => 0  (3, 5] => 1 (5, 6] => 2 (6, ) => 3
    *
    */
  class ZipperLB(as: Array[Long]) {
    def apply(x: Long): Int = {
      lowerBound(as, x)
    }
  }

  /**
    * まじめなBSTつくるの大変だからlesserThanをカウントできるだけのものを用意した
    * java.util.TreeSetじゃできない
    */
  class ZippedCounter(as: Array[Long]) {
    val n = as.length
    val zip = new ZipperLB(as)
    val bit = new BIT(n + 1) // zipされたレンジはn + 1個になる
    var cnt = 0

    /**
      * @param x 必ずレンジの上限を追加しないいけない
      */
    def add(x: Long): Unit = {
      val i = zip(x)
      assert(i < n && x == as(i))
      bit.add(i, 1)
      cnt += 1
    }

    def countLt(x: Long): Int = {
      // レンジの上限の値しか存在しないので、ある値より小さい = より小さいレンジ と置き換えることができる
      val i = zip(x)
      if (i > 0) bit.sum(i - 1).toInt
      else 0
    }

    def countLe(x: Long): Int = {
      countLt(x + 1)
    }

    def countGe(x: Long): Int = {
      cnt - countLt(x)
    }

    def countGt(x: Long): Int = {
      cnt - countLe(x)
    }
  }

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

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

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

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

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

//package codeforces

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

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()

    val scores = new Array[(Long, Long, Long, Int)](n)

    (0 until n).foreach(i => scores(i) = {
      val (x, y) = readLongPair()
      (x, y, y - x, i)
    })

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    (0 until n).foreach(i => indexWhenSorted(scoresSorted(i)._4) = i)

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    (1 until n).foreach(i => prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2))

    val enmitites = Array.fill[List[Int]](n)(List())

    (0 until m).foreach { _ =>
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)
    }

    println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

}

//package codeforces

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

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()
    val rangeN = 0 until n
    val rangeM = 0 until m

    val scores = new Array[(Long, Long, Long, Int)](n)

    rangeN.foreach(i => scores(i) = {
      val (x, y) = readLongPair()
      (x, y, y - x, i)
    })

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    rangeN.foreach(i => indexWhenSorted(scoresSorted(i)._4) = i)

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    (1 until n).foreach(i => prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2))

    val enmitites = Array.fill[List[Int]](n)(List())

    rangeM.foreach { _ =>
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)
    }

    println(rangeN.foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

}

//package codeforces

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

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  //def input: Array[Long] = StdIn.readLine.split(" ").map(_.toLong)

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

    val scores = new Array[(Long, Long, Long, Int)](n)

    var k = 0
    while (k < n) {
      scores(k) = {
        val (x, y) = readLongPair()
        (x, y, y - x, k)
      }
      k += 1
    }

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    var i = 0
    while (i < n) {
      indexWhenSorted(scoresSorted(i)._4) = i
      i += 1
    }

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    i = 1
    while (i < n) {
      prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)
      i += 1
    }

    val enmitites = Array.fill[List[Int]](n)(List())

    k = 0
    while (k < m) {
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)

      k += 1
    }

    val sb = new StringBuilder
    i = 0
    while (i < n) {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      sb.append(result + " ")
      i += 1
    }
    println(sb.toString())
  }

  //  implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {
  //
  //    import Numeric.Implicits._
  //
  //    def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)
  //
  //    def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)
  //
  //  }

}

//package codeforces

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

object TrainHardWinEasy {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def main(args: Array[String]): Unit = {
    val (n, m) = readIntPair()

    val scores = new Array[(Long, Long, Long, Int)](n)

    var k = 0
    while (k < n) {
      scores(k) = {
        val (x, y) = readLongPair()
        (x, y, y - x, k)
      }
      k += 1
    }

    val indexWhenSorted = new Array[Int](n)
    val scoresSorted = scores.sortBy(_._3)

    var i = 0
    while (i < n) {
      indexWhenSorted(scoresSorted(i)._4) = i
      i += 1
    }

    val prefixSum = new Array[(Long, Long)](n)
    prefixSum(0) = (scoresSorted(0)._1, scoresSorted(0)._2)
    i = 1
    while (i < n) {
      prefixSum(i) = (scoresSorted(i)._1 + prefixSum(i - 1)._1, scoresSorted(i)._2 + prefixSum(i - 1)._2)
      i += 1
    }

    val enmitites = Array.fill[List[Int]](n)(List())

    k = 0
    while (k < m) {
      val (x, y) = readIntPair()
      enmitites(x - 1) = (y - 1) :: enmitites(x - 1)
      enmitites(y - 1) = (x - 1) :: enmitites(y - 1)

      k += 1
    }

    (0 until n).view.force

    println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    //println((0 until n).foldLeft(new StringBuilder())((sb, i) => sb.append(compute(i)).append(" ")).toString())

    def compute(i: Int): Long = {
      val sortedIdx = indexWhenSorted(i)

      var result = 0l

      if (sortedIdx > 0) {
        result += scores(i)._1 * sortedIdx.toLong + prefixSum(sortedIdx - 1)._2
      }

      result += (prefixSum(n - 1)._1 - prefixSum(sortedIdx)._1) + scores(i)._2 * (n - 1 - sortedIdx)

      enmitites(i).foreach(idx => result -= scores(i)._1 + scores(idx)._2 min scores(i)._2 + scores(idx)._1)

      result
    }
  }

  //  implicit class TuppleAdd[A: Numeric, B: Numeric](p: (A, B)) {
  //
  //    import Numeric.Implicits._
  //
  //    def +(t: (A, B)): (A, B) = (p._1 + t._1, p._2 + t._2)
  //
  //    def -(t: (A, B)): (A, B) = (p._1 - t._1, p._2 - t._2)
  //
  //  }

}


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 = na(N)
    val set = mutable.Map[Long, Int]().withDefaultValue(0)
    REP(N) { i =>
      set(A(i)) = set(A(i)) + 1
    }

    val MAX = 32
//    val MAX = 4

    val ans = map(N)(identity).count { i =>
      val ok = map(MAX)(identity).exists { k =>
        val b = (2L << k) - A(i)
        if (b == A(i))
          set(b) > 1
        else
          b > 0 && set.contains(b)
      }
//      System.err.println(s"${A(i)} $ok")
      !ok
    }

    out.println(ans)
  }

  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.collection.mutable._

object Solution {

  def solve(ls: List[Int]): Int = {
    var f = new HashMap[Int, Int]()
    ls.foreach(x => {
      f.get(x) match {
        case Some(y) => f += (x -> (y+1))
        case None => f += (x -> 1)
      }
    })

    var cnt = 0

    val p2 = (0 to 31).toList.map(x => 1 << x)
    ls.foreach(x => {
      val hasComplement = p2.foldLeft(false) { (acc, b) => {
          val v = f.get(b-x) match {
            case Some(y) => {
              if (b-x == x) {
                if (y > 1) true
                else false
              } else true
            }
            case None => false
          }
          acc || v
        }

      }
      if (!hasComplement) cnt += 1
    })

    cnt
  }

  def main(args: Array[String]) {
    val t = io.StdIn.readLine
    val ls = io.StdIn.readLine.split(" ").map(_.toInt).toList
    println(solve(ls))
  }
}

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

object Codeforces1005C {

  def getMinimumRemoveForBeingGood(elements: Array[Int]): Int = {
    val powers = (0 to 33).map(power => 1L << power)

    val elementMatchMap = new mutable.HashMap[Long, Data]()

    elements.foreach(element => {
      if (elementMatchMap.contains(element)) {
        elementMatchMap(element).frequency += 1
      } else {
        elementMatchMap.put(element, new Data(1, false))
      }
    })

    for (element <- elementMatchMap.keySet) {
      powers
        .map(p => p - element)
        .filter(e => elementMatchMap.contains(e))
        .filter(e => e != element || elementMatchMap(e).frequency != 1)
        .foreach(matchedElement => {
          elementMatchMap(element).hasMatched = true
          elementMatchMap(matchedElement).hasMatched = true
        })
    }

    var misMatchCount = 0
    for ((_, data) <- elementMatchMap) {
      if (!data.hasMatched)
        misMatchCount += data.frequency
    }
    misMatchCount
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val elements = StdIn.readLine.split(" ").map(_.trim.toInt)
    val result = getMinimumRemoveForBeingGood(elements)
    println(result)
  }

  class Data(var frequency: Int, var hasMatched: Boolean)

}


object Main {
  import java.io.PrintStream

  def main(args: Array[String]): Unit = {
    val s = new Main()
    val ps = new PrintStream(Console.out)
    Console.withOut(ps) {
      s.solve()
    }
    ps.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
  import scala.Console

  val MOD = 1000000007

  def solve(): Unit = {
    val N, M = ni()
    val V = Array.ofDim[Int](N + 1)
    rep(N) { i =>
      V(i) = ni()
    }
    V(N) = 1e9.toInt
    radixSort(V)

    val H_buff = ArrayBuffer[Int]()
    rep(M) { _ =>
      val x1, x2, _ = ni()
      if (x1 == 1) {
        H_buff += upperBound(V, x2)
      }
    }

    val H = radixSort(H_buff.toArray)
    var ans = 1e9.toInt
    var h = 0
    rep(N + 1) { i =>
      while(h < H.length && H(h) <= i){ h += 1}
      ans = min(ans, i + H.length - h)
    }

    println(ans)
  }

  // 要はcountLe
  def upperBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) > x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  /**
    * 正の値のみのときだけ
    */
  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(as: Array[Int], n: Int): Array[Int] = {
    val n = as.length
    val xs = Array(as, new Array[Int](n))
    val b = Array.ofDim[Int](65537)

    def step(k: Int, x: Int): Unit = {
      rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }
      rep(65536, 1){ i => b(i) += b(i - 1) }
      rep(n){ i =>
        val j = xs(x)(i) >>> k & 0xffff
        xs(x ^ 1)(b(j)) = xs(x)(i)
        b(j) += 1
      }
    }

    step(0, 0)
    java.util.Arrays.fill(b, 0)
    step(16, 1)

    as
  }

  class InputReader(reader: BufferedReader) {
    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(Console.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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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

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

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

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

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

  def solve(): Unit = {
    val MIN = 1
    val MAX = 1e9.toInt

    val N, M = ni()
    val V = na(N)
    radixSort(V)

    case class Line(from: Int, to: Int)
    val H = mutable.Map[Int, ArrayBuffer[Line]]()
    rep(M) { _ =>
      val l, r, y = ni()
      if (!H.contains(y)) {
        H(y) = ArrayBuffer()
      }
      H(y) += Line(l, r)
    }

    def merge(lines: ArrayBuffer[Line]): Line = {
      if (lines.length == 1) lines.head
      else {
        val sorted = lines.sortBy(_.to)
        var to = sorted.head.to
        rep(sorted.length - 1, 1) { i =>
          val l = sorted(i)
          if (to + 1 < l.from) return Line(sorted.head.from, to)
          to = l.to
        }
        Line(sorted.head.from, to)
      }
    }

    def calcV(lines: ArrayBuffer[Line]): Int = {
      val aLine = merge(lines)
      if (aLine.from > MIN) 0 // 一番左が空いている
      else if (aLine.to == MAX) Integer.MAX_VALUE // 全部埋まってる
      else {
        lowerBound(V, aLine.to + 1)
      }
    }

    val L = Array.ofDim[Int](H.size) // 可変だと面倒なので0もいれることにする
    var li = 0
    H.values.foreach { lines =>
      L(li) = calcV(lines)
      li += 1
    }

    radixSort(L)

    var ans = Integer.MAX_VALUE
    rep(N + 1) { i =>
      val cutH = L.length - lowerBound(L, i + 1)
      val cutV = i
      ans = min(ans, cutH + cutV)
    }

    out.println(ans)
  }

  // あえてコピペ
  // 要はcountLt
  def lowerBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  /**
    * 正の値のみのときだけ
    */
  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(as: Array[Int], n: Int): Array[Int] = {
    val n = as.length
    val xs = Array(as, new Array[Int](n))
    val b = Array.ofDim[Int](65537)

    def step(k: Int, x: Int): Unit = {
      rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }
      rep(65536, 1){ i => b(i) += b(i - 1) }
      rep(n){ i =>
        val j = xs(x)(i) >>> k & 0xffff
        xs(x ^ 1)(b(j)) = xs(x)(i)
        b(j) += 1
      }
    }

    step(0, 0)
    java.util.Arrays.fill(b, 0)
    step(16, 1)

    as
  }

  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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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

import java.util

import scala.collection.mutable

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)) }

  case class Hor(x: Int, y: Int)

  val Array(n, m) = readInts(2)
  val vs = Array.fill(n){ readLine.toInt }.sorted :+ 1000000000

  val hsBuilder = new mutable.ArrayBuilder.ofRef[Hor]
  for (_ <- 0 until m) {
    val Array(x1, x2, y) = readInts(3)
    if (x1 == 1) hsBuilder += Hor(x2, y)
  }
  val hs = hsBuilder.result.sortBy(- _.x)

  val longer = new util.TreeMap[Integer, Integer]
  var count = 0
  for (h <- hs) {
    count += 1
    longer.put(h.x, count)
  }

  val max = hs.length

  var res = Int.MaxValue
  for (i <- vs.indices) {
    val j = longer.ceilingKey(vs(i))
    val total = if (j == null) i else i + longer.get(j)
    if (total < res) res = total
  }

  println(res)
}

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

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

object A extends App {

  case class Point(x: Int, y: Int)

  @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val m = in.nextInt
    val vert = Array.fill(n)(in.nextInt)
    val h = ArrayBuffer[Int]()
    var const = 0
    (1 to m).foreach { _ =>
      val x1, x2 = in.nextInt
      in.nextInt
      if (x1 == 1 && x2 == 1000000000)
        const += 1
      else if (x1 == 1)
        h.append(x2)
    }

    val hor = h.toArray

    util.Arrays.sort(vert)
    util.Arrays.sort(hor)

    var ans = hor.length
    var v = 0
    hor.indices.foreach { x =>
      while (v < n && vert(v) <= hor(x))
        v += 1
      ans = math.min(ans, hor.length - x - 1 + v)
    }

    println(ans + const)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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

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

object A extends App {

  case class Point(x: Int, y: Int)

  @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val m = in.nextInt
    val vert = Array.fill(n)(in.nextInt)
    val hor = ArrayBuffer[Int]()
    var const = 0
    (1 to m).foreach { _ =>
      val x1, x2 = in.nextInt
      in.nextInt
      if (x1 == 1 && x2 == 1000000000)
        const += 1
      else if (x1 == 1)
        hor.append(x2)
    }
    var ans = n + hor.size
    var v = 0
    hor.indices.foreach { x =>
      while (v < n && vert(v) <= hor(x))
        v += 1
      ans = math.min(ans, hor.size - x - 1 + v)
    }

    println(ans + const)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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

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

object A extends App {

  case class Point(x: Int, y: Int)

  @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val m = in.nextInt
    val vert = Array.fill(n)(in.nextInt)
    val hor = ArrayBuffer[Int]()
    var const = 0
    (1 to m).foreach { _ =>
      val x1, x2 = in.nextInt
      in.nextInt
      if (x1 == 1 && x2 == 1000000000)
        const += 1
      else if (x1 == 1)
        hor.append(x2)
    }
    var ans = hor.size
    var v = 0
    hor.indices.foreach { x =>
      while (v < n && vert(v) <= hor(x))
        v += 1
      ans = math.min(ans, hor.size - x - 1 + v)
    }

    println(ans + const)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}