In this problem we consider a very simplified model of Barcelona city.Barcelona can be represented as a plane with streets of kind $$$x = c$$$ and $$$y = c$$$ for every integer $$$c$$$ (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points $$$(x, y)$$$ for which $$$ax + by + c = 0$$$.One can walk along streets, including the avenue. You are given two integer points $$$A$$$ and $$$B$$$ somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to $$$B$$$ from $$$A$$$.

The first line contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$-10^9\leq a, b, c\leq 10^9$$$, at least one of $$$a$$$ and $$$b$$$ is not zero) representing the Diagonal Avenue. The next line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$-10^9\leq x_1, y_1, x_2, y_2\leq 10^9$$$) denoting the points $$$A = (x_1, y_1)$$$ and $$$B = (x_2, y_2)$$$.

Find the minimum possible travel distance between $$$A$$$ and $$$B$$$. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteThe first example is shown on the left picture while the second example us shown on the right picture below. The avenue is shown with blue, the origin is shown with the black dot.

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 = {
    import java.awt.geom.Point2D
    val a, b, c = ni()
    val x1, y1, x2, y2 = ni()

    val S = (x1.toDouble, y1.toDouble)
    val T = (x2.toDouble, y2.toDouble)

    def rangeX(x: Double) = min(x1, x2) <= x && x <= max(x1, x2)
    def rangeY(y: Double) = min(y1, y2) <= y && y <= max(y1, y2)

    val py1 = (-(c + b.toDouble * y1) / a, y1.toDouble)
    val py2 = (-(c + b.toDouble * y2) / a, y2.toDouble)

    val px1 = (x1.toDouble, -(c + a.toDouble * x1) / b)
    val px2 = (x2.toDouble, -(c + a.toDouble * x2) / b)

    def dist(p1: (Double, Double), p2: (Double, Double)) = {
      Point2D.distance(p1._1, p1._2, p2._1, p2._2)
    }

    def distM(p1: (Double, Double), p2: (Double, Double)) = {
      abs(p1._1 - p2._1) + abs(p1._2 - p2._2)
    }

    val points = Seq(py1, py2, px1, px2).filter(p => rangeX(p._1) && rangeY(p._2))
    val ans = if (points.length >= 2) {
      val p1 = points(0)
      val p2 = points(1)
      val d1 = distM(S, p1) + dist(p1, p2) + distM(T, p2)
      val d2 = distM(S, p2) + dist(p1, p2) + distM(T, p1)
      min(distM(S, T), min(d1, d2))
    } else {
      distM(S, T)
    }
    out.println(f"$ans%.9f")
  }

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

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

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

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

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

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

object D extends App {

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

  val Array(a, b, c) = readLongs(3)
  val Array(x1, y1, x2, y2) = readLongs(4)

  val manhattan = Math.abs(x1 - x2) + Math.abs(y1 - y2)

  def dist(x1: Double, y1: Double, x2: Double, y2: Double): Double = {
    val x = x1 - x2
    val y = y1 - y2
    Math.sqrt(x * x + y * y)
  }

  if (a != 0 && b != 0) {
    val dx1 = - (b.toDouble * y1 + c) / a
    val dy1 = - (a.toDouble * x1 + c) / b
    val dx2 = - (b.toDouble * y2 + c) / a
    val dy2 = - (a.toDouble * x2 + c) / b

    val distXX = Math.abs(x1 - dx1) + dist(dx1, y1, dx2, y2) + Math.abs(x2 - dx2)
    val distXY = Math.abs(x1 - dx1) + dist(dx1, y1, x2, dy2) + Math.abs(y2 - dy2)
    val distYX = Math.abs(y1 - dy1) + dist(x1, dy1, dx2, y2) + Math.abs(x2 - dx2)
    val distYY = Math.abs(y1 - dy1) + dist(x1, dy1, x2, dy2) + Math.abs(y2 - dy2)

    val res = manhattan.toDouble min distXX min distXY min distYX min distYY
    println(res)
  } else {
    println(manhattan)
  }
}

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 = {
    import java.awt.geom.Point2D
    val a, b, c = ni()
    val x1, y1, x2, y2 = ni()

    val S = (x1.toDouble, y1.toDouble)
    val T = (x2.toDouble, y2.toDouble)

    def rangeX(x: Double) = min(x1, x2) <= x && x <= max(x1, x2)
    def rangeY(y: Double) = min(y1, y2) <= y && y <= max(y1, y2)

    val py1 = (-(c.toDouble + b * y1) / a, y1.toDouble)
    val py2 = (-(c.toDouble + b * y2) / a, y2.toDouble)

    val px1 = (x1.toDouble, -(c.toDouble + a * x1) / b)
    val px2 = (x2.toDouble, -(c.toDouble + a * x2) / b)

    def dist(p1: (Double, Double), p2: (Double, Double)) = {
      Point2D.distance(p1._1, p1._2, p2._1, p2._2)
    }

    def distM(p1: (Double, Double), p2: (Double, Double)) = {
      abs(p1._1 - p2._1) + abs(p1._2 - p2._2)
    }

    val points = Seq(py1, py2, px1, px2).filter(p => rangeX(p._1) && rangeY(p._2))
    val ans = if (points.length >= 2) {
      val p1 = points(0)
      val p2 = points(1)
      min(distM(S, p1) + dist(p1, p2) + distM(T, p2), distM(S, p2) + dist(p1, p2) + distM(T, p1))
    } else {
      distM(S, T)
    }
    out.println(f"$ans%.9f")
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    import java.awt.geom.Point2D
    val a, b, c = ni()
    val x1, y1, x2, y2 = ni()

    val r = math.atan2(b, a)
    val p = (x2 - x1).toLong * (y2 - y1)
    if (p < 0 && r > 0 && r < Math.PI / 2 || p > 0 && r < 0 && r > -Math.PI / 2) {
      // x
      val x_t = - (c.toDouble + b * y1) / a
      val x_b = - (c.toDouble + b * y2) / a

      // y
      val y_l = - (c.toDouble + a * x1) / b
      val y_r = - (c.toDouble + a * x2) / b

      val ans = if (x1 <= x_t && x_t <= x2) {
        abs(x_t - x1) + abs(y_r - y2) + Point2D.distance(x_t, y1, x2, y_r)
      } else {
        abs(y_l - y1) + abs(x2 - x_b) + Point2D.distance(x1, y_l, x_b, y2)
      }
      out.println(f"$ans%.9f")
    } else {
      val ans = abs(x2 - x1) + abs(y2 - y1)
      out.println(ans)
    }
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    import java.awt.geom.Point2D
    val a, b, c = ni()
    val x1, y1, x2, y2 = ni()

    val S = (x1.toDouble, y1.toDouble)
    val T = (x2.toDouble, y2.toDouble)

    def rangeX(x: Double) = min(x1, x2) <= x && x <= max(x1, x2)
    def rangeY(y: Double) = min(y1, y2) <= y && y <= max(y1, y2)

    val py1 = (-(c.toDouble + b * y1) / a, y1.toDouble)
    val py2 = (-(c.toDouble + b * y2) / a, y2.toDouble)

    val px1 = (x1.toDouble, -(c.toDouble + a * x1) / b)
    val px2 = (x2.toDouble, -(c.toDouble + a * x2) / b)

    def dist(p1: (Double, Double), p2: (Double, Double)) = {
      Point2D.distance(p1._1, p1._2, p2._1, p2._2)
    }

    def distM(p1: (Double, Double), p2: (Double, Double)) = {
      abs(p1._1 - p2._1) + abs(p1._2 - p2._2)
    }

    val points = Seq(py1, py2, px1, px2).filter(p => rangeX(p._1) && rangeY(p._2))
    val ans = if (points.length >= 2) {
      val p1 = points(0)
      val p2 = points(1)
      val d1 = distM(S, p1) + dist(p1, p2) + distM(T, p2)
      val d2 = distM(S, p2) + dist(p1, p2) + distM(T, p1)
      min(distM(S, T), min(d1, d2))
    } else {
      distM(S, T)
    }
    out.println(f"$ans%.9f")
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    import java.awt.geom.Point2D
    val a, b, c = ni()
    val x1, y1, x2, y2 = ni()

    val S = (x1.toDouble, y1.toDouble)
    val T = (x2.toDouble, y2.toDouble)

    val rangeX = min(x1, x2) to max(x1, x2)
    val rangeY = min(y1, y2) to max(y1, y2)

    val pt = (-(c.toDouble + b * y1) / a, y1.toDouble)
    val pb = (-(c.toDouble + b * y2) / a, y2.toDouble)

    val pl = (x1.toDouble, -(c.toDouble + a * x1) / b)
    val pr = (x2.toDouble, -(c.toDouble + a * x2) / b)

    def dist(p1: (Double, Double), p2: (Double, Double)) = {
      Point2D.distance(p1._1, p1._2, p2._1, p2._2)
    }

    val points = Seq(pt, pb, pl, pr).filter(p => rangeX.contains(p._1) && rangeY.contains(p._2))
    val ans = if (points.length == 2) {
      val p1 = points(0)
      val p2 = points(1)
      min(dist(S, p1) + dist(p1, p2) + dist(T, p2), dist(S, p2) + dist(p1, p2) + dist(T, p1))
    } else {
      dist(S, T)
    }
    out.println(f"$ans%.9f")
  }

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

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

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

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

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

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


There are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (xi, yi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0, 0) the laser ray is released in the direction of point (1, 1). The ray travels with a speed of  meters per second. Thus, the ray will reach the point (1, 1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print  - 1 for such sensors.

The first line of the input contains three integers n, m and k (2 ≤ n, m ≤ 100 000, 1 ≤ k ≤ 100 000) — lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1 ≤ xi ≤ n - 1, 1 ≤ yi ≤ m - 1) — coordinates of the sensors. It's guaranteed that no two sensors are located at the same point.

Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or  - 1 if this will never happen.

NoteIn the first sample, the ray will consequently pass through the points (0, 0), (1, 1), (2, 2), (3, 3). Thus, it will stop at the point (3, 3) after 3 seconds.  In the second sample, the ray will consequently pass through the following points: (0, 0), (1, 1), (2, 2), (3, 3), (2, 4), (1, 3), (0, 2), (1, 1), (2, 0), (3, 1), (2, 2), (1, 3), (0, 4). The ray will stop at the point (0, 4) after 12 seconds. It will reflect at the points (3, 3), (2, 4), (0, 2), (2, 0) and (3, 1).

import java.io._
import scala.io.Source
import scala.annotation.tailrec
import scala.reflect.ClassTag

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

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

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line = lines.next()
    val strings = line.split(' ')
    val n = strings(0).toInt
    val m = strings(1).toInt
    val k = strings(2).toInt
    val signals = Array.ofDim[Point](k)
    for (i <- 0 until k) {
      val row = lines.next()
      val coords = row.split(' ').map(_.toInt)
      signals(i) = Point(coords(0), coords(1))
    }

    val firstTimeEachSignalIsHit = solve(n, m, k, signals)
    firstTimeEachSignalIsHit.map {
      case Some(tme) => tme.toString
      case _ => "-1"
    }.foreach { str =>
      bw.write(str)
      bw.newLine()
    }
  }

  sealed trait Direction { def inverse: Direction }
  final object NorthWest extends Direction { override val inverse = SouthEast }
  final object SouthWest extends Direction { override val inverse = NorthEast }
  final object NorthEast extends Direction { override val inverse = SouthWest }
  final object SouthEast extends Direction { override val inverse = NorthWest }

  class Border[T:ClassTag](val rowCount: Int, val columnCount: Int, initialValue: T)
  {
    val pointCount = 2 * (rowCount + columnCount)
    private val points: Array[T] = Array.fill[T](pointCount)(initialValue)
    def get(edgePoint: Point): T = points(pointToIndex(edgePoint))
    def set(edgePoint: Point, value: T): Unit = { points(pointToIndex(edgePoint)) = value }
    def pointToIndex(edgePoint: Point): Int = edgePoint match {
      case Point(x, 0) => x
      case Point(x, y) if x == columnCount => columnCount + y
      case Point(x, y) if y == rowCount    => rowCount + 2 * columnCount - x
      case Point(0, y) => 2 * (rowCount + columnCount) - y
      case _ => throw new IllegalArgumentException(s"Point (${edgePoint.x}, ${edgePoint.y}) is not a border point")
    }
    def isCornerPoint(point: Point): Boolean = point match {
      case Point(0, 0) => true
      case Point(0, y) if y == rowCount => true
      case Point(x, 0) if x == columnCount => true
      case Point(x, y) if x == columnCount && y == rowCount => true
      case _ => false
    }
  }
  case class Arrow(val position: Point, val direction: Direction, val timeSteps: Long) {
    def +(other: Arrow): Arrow = Arrow(other.position, other.direction, this.timeSteps + other.timeSteps)
  }
  case class SignalFromEdge(val index: Int, arrowToSignal: Arrow)

  def solve(n: Int, m: Int, k: Int, signals: Array[Point]): Array[Option[Long]] = {
    // Take a starting point and direction, and project to an edge of the n x m box.
    // Return a new arrow with its start point as the end point of the last arrow,
    // its direction the reflection of the previous arrow, and with timeSteps
    // based on how long previous arrow travelled for to reach the start of this arrow:
    def projectToBorder(startArrow: Arrow): Arrow = startArrow match {
      case Arrow(Point(x, y), NorthEast, _) if m - y <= n - x => Arrow(Point(x + m - y, m), SouthEast, m-y)
      case Arrow(Point(x, y), NorthEast, _)               => Arrow(Point(n, y + n - x), NorthWest, n - x)
      case Arrow(Point(x, y), NorthWest, _) if x + y <= m => Arrow(Point(0, y + x), NorthEast, x)
      case Arrow(Point(x, y), NorthWest, _)               => Arrow(Point(x + y - m, m), SouthWest, m - y)
      case Arrow(Point(x, y), SouthEast, _) if x + y <= n => Arrow(Point(x + y, 0), NorthEast, y)
      case Arrow(Point(x, y), SouthEast, _)               => Arrow(Point(n, x + y - n), SouthWest, n - x)
      case Arrow(Point(x, y), SouthWest, _) if y <= x     => Arrow(Point(x - y, 0), NorthWest, y)
      case Arrow(Point(x, y), SouthWest, _)               => Arrow(Point(0, y - x), SouthEast, x)
    }

    val signalTimes = Array.fill[Option[Long]](k)(None)
    val diagonals = new Border[List[SignalFromEdge]](m, n, List.empty[SignalFromEdge])

    // Add signals along each diagonal by point on the border:
    val signalsFromEdges = for {
      i <- 0 until k
      dir <- List(NorthEast, NorthWest, SouthEast, SouthWest)
    } yield SignalFromEdge(i, projectToBorder(Arrow(signals(i), dir, 0)).copy(direction = dir.inverse))

    for (sig <- signalsFromEdges) {
      val pos = sig.arrowToSignal.position
      diagonals.set(pos, sig :: diagonals.get(pos))
    }

    @tailrec
    def projectRay(acc: Arrow): Unit = {
      // Update distances to signals along the current diagonal:
      val signalsOnDiagonal = diagonals.get(acc.position).filter(_.arrowToSignal.direction == acc.direction)
      for (sig <- signalsOnDiagonal) {
        if (signalTimes(sig.index) == None) {
          val timeToSignal = (acc + sig.arrowToSignal).timeSteps
          signalTimes(sig.index) = Some(timeToSignal)
        }
      }
      // Determine new position:
      val newAcc = acc + projectToBorder(acc)
      if (!diagonals.isCornerPoint(newAcc.position)) projectRay(newAcc)
    }

    projectRay(Arrow(Point(0, 0), NorthEast, 0))
    signalTimes
  }
}

import java.io._
import scala.io.Source
import scala.annotation.tailrec
import scala.reflect.ClassTag

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

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

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line = lines.next()
    val strings = line.split(' ')
    val n = strings(0).toInt
    val m = strings(1).toInt
    val k = strings(2).toInt
    val signals = Array.ofDim[Point](k)
    for (i <- 0 until k) {
      val row = lines.next()
      val coords = row.split(' ').map(_.toInt)
      signals(i) = Point(coords(0), coords(1))
    }

    val firstTimeEachSignalIsHit = solve(n, m, k, signals)
    firstTimeEachSignalIsHit.map {
      case Some(tme) => tme.toString
      case _ => "-1"
    }.foreach { str =>
      bw.write(str)
      bw.newLine()
    }
  }

  sealed trait Direction { def inverse: Direction }
  final object NorthWest extends Direction { override val inverse = SouthEast }
  final object SouthWest extends Direction { override val inverse = NorthEast }
  final object NorthEast extends Direction { override val inverse = SouthWest }
  final object SouthEast extends Direction { override val inverse = NorthWest }

  class Border[T:ClassTag](val rowCount: Int, val columnCount: Int, initialValue: T)
  {
    val pointCount = 2 * (rowCount + columnCount)
    private val points: Array[T] = Array.fill[T](pointCount)(initialValue)
    def get(edgePoint: Point): T = points(pointToIndex(edgePoint))
    def set(edgePoint: Point, value: T): Unit = { points(pointToIndex(edgePoint)) = value }
    def pointToIndex(edgePoint: Point): Int = edgePoint match {
      case Point(x, 0) => x
      case Point(x, y) if x == columnCount => columnCount + y
      case Point(x, y) if y == rowCount    => rowCount + 2 * columnCount - x
      case Point(0, y) => 2 * (rowCount + columnCount) - y
      case _ => throw new IllegalArgumentException(s"Point (${edgePoint.x}, ${edgePoint.y}) is not a border point")
    }
    def isCornerPoint(point: Point): Boolean = point match {
      case Point(0, 0) => true
      case Point(0, y) if y == rowCount => true
      case Point(x, 0) if x == columnCount => true
      case Point(x, y) if x == columnCount && y == rowCount => true
      case _ => false
    }
  }
  case class Arrow(position: Point, direction: Direction, timeSteps: Long) {
    def +(other: Arrow): Arrow = Arrow(other.position, other.direction, this.timeSteps + other.timeSteps)
  }
  case class SignalFromEdge(index: Int, arrowToSignal: Arrow)

  def solve(n: Int, m: Int, k: Int, signals: Array[Point]): Array[Option[Long]] = {
    // Take a starting point and direction, and project to an edge of the n x m box.
    // Return a new arrow with its start point as the end point of the last arrow,
    // its direction the reflection of the previous arrow, and with timeSteps
    // based on how long previous arrow travelled for to reach the start of this arrow:
    def projectToBorder(startArrow: Arrow): Arrow = startArrow match {
      case Arrow(Point(x, y), NorthEast, _) if m - y <= n - x => Arrow(Point(x + m - y, m), SouthEast, m-y)
      case Arrow(Point(x, y), NorthEast, _)               => Arrow(Point(n, y + n - x), NorthWest, n - x)
      case Arrow(Point(x, y), NorthWest, _) if x + y <= m => Arrow(Point(0, y + x), NorthEast, x)
      case Arrow(Point(x, y), NorthWest, _)               => Arrow(Point(x + y - m, m), SouthWest, m - y)
      case Arrow(Point(x, y), SouthEast, _) if x + y <= n => Arrow(Point(x + y, 0), NorthEast, y)
      case Arrow(Point(x, y), SouthEast, _)               => Arrow(Point(n, x + y - n), SouthWest, n - x)
      case Arrow(Point(x, y), SouthWest, _) if y <= x     => Arrow(Point(x - y, 0), NorthWest, y)
      case Arrow(Point(x, y), SouthWest, _)               => Arrow(Point(0, y - x), SouthEast, x)
    }

    val signalTimes = Array.fill[Option[Long]](k)(None)
    val diagonals = new Border[List[SignalFromEdge]](m, n, List.empty[SignalFromEdge])

    // Add signals along each diagonal by point on the border:
    val signalsFromEdges = for {
      i <- 0 until k
      dir <- List(NorthEast, NorthWest, SouthEast, SouthWest)
    } yield SignalFromEdge(i, projectToBorder(Arrow(signals(i), dir, 0)).copy(direction = dir.inverse))

    for (sig <- signalsFromEdges) {
      val pos = sig.arrowToSignal.position
      diagonals.set(pos, sig :: diagonals.get(pos))
    }

    @tailrec
    def projectRay(acc: Arrow): Unit = {
      // Update distances to signals along the current diagonal:
      val signalsOnDiagonal = diagonals.get(acc.position).filter(_.arrowToSignal.direction == acc.direction)
      for (sig <- signalsOnDiagonal) {
        if (signalTimes(sig.index) == None) {
          val timeToSignal = (acc + sig.arrowToSignal).timeSteps
          signalTimes(sig.index) = Some(timeToSignal)
        }
      }
      // Determine new position:
      val newAcc = acc + projectToBorder(acc)
      if (!diagonals.isCornerPoint(newAcc.position)) projectRay(newAcc)
    }

    projectRay(Arrow(Point(0, 0), NorthEast, 0))
    signalTimes
  }
}

import java.io._
import scala.io.Source
import scala.annotation.tailrec
import scala.reflect.ClassTag

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

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

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line = lines.next()
    val strings = line.split(' ')
    val n = strings(0).toInt
    val m = strings(1).toInt
    val k = strings(2).toInt
    val signals = Array.ofDim[Point](k)
    for (i <- 0 until k) {
      val row = lines.next()
      val coords = row.split(' ').map(_.toInt)
      signals(i) = Point(coords(0), coords(1))
    }

    val firstTimeEachSignalIsHit = solve(n, m, k, signals)
    firstTimeEachSignalIsHit.map {
      case Some(tme) => tme.toString
      case _ => "-1"
    }.foreach { str =>
      bw.write(str)
      bw.newLine()
    }
  }

  sealed trait Direction { def inverse: Direction }
  final object NorthWest extends Direction { override val inverse = SouthEast }
  final object SouthWest extends Direction { override val inverse = NorthEast }
  final object NorthEast extends Direction { override val inverse = SouthWest }
  final object SouthEast extends Direction { override val inverse = NorthWest }

  class Border[T:ClassTag](val rowCount: Int, val columnCount: Int, initialValue: T)
  {
    val pointCount = 2 * (rowCount + columnCount)
    private val points: Array[T] = Array.fill[T](pointCount)(initialValue)
    def get(edgePoint: Point): T = points(pointToIndex(edgePoint))
    def set(edgePoint: Point, value: T): Unit = { points(pointToIndex(edgePoint)) = value }
    def pointToIndex(edgePoint: Point): Int = edgePoint match {
      case Point(x, 0) => x
      case Point(x, y) if x == columnCount => rowCount + y
      case Point(x, y) if y == rowCount    => 2 * rowCount + columnCount - x
      case Point(0, y) => 2 * (rowCount + columnCount) - y
      case _ => throw new IllegalArgumentException(s"Point (${edgePoint.x}, ${edgePoint.y}) is not a border point")
    }
    def isCornerPoint(point: Point): Boolean = point match {
      case Point(0, 0) => true
      case Point(0, y) if y == rowCount => true
      case Point(x, 0) if x == columnCount => true
      case Point(x, y) if x == columnCount && y == rowCount => true
      case _ => false
    }
  }
  case class Arrow(val position: Point, val direction: Direction, val timeSteps: Long) {
    def +(other: Arrow): Arrow = Arrow(other.position, other.direction, this.timeSteps + other.timeSteps)
  }
  case class SignalFromEdge(val index: Int, arrowToSignal: Arrow)

  def solve(n: Int, m: Int, k: Int, signals: Array[Point]): Array[Option[Long]] = {
    // Take a starting point and direction, and project to an edge of the n x m box.
    // Return a new arrow with its start point as the end point of the last arrow,
    // its direction the reflection of the previous arrow, and with timeSteps
    // based on how long previous arrow travelled for to reach the start of this arrow:
    def projectToBorder(startArrow: Arrow): Arrow = startArrow match {
      case Arrow(Point(x, y), NorthEast, _) if y >= x     => Arrow(Point(x + m - y, m), SouthEast, m-y)
      case Arrow(Point(x, y), NorthEast, _)               => Arrow(Point(n, y + n - x), NorthWest, n - x)
      case Arrow(Point(x, y), NorthWest, _) if x + y <= m => Arrow(Point(0, y + x), NorthEast, x)
      case Arrow(Point(x, y), NorthWest, _)               => Arrow(Point(x + y - m, m), SouthWest, m - y)
      case Arrow(Point(x, y), SouthEast, _) if x + y <= n => Arrow(Point(x + y, 0), NorthEast, y)
      case Arrow(Point(x, y), SouthEast, _)               => Arrow(Point(n, x + y - n), SouthWest, n - x)
      case Arrow(Point(x, y), SouthWest, _) if y <= x     => Arrow(Point(x - y, 0), NorthWest, y)
      case Arrow(Point(x, y), SouthWest, _)               => Arrow(Point(0, y - x), SouthEast, x)
    }

    val signalTimes = Array.fill[Option[Long]](k)(None)
    val diagonals = new Border[List[SignalFromEdge]](m, n, List.empty[SignalFromEdge])

    // Add signals along each diagonal by point on the border:
    val signalsFromEdges = for {
      i <- 0 until k
      dir <- List(NorthEast, NorthWest, SouthEast, SouthWest)
    } yield SignalFromEdge(i, projectToBorder(Arrow(signals(i), dir, 0)).copy(direction = dir.inverse))

    for (sig <- signalsFromEdges) {
      val pos = sig.arrowToSignal.position
      diagonals.set(pos, sig :: diagonals.get(pos))
    }

    @tailrec
    def projectRay(acc: Arrow): Unit = {
      // Update distances to signals along the current diagonal:
      val signalsOnDiagonal = diagonals.get(acc.position).filter(_.arrowToSignal.direction == acc.direction)
      for (sig <- signalsOnDiagonal) {
        if (signalTimes(sig.index) == None) {
          val timeToSignal = (acc + sig.arrowToSignal).timeSteps
          signalTimes(sig.index) = Some(timeToSignal)
        }
      }
      // Determine new position:
      val newAcc = acc + projectToBorder(acc)
      if (!diagonals.isCornerPoint(newAcc.position)) projectRay(newAcc)
    }

    projectRay(Arrow(Point(0, 0), NorthEast, 0))
    signalTimes
  }
}


Ivan has $$$n$$$ songs on his phone. The size of the $$$i$$$-th song is $$$a_i$$$ bytes. Ivan also has a flash drive which can hold at most $$$m$$$ bytes in total. Initially, his flash drive is empty.Ivan wants to copy all $$$n$$$ songs to the flash drive. He can compress the songs. If he compresses the $$$i$$$-th song, the size of the $$$i$$$-th song reduces from $$$a_i$$$ to $$$b_i$$$ bytes ($$$b_i < a_i$$$).Ivan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most $$$m$$$. He can compress any subset of the songs (not necessarily contiguous).Ivan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to $$$m$$$).If it is impossible to copy all the songs (even if Ivan compresses all the songs), print "-1". Otherwise print the minimum number of songs Ivan needs to compress.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5, 1 \le m \le 10^9$$$) — the number of the songs on Ivan's phone and the capacity of Ivan's flash drive. The next $$$n$$$ lines contain two integers each: the $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$, $$$a_i > b_i$$$) — the initial size of the $$$i$$$-th song and the size of the $$$i$$$-th song after compression.

If it is impossible to compress a subset of the songs in such a way that all songs fit on the flash drive, print "-1". Otherwise print the minimum number of the songs to compress.

NoteIn the first example Ivan can compress the first and the third songs so after these moves the sum of sizes will be equal to $$$8 + 7 + 1 + 5 = 21 \le 21$$$. Also Ivan can compress the first and the second songs, then the sum of sizes will be equal $$$8 + 4 + 3 + 5 = 20 \le 21$$$. Note that compressing any single song is not sufficient to copy all the songs on the flash drive (for example, after compressing the second song the sum of sizes will be equal to $$$10 + 4 + 3 + 5 = 22 > 21$$$).In the second example even if Ivan compresses all the songs the sum of sizes will be equal $$$8 + 4 + 1 + 4 = 17 > 16$$$.

object Main {
  import java.io._

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, M = sc.nextInt()
    val files = Array.ofDim[(Long, Long)](N)
    rep(N) { i =>
      val a, b = sc.nextLong()
      files(i) = (a, b)
    }

    var SUM = files.sumBy(_._1)
    Sorting.quickSort(files)(Ordering.by[(Long, Long), Long](x => x._2 - x._1))
    var i = 0
    while(SUM > M && i < N) {
      val (a, b) = files(i)
      SUM -= a - b
      i += 1
    }

    if (SUM > M) out.println(-1)
    else out.println(i)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  class InputReader(val stream: InputStream) {

    import java.util.StringTokenizer

    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)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object CF501C extends App {
  import scala.io.StdIn

  val Array(n, m) = StdIn.readLine.split(' ').map(_.toInt)// number of songs

  val input = (0 until n).map(_ => StdIn.readLine.split(' ').map(_.toLong)).toArray.transpose

  val as = input(0) // original sizes
  val bs = input(1) // compressed sizes

  val originalSum = as.sum
  val compressedSum = bs.sum

  if (compressedSum > m) {
    println("-1")
  } else {
    val diff = as.zip(bs).map(x => x._1 - x._2).sorted.reverse
    val overflow = originalSum - m
    var sumDiff: Long = 0
    println(diff.takeWhile(x => {
      val b = sumDiff < overflow
      sumDiff += x
      b
    }).length)
  }
}

object CF501C extends App {

  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve = {
    val n = in.nextInt() // number of songs
    val m = in.nextInt() // capacity

    val input = (0 until n).map(_ => Array(in.nextLong(), in.nextLong())).toArray.transpose

    val as = input(0) // original sizes
    val bs = input(1) // compressed sizes

    val originalSum = as.sum
    val compressedSum = bs.sum

    if (compressedSum > m) {
      out.println("-1")
    } else {
      val diff = as.zip(bs).map(x => x._1 - x._2).sorted.reverse
      val overflow = originalSum - m
      var sumDiff: Long = 0
      out.println(diff.takeWhile(x => {
        val b = sumDiff < overflow
        sumDiff += x
        b
      }).length)
    }
  }

  solve
  out.flush
  out.close
}

// https://codeforces.com/blog/entry/21074
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */
class Scanner2(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

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

  /**
    * Unlike Java's scanner which returns till end of current line, this actually returns the next line
    * @see line() if you want the Java behaviour
    */
  def nextLine(): String = {
    current = None   // reset
    reader.readLine()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

object CF501C extends App {

  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner2(System.in)
  val out = new PrintWriter(System.out)

  def solve = {
    val n = in.nextInt() // number of songs
    val m = in.nextInt() // capacity

    val input = (0 until n).map(_ => Array(in.nextLong(), in.nextLong())).toArray.transpose

    val as = input(0) // original sizes
    val bs = input(1) // compressed sizes

    val originalSum = as.sum
    val compressedSum = bs.sum

    if (compressedSum > m) {
      out.println("-1")
    } else {
      val diff = as.zip(bs).map(x => x._1 - x._2).sorted.reverse
      val overflow = originalSum - m
      var sumDiff: Long = 0
      out.println(diff.takeWhile(x => {
        val b = sumDiff < overflow
        sumDiff += x
        b
      }).length)
    }
  }

  solve
  out.flush
  out.close
}

// https://codeforces.com/blog/entry/21074
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */
class Scanner2(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

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

  /**
    * Unlike Java's scanner which returns till end of current line, this actually returns the next line
    * @see line() if you want the Java behaviour
    */
  def nextLine(): String = {
    current = None   // reset
    reader.readLine()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

object CF501C extends App {

  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve = {
    val n = in.nextInt // number of songs
    val m = in.nextInt // capacity

    val input = (0 until n).map(_ => Array(in.nextLong, in.nextLong)).toArray.transpose
    val as = input(0) // original sizes
    val bs = input(1) // compressed sizes

    val originalSum = as.sum
    val compressedSum = bs.sum

    if (compressedSum > m) {
      out.println("-1")
    } else {
      val diff = as.zip(bs).map(x => x._1 - x._2).sorted.reverse
      val overflow = originalSum - m
      var sumDiff: Long = 0
      out.println(diff.takeWhile(x => {
        sumDiff += x

        sumDiff < overflow
      }).length)
    }
  }

  solve
  out.flush
  out.close
}

object CF501C extends App {

  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve = {
    val n = in.nextInt // number of songs
    val m = in.nextInt // capacity

    val input = (0 until n).map(_ => Array(in.nextLong, in.nextLong)).toArray.transpose
    val as = input(0) // original sizes
    val bs = input(1) // compressed sizes

    val originalSum = as.sum
    val compressedSum = bs.sum

    if (compressedSum > m) {
      out.println("-1")
    } else {
      val diff = as.zip(bs).map(x => x._1 - x._2).sorted
      val overflow = originalSum - m
      var sumDiff: Long = 0
      out.println(diff.takeWhile(x => {
        sumDiff += x

        sumDiff < overflow
      }).length)
    }
  }

  solve
  out.flush
  out.close
}


You are given three positive integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$a < b < c$$$). You have to find three positive integers $$$x$$$, $$$y$$$, $$$z$$$ such that:$$$$$$x \bmod y = a,$$$$$$ $$$$$$y \bmod z = b,$$$$$$ $$$$$$z \bmod x = c.$$$$$$Here $$$p \bmod q$$$ denotes the remainder from dividing $$$p$$$ by $$$q$$$. It is possible to show that for such constraints the answer always exists.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a < b < c \le 10^8$$$).

For each test case output three positive integers $$$x$$$, $$$y$$$, $$$z$$$ ($$$1 \le x, y, z \le 10^{18}$$$) such that $$$x \bmod y = a$$$, $$$y \bmod z = b$$$, $$$z \bmod x = c$$$. You can output any correct answer.

 import scala.io.StdIn

 object HelloWorld extends App {
    var t = StdIn.readInt();
    val range = 1 to t
    for (num <- range){
        var ip = StdIn.readLine().split(" ");
        val a = ip(0).toLong;
        val b = ip(1).toLong;
        val c = ip(2).toLong;
        val x:Long = c*b+a
        println(s"$x $b $c")

    }
 }

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

object Main {

  def main(args: Array[String]): Unit = {
    val reader = new InputReader()
    val t = reader.nextInt()
    (1 to t).foreach { i =>
      val a = reader.nextInt()
      val b = reader.nextInt()
      val c = reader.nextInt()

      System.out.println((a + b + c) + " " + (b + c) + " " + c)
    }

  }

  class InputReader() {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var line: Array[String] = null
    var cur: Int = 0

    def nextString(): String = {
      while (line == null || cur >= line.length) {
        cur = 0
        line = reader.readLine().split(""" """)
      }
      cur += 1
      line(cur - 1)
    }

    def nextInt(): Int = {
      nextString().toInt
    }

    def nextLong(): Int = {
      nextString().toInt
    }

  }

}

 import scala.io.StdIn
 object HelloWorld extends App {
    var t = StdIn.readInt();
    val range = 1 to t
    for (num <- range){
        var ip = StdIn.readLine().split(" ");
        val a = ip(0).toInt;
        val b = ip(1).toInt;
        val c = ip(2).toInt;
        val x :Long = c*b+a;
        println(s"${x} ${b} ${c}")

    }
 }

 import scala.io.StdIn
 object HelloWorld extends App {
    var t = StdIn.readInt();
    val range = 1 to t
    for (num <- range){
        var ip = StdIn.readLine().split(" ");
        val a = ip(0).toInt;
        val b = ip(1).toInt;
        val c = ip(2).toInt;
        println(s"${c*b+a} ${b} ${c}")

    }
 }


A median in an array with the length of n is an element which occupies position number  after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression  as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.

The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.

Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.

NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.

object Median extends App {
  val input = io.Source.stdin.getLines
  val (n, median) = {
    val line = input.next.split(" ").map(_.toInt)
    (line(0), line(1))
  }
  val arr = input.next.split(" ").map(_.toInt)
  var less = 0
  var greater = 0
  arr foreach { n =>
    if(n > median) greater += 1
    else if(n < median) less += 1
  }
  val numToAdd = List(
    2 * greater - n,
    2 * less - n + 1,
    0).max
  println(numToAdd)
}

object Median extends App {
  val input = io.Source.stdin.getLines
  val (n, median) = {
    val line = input.next.split(" ").map(_.toInt)
    (line(0), line(1))
  }
  val arr = input.next.split(" ").map(_.toInt)
  var less = 0
  var greater = 0
  arr foreach { n =>
    if(n > median) greater += 1
    else if(n < median) less += 1
  }
  val numToAdd = List(
    2 * greater - n - 1,
    2 * less - n - 1).max
  println(numToAdd)
}

object Median extends App {
  val input = io.Source.stdin.getLines
  val (n, median) = {
    val line = input.next.split(" ").map(_.toInt)
    (line(0), line(1))
  }
  val arr = input.next.split(" ").map(_.toInt)
  var less = 0
  var greater = 0
  arr foreach { n =>
    if(n > median) greater += 1
    else if(n < median) less += 1
  }
  val numToAdd = List(
    2 * greater - n,
    2 * less - n + 1).max
  println(numToAdd)
}

object Median extends App {
  val input = io.Source.stdin.getLines
  val (n, median) = {
    val line = input.next.split(" ").map(_.toInt)
    (line(0), line(1))
  }
  val arr = input.next.split(" ").map(_.toInt)
  var less = 0
  var eq = 0
  var greater = 0
  arr foreach { n =>
    if(n > median) greater += 1
    else if(n < median) less += 1
    else eq += 1
  }
  val numToAdd = List(
    n - 2 * (greater + eq),
    n - 2 * (less + eq),
    if(eq == 0) 1 else 0).max
  println(numToAdd)
}

object Median extends App {
  val input = io.Source.stdin.getLines
  val (n, median) = {
    val line = input.next.split(" ").map(_.toInt)
    (line(0), line(1))
  }
  val arr = input.next.split(" ").map(_.toInt)
  var less = 0
  var greater = 0
  arr foreach { n =>
    if(n > median) greater += 1
    else if(n < median) less += 1
  }
  val numToAdd = List(
    2 * greater - n,
    2 * less - n - 1).max
  println(numToAdd)
}


There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $$$1$$$ to $$$n$$$, the junction $$$1$$$ is called the root.A subtree of a junction $$$v$$$ is a set of junctions $$$u$$$ such that the path from $$$u$$$ to the root must pass through $$$v$$$. Note that $$$v$$$ itself is included in a subtree of $$$v$$$.A leaf is such a junction that its subtree contains exactly one junction.The New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction $$$t$$$ that all light bulbs in the subtree of $$$t$$$ have different colors.Arkady is interested in the following question: for each $$$k$$$ from $$$1$$$ to $$$n$$$, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to $$$k$$$?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of junctions in the tree. The second line contains $$$n - 1$$$ integers $$$p_2$$$, $$$p_3$$$, ..., $$$p_n$$$ ($$$1 \le p_i < i$$$), where $$$p_i$$$ means there is a branch between junctions $$$i$$$ and $$$p_i$$$. It is guaranteed that this set of branches forms a tree.

Output $$$n$$$ integers. The $$$i$$$-th of them should be the minimum number of colors needed to make the number of happy junctions be at least $$$i$$$.

NoteIn the first example for $$$k = 1$$$ and $$$k = 2$$$ we can use only one color: the junctions $$$2$$$ and $$$3$$$ will be happy. For $$$k = 3$$$ you have to put the bulbs of different colors to make all the junctions happy.In the second example for $$$k = 4$$$ you can, for example, put the bulbs of color $$$1$$$ in junctions $$$2$$$ and $$$4$$$, and a bulb of color $$$2$$$ into junction $$$5$$$. The happy junctions are the ones with indices $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ then.

import scala.collection.mutable

object D extends App {

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

  val Array(n) = readInts(1)
  val ps = readInts(n - 1).map(_ - 1)

  val childBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (i <- 0 until n - 1) {
    childBuilders(ps(i)) += i + 1
  }

  val children = childBuilders.map(_.result())
  val counts = Array.fill(n)(0)

  def dfs(u: Int): Int = {
    if (children(u).isEmpty) {
      counts(u) = 1
    } else {
      var i = 0
      while (i < children(u).length) {
        counts(u) += dfs(children(u)(i))
        i += 1
      }
    }
    counts(u)
  }

  dfs(0)

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

  println(counts.sorted.mkString(" "))

  Console.flush
}


A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities — roads cannot be constructed between these pairs of cities.Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.

The first line consists of two integers n and m . Then m lines follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that it is not possible to construct a road connecting cities ai and bi. Consider the cities are numbered from 1 to n. It is guaranteed that every pair of cities will appear at most once in the input.

You should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that a road should be constructed between cities ai and bi. If there are several solutions, you may print any of them.

NoteThis is one possible solution of the example:   These are examples of wrong solutions:   The above solution is wrong because it doesn't use the minimum number of edges (4 vs 3). In addition, it also tries to construct a road between cities 1 and 3, while the input specifies that it is not allowed to construct a road between the pair.   The above solution is wrong because you need to traverse at least 3 roads to go from city 1 to city 3, whereas in your country it must be possible to go from any city to another by traversing at most 2 roads.   Finally, the above solution is wrong because it must be possible to go from any city to another, whereas it is not possible in this country to go from city 1 to 3, 2 to 3, and 4 to 3.

import scala.util.control.Breaks

object RoadConstruction {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    var arr = in.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val m = arr(1)
    val forbiddenPathVertices=Array.fill[Boolean](n)(false)
    for(i<- 0 until m){
      arr = in.readLine().split(" ").map(_.toInt-1)
      forbiddenPathVertices(arr(0))=true
      forbiddenPathVertices(arr(1))=true
    }
    var hubVertex= -1
    Breaks.breakable {
      for (i <- 0 until n) {
        if (!forbiddenPathVertices(i)) {
          hubVertex = i
          Breaks.break()
        }
      }
    }
    println(n-1)
    for (i <- 0 until n if(i!=hubVertex)) {
      println((i+1)+" "+(hubVertex+1))
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).flatMap{_ =>
    in.next().split(" ").map(_.toInt)
  }.toSet
  val el = Range(1, n + 1).find(x => !data.contains(x)).get
  println(n - 1)
  Range(1, n + 1).foreach { i =>
    if (i != el)
      println(s"$i $el")
  }
}

object tmp extends App {

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

  class MyScanner(br: BufferedReader) {
    var st = new StringTokenizer("")

    def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))

    private def next() = {

      while (!st.hasMoreElements) {
        st = new StringTokenizer(br.readLine())
      }
      st.nextToken()
    }

    def nextInt() = java.lang.Integer.parseInt(next())

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

    def nextLine() = br.readLine()
  }

  val sc = new MyScanner(System.in)
  val n = sc.nextInt()
  val m = sc.nextInt()
  val vertices = Array.fill(n)(true)
  for (_ <- 0 until m) {
    vertices(sc.nextInt() - 1) = false
    vertices(sc.nextInt() - 1) = false
  }
  val center = vertices.zipWithIndex.find(x => x._1).get._2 + 1
  println(n - 1)
  for (i <- 1 to n) {
    if (i != center) {
      println(s"$i $center")
    }
  }
}

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 P330B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = sc.nextInt
    out.println(N - 1)
    val E0 = List.fill(N)(new ListBuffer[Int])

    for (_ <- 0 until K) {
      val u, v = sc.nextInt - 1
      E0(u) += v
      E0(v) += u
    }

    var root = -1
    breakable {
      for (i <- 0 until N) {
        if (E0(i).isEmpty) {
          root = i
          break
        }
      }
    }

    0 until N foreach { i =>
      if (i != root) {
        out.println(List(root, i).map(_ + 1).mkString(" "))
      }
    }
  }

  solve
  out.close
}

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

    val a = (1 to m).map(_ => readLine().split(" ").map(_.toInt))

    val s = Set() ++ (1 to n) -- a.flatten
    val u = s.toSeq.apply(0)

    println(n - 1)
    for (i <- 1 to n if i != u) println(i + " " + u)
  }
}

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 P330B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = sc.nextInt
    val E0 = Array.fill(N)(new ListBuffer[Int])

    for (_ <- 0 until K) {
      val u, v = sc.nextInt - 1
      E0(u) += v
      E0(v) += u
    }

    val E: Array[Set[Int]] = E0.map(_.toSet)

    val c0: Set[Int] = List.range(1, N).toSet -- E(0)
    c0.foreach { i =>
      out.println(List(1, i + 1).mkString(" "))
    }
    val c1: Set[Int] = E(0)
    c1 foreach { i =>
      c0.find { j =>
        ! E(i).contains(j)
      }.map { j =>
        val res = List(i, j).map(_ + 1).mkString(" ")
        out.println(res)
      }
    }
  }

  solve
  out.close
}

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 P330B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Int = sc.nextInt - 1

  out.println(solve)
  out.close
}

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 P330B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = sc.nextInt
    out.println(N - 1)
    val E0 = Array.fill(N)(new ListBuffer[Int])

    for (_ <- 0 until K) {
      val u, v = sc.nextInt - 1
      E0(u) += v
      E0(v) += u
    }

    val E: Array[Set[Int]] = E0.map(_.toSet)

    val c0: Set[Int] = List.range(1, N).toSet -- E(0)
    c0.foreach { i =>
      out.println(List(1, i + 1).mkString(" "))
    }
    val c1: Set[Int] = E(0)
    c1 foreach { i =>
      c0.find { j =>
        ! E(i).contains(j)
      }.map { j =>
        val res = List(i, j).map(_ + 1).mkString(" ")
        out.println(res)
      }
    }
  }

  solve
  out.close
}

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

    val a = (1 to m).map(_ => readLine().split(" ").map(_.toInt))

    val s = Set() ++ (1 to n) -- a.flatten
    val u = s.toSeq.apply(0)

    for (i <- 1 to n if i != u) println(i + " " + u)
  }
}


You are given a positive integer $$$n$$$, it is guaranteed that $$$n$$$ is even (i.e. divisible by $$$2$$$).You want to construct the array $$$a$$$ of length $$$n$$$ such that:   The first $$$\frac{n}{2}$$$ elements of $$$a$$$ are even (divisible by $$$2$$$);  the second $$$\frac{n}{2}$$$ elements of $$$a$$$ are odd (not divisible by $$$2$$$);  all elements of $$$a$$$ are distinct and positive;  the sum of the first half equals to the sum of the second half ($$$\sum\limits_{i=1}^{\frac{n}{2}} a_i = \sum\limits_{i=\frac{n}{2} + 1}^{n} a_i$$$). If there are multiple answers, you can print any. It is not guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the array. It is guaranteed that that $$$n$$$ is even (i.e. divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — "NO" (without quotes), if there is no suitable answer for the given test case or "YES" in the first line and any suitable array $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) satisfying conditions from the problem statement on the second line.

import scala.io.StdIn

object SolutionB extends App {
  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val n = StdIn.readInt();
    val l = n / 2
    if (l % 2 == 1) {
      println("NO")
    } else {
      println("YES")
      val first = Array.ofDim[Int](l)
      for (idx <- 1 to l) {
        first(idx-1) = idx * 4
      }
      val second = Array.ofDim[Int](l)
      for (idx <- 1 to l) {
        second(idx-1) = if (idx % 2 == 0) {
          first(idx-1) + 1
        } else {
          first(idx-1) - 1
        }
      }
      print(first.mkString(" "))
      print(" ")
      println(second.mkString(" "))
    }
  }
}

object B {
  import InOut._
  def main(args: Array[String]): Unit = {}

  for (_ <- 1 to nextInt) {
    val n = nextInt
    val h = n / 2
    if (h % 2 == 1) {
      out.println("NO")
    } else {
      val l = Array.tabulate(h)(i => 2 + 2 * i)
      val r = Array.tabulate(h - 1)(i => 1 + 2 * i)
      val res = l ++ r ++ Array(l.sum - r.sum)
      out.println("YES")
      out.println(res.mkString(" "))
    }
  }

  out.flush()

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

import scala.io.StdIn._

object Main2 extends App {
  val testCaseNumber = readInt()
  1.to(testCaseNumber).foreach{ _ =>
    val n = readInt()
    if (n/2 % 2 == 1) {
      println("NO")
    } else {
      println("YES")
      val (even, odd) = 1.to(n).partition(_ % 2 == 0)
      println((even ++ odd.take(n/2 - 1) :+ (odd.last + n/2)).mkString(" "))
    }
  }
}

import scala.io.StdIn

object SolutionB extends App {
  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val n = StdIn.readInt();
    val l = n / 2
    if (l % 2 == 1) {
      println("NO")
    } else {
      println("YES")
      val first = Array.ofDim[Int](l)
      for (idx <- 1 to l) {
        first(idx-1) = idx * 4
      }
      val second = Array.ofDim[Int](l)
      for (idx <- 1 to l) {
        second(idx-1) = if (idx % 2 == 0) {
          first(idx-1) + 1
        } else {
          first(idx-1) - 1
        }
      }
      print(first.mkString(" "))
      print(" ")
      print(second.mkString(" "))
    }
  }
}

import scala.io.StdIn._

object Main2 extends App {
  val testCaseNumber = readInt()
  1.to(testCaseNumber).foreach{ _ =>
    val n = readInt()
    if (n/2 % 2 == 1) {
      println("NO")
    } else {
      println("YES")
      val (even, odd) = 1.to(n).partition(_ % 2 == 0)
      println((even ++ odd).mkString(" "))
    }
  }
}


You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):  choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number);  swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmp = a[i], a[i] = a[j], a[j] = tmp (tmp is a temporary variable). You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n distinct integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ n).

In the first line, print integer k (0 ≤ k ≤ 5n) — the number of used operations. Next, print the operations. Each operation must be printed as "i j" (1 ≤ i < j ≤ n; (j - i + 1) is a prime). If there are multiple answers, you can print any of them.

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer
import java.io.PrintWriter

/**
 * Created by hama_du on 2014/05/18.
 */
object ProblemC extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val result = new ArrayBuffer[(Int,Int)]()

  val n = in.nextInt()
  val a = (0 until n).map(_ => in.nextInt()-1).toArray
  val positions = new Array[Int](n)
  (0 until n).foreach(i => {
    positions(a(i)) = i
  })
  val primes = generatePrimes(100000)

  (n-1 until 0 by -1).foreach(idx => {
    val needToMove = (idx - positions(idx))
    solve(needToMove).foreach(p => {
      result += ((positions(idx)+1, positions(idx)+p))
      swap(positions(idx), positions(idx)+p-1, positions, a)
    })
  })

  out.println(result.size)
  result.foreach(p => {
    out.println(p._1 + " " + p._2)
  })
  out.flush()

  def swap(p: Int, q: Int, positions: Array[Int], a: Array[Int]) {
    val x = a(p)
    val y = a(q)
    a(p) = y
    a(q) = x
    positions(x) = q
    positions(y) = p
  }

  def primeTable(p: Int, primes: Array[Boolean]) {
    if (p*p < primes.length) {
      if (primes(p)) {
        for (i <- p*2 until primes.length by p) {
          primes(i) = false
        }
      }
      primeTable(p+1, primes)
    }
  }

  def generatePrimes(upto: Int): Array[Int] = {
    val primes = Array.fill[Boolean](upto)(true)
    primes(0) = false
    primes(1) = false
    primeTable(2, primes)
    (0 until upto).map(i => i).filter(p => primes(p)).toArray
  }

  def solve(sum: Int): List[Int] = {
    if (sum == 0) {
      List()
    } else {
      val picked = binarySearch(-1, primes.size, sum, primes)
      picked :: solve(sum - (picked - 1))
    }
  }

  def binarySearch(min: Int, max: Int, find: Int, primes: Array[Int]): Int = {
    if (max - min <= 1) {
      primes(min)
    } else {
      val med = (min + max) / 2
      if (primes(med) - 1 <= find) {
        binarySearch(med, max, find, primes)
      } else {
        binarySearch(min, med, find, primes)
      }
    }
  }
}


Polycarp has $$$n$$$ friends, the $$$i$$$-th of his friends has $$$a_i$$$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $$$a_i$$$ to be the same. To solve this, Polycarp performs the following set of actions exactly once:   Polycarp chooses $$$k$$$ ($$$0 \le k \le n$$$) arbitrary friends (let's say he chooses friends with indices $$$i_1, i_2, \ldots, i_k$$$);  Polycarp distributes their $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies among all $$$n$$$ friends. During distribution for each of $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies he chooses new owner. That can be any of $$$n$$$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $$$k$$$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $$$k$$$.For example, if $$$n=4$$$ and $$$a=[4, 5, 2, 5]$$$, then Polycarp could make the following distribution of the candies:   Polycarp chooses $$$k=2$$$ friends with indices $$$i=[2, 4]$$$ and distributes $$$a_2 + a_4 = 10$$$ candies to make $$$a=[4, 4, 4, 4]$$$ (two candies go to person $$$3$$$). Note that in this example Polycarp cannot choose $$$k=1$$$ friend so that he can redistribute candies so that in the end all $$$a_i$$$ are equal.For the data $$$n$$$ and $$$a$$$, determine the minimum value $$$k$$$. With this value $$$k$$$, Polycarp should be able to select $$$k$$$ friends and redistribute their candies so that everyone will end up with the same number of candies.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output:    the minimum value of $$$k$$$, such that Polycarp can choose exactly $$$k$$$ friends so that he can redistribute the candies in the desired way;  "-1" if no such value $$$k$$$ exists.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toLong)

    val s = an.sum

    val ans =
      if (s % n != 0) -1
      else {
        val g = s / n
        an.count(_ > g)
      }

    println(ans)
  }
}


Alice and Bob are playing a game on a line with $$$n$$$ cells. There are $$$n$$$ cells labeled from $$$1$$$ through $$$n$$$. For each $$$i$$$ from $$$1$$$ to $$$n-1$$$, cells $$$i$$$ and $$$i+1$$$ are adjacent.Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers $$$x_1, x_2, \ldots, x_k$$$ in order. In the $$$i$$$-th question, Bob asks Alice if her token is currently on cell $$$x_i$$$. That is, Alice can answer either "YES" or "NO" to each Bob's question.At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.You are given $$$n$$$ and Bob's questions $$$x_1, \ldots, x_k$$$. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions. Let $$$(a,b)$$$ denote a scenario where Alice starts at cell $$$a$$$ and ends at cell $$$b$$$. Two scenarios $$$(a_i, b_i)$$$ and $$$(a_j, b_j)$$$ are different if $$$a_i \neq a_j$$$ or $$$b_i \neq b_j$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n,k \leq 10^5$$$) — the number of cells and the number of questions Bob asked. The second line contains $$$k$$$ integers $$$x_1, x_2, \ldots, x_k$$$ ($$$1 \leq x_i \leq n$$$) — Bob's questions.

Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.

NoteThe notation $$$(i,j)$$$ denotes a scenario where Alice starts at cell $$$i$$$ and ends at cell $$$j$$$.In the first example, the valid scenarios are $$$(1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5)$$$. For example, $$$(3,4)$$$ is valid since Alice can start at cell $$$3$$$, stay there for the first three questions, then move to cell $$$4$$$ after the last question. $$$(4,5)$$$ is valid since Alice can start at cell $$$4$$$, stay there for the first question, the move to cell $$$5$$$ for the next two questions. Note that $$$(4,5)$$$ is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.In the second example, Alice has no valid scenarios.In the last example, all $$$(i,j)$$$ where $$$|i-j| \leq 1$$$ except for $$$(42, 42)$$$ are valid scenarios.

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(K)
    val C = Array.fill[java.util.TreeSet[Integer]](N + 1)(new java.util.TreeSet)
    REP(K) { i =>
      C(A(i)).add(i)
    }

    var ans = 0
    TO(1, N) { b =>
      val cnt =  if (C(b).isEmpty) {
        var v = 1
        if (b < N) v += 1
        if (b > 1) v += 1
        v
      } else {
        val i = C(b).last
        var v = 0
        if (b < N && C(b + 1).lower(i) == null) v += 1
        if (b > 1 && C(b - 1).lower(i) == null) v += 1
        v
      }
      ans += cnt
    }
    out.println(ans)
  }
}

import java.util.Scanner

import scala.io.StdIn

object Ctask557 extends App {

  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()
  val k = line.nextInt()

  val x = StdIn.readLine().split(' ').map(_.toInt)
  var blocks = Array.fill(n){0}

  var result = 1 + (n - 1) * 3
  for (i <- 0 until k) {
    if (blocks(x(i) - 1) == 0) {
      blocks(x(i) - 1) += 1
      result -= 1
    }
    if (x(i)-2 >= 0 && blocks(x(i) - 2) >= 1 && (blocks(x(i) -1) == 1 || blocks(x(i) -1) == 11)) {
      result -= 1
      blocks(x(i) -1) += 1
    }
    if (x(i) < n && blocks(x(i)) >= 1 && (blocks(x(i) - 1) == 1 || blocks(x(i) - 1) == 2)) {
      result -= 1
      blocks(x(i) -1) += 10
    }
  }
  if (result < 0) {
    result = 0
  }
  println(result)
}

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(K)
    val C = Array.fill[java.util.TreeSet[Integer]](N + 1)(new java.util.TreeSet)
    REP(K) { i =>
      C(A(i)).add(i)
    }

    var ans = 0
    TO(1, N) { b =>
      val cnt =  if (C(b).isEmpty) {
        if (b == 1 || b == N) 2 else 3
      } else if (C(b).size == 1) {
        val i = C(b).first()
        var v = 0
        if (b < N && C(b + 1).lower(i) == null) v += 1
        if (b > 1 && C(b - 1).lower(i) == null) v += 1
        v
      } else {
        0
      }
      ans += cnt
    }
    out.println(ans)
  }
}

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(K)
    val C = Array.fill[java.util.TreeSet[Integer]](N + 1)(new java.util.TreeSet)
    REP(K) { i =>
      C(A(i)).add(i)
    }

    var ans = 0
    TO(1, N) { b =>
      val cnt =  if (C(b).isEmpty) {
        var v = 1
        if (b < N) v += 1
        if (b > 1) v += 1
        v
      } else if (C(b).size == 1) {
        val i = C(b).first()
        var v = 0
        if (b < N && C(b + 1).lower(i) == null) v += 1
        if (b > 1 && C(b - 1).lower(i) == null) v += 1
        v
      } else {
        0
      }
      ans += cnt
    }
    out.println(ans)
  }
}

import java.util.Scanner

import scala.io.StdIn

object Ctask557 extends App {

  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()
  val k = line.nextInt()

  val x = StdIn.readLine().split(' ').map(_.toInt)
  var blocks = Array.fill(n){0}

  var result = 1 + (n - 1) * 3
  for (i <- 0 until k) {
    blocks(x(i)-1) += 1
    if (blocks(x(i) - 1) == 1) {
      result -= 1
    }
    if (x(i)-2 >= 0 && blocks(x(i) - 2) >= 1 && (blocks(x(i) -1) == 1 || blocks(x(i) -1) == 11)) {
      result -= 1
      blocks(x(i) -1) += 1
    }
    if (x(i) < n && blocks(x(i)) >= 1 && blocks(x(i) - 1) != 11 && blocks(x(i) - 1) != 12) {
      result -= 1
      blocks(x(i) -1) += 10
    }
  }
  if (result < 0) {
    result = 0
  }
  println(result)
}

import java.util.Scanner

import scala.io.StdIn

object Ctask557 extends App {

  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()
  val k = line.nextInt()

  val x = StdIn.readLine().split(' ').map(_.toInt)
  var blocks = Array.fill(n){0}

  var result = 1 + (n - 1) * 3
  for (i <- 0 until k) {
    blocks(x(i)-1) += 1
    if (blocks(x(i) - 1) == 1) {
      result -= 1
    }
    if (x(i)-2 >= 0 && blocks(x(i) - 2) >= 1 && (blocks(x(i) -1) != 2 || blocks(x(i) -1) == 11)) {
      result -= 1
      blocks(x(i) -1) += 1
    }
    if (x(i) < n && blocks(x(i)) >= 1 && blocks(x(i) - 1) != 11 && blocks(x(i) - 1) != 12) {
      result -= 1
      blocks(x(i) -1) += 10
    }
  }
  if (result < 0) {
    result = 0
  }
  println(result)
}

import java.util.Scanner

import scala.io.StdIn

object Ctask557 extends App {

  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()
  val k = line.nextInt()

  val x = StdIn.readLine().split(' ').map(_.toInt)
  var blocks = Array.fill(n){0}

  var result = 1 + (n - 1) * 3
  for (i <- 0 until k) {
    if (blocks(x(i) - 1) == 0) {
      blocks(x(i) - 1) += 1
    }
    if (blocks(x(i) - 1) == 1) {
      result -= 1
    }
    if (x(i)-2 >= 0 && blocks(x(i) - 2) >= 1 && (blocks(x(i) -1) == 1 || blocks(x(i) -1) == 11)) {
      result -= 1
      blocks(x(i) -1) += 1
    }
    if (x(i) < n && blocks(x(i)) >= 1 && (blocks(x(i) - 1) == 1 || blocks(x(i) - 1) == 2)) {
      result -= 1
      blocks(x(i) -1) += 10
    }
  }
  if (result < 0) {
    result = 0
  }
  println(result)
}