import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val prefix = new MutableMultiSet[Int](List.empty)
    val suffix = new MutableMultiSet[Int](a.toList)
    var canWrongSort = false
    a.dropRight(1).foreach { v =>
      prefix.add(v)
      suffix.remove(v)
      if (prefix.max > suffix.min) canWrongSort = true
    }
    if (canWrongSort) println("YES") else println("NO")
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import scala.io.Source
import scala.util.control.Breaks

object Contest extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val arrays = new Array[Array[Int]](t)
  for (i <- 0 until t) {
    val n = input.next()
    arrays(i) = input.next().split(" ").map(_.toInt)
  }

  arrays.map(check).foreach(println)

  def check(arr: Array[Int]): String = {
    val n = arr.length
    val maxes = arr.scanLeft(0)(math.max)
    val mins = arr.scanRight(Int.MaxValue)(math.min)
    var res = "NO"
    Breaks.breakable {
      for (i <- 1 until n) {
        if (maxes(i) > mins(i)) {
          res = "YES"
          Breaks.break()
        }
      }
    }
    res
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val prefix = new MutableMultiSet[Int](List.empty)
    val suffix = new MutableMultiSet[Int](a.toList)
    var canSort = false
    a.dropRight(1).foreach { v =>
      prefix.add(v)
      suffix.remove(v)
      if (prefix.max <= suffix.min) canSort = true
    }
    if (canSort || a.length == 1) println("NO") else println("YES")
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val prefix = new MutableMultiSet[Int](List.empty)
    val suffix = new MutableMultiSet[Int](a.toList)
    var canSort = false
    a.dropRight(1).foreach { v =>
      prefix.add(v)
      suffix.remove(v)
      if (prefix.max <= suffix.min) canSort = true
    }
    if (canSort) println("NO") else println("YES")
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val max = a.max
    if (max != a.last) println("YES") else println("NO")
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import scala.io.Source
import scala.util.control.Breaks

object Contest extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val arrays = new Array[Array[Int]](t)
  for (i <- 0 until t) {
    val n = input.next()
    arrays(i) = input.next().split(" ").map(_.toInt)
  }

  arrays.map(check).foreach(println)

  def check(arr: Array[Int]): String = {
    val n = arr.length
    val maxes = arr.scanLeft(0)(math.max)
    val mins = arr.scanRight(Int.MaxValue)(math.min)
    var res = "NO"
    Breaks.breakable {
      for (i <- 1 until n) {
        println(maxes(i), mins(i))
        if (maxes(i) > mins(i)) {
          res = "YES"
          Breaks.break()
        }
      }
    }
    res
  }
}

import scala.io.Source
import scala.util.control.Breaks

object Contest extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val arrays = new Array[Array[Int]](t)
  for (i <- 0 until t) {
    val n = input.next()
    arrays(i) = input.next().split(" ").map(_.toInt)
  }

  arrays.map(check).foreach(println)

  def check(arr: Array[Int]): String = {
    val n = arr.length
    val maxes = arr.scanLeft(0)(math.max)
    val mins = arr.scanRight(Int.MaxValue)(math.min)
    var res = "YES"
    Breaks.breakable {
      for (i <- 1 until n - 2) {
        if (maxes(i) <= mins(i + 1)) {
          res = "NO"
          Breaks.break()
        }
      }
    }
    res
  }
}


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

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

  val n = readInt
  val a = readInts
  def ans = a.count(n<) + a.filter(n>=).groupBy(x => x).values.map(_.size - 1).sum

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

object P137B extends App {

    readLine
    var numbers = readLine.split(" ").map(_.toInt).toList.sorted
    numbers = numbers.distinct ++ (numbers diff numbers.distinct)

    def solve(acc: Int, list: List[Int]):Int = list match{
      case (h::Nil) => acc
      case (h::t) => if (h+1 == t.head) solve(acc,t) else solve(acc+1,h+1::t.slice(0,t.size-1))
    }

    println(if(numbers.head == 1) solve(0,numbers) else solve(1,1::numbers.slice(0,numbers.size-1)))

}

object P137B extends App {
    var n = readLine toInt
    var a = new Array[Int](5001)
    for(i <- readLine.split(" ")) a(i.toInt-1) = 1
    println(a.take(n).filter(_ < 1).size)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(n - in.next().split(' ').map(_.toInt).filter(_ <= n).distinct.length)
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

object P137B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Int = {
    val N = sc.nextInt
    N - List.fill(N)(sc.nextInt).filter(x => 1 <= x && x <= N).distinct.size
  }

  out.println(solve)
  out.close
}

// codeforces 137B
object Perestanovki extends App {
  val n = Console.readLine toInt
  val al = Console readLine() split(" ") map (_.toInt)
  val agood = Array.fill(n)(0)

  for {
    i <- 0 until n
    if 1<= al(i) && al(i) <= n
  } agood(al(i) - 1) = 1
  val sm:Int = ((agood toList) sum)
  //println("sm = " + sm)
  //println("agood = " + (agood.toList.mkString(" ")))
  val s = (n-sm) toString;
  println(s)

}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)
    val count = (1 to n).foldLeft(0){ (a, i) => map.get(i) match {
      case Some(_) => a
      case None => a + 1
    }}
    println(count)
  }
}

object P137B extends App {
    readLine
    var n = readLine.split(" ").map(_.toInt).toList.sorted
    val d = n.distinct
    n = d ++ (n diff d)
    def s(a: Int, l: List[Int]):Int = l match{
      case (h::Nil) => a
      case (h::t) => if (h+1 == t.head) s(a, t) else s(a+1, h+1::t.slice(0,t.size-1))
    }
    println(if(n.head == 1) s(0,n) else s(1,1::n.slice(0,n.size-1)))
}

object P137B extends App {

    readLine
    var numbers = readLine.split(" ").map(_.toInt).toList.sorted
    numbers = numbers.distinct ++ (numbers diff numbers.distinct)

    def solve(acc: Int, list: List[Int]):Int = list match{
      case (h::Nil) => acc
      case (h::t) => if (h+1 == t.head) solve(acc,t) else solve(acc+1,h+1::t.slice(0,t.size-1))
    }

    println(solve(0,numbers))

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(n - in.next().split(' ').distinct.length)
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

object P137B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Int = {
    val N = sc.nextInt
    N - List.fill(N)(sc.nextInt).distinct.size
  }

  out.println(solve)
  out.close
}


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

object Codeforces1130B {

  def getMinimumDistanceForTwoCakes(n: Int, a: Seq[Int]): Long = {
    val numberPositionMap = new mutable.HashMap[Int, (Long, Long)]()
    for (i <- a.indices) {
      if (numberPositionMap.contains(a(i)))
        numberPositionMap(a(i)) = (numberPositionMap(a(i))._1, i)
      else
        numberPositionMap(a(i)) = (i, -1)
    }

    val positionStart = numberPositionMap(1)
    var totalDistance = positionStart._1 + positionStart._2
    for (cursor <- 1 until n) {
      val positionFrom = numberPositionMap(cursor)
      val positionTo = numberPositionMap(cursor + 1)
      val distance1 = math.abs(positionFrom._1 - positionTo._1) + math.abs(positionFrom._2 - positionTo._2)
      val distance2 = math.abs(positionFrom._1 - positionTo._2) + math.abs(positionFrom._2 - positionTo._1)
      totalDistance += math.min(distance1, distance2)
    }
    totalDistance
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)
    val d = getMinimumDistanceForTwoCakes(n, a)
    println(d)
  }

}

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(2 * N, -1)

    // 貪欲に左右に分割するのが最適
    val fst, snd = Array.fill[Int](N)(-1)
    REP(2 * N) { i =>
      if (fst(A(i)) == -1) fst(A(i)) = i
      else snd(A(i)) = i
    }

    // 1-Nを順番に辿ったときの距離
    def dist(D: Array[Int]): Long = {
      var ans = 0L
      var pre = 0
      REP(N) { i =>
        val d = abs(D(i) - pre)
        ans += d
        pre = D(i)
      }
      ans
    }

    val ans = dist(fst) + dist(snd)
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

object Codeforces1130B {

  def getMinimumDistanceForTwoCakes(n: Int, a: Seq[Int]): Int = {
    val numberPositionMap = new mutable.HashMap[Int, (Int, Int)]()
    for (i <- a.indices) {
      if (numberPositionMap.contains(a(i))) {
        numberPositionMap(a(i)) = (numberPositionMap(a(i))._1, i)
      } else {
        numberPositionMap(a(i)) = (i, -1)
      }
    }
    var totalDistance = 0
    var cursor = n
    while (cursor > 1) {
      val positionFrom = numberPositionMap(cursor)
      val positionTo = numberPositionMap(cursor - 1)
      val distance1 = math.abs(positionFrom._1 - positionTo._1) + math.abs(positionFrom._2 - positionTo._2)
      val distance2 = math.abs(positionFrom._1 - positionTo._2) + math.abs(positionFrom._2 - positionTo._1)
      totalDistance += math.min(distance1, distance2)
      cursor -= 1
    }
    val positionStart = numberPositionMap(1)
    totalDistance += positionStart._1 + positionStart._2
    totalDistance
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)
    val d = getMinimumDistanceForTwoCakes(n, a)
    println(d)
  }

}


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

import scala.collection.immutable.IndexedSeq

object _570C extends CodeForcesApp[Seq[Int]]({scanner => import scanner._
  def f(str: String, pos: Int = 0): Int = str.indexOf("..", pos) match {
    case -1 => 0
    case p => 1 + f(str, p+1)
  }

  def dotInt(c: Char) = if (c == '.') 1 else 0

  val (n, m, _s) = (nextInt, nextInt, next)

  var t = f(_s)
  var s: IndexedSeq[Int] = s"x${_s}x" map dotInt

  repeat(m) {
    val (i, c) = (nextInt, dotInt(next.head))

    val delta = (s(i-1), s(i), s(i+1), c) match {
      case (_, 1, _, 1) =>  0
      case (_, 0, _, 0) =>  0

      case (0, 1, 0, 0) =>  0
      case (0, 1, 1, 0) => -1
      case (1, 1, 0, 0) => -1
      case (1, 1, 1, 0) => -2

      case (0, 0, 0, 1) =>  0
      case (0, 0, 1, 1) =>  1
      case (1, 0, 0, 1) =>  1
      case (1, 0, 1, 1) =>  2
    }

    s = s.updated(i, c)
    t += delta

    t
  }
}) {
  override def format(result: Seq[Int]) = result mkString "\n"
}
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 {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn.readLine

/**
 * @author slie742
 */
object Replacement {
   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Char) = {
     val line = readLine.split(' ')
     (line(0).toInt,line(1).charAt(0))
   }

  def main(args: Array[String]) {
    val nm = readInts
    val n = nm(0)
    val m = nm(1)
    val s = ('x' + readLine + 'x').toArray
    var i = 1
    var total = 0
    while (i <= n) {
      if (s(i) == '.' && s(i-1) == '.') total +=1
      i += 1
    }
    i = 0
    val output = new Array[Int](m)
    while (i < m) {
      val (p,c) = readTuple
      if (c == '.') {
        if (s(p) != c) {
          if (s(p-1) == '.' && s(p+1) == '.') total +=2
          else if (s(p-1) == '.' || s(p+1) == '.') total +=1
        }
      } else { // s(p) != '.'
        if (s(p) == '.') {
           if (s(p-1) == '.' && s(p+1) == '.') total -=2
          else if (s(p-1) == '.' || s(p+1) == '.') total -=1
        }
      }
      s(p) = c
      output(i) = total
      i += 1
    }
    println(output.mkString("\n"))

  }
}

import scala.io.StdIn._

object C extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  //  val n = 299999
  //  val m = 300000
  //  val s = (" " + ("." * n) + " ").toCharArray
  val s = (" " + readLine() + " ").toCharArray

  var current = 0
  for (i <- 1 until n) {
    if (s(i) == '.' && s(i + 1) == '.') current += 1
  }

  def count(x: Int, c: Char): Int = {
    val curr = s(x)
    val isCurrPeriod = curr == '.'
    val isInsertedPeriod = c == '.'
    val isChange = isCurrPeriod ^ isInsertedPeriod

    if (isChange) {
      val prev = s(x - 1)
      val next  = s(x + 1)

      var amount = 0
      if (prev == '.') amount += 1
      if (next == '.') amount += 1

      if (isInsertedPeriod) {
        current += amount
      } else {
        current -= amount
      }

      s(x) = c
    }

    current
  }

  val sb = new scala.collection.mutable.StringBuilder
  for (_ <- 1 to m) {
    val Array(x, c) = readLine().split(" ")
    sb.append(count(x.toInt, c.head)).append('\n')
  }
  print(sb)

  //  for (i <- 1 to m) {
  ////    val arr = readLine().split(" ")
  //    val arr = s"$i .".split(" ")
  //    val x = Math.min(arr(0).toInt, n)
  //    val c = arr(1)(0)
  //    println(count(x, c))
  //  }

}

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

object Solution {

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

    val s = readLine()
    val f = Array.fill[Boolean](n+2)(false)

    var num = 0
    var seg = 0

    for (i <- (1 to n)) {
      if (s(i-1) == '.') {
        f(i) = true
        num += 1
        if (i == 1 || s(i-2) != '.') seg += 1
      }
    }

    val sb = new mutable.StringBuilder
    for (_ <- (1 to m)) {
      val Array(ids, ch) = readLine().split(" ")
      val id = ids.toInt
      val nc = (ch == ".")
      val c = f(id)
      if (nc != c) {
        f(id) = nc
        num = if (nc) num+1 else num-1
        if (f(id-1) && f(id+1) && nc) seg -= 1
        if (!f(id-1) && !f(id+1) && nc) seg += 1
        if (f(id-1) && f(id+1) && !nc) seg += 1
        if (!f(id-1) && !f(id+1) && !nc) seg -= 1
      }
      sb.append(num-seg).append('\n')
    }
    print(sb)

  }
}

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

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solveBruteForce(str1: Array[Char], pos: Int, ch: Char) = {
    val str = new Array[Char](str1.length)
    Array.copy(str1, 0, str, 0, str1.length)
    str(pos) = ch
    var cnt = 0
    var fx = 0
    for (i <- 0 until str.length) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    fx
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val str = next.toCharArray
    var fx = 0
    var cnt = 0
    for (i <- 0 until n) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    for (i <- 0 until m) {
      val pos = nextInt - 1
      val ch = next.toCharArray()(0)
      if (n == 1) {
        out.println(0)
      } else {
//        out.print(solveBruteForce(str, pos, ch) + " ")
        if (ch != str(pos)) {
          if (ch == '.') {
            if (pos == 0) {
              if (str(1) == '.')
                fx += 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx += 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c += 1
              }
              if (str(pos + 1) == '.') {
                c += 1
              }
              fx += c
            }
          } else if (str(pos) == '.'){
            if (pos == 0) {
              if (str(1) == '.')
                fx -= 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx -= 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c -= 1
              }
              if (str(pos + 1) == '.') {
                c -= 1
              }
              fx += c
            }
          }
        }
        if (fx < 0) {
          fx = 0
        }
        str(pos) = ch
        out.println(fx)
      }
    }
    return 0
  }
}

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

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solveBruteForce(str1: Array[Char], pos: Int, ch: Char) = {
    val str = new Array[Char](str1.length)
    Array.copy(str1, 0, str, 0, str1.length)
    str(pos) = ch
    var cnt = 0
    var fx = 0
    for (i <- 0 until str.length) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    fx
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val str = next.toCharArray
    var fx = 0
    var cnt = 0
    for (i <- 0 until n) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    for (i <- 0 until m) {
      val pos = nextInt - 1
      val ch = next.toCharArray()(0)
      if (n == 1) {
        out.println(0)
      } else {
        out.print(solveBruteForce(str, pos, ch) + " ")
        if (ch != str(pos)) {
          if (ch == '.') {
            if (pos == 0) {
              if (str(1) == '.')
                fx += 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx += 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c += 1
              }
              if (str(pos + 1) == '.') {
                c += 1
              }
              fx += c
            }
          } else if (str(pos) == '.'){
            if (pos == 0) {
              if (str(1) == '.')
                fx -= 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx -= 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c -= 1
              }
              if (str(pos + 1) == '.') {
                c -= 1
              }
              fx += c
            }
          }
        }
        if (fx < 0) {
          fx = 0
        }
        str(pos) = ch
        out.println(fx)
      }
    }
    return 0
  }
}

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

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val str = next.toCharArray
    var fx = 0
    var cnt = 0
    for (i <- 0 until n) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    for (i <- 0 until m) {
      val pos = nextInt - 1
      val ch = next.toCharArray()(0)
      if (n == 1) {
        out.println(0)
      } else {
        if (ch != str(pos)) {
          if (ch == '.') {
            if (pos == 0) {
              if (str(1) == '.')
                fx += 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx += 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c += 1
              }
              if (str(pos + 1) == '.') {
                c += 1
              }
              fx += c
            }
          } else {
            if (pos == 0) {
              if (str(1) == '.')
                fx -= 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx -= 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c -= 1
              }
              if (str(pos + 1) == '.') {
                c -= 1
              }
              fx += c
            }
          }
        }
        if (fx < 0) {
          fx = 0
        }
        str(pos) = ch
        out.println(fx)
      }
    }
    return 0
  }
}

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

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val str = next.toCharArray
    var fx = 0
    var cnt = 0
    for (i <- 0 until n) {
      if (str(i) == '.') {
        cnt += 1
      } else {
        if (cnt != 0) {
          fx += cnt - 1
        }
        cnt = 0
      }
    }
    if (cnt > 0) {
      fx += cnt - 1
    }
    for (i <- 0 until m) {
      val pos = nextInt - 1
      val ch = next.toCharArray()(0)
      if (n == 1) {
        out.println(0)
      } else {
        if (ch != str(pos)) {
          if (ch == '.') {
            if (pos == 0) {
              if (str(1) == '.')
                fx += 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx += 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c += 1
              }
              if (str(pos + 1) == '.') {
                c += 1
              }
              fx += c
            }
          } else {
            if (pos == 0) {
              if (str(1) == '.')
                fx -= 1
            } else if (pos == n - 1) {
              if (str(n - 2) == '.')
                fx -= 1
            } else {
              var c = 0
              if (str(pos - 1) == '.') {
                c -= 1
              }
              if (str(pos + 1) == '.') {
                c -= 1
              }
              fx += c
            }
          }
        }

        str(pos) = ch
        out.println(fx)
      }
    }
    return 0
  }
}

import scala.io.StdIn._

object C extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
//  val n = 299999
//  val m = 300000
//  val s = (" " + ("." * n) + " ").toCharArray
  val s = (" " + readLine() + " ").toCharArray

  var current = 0
  for (i <- 1 until n) {
    if (s(i) == '.' && s(i + 1) == '.') current += 1
  }

  def count(x: Int, c: Char): Int = {
    val prev = s(x - 1)
    val curr = s(x)
    val isCurrPeriod = curr == '.'
    val next  = s(x + 1)

    if (c == '.' && !isCurrPeriod) {
      if (prev == '.' && next == '.') {
        current += 2
      } else if (next == '.') {
        current += 1 // b[b]. <- .
      } else if (prev == '.') {
        current += 1 // b[b]. <- .
      }
    } else {
      if (prev == '.' && next == '.' && isCurrPeriod) {
        current -= 2
      } else if (next == '.') {
        current -= 1 // b[.]. <- b
      } else if (prev == '.') {
        current -= 1 // b[.]. <- b
      }

    }

    s(x) = c
    current
  }

  for (_ <- 1 to m) {
    val arr = readLine().split(" ")
    val (x, c) = (arr(0).toInt, arr(1).head)
    println(count(x, c))
  }

//  for (i <- 1 to m) {
////    val arr = readLine().split(" ")
//    val arr = s"$i .".split(" ")
//    val x = Math.min(arr(0).toInt, n)
//    val c = arr(1)(0)
//    println(count(x, c))
//  }

}


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

object Main {
  def main(args: Array[String]): Unit = {
    val input = StdIn.readLine().split(" ").map(_.toInt)
    val (x, y, a, b) = (input(0), input(1), input(2), input(3))
    val arr: IndexedSeq[String] = for(i <- a to x; j <- b to min(i, y) if i > j) yield i + " " + j
    println(arr.length)
    arr.foreach(println(_))
  }
}

object Main {
  def main(args: Array[String]) = {
    val xyab = readLine() split(" ") map(_.toInt)
    val x = xyab(0)
    val y = xyab(1)
    val a = xyab(2)
    val b = xyab(3)

    val s = for {
      i <- a to x
      j <- b to y
      if i > j
    } yield(i, j)
    println(s.size)
    s.foreach{ t => println(t._1 + " " + t._2) }
  }
}

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

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

  val Array(x, y, a, b) = readInts
  val outcomes = (for(i <- a to x) yield for(j <- b to y.min(i - 1)) yield Array(i, j)).flatMap(x => x)
  def ans = (outcomes.size +: outcomes.map(_.mkString(" "))).mkString("\n")

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

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(x, y, a, b) = in.next().split(' ').map(_.toInt)
  val res = (Math.max(a, b + 1) to x).flatMap(i => (b to Math.min(y, i - 1)).map(j => s"$i $j"))
  println(res.length)
  println(res.mkString("\n"))
}

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

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

  val x, y, a, b = sc.nextInt()

  val ans = (a to x) flatMap { x => (b to (math.min(y, x - 1))).map(x + " " + _) }

  println(ans.length)
  println(ans.mkString("\n"))
}

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

object P242A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  // Vasya => x times
  // Petya => y times
  // gets head => one point
  // more points win or draw

  val X, Y, A, B = sc.nextInt

  def solve(): Seq[List[Int]] = {
    for {
      i <- A to X
      j <- B to ((i - 1) min Y)
    }
    yield List(i, j)
  }

  val answer = solve
  out.println(answer.size)
  answer foreach { stats =>
    out.println(stats.mkString(" "))
  }
  out.close
}

import java.util.Scanner

object Main extends App
{
	val sc=new Scanner(System.in)
	val x,y,a,b=sc.nextInt()
	val ans=for(i<-List.range(a,x+1) ;
				j<-List.range(b,y+1) if (i>j)) yield i.toString+' '+j.toString
	println(ans.length)
	println(ans.mkString("\n"))
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val input = StdIn.readLine().split(" ").map(_.toInt)
    val (x, y, a, b) = (input(0), input(1), input(2), input(3))
    val arr: IndexedSeq[String] = for(i <- a + 1 to x; j <- b until i) yield i + " " + j
    println(arr.length)
    arr.foreach(println(_))
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val input = StdIn.readLine().split(" ").map(_.toInt)
    val (x, y, a, b) = (input(0), input(1), input(2), input(3))
    val arr: IndexedSeq[String] = for(i <- a to x; j <- b until i) yield i + " " + j
    println(arr.length)
    arr.foreach(println(_))
  }
}

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

object P242A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  // Vasya => x times
  // Petya => y times
  // gets head => one point
  // more points win or draw

  val X, Y, A, B = sc.nextInt

  def solve(): Seq[List[Int]] = {
    for {
      i <- A to X
      j <- B until (i max Y)
    }
    yield List(i, j)
  }

  val answer = solve
  out.println(answer.size)
  answer foreach { stats =>
    out.println(stats.mkString(" "))
  }
  out.close
}

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

object P242A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  // Vasya => x times
  // Petya => y times
  // gets head => one point
  // more points win or draw

  val X, Y, A, B = sc.nextInt

  def solve(): Seq[List[Int]] = {
    for {
      i <- A to X
      j <- B until (i min Y)
    }
    yield List(i, j)
  }

  val answer = solve
  out.println(answer.size)
  answer foreach { stats =>
    out.println(stats.mkString(" "))
  }
  out.close
}

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

object P242A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  // Vasya => x times
  // Petya => y times
  // gets head => one point
  // more points win or draw

  val X, Y, A, B = sc.nextInt

  def solve(): Seq[List[Int]] = {
    for {
      i <- A to X
      j <- B until i
    }
    yield List(i, j)
  }

  val answer = solve
  out.println(answer.size)
  answer foreach { stats =>
    out.println(stats.mkString(" "))
  }
  out.close
}


object C extends App {

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

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

  val len = Array.fill(n + 1){ 0 }

  for (p <- ps) len(p) = len(p - 1) + 1

  println(n - len.max)
}

object b extends App {
  var n = readInt
  var arr = readLine.split("\\s+").map(_.toInt)
  var dp = new Array[Int](n + 1)

  for (i <- 0 to n - 1)
    dp(arr(i)) = dp(arr(i) - 1) + 1

  println(n - dp.max)
}

/*
 * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/
 */

object Main extends App {
  import java.{util => ju}
  import scala.annotation._
  import scala.collection._
  import scala.collection.{mutable => mu}
  import scala.collection.JavaConverters._
  import scala.math._

  val sc = new ju.Scanner(System.in)

  val n = sc.nextInt
  val a = Array.fill(n)(sc.nextInt - 1)
  val b = Array.fill(n + 1)(-1)
  (0 until n) foreach {i => b(a(i)) = i}
  var ma = 0
  var cur, start = 0
  (0 to n) foreach {i =>
    if (b(i) < cur) {
      ma = ma max (i - start)
      start = i
    }
    cur =  b(i)
  }
  println(n - ma)

}

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

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val a = new Array[Int](n)
    val was = new Array[Boolean](n)
    val good = new Array[Boolean](n)
    for (i <- 0 until n) {
      a(i) = in.nextInt() - 1
      was(a(i)) = true
      if (a(i) != 0 && was(a(i) - 1)) {
        good(a(i)) = true
      }
    }
    var cur, best = 1
    for (i <- 0 until n) if (good(i)) {
      cur += 1
      if (cur > best) best = cur
    } else {
      cur = 1
    }
    out.println(n - best)
  }

  def main (args: Array[String]): Unit = {
    val in = new Scanner()
    val out = new PrintWriter(System.out)

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val block = data.foldLeft(Map.empty[Int, Int]) {
    case (map, value) if map.contains(value - 1) => map + (value -> (map(value - 1) + 1)) - (value - 1)
    case (map, value) => map + (value -> 1)
  }
  println(n - block.values.max)

}

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

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val a = new Array[Int](n)
    val was = new Array[Boolean](n)
    val good = new Array[Boolean](n)
    for (i <- 0 until n) {
      a(i) = in.nextInt() - 1
      was(a(i)) = true
      if (a(i) == 0 || was(a(i) - 1)) {
        good(a(i)) = true
      }
    }
    var cur, best = 0
    for (i <- 0 until n) if (good(i)) {
      cur += 1
      if (cur > best) best = cur
    } else {
      cur = 0
    }
    out.println(n - best)
  }

  def main (args: Array[String]): Unit = {
    val in = new Scanner()
    val out = new PrintWriter(System.out)

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

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

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val a = new Array[Int](n)
    val was = new Array[Boolean](n)
    val good = new Array[Boolean](n)
    for (i <- 0 until n) {
      a(i) = in.nextInt() - 1
      was(a(i)) = true
      if (a(i) != 0 && was(a(i) - 1)) {
        good(a(i)) = true
      }
    }
    var cur, best = 0
    for (i <- 0 until n) if (good(i)) {
      cur += 1
      if (cur > best) best = cur
    } else {
      cur = 1
    }
    out.println(n - best)
  }

  def main (args: Array[String]): Unit = {
    val in = new Scanner()
    val out = new PrintWriter(System.out)

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

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

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val a = new Array[Int](n)
    val was = new Array[Boolean](n)
    val good = new Array[Boolean](n)
    for (i <- 0 until n) {
      a(i) = in.nextInt() - 1
      was(a(i)) = true
      if (a(i) != 0 && was(a(i) - 1)) {
        good(a(i)) = true
      }
    }
    var cur, best = 1
    println(cur + " " + best)
    for (i <- 0 until n) if (good(i)) {
      cur += 1
      if (cur > best) best = cur
    } else {
      cur = 1
    }
    out.println(n - best)
  }

  def main (args: Array[String]): Unit = {
    val in = new Scanner()
    val out = new PrintWriter(System.out)

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

object b extends App {
  var n = readInt
  var arr = readLine.split("\\s+").map(_.toInt)

  def solve(arr: Array[Int], pos: Int, took: Int, op: (Int, Int) => Int): Int =
    if (pos >= arr.length || pos < 0)
      took
    else
      if (arr(pos) == op(took, 1))
        solve(arr, op(pos, 1), op(took, 1), op)
      else
        solve(arr, op(pos, 1), took, op)

  println((n - solve(arr, 0, 0, _ + _)) min (solve(arr, n - 1, n + 1, _ - _) - 1))
}


import java.io._
import java.util.Scanner
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new Scanner(System.in)
    val writer =  new PrintWriter(System.out)

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

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

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

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

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

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

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

    def solve(t: Int = 0): Unit = {
        val n = reader.nextInt()
        var c = 0
        while (f(c) < n) c += 1

        if (f(c) == n) {
            writer.println(s"1 ${c + 1}")
            return
        }

        val sub = n - f(c - 1)
        if (c - 1 == sub)
            writer.println(s"$c $c")
        else if (c - 1 > sub)
            writer.println(s"${1 + sub} $c")
        else
            writer.println(s"$c ${2*c - sub - 1}")
    }

    def multiTest(f: Int => Unit): Unit = {
        val t = reader.nextInt()
        for (i <- 1 to t) f(i)
    }

    val f = new Array[Int](40000)
    def main(args: Array[String]) {
        var i = 1
        var c = 1
        var size = 1
        f(0) = c
        while (c < 1000000000) {
            c += i
            i += 2
            f(size) = c
            size += 1
        }
        multiTest(solve)
        //solve()
        writer.flush()
    }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val k = readInt()

    val i = {
      @annotation.tailrec
      def go(i: Int): Int = if (i * i >= k) i else go(i + 1)
      go(1)
    }

    val j = k - (i - 1) * (i - 1)

    val (r, c) = if (j <= i) (j, i) else (i, i - (j - i))

    println(s"$r $c")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val k = readInt()

    val row        = math.sqrt(k).ceil.toInt
    val (from, to) = ((row - 1) * (row - 1) + 1, row * row)
    val length     = to - from + 1
    val half       = length / 2
    val index      = k - from

    val (r, c) =
      if (index < half) (index + 1, row)
      else if (index > half) (row, length - index)
      else (row, row)

    println(s"$r $c")
  }
}


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

object Main {
  var tokenizer = new util.StringTokenizer("")
  val out = new PrintWriter(System.out)
  val br = new BufferedReader(new InputStreamReader(System.in))

  def readToken = {
    while (!tokenizer.hasMoreTokens) tokenizer = new util.StringTokenizer(readLine)
    tokenizer.nextToken
  }

  def readInt = readToken.toInt

  val ancLevel = 18
  val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)
  val dep = Array.ofDim[Int](1000000 + 20)

  def getLca(x: Int, y: Int) = {
    var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)
    for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)
    if (a == b) {
      a
    } else {
      for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {
        a = anc(lv)(a)
        b = anc(lv)(b)
      }
      anc(0)(a)
    }
  }

  var d = 2

  def check(cur: Int, far: Int) = {
    val lca = getLca(cur, far)
    val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)
    if (curD > d) {
      d = curD
      true
    } else {
      false
    }
  }

  def main(args: Array[String]) {
    var p1 = 2
    var p2 = 3
    val q = br.readLine.toInt

    for (i <- 2 to 4) {
      anc(0)(i) = 1
      dep(i) = 1
    }

    var n = 4
    for (i <- 0 until q) {
      val x = br.readLine.toInt
      anc(0)(n + 1) = x
      anc(0)(n + 2) = x
      n += 2
    }

    for (p <- 5 to n) {
      dep(p)= dep(anc(0)(p)) + 1
      for (lv <- 1 until ancLevel) {
        anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))
      }
    }

    n = 4
    for (i <- 0 until q) {
      if (check(n + 1, p1)) {
        p2 = n + 1
      } else if (check(n + 1, p2)) {
        p1 = n + 1
      }
      out.println(d)
      n += 2
    }
    out.flush()
  }
}

import java.util
import java.io.PrintWriter

object Main {
  var tokenizer = new util.StringTokenizer("")
  val out = new PrintWriter(System.out)

  def readToken = {
    while (!tokenizer.hasMoreTokens)
		tokenizer = new util.StringTokenizer(scala.io.StdIn.readLine)
    tokenizer.nextToken
  }

  def readInt = readToken.toInt

  val ancLevel = 18
  val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)
  val dep = Array.ofDim[Int](1000000 + 20)

  def getLca(x: Int, y: Int) = {
    var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)
    for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)
    if (a == b) {
      a
    } else {
      for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {
        a = anc(lv)(a)
        b = anc(lv)(b)
      }
      anc(0)(a)
    }
  }

  var d = 2

  def check(cur: Int, far: Int) = {
    val lca = getLca(cur, far)
    val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)
    if (curD > d) {
      d = curD
      true
    } else {
      false
    }
  }

  def main(args: Array[String]) {
    var p1 = 2
    var p2 = 3
    val q = scala.io.StdIn.readLine.toInt

    for (i <- 2 to 4) {
      anc(0)(i) = 1
      dep(i) = 1
    }

    var n = 4
    for (i <- 0 until q) {
      val x = scala.io.StdIn.readLine.toInt
      anc(0)(n + 1) = x
      anc(0)(n + 2) = x
      n += 2
    }

    for (p <- 5 to n) {
      dep(p)= dep(anc(0)(p)) + 1
      for (lv <- 1 until ancLevel) {
        anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))
      }
    }

    n = 4
    for (i <- 0 until q) {
      if (check(n + 1, p1)) {
        p2 = n + 1
      } else if (check(n + 1, p2)) {
        p1 = n + 1
      }
      out.println(d)
      n += 2
    }
    out.flush()
  }
}

import java.util
import java.io.PrintWriter

object Main {
  var tokenizer = new util.StringTokenizer("")
  val out = new PrintWriter(System.out)

  def readToken = {
    while (!tokenizer.hasMoreTokens) tokenizer = new util.StringTokenizer(readLine)
    tokenizer.nextToken
  }

  def readInt = readToken.toInt

  val ancLevel = 18
  val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)
  val dep = Array.ofDim[Int](1000000 + 20)

  def getLca(x: Int, y: Int) = {
    var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)
    for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)
    if (a == b) {
      a
    } else {
      for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {
        a = anc(lv)(a)
        b = anc(lv)(b)
      }
      anc(0)(a)
    }
  }

  var d = 2

  def check(cur: Int, far: Int) = {
    val lca = getLca(cur, far)
    val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)
    if (curD > d) {
      d = curD
      true
    } else {
      false
    }
  }

  def main(args: Array[String]) {
    var p1 = 2
    var p2 = 3
    val q = readInt

    for (i <- 2 to 4) {
      anc(0)(i) = 1
      dep(i) = 1
    }

    var n = 4
    for (i <- 0 until q) {
      val x = readLine.toInt
      anc(0)(n + 1) = x
      anc(0)(n + 2) = x
      n += 2
    }

    for (p <- 5 to n) {
      dep(p)= dep(anc(0)(p)) + 1
      for (lv <- 1 until ancLevel) {
        anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))
      }
    }

    n = 4
    for (i <- 0 until q) {
      if (check(n + 1, p1)) {
        p2 = n + 1
      } else if (check(n + 1, p2)) {
        p1 = n + 1
      }
      out.println(d)
      n += 2
    }
    out.flush()
  }
}

import java.util
import java.io.PrintWriter

object Main {
  var tokenizer = new util.StringTokenizer("")
  val out = new PrintWriter(System.out)

  def readToken = {
    while (!tokenizer.hasMoreTokens) tokenizer = new util.StringTokenizer(readLine)
    tokenizer.nextToken
  }

  def readInt = readToken.toInt

  val ancLevel = 18
  val anc = Array.ofDim[Int](ancLevel, 1000000 + 20)
  val dep = Array.ofDim[Int](1000000 + 20)

  def getLca(x: Int, y: Int) = {
    var (a, b) = if (dep(x) >= dep(y)) (x, y) else (y, x)
    for (lv <- ancLevel - 1 to 0 by -1; if dep(a) - (1 << lv) >= dep(b)) a = anc(lv)(a)
    if (a == b) {
      a
    } else {
      for (lv <- ancLevel - 1 to 0 by -1; if anc(lv)(a)!= anc(lv)(b)) {
        a = anc(lv)(a)
        b = anc(lv)(b)
      }
      anc(0)(a)
    }
  }

  var d = 2

  def check(cur: Int, far: Int) = {
    val lca = getLca(cur, far)
    val curD = dep(cur) - dep(lca) + dep(far) - dep(lca)
    if (curD > d) {
      d = curD
      true
    } else {
      false
    }
  }

  def main(args: Array[String]) {
    var p1 = 2
    var p2 = 3
    val q = readLine.toInt

    for (i <- 2 to 4) {
      anc(0)(i) = 1
      dep(i) = 1
    }

    var n = 4
    for (i <- 0 until q) {
      val x = readLine.toInt
      anc(0)(n + 1) = x
      anc(0)(n + 2) = x
      n += 2
    }

    for (p <- 5 to n) {
      dep(p)= dep(anc(0)(p)) + 1
      for (lv <- 1 until ancLevel) {
        anc(lv)(p) = anc(lv-1)(anc(lv-1)(p))
      }
    }

    n = 4
    for (i <- 0 until q) {
      if (check(n + 1, p1)) {
        p2 = n + 1
      } else if (check(n + 1, p2)) {
        p1 = n + 1
      }
      out.println(d)
      n += 2
    }
    out.flush()
  }
}


/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import Ordering.Implicits._

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def solve(): Unit = {
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    val tested = (for (i <- Range(0, k)) yield nextInt).toArray
    val sumk = tested.sum
    val first = math.min(n - k, n / 2 - tested.count(_ < y))
    if (first < 0 || sumk + first + (n - k - first) * y > x) {
      println(-1)
    } else {
      for (i <- 0 until first) {
        printf("%d ", 1)
      }
      for (i <- 0 until n - k - first) {
        printf("%d ", y)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, k, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, k, p, x, y, scores) = problem

    def isMedianSatisfied(s: List[Int]) = (s ::: scores).count(_ >= y) >= (n + 1)/2

    @scala.annotation.tailrec
    def score(newScores: List[Int]): List[Int] = if (newScores.length == n - k) {
      newScores
    } else if (isMedianSatisfied(newScores)) {
      score(1 :: newScores)
    } else {
      score(y :: newScores)
    }

    val solution = score(Nil)
    if (isMedianSatisfied(solution) && (solution ::: scores).sum <= x) Some(solution) else None
  }

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

import Array._

object main extends App with fastIO {

  var Array(n, k, p, x, y) = readLine split(" ") map(_.toInt)
  var a = Array.fill(k)(nextInt)

  var r = a.count(_ >= y)

  var b = Vector[Int]()
  for (i <- r until (n >> 1) + 1) b = b :+ y
  for (i <- a.length + b.length until n) b = b :+ 1

  if (b.length <= n - k && a.sum + b.sum <= x)
    println(b.mkString(" ")) else
    println(-1)

  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

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

object B540 extends App {
  import java.util.Scanner
  def apply(problem: String): String = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /***************************************************************************/
  type Input = (Int, Int, Int, Int, Int, List[Int])

  type Output = Option[List[Int]]

  def solve(input: Input): Output = {
    val (n, k, p, x, y, s) = input
    val numOfYs = ((n+1)/2 - s.count(_ >= y)) max 0 min (n-k)
    val numOf1s = n - k - numOfYs
    val solution = List.fill(numOfYs)(y) ::: List.fill(numOf1s)(1)
    val result = s ::: solution
    if (result.sum <= x && result.count(_ >= y) >= (n+1)/2) Some(solution) else None
  }

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, k, p, x, y, List.fill(k)(nextInt))
  }

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"
}

object main{
  object Solver extends InputReader{
    def solve(){
      val n = getInt()
      val k = getInt()
      val p = getInt()
      val x = getInt()
      val y = getInt()

      val a = new Array[Int](n)
      for(i <- 0 to k - 1)
        a(i) = getInt()

      var s = a.sum
      for(i <- k to n - 1){
        val can = x - s
        val rest = n - 1 - i

        a(i) = Math.min(can - rest, y)
        s += a(i)
      }

      val b = a.sorted

      if(b(0) > 0 && b(n / 2) >= y){
        for(i <- k to n - 1)
          print(a(i) + " ")
        println()
      }else{
        println(-1)
      }
    }
  }

  // TEMPLATE ------------------------

  def main(args: Array[String]){
    Solver.solve()
  }

  trait InputReader{
    import java.io._
    import java.util._
    protected val stream = System.in
    private val reader = new BufferedReader(new InputStreamReader(stream))
    private var tokenizer = new StringTokenizer(reader.readLine())

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

    def getInt(): Int = getStr().toInt
    def getLong(): Long = getStr().toLong
    def getDouble(): Double = getStr().toDouble
  }
}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import Ordering.Implicits._

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def solve(): Unit = {
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    val tested = (for (i <- Range(0, k)) yield nextInt).toArray
    val sumk = tested.sum
    val (first, second) = (n / 2 - tested.count(_ < y), (n + 1) / 2 - tested.count(_ >= y))
    if (first < 0 || second < 0 || sumk + first + second * y > x) {
      println(-1)
    } else {
      for (i <- 0 until first) {
        printf("%d ", 1)
      }
      for (i <- 0 until second) {
        printf("%d ", y)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import Ordering.Implicits._

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def solve(): Unit = {
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    val tested = (for (i <- Range(0, k)) yield nextInt).toArray
    val sumk = tested.sum
    val first = math.min(n - k, n / 2 - tested.count(_ < y))
    println (first)
    if (first < 0 || sumk + first + (n - k - first) * y > x) {
      println(-1)
    } else {
      for (i <- 0 until first) {
        printf("%d ", 1)
      }
      for (i <- 0 until n - k - first) {
        printf("%d ", y)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import Ordering.Implicits._

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def solve(): Unit = {
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    val tested = (for (i <- Range(0, k)) yield nextInt).toArray
    val sumk = tested.sum
    val (first, second) = (n / 2 - tested.count(_ < y), (n + 1) / 2 - tested.count(_ >= y))
    if (sumk + first + second * y > x) {
      println(-1)
    } else {
      for (i <- 0 until first) {
        printf("%d ", 1)
      }
      for (i <- 0 until second) {
        printf("%d ", y)
      }
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

object B540 extends App {
  import java.util.Scanner
  def apply(problem: String): String = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /***************************************************************************/
  type Input = (Int, Int, Int, Int, Int, List[Int])

  type Output = Option[List[Int]]

  def solve(input: Input): Output = {
    val (n, k, p, x, y, s) = input
    val numOfYs = ((n+1)/2 - s.count(y <=)) max 0
    val numOf1s = n - k - numOfYs
    val best = List.fill(numOfYs)(y) ::: List.fill(numOf1s)(1)
    if ((s ::: best).sum <= x) Some(best) else None
  }

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, k, p, x, y, List.fill(k)(nextInt))
  }

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 => when(1 <= target && target <= p)(List(target))
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets < left || median(strategy ::: scores) >= y}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      solve(x - total, left)
    }
  }

  def median(l: List[Int]) = {
    require(l.length % 2 == 1)
    l.sorted.apply(l.length/2)
  }

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

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 => when(1 <= target && target <= p)(List(target))
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets%2 == 0 || median(strategy ::: scores) >= y}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      solve(x - total, left)
    }
  }

  def median(l: List[Int]) = {
    require(l.length % 2 == 1)
    l.sorted.apply(l.length/2 + 1)
  }

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

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 => when(1 <= target && target <= p)(List(target))
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets < (x - total) || median(strategy ::: scores) >= y}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      solve(x - total, left)
    }
  }

  def median(l: List[Int]) = {
    require(l.length % 2 == 1)
    l.sorted.apply(l.length/2 + 1)
  }

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

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 => when(1 <= target && target <= p)(List(target))
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets < left || median(strategy ::: scores) >= y}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      solve(x - total, left)
    }
  }

  def median(l: List[Int]) = {
    require(l.length % 2 == 1)
    l.sorted.apply(l.length/2 + 1)
  }

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

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 if 1 <= target && target <= p => Some(List(target))
        case 1 => None
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      val strategy = solve(x - total, left)
      strategy filter {s => median(s ::: scores) >= y}
    }
  }

  def median(l: List[Int]) = {
    require(l.length %2 == 1)
    l.sorted.apply(l.length/2 + 1)
  }

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}


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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toLong).sorted

    val e = b - a
    val m =
      if (e == 0) 0
      else if (a % e == b % e) (a % e) min (e - a % e)
      else a

    println(s"$e $m")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toLong).sorted

    val e = b - a
    val m =
      if (e == 0) 0
      else if (a % e == b % e) (a % e) min (e - a % e) min a
      else a

    println(s"$e $m")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toLong).sorted

    val e = b - a
    val m =
      if (e == 0) 0
      else if (a % e == b % e) {
        if (a % e == 0) 0 else (e - a % e) min a
      } else a

    println(s"$e $m")
  }
}


import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

object P385B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Long = {
    val S = sc.nextLine
    val L = S.length

    @tailrec
    def loop(acc: Long, i: Int): Long = {
      val j = S.indexOf("bear", i)
      if (j < 0) acc
      else loop(acc + (j - i + 1) * (L - j - 3), j + 1)
    }

    loop(0, 0)
  }

  out.println(solve)
  out.close
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val str = in.next()
  val l = str.length
  println((0 until str.length).foldLeft(0L) {
    case(count, i) =>
      val index = str.indexOf("bear", i)
      count + (if (index == -1) 0 else l - index - 3)
  })
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

object P385B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Long = {
    val S = sc.nextLine
    val L = S.length

    @tailrec
    def loop(acc: Long, i: Int): Long = {
      val j = S.indexOf("bear", i)
      if (j < 0) acc
      else loop(acc + (j + 1) * (L - j - 3), j + 1)
    }

    loop(0, 0)
  }

  out.println(solve)
  out.close
}


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

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

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

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val A = na(N)
    val D = Array.ofDim[Int](N - 1)
    REP(N - 1) { i =>
      D(i) = A(i + 1) - A(i)
    }
    sort(D)
    debug(D)
    val ans = sumL(D.take(max(0, N - K)))
    out.println(ans)
  }

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

//package codeforces.contest1197

object ArraySplitting {

  def main(args: Array[String]): Unit = {
    val Array(n, k) = io.StdIn.readLine().split(" ").map(_.toInt)
    println(
      if (n == 1) {
        io.StdIn.readInt()
        0
      }
      else {
        io.StdIn
          .readLine()
          .split(" ")
          .map(_.toInt)
          .sliding(2)
          .map(arr => arr(1) - arr(0))
          .toArray
          .sorted
          .slice(0, n - k)
          .sum
      }
    )
  }
}