You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.

The first line of the input contains following integers:   n: the number of towers in the building (1 ≤ n ≤ 108),  h: the number of floors in each tower (1 ≤ h ≤ 108),  a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h),  k: total number of queries (1 ≤ k ≤ 104).  Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.

For each query print a single integer: the minimum walking time between the locations in minutes.

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

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

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

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

  def solve(): Unit = {
    val N, H, A, B, K = ni()
    REP(K) { i =>
      val ta, fa, tb, fb = ni()
      val ans = if (ta == tb) {
        abs(fa - fb)
      } else if (A <= fa && fa <= B && A <= fb && fb <= B) {
        abs(tb - ta) + abs(fa - fb)
      } else {
        abs(tb - ta) + (for {
          f <- Seq(A, B)
        } yield abs(f - fa) + abs(f - fb)).min
      }
      out.println(ans)
    }
  }

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

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

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

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

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

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

object CF503A extends App {
  import scala.io.StdIn

  val Array(n, h, a, b, k) = StdIn.readLine.split(' ').map(_.toInt)
  val queries = (0 until k).map(_ => StdIn.readLine.split(' ').map(_.toInt))

  for (query <- queries) {
    var Array(ta, fa, tb, fb) = query
    var time = 0
    if (ta != tb) {
      if (fa < a) {
        time = a - fa
        fa = a
      } else if (fa > b) {
        time = fa - b
        fa = b
      }
      time += (tb - ta).abs
    }
    time += (fa - fb).abs
    println(time)
  }
}

import scala.io.StdIn

object A {

  def main(args: Array[String]): Unit = {
    val input = StdIn.readLine().split(' ').map(_.toInt)

    print {
      val n = input(0)
      val h = input(1)
      val a = input(2)
      val b = input(3)
      val k = input(4)

      (1 to k).map { index =>
        val in = StdIn.readLine().split(' ').map(_.toInt)

        val ta = in(0)
        val fa = in(1)
        val tb = in(2)
        val fb = in(3)

        val tdiff = Math.abs(ta - tb)

        if (tdiff == 0) Math.abs(fa - fb)
        else if (fa < a) tdiff + a - fa + Math.abs(a - fb)
        else if (fa > b) tdiff + fa - b + Math.abs(b - fb)
        else tdiff + Math.abs(fa - fb)
      }.mkString(" ")
    }

  }

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_503_A {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val line = readLine
    val n = line.int
    val h = line.int
    val a = line.int
    val b = line.int
    val k = line.int

    for (i <- 1 to k) {
      val qLine = readLine
      val t1 = qLine.int
      val f1 = qLine.int
      val t2 = qLine.int
      val f2 = qLine.int
      debug(s"$i: $t1 $f1 -> $t2 $f2")

      if (t1 == t2) {
        val path = (f1 - f2).abs
        outLn(path)
        debug("same " + path)
      } else {
        var toTunnel = 0
        var exitIn2 = f1
        if (f1 < a) { toTunnel = a-f1; exitIn2 = a; }
        if (f1 > b) { toTunnel = f1-b; exitIn2 = b; }
        debug(s" $toTunnel $exitIn2")
        var path = toTunnel + (t2 - t1).abs + (exitIn2 - f2).abs
        outLn(path)
      }
    }
//    val arr = new Array[String](n)
//    (0 until n).foreach(arr(_) = readLine.string)
//    debug("n = " + n)

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

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
3 6 2 3 3
1 2 1 3
1 4 3 4
1 2 2 3
"""

val sa2 = """
"""

val sa3 = """
"""
}

}

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

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

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

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

  def solve(): Unit = {
    val N, H, A, B, K = ni()
    REP(K) { i =>
      val ta, fa, tb, fb = ni()
      val ans = if (A <= fa && fa <= B && A <= fb && fb <= B) {
        abs(tb - ta) + abs(fa - fb)
      } else {
        abs(tb - ta) + (for {
          f <- Seq(A, B)
        } yield abs(f - fa) + abs(f - fb)).min
      }
      out.println(ans)
    }
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, H, A, B, K = ni()
    REP(K) { i =>
      val ta, fa, tb, fb = ni()
      val ans = if (A <= ta && ta <= B) {
        abs(tb - ta) + abs(fa - fb)
      } else {
        abs(tb - ta) + (for {
          f <- Seq(A, B)
        } yield abs(f - fa) + abs(f - fb)).min
      }
      out.println(ans)
    }
  }

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

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

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

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

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

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

object CF503A extends App {
  import scala.io.StdIn

  val Array(n, h, a, b, k) = StdIn.readLine.split(' ').map(_.toInt)
  val queries = (0 until k).map(_ => StdIn.readLine.split(' ').map(_.toInt))

  for (query <- queries) {
    var Array(ta, fa, tb, fb) = query
    var time = 0
    if (fa < a) {
      time = a - fa
      fa = a
    } else if (fa > b) {
      time = fa - b
      fa = b
    }
    time += (tb - ta).abs
    time += (fa - fb).abs
    println(time)
  }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_503_A {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val line = readLine
    val n = line.int
    val h = line.int
    val a = line.int
    val b = line.int
    val k = line.int

    for (i <- 1 to k) {
      val qLine = readLine
      val t1 = qLine.int
      val f1 = qLine.int
      val t2 = qLine.int
      val f2 = qLine.int
      debug(s"$i: $t1 $f1 -> $t2 $f2")

      if (t1 == t2) {
        val path = (f1 - f2).abs
        outLn(path)
        debug("same " + path)
      } else {
        var toTunnel = 0
        var exitIn2 = f1
        if (f1 < a) { toTunnel = a-f1; exitIn2 = a; }
        if (f1 > b) { toTunnel = f1-b; exitIn2 = b; }
        debug(s" $toTunnel $exitIn2")
        var path = toTunnel + (t2 - t1) + (exitIn2 - f2).abs
        outLn(path)
      }
    }
//    val arr = new Array[String](n)
//    (0 until n).foreach(arr(_) = readLine.string)
//    debug("n = " + n)

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

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
3 6 2 3 3
1 2 1 3
1 4 3 4
1 2 2 3
"""

val sa2 = """
"""

val sa3 = """
"""
}

}


You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$).

Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays.

//package codeforces

/*
https://codeforces.com/contest/1175/problem/D

Strategy-

s = suffix sum array
f = indexes array

** f(0) is always 0

this implies =>
  res = s(f(0)) - s(f(1)) + 2*(s(f(1)) - s(f(2))) + 3*(s(f(2)) - s(f(3))) + ...
  res = s(f(0)) + s(f(1)) + s(f(2)) + s(f(3)) + ...
  this means we select the top k max elements form the suffix sum array

 */
object ArraySplitting {

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

    val suffixSum = seq.scanRight(0l)(_ + _)
    println(suffixSum(0) + suffixSum.drop(1).dropRight(1).sorted.takeRight(k - 1).sum)
  }

}

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

  case class Entry(i: Int, sum: Long)
  def solve(): Unit = {
    import java.util.Comparator
    val N, K = ni()
    val A = na(N)
    val cumR = cumSum(A.reverse).reverse

    // 一番左を２番目以降のグループにすることはできない
    val E = Array.ofDim[Entry](N - 1)
    REP(N - 1) { i =>
      E(i) = Entry(i + 1, cumR(i + 1))
    }
    sort(E, new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = -java.lang.Long.compare(o1.sum, o2.sum)
    })

    debug(cumR)
    debug(E.mkString(" "))

    var ans = sumL(A)
    for {
      e <- E.take(K - 1)
    } ans += e.sum

    out.println(ans)
  }
}

//package codeforces

/*
https://codeforces.com/contest/1175/problem/D
 */
object ArraySplitting {

  def main(args: Array[String]): Unit = {
    val Array(n, k) = io.StdIn.readLine().split(" ").map(_.toInt)
    val seq = io.StdIn.readLine().split(" ").map(_.toLong)
    val prefixSum = seq.scanRight(0l)(_ + _)

    val segmentTree = new MaxSegmentTree(prefixSum)

    def loop(i: Int, k: Int, prevMax: Long, result: Long): Long = {
      if (k == 1)
        result + prefixSum(0) - prevMax
      else {
        val (value, index) = segmentTree.query(k - 1, i)
        loop(index - 1, k - 1, value, result + (value - prevMax) * k)
      }
    }

    println(loop(seq.length - 1, k, 0, 0l))
  }

}

/*
right biased max segment tree with index
 */
class MaxSegmentTree private(segmentArr: Array[(Long, Int)], arr: Array[Long]) {

  def this(arr: Array[Long]) = {
    this(new Array[(Long, Int)](4 * arr.length), arr)
  }

  preCompute(0, arr.length - 1, 0)

  private def preCompute(l: Int, r: Int, i: Int): Unit = {
    if (l == r) segmentArr(i) = (arr(l), l)
    else {
      val m = (l + r) / 2
      preCompute(l, m, 2 * i + 1)
      preCompute(m + 1, r, 2 * i + 2)
      segmentArr(i) =
        if (segmentArr(2 * i + 1)._1 <= segmentArr(2 * i + 2)._1)
          segmentArr(2 * i + 2)
        else
          segmentArr(2 * i + 1)
    }
  }

  /**
    *
    * @param left  left index inclusive
    * @param right right index inclusive
    * @return result
    */
  def query(left: Int, right: Int): (Long, Int) = {
    assert(left <= right)
    assert(left >= 0 && right < arr.length)

    def query(l: Int, r: Int, i: Int, x: Int, y: Int): (Long, Int) = {
      if (l == x && r == y) segmentArr(i)
      else {
        val m = (l + r) / 2

        if (y <= m) query(l, m, 2 * i + 1, x, y)
        else if (m < x) query(m + 1, r, 2 * i + 2, x, y)
        else {
          val lR = query(l, m, 2 * i + 1, x, m)
          val rR = query(m + 1, r, 2 * i + 2, m + 1, y)

          if (lR._1 <= rR._1) rR else lR
        }
      }

    }

    query(0, arr.length - 1, 0, left, right)
  }
}

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

  case class Entry(i: Int, sum: Long)
  def solve(): Unit = {
    import java.util.Comparator
    val N, K = ni()
    val A = na(N)
    val cumR = cumSum(A.reverse).reverse
    val E = Array.ofDim[Entry](N)
    REP(N) { i =>
      E(i) = Entry(i, cumR(i))
    }
    sort(E, new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = -java.lang.Long.compare(o1.sum, o2.sum)
    })

    debug(cumR)
    debug(E.mkString(" "))

    var ans = sumL(A)
    for {
      e <- E.take(K - 1)
    } ans += e.sum

    out.println(ans)
  }
}


Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.

The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.

For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.

NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.

object A1262 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      val Array(n) = readInts(1)
      var a = Integer.MAX_VALUE
      var b = Integer.MIN_VALUE
      var c = Integer.MAX_VALUE
      var d = Integer.MIN_VALUE
      val arr = Array.fill(n)((0, 0))
      for (i <- 0 until n) {
        val Array(x, y) = readInts(2)
        a = math.min(a, x);
        b = math.max(b, x);
        c = math.min(c, y);
        d = math.max(d, y);
        arr(i) = (x, y)
      }
      var res = Integer.MAX_VALUE
      for ((x, y) <- Array(
             (a, a),
             (b, b),
             (c, c),
             (d, d),
             (a, b),
             (a, c),
             (a, d),
             (b, c),
             (b, d),
             (c, d)
           )) {
        if (arr.forall {
              case (i, j) =>
                (x >= math.min(i, j) && y <= math.max(i, j))
            }) res = math.min(res, math.abs(y - x))
      }
      out.println(res)
      tests -= 1
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.StdIn._
object Main extends App{
    // Your code here!
    val t = readInt()
    for (i <- 1 to t) {
        val n = readInt()
        var minR = Integer.MAX_VALUE
        var maxL=Integer.MIN_VALUE
        for (j <- 1 to n) {
            val arr = readLine().split(" ").map(_.toInt)
            minR = Math.min(minR, arr(1))
            maxL = Math.max(maxL, arr(0))
        }
        println(if (minR >= maxL) 0 else (maxL - minR))
    }
}

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[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final 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()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

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

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

object Workspace {
  import Main._
}

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      var L = 0
      var R = 1e9.toInt
      REP(N) { _ =>
        val l, r = ni()
        L = max(l, L)
        R = min(r, R)
      }
      debug(s"L:$L R:$R")
      val ans = max(0, L - R)
      out.println(ans)
    }
  }
}

object A1262 {

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

  def main(args: Array[String]): Unit = {
    var tests = readInt
    while (tests > 0) {
      val Array(n) = readInts(1)
      var a = Integer.MAX_VALUE
      var b = Integer.MIN_VALUE
      var c = Integer.MAX_VALUE
      var d = Integer.MIN_VALUE
      val arr = Array.fill(n)((0, 0))
      for (i <- 0 until n) {
        val Array(x, y) = readInts(2)
        a = math.min(a, x);
        b = math.max(b, x);
        c = math.min(c, y);
        d = math.max(d, y);
        arr(i) = (x, y)
      }
      var res = Integer.MAX_VALUE
      for ((x, y) <- Array((a, b), (a, c), (a, d), (b, c), (b, d), (c, d))) {
        if (arr.forall {
              case (i, j) =>
                (x >= math.min(i, j) && y <= math.max(i, j))
            }) res = math.min(res, math.abs(y - x))
      }
      out.println(res)
      tests -= 1
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times. When he came to the fruit stall of Ashot, he saw that the seller hadn't distributed price tags to the goods, but put all price tags on the counter. Later Ashot will attach every price tag to some kind of fruits, and Valera will be able to count the total price of all fruits from his list. But Valera wants to know now what can be the smallest total price (in case of the most «lucky» for him distribution of price tags) and the largest total price (in case of the most «unlucky» for him distribution of price tags).

The first line of the input contains two integer number n and m (1 ≤ n, m ≤ 100) — the number of price tags (which is equal to the number of different kinds of fruits that Ashot sells) and the number of items in Valera's list. The second line contains n space-separated positive integer numbers. Each of them doesn't exceed 100 and stands for the price of one fruit of some kind. The following m lines contain names of the fruits from the list. Each name is a non-empty string of small Latin letters which length doesn't exceed 32. It is guaranteed that the number of distinct fruits from the list is less of equal to n. Also it is known that the seller has in stock all fruits that Valera wants to buy.

Print two numbers a and b (a ≤ b) — the minimum and the maximum possible sum which Valera may need to buy all fruits from his list.

6 5
3 5 1 6 8 1
peach
grapefruit
banana
orange
orange

import java.util.Scanner

object Fruits extends App {

  val s = new Scanner(System.in)
  val (n, m) = (s.nextInt(), s.nextInt())
  val prices = (0 until n).map(_ => s.nextInt())
  val fruits = (0 until m).map(_ => (s.next() -> 1)).groupBy(_._1).values.map(x => x.map(_._2)).map(_.sum).toList

  val min = (fruits.sortBy(-_) zip prices.sorted).map(x => x._1 * x._2).sum
  val max = (fruits.sortBy(-_) zip prices.sortBy(-_)).map(x => x._1 * x._2).sum
  println(min + " " + max)

}

object C12 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val map = cu.Map.empty[String, Int].withDefaultValue(0)
    for(_ <- 1 to m) {
      val s = read
      map(s) += 1
    }
    val vals = map.values.toArray.sorted.reverse
    val min = a.zip(vals).map{case (x, y) => x*y}.sum
    val max = a.reverse.zip(vals).map{case (x, y) => x*y}.sum
    println(s"$min $max")
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null
  val ints = new Array[Int](10)

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

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

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

  def comp(x: (String, Int), y: (String, Int)): Boolean = {
    x._2 > y._2
  }

  def solve = {
    val n = nextInt
    val m = nextInt
    val fruitPrice = new Array[Int](n)
    for (i <- 0 until n) {
      fruitPrice(i) = nextInt
    }
    val fruits = new util.HashMap[String, Int](m)
    for (i <- 0 until m) {
      val fruit = next
      if (fruits.containsKey(fruit)) {
        val num = fruits.get(fruit)
        fruits.put(fruit, num + 1)
      } else {
        fruits.put(fruit, 1)
      }
    }
    val fruitsWithIndex = fruits.keySet().toArray(new Array[String](0)).map(x => (x, fruits.get(x))).sortWith(comp)
//    fruitsWithIndex.foreach(print)
    val sortedFruitPrice = fruitPrice.sorted
    var ind = 0
    var minPrice = 0
    var maxPrice = 0
    for (i <- 0 until fruitsWithIndex.length) {
      minPrice += fruitsWithIndex(i)._2 * sortedFruitPrice(ind)
      maxPrice += fruitsWithIndex(i)._2 * sortedFruitPrice(sortedFruitPrice.length - ind - 1)
      ind += 1
    }
    out.print(minPrice + " " + maxPrice)
  }

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


Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?Help Yaroslav.

The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value.

In a single line print the answer to the problem — the maximum sum that Yaroslav can get.

NoteIn the first sample you do not need to change anything. The sum of elements equals 150.In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.

object Sequence {
  def main(args: Array[String]) {
    val n = readInt()
    val nums = readLine().split(" ").map(_.toInt)
    val nums_abs = nums.map(_.abs)

    if (n % 2 == 1 || nums.count(_ < 0) % 2 == 0)
      println(nums_abs.sum)
    else
      println(nums_abs.sum - 2 * nums_abs.min)
  }
}

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

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

  val N = sc.nextInt
  val as = List.fill(2 * N - 1)(sc.nextInt).sorted

  def flipSum(n: Int): Int = {
    val (fs, rs) = as.splitAt(n)
    if (n > 2 * N - 1) Int.MinValue
    else fs.map(_ * -1).sum + rs.sum
  }

  val answer: Int = {
    val neg = as.count(_ < 0)
    if (N % 2 == 1) as.map(scala.math.abs(_)).sum
    else if (neg % 2 == 0) flipSum(neg)
    else flipSum(neg - 1) max flipSum(neg + 1)
  }

  out.println(answer)
  out.close
}

object Sequence {
  def main(args: Array[String]) {
    val n = readInt()
    val nums = readLine().split(" ").map(_.toInt).sorted
    val ans = nums.zipWithIndex.foldLeft(0) {
      case (a, (k, i)) =>
      if (i < n && k < 0)
        a - k
      else
        a + k
    }
    println(ans)
  }
}

object Sequence {
  def main(args: Array[String]) {
    val n = readInt()
    val nums = readLine().split(" ").map(_.toInt).sorted
    if (n > 2)
      println(nums.map(_.abs).sum)
    else {
      val ans = nums.zipWithIndex.foldLeft(0) {
        case (a, (k, i)) =>
        if (i < n && k < 0)
          a - k
        else
          a + k
      }
      println(ans)
    }
  }
}

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

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

  val N = sc.nextInt
  val as = List.fill(2 * N - 1)(sc.nextInt).sorted

  def flipSum(n: Int): Int = {
    val (fs, rs) = as.splitAt(n)
    if (n > N) Int.MinValue
    else fs.map(_ * -1).sum + rs.sum
  }

  val answer: Int = {
    val neg = as.count(_ < 0)
    if (N < neg) flipSum(N)
    else if (N % 2 == neg % 2) flipSum(neg)
    else if (N % 2 == 0) flipSum(neg / 2 * 2) max flipSum(neg / 2 * 2 + 2)
    else flipSum(neg - 1) max flipSum(neg + 1)

  }

  out.println(answer)
  out.close
}

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

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

  val N = sc.nextInt
  val as = List.fill(2 * N - 1)(sc.nextInt).sorted

  def flipSum(n: Int): Int = {
    val (fs, rs) = as.splitAt(n)
    if (n > 2 * N - 1) Int.MinValue
    else fs.map(_ * -1).sum + rs.sum
  }

  val answer: Int = {
    val neg = as.count(_ < 0)
    if (neg % 2 == 0) flipSum(neg)
    else flipSum(neg - 1) max flipSum(neg + 1)
  }

  out.println(answer)
  out.close
}

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

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

  val N = sc.nextInt
  val as = List.fill(2 * N - 1)(sc.nextInt).sorted

  def flipSum(n: Int): Int = {
    val (fs, rs) = as.splitAt(n)
    if (n > N) Int.MinValue
    else fs.map(_ * -1).sum + rs.sum
  }

  val answer: Int = {
    val neg = as.filter(_ < 0).size
    val n = neg / 2 * 2
    flipSum(n) max flipSum(n + 2)
  }

  out.println(answer)
  out.close
}


In Berland, $$$n$$$ different types of banknotes are used. Banknotes of the $$$i$$$-th type have denomination $$$10^{a_i}$$$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $$$1$$$.Let's denote $$$f(s)$$$ as the minimum number of banknotes required to represent exactly $$$s$$$ burles. For example, if the denominations of banknotes used in Berland are $$$1$$$, $$$10$$$ and $$$100$$$, then $$$f(59) = 14$$$: $$$9$$$ banknotes with denomination of $$$1$$$ burle and $$$5$$$ banknotes with denomination of $$$10$$$ burles can be used to represent exactly $$$9 \cdot 1 + 5 \cdot 10 = 59$$$ burles, and there's no way to do it with fewer banknotes.For a given integer $$$k$$$, find the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes (that is, $$$f(s) > k$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10; 1 \le k \le 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 = a_1 < a_2 < \dots < a_n \le 9$$$).

For each test case, print one integer — the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes.

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class pair(var s: Int, var a:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (a == that.a && s == that.s)
                return 0
            if (a > that.s && that.a <= s)
                return 1
            if (a <= that.s && that.a > s)
                return -1
            if (a == that.a) {
                if (s < that.s)
                    return -1
                else
                    return 1
            }
            if (a < that.a)
                return -1
            else
                return 1
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        var k = readLong()+1L
        val a = new Array[Long](n)
        for (i <- 1 to n) {
            a(i-1) = pow(10, readInt()).toLong
        }
        var ans = 0L
        var ind = 0
        while (k > 0) {
            if (ind < n - 1) {
                val tmp = a(ind+1)/a(ind)-1
                ans += a(ind) * min(tmp, k).toLong
                k -= min(tmp, k)
            } else {
                ans += k * a(ind)
                k = 0
            }
            ind += 1
        }
        writer.println(ans)
    }
    writer.flush()
}


Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?

The only line of the input contains single integer n (1 ≤ n ≤ 109) — the length of some side of a right triangle.

Print two integers m and k (1 ≤ m, k ≤ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.

//package merofeev.contests.codeforces.rnd368

import java.util.Scanner

/**
  * @author erofeev
  * @since 03.09.16
  */
object CPifagorian {

  def main(args: Array[String]): Unit = {
    //hypotenuse of every triangle > 4 is a cathetus of the other triangle
    val n = new Scanner(System.in).nextLong()
    //a2 + n2 = c2
    //n2 = a2 - c2
    //n2 = (a - c) * (a + c)
    if (n < 3) {
      println("-1")
    }
    else if (n % 2 == 0) {
      val c = n * n / 4 - 1
      val a = c + 2
      println(s"$a $c")
    } else {
      //n2 = (1) * (n2)
      // a - c = 1; a + c = b2
      val c = (n * n - 1) / 2
      val a = c + 1
      println(s"$a $c")
    }
  }

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val a = in.next().toLong
  if (a < 3) println(-1)
  else if (a % 2 == 1) println(s"${a * a / 2} ${a * a / 2 + 1}")
  else println(s"${a * a / 4 - 1} ${a * a / 4 + 1}")
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _707C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val x = read[Long]
    var sx = x
    while(sx % 2 == 0) {
      sx /= 2
    }

    val (a, b, c) =
      if (sx == 1) {
        val s = x*x/2
        val y = s/2 - 1
        val z = y + 2
        (x, y, z)
      } else {
        val s = sx*sx
        val y = s/2
        val z = y + 1
        (x, x/sx * y, x/sx * z)
      }

    if(a*a + b*b == c*c && a > 0 && b > 0 && c > 0 && a + b > c) {
      write(b, c)
    } else {
      write(-1)
    }
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)

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

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)

    val n = sc.nextLong()

    if(n <= 2)
      println(-1)
    else if(n % 2 == 0)
      println((n/2)*(n/2)-1 + " " + ((n/2)*(n/2)+1))
    else
      println((n*n-1)/2 + " " + (n*n+1)/2)
  }
}

//package merofeev.contests.codeforces.rnd368

import java.util.Scanner

/**
  * @author erofeev
  * @since 03.09.16
  */
object CPifagorian {

  def main(args: Array[String]): Unit = {
    //hypotenuse of every triangle > 4 is a cathetus of the other triangle
    val n = new Scanner(System.in).nextInt()
    //a2 + n2 = c2
    //n2 = a2 - c2
    //n2 = (a - c) * (a + c)
    if (n < 3) {
      println("-1")
    }
    if (n % 2 == 0) {
      val c = n * n / 4 - 1
      val a = c + 2
      println(s"$a $c")
    } else {
      //n2 = (1) * (n2)
      // a - c = 1; a + c = b2
      val c = (n * n - 1) / 2
      val a = c + 1
      println(s"$a $c")
    }
  }

}

//package merofeev.contests.codeforces.rnd368

import java.util.Scanner

/**
  * @author erofeev
  * @since 03.09.16
  */
object CPifagorian {

  def main(args: Array[String]): Unit = {
    //hypotenuse of every triangle > 4 is a cathetus of the other triangle
    val n = new Scanner(System.in).nextInt()
    //a2 + n2 = c2
    //n2 = a2 - c2
    //n2 = (a - c) * (a + c)
    if (n < 3) {
      println("-1")
    }
    else if (n % 2 == 0) {
      val c = n * n / 4 - 1
      val a = c + 2
      println(s"$a $c")
    } else {
      //n2 = (1) * (n2)
      // a - c = 1; a + c = b2
      val c = (n * n - 1) / 2
      val a = c + 1
      println(s"$a $c")
    }
  }

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val a = in.next().toInt
  if (a < 3) println(-1)
  else if (a % 2 == 1) println(s"${a * a / 2} ${a * a / 2 + 1}")
  else println(s"${a * a / 4 - 1} ${a * a / 4 + 1}")
}


There are $$$n$$$ points on the plane, the $$$i$$$-th of which is at $$$(x_i, y_i)$$$. Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.The strange area is enclosed by three lines, $$$x = l$$$, $$$y = a$$$ and $$$x = r$$$, as its left side, its bottom side and its right side respectively, where $$$l$$$, $$$r$$$ and $$$a$$$ can be any real numbers satisfying that $$$l < r$$$. The upper side of the area is boundless, which you can regard as a line parallel to the $$$x$$$-axis at infinity. The following figure shows a strange rectangular area.  A point $$$(x_i, y_i)$$$ is in the strange rectangular area if and only if $$$l < x_i < r$$$ and $$$y_i > a$$$. For example, in the above figure, $$$p_1$$$ is in the area while $$$p_2$$$ is not.Tokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \times 10^5$$$) — the number of points on the plane. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$1 \leq x_i, y_i \leq 10^9$$$) — the coordinates of the $$$i$$$-th point. All points are distinct.

Print a single integer — the number of different non-empty sets of points she can obtain.

NoteFor the first example, there is exactly one set having $$$k$$$ points for $$$k = 1, 2, 3$$$, so the total number is $$$3$$$.For the second example, the numbers of sets having $$$k$$$ points for $$$k = 1, 2, 3$$$ are $$$3$$$, $$$2$$$, $$$1$$$ respectively, and their sum is $$$6$$$.For the third example, as the following figure shows, there are  $$$2$$$ sets having one point;  $$$3$$$ sets having two points;  $$$1$$$ set having four points. Therefore, the number of different non-empty sets in this example is $$$2 + 3 + 0 + 1 = 6$$$.

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N = ni()
    val C = Array.ofDim[Coord](N)
    val X = Array.ofDim[Int](N)
    val zip = new Zipper
    REP(N) { i =>
      val x, y = ni()
      C(i) = Coord(x, y)
      X(i) = x
    }
    sort(X)
    REP(N) { i =>
      zip.get(X(i))
    }

    // y降順
    java.util.Arrays.sort(C, new Comparator[Coord] {
      override def compare(o1: Coord, o2: Coord): Int = {
        -Integer.compare(o1.y, o2.y)
      }
    })

    var ans = 0L
    val bit = new BIT(zip.gen, 0)(_ + _)
    val cur = new java.util.TreeSet[Int]

    def calc(): Unit = {
      var pre = 0
      val it = cur.iterator()
      while(it.hasNext) {
        val j = it.next()
        if (bit.query(j, j + 1)(_-_) == 0) bit.add(j, 1)
        val s = bit.sum(j)
        val len = s - pre
        debug(s"prev j:$j len:$len")
        ans -= len.toLong * (len + 1) / 2
        pre = s + 1
      }

      {
        val s = bit.sumAll
        val len = s - pre
        debug(s"prev j:last len:$len")
        ans -= len.toLong * (len + 1) / 2
      }

      val len = bit.sumAll
      debug(s"len:$len")
      ans += len.toLong * (len + 1) / 2
      cur.clear()
    }

    var i = 0
    while(i < N) {
      while (i + 1 < N && C(i).y == C(i + 1).y) {
        cur.add(zip.get(C(i).x))
        i += 1
      }
      cur.add(zip.get(C(i).x))
      i += 1
      calc()
    }

    out.println(ans)
  }

  class Zipper {
    type A = Long
    var gen = 0
    val id = mutable.HashMap[A, Int]()

    def get(x: A): Int = {
      id.getOrElseUpdate(x, {
        val i = gen
        gen += 1
        i
      })
    }
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    java.util.Arrays.sort(a)
    a
  }
class BIT(n: Int, zero: Int)(f: (Int, Int) => Int) {
  def this(n: Int) = this(n, 0)(_ + _)

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

  /**
    * 1 index
    * addとindex違うよ
    * cumsumなんかといっしょ
    */
  def sum(i: Int): Int = {
    assert(i <= n)
    var x = i
    var s: Int = 0
    while(x > 0) {
      s = f(s, bit(x))
      x -= x & -x
    }
    s
  }

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

  def sumAll: Int = sum(n)

  /**
    * [l, r)
    */
  def query(l: Int, r: Int)(sub: (Int, Int) => Int): Int = {
    assert(r > l)
    sub(sum(r), sum(l))
  }

  def lowerBound(W: Int)(sub: (Int, Int) => Int, lt: (Int, Int) => Boolean): Int = {
    var k = N
    var x = 0
    var w = W
    while(k > 0) {
      if (x + k <= N && lt(bit(x + k), w)) {
        w = sub(w, bit(x + k))
        x += k
      }
      k /= 2
    }
    x
  }
}
}

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N = ni()
    val C = Array.ofDim[Coord](N)
    REP(N) { i =>
      val x, y = ni()
      C(i) = Coord(x, y)
    }

    // y降順
    sort(C, new Comparator[Coord] {
      override def compare(o1: Coord, o2: Coord): Int = {
        -Integer.compare(o1.y, o2.y)
      }
    })

    var ans = 0L
    val xs = mutable.Set[Int]()
    REP(N) { i =>
      if (i > 0 && C(i - 1).y != C(i).y) {
        val len = xs.size.toLong
        ans += len * (len + 1) / 2
      }
      xs += C(i).x
    }
    val len = xs.size.toLong
    ans += len * (len + 1) / 2

    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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N = ni()
    val C = Array.ofDim[Coord](N)
    REP(N) { i =>
      val x, y = ni()
      C(i) = Coord(x, y)
    }

    // y降順
    sort(C, new Comparator[Coord] {
      override def compare(o1: Coord, o2: Coord): Int = {
        -Integer.compare(o1.y, o2.y)
      }
    })

    var ans = 0L
    val pre = mutable.Set[Int]()
    val xs = mutable.Set[Int]()
    REP(N) { i =>
      if (i > 0 && C(i - 1).y != C(i).y) {
        val len2 = pre.size.toLong
        pre ++= xs
        val len1 = pre.size.toLong
        debug(s"len1:$len1 len2:$len2")
        ans += len1 * (len1 + 1) / 2 - len2 * (len2 + 1) / 2
        pre ++= xs
        xs.clear()
      }
      pre -= C(i).x
      xs += C(i).x
    }
    val len2 = pre.size.toLong
    pre ++= xs
    val len1 = pre.size.toLong
    debug(s"len1:$len1 len2:$len2")
    ans += len1 * (len1 + 1) / 2 - len2 * (len2 + 1) / 2

    out.println(ans)
  }
}


Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i < c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.

The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i < c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i < c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.

Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).

NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$:   Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &= 16. \end{align*} $$$$$$  Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &= 21. \end{align*} $$$$$$  Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int, val c: Long)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        val k = readInt()
        val x = new Array[Long](n+1)
        for (i <- 1 to n) {
            x(i) = readInt()
        }
        val s = new Array[Vector[Int]](n+1)
        val e = new Array[Vector[Int]](n+1)
        for (i <- 1 to n) {
            s(i) = Vector[Int]()
            e(i) = Vector[Int]()
        }
        val l = new Array[pair](k+1)
        val d = new Array[Long](k+1)
        var i1 = 0
        var i2 = 0
        var i3 = 0
        var i4 = 0
        var i5 = 0
        for (i <- 1 to k) {
            i1 = readInt()
            i2 = readInt()
            i3 = readInt()
            i4 = readInt()
            i5 = readInt()
            s(i1) +:= i
            e(i3) +:= i
            l(i) = pair(i2, i4, i5)
        }
        var tmp = pair(0, 0, 0)
        for (i <- e(n).indices) {
            tmp = l(e(n)(i))
            d(e(n)(i)) = (m-tmp.b).toLong * x(n) - tmp.c
        }
        val inf = (1e18 + 1).toLong
        for (j <- (1 until n).reverse) {
            var lad = Vector[pair]()
            for (i <- s(j).indices) {
                lad +:= pair(l(s(j)(i)).a, s(j)(i), 0)
            }
            for (i <- e(j).indices) {
                lad +:= pair(l(e(j)(i)).b, e(j)(i), 1)
            }
            lad = lad.sorted
            var ans = inf
            for (i <- lad.indices) {
                if (i != 0) {
                    if (ans != inf) {
                        ans += x(j) * (lad(i).a - lad(i-1).a)
                    }
                }
                if (lad(i).c == 0) {
                    ans = min(ans, d(lad(i).b))
                } else {
                    d(lad(i).b) = ans
                }
            }
            ans = inf
            for (i <- (lad.indices).reverse) {
                if (i != lad.length-1) {
                    if (ans != inf) {
                        ans += x(j) * (lad(i+1).a - lad(i).a)
                    }
                }
                if (lad(i).c == 0) {
                    ans = min(ans, d(lad(i).b))
                } else {
                    d(lad(i).b) = min(d(lad(i).b), ans)
                    if (d(lad(i).b) != inf) {
                        d(lad(i).b) -= l(lad(i).b).c
                    }
                }
            }
        }
        var ans = inf
        for (i <- s(1).indices) {
            if (d(s(1)(i)) != inf) {
                ans = min(ans, d(s(1)(i)) + x(1) * (l(s(1)(i)).a - 1))
            }
        }
        if (ans == inf) {
            writer.println("NO ESCAPE")
        } else {
            writer.println(ans)
        }

        def check(kk: Long): Boolean = {
            return true
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}