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

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

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 = """
"""
}

}


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


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

}

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

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

}


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

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

}


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
}


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

}

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


import scala.io.StdIn

object Main {

  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- Range(0, t)) {
      val n = StdIn.readInt()
      println(n / 2)
    }
  }
}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  import scala.io.Codec

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

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

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

    n.times {
      val m = in.nextInt()

      println(m / 2)

    }
  }

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

  /**
    * Util methods
    */

  def readMatrix(rows: Int, cols: Int) = {
    (1.to(rows))
      .map(_ => {
        (1.to(cols)
          .map(_ => {
            in.nextInt()
          }))
      })
  }

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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

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

    for (_ <- 1 to nextInt) {
      val n = nextInt

      out.println(n/2)
      out.flush()
    }

  }

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


import scala.collection._

object C extends App {

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

  val LIM = 316

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

  val Array(n, m, q) = readInts(3)
  val as = readLongs(n)
  val ss = Array.fill(m){
    val t = tokenizeLine
    val sn = t.nextToken.toInt
    Array.fill(sn)(t.nextToken.toInt - 1).sorted
  }

  val larges = (0 until m).filter(ss(_).size > LIM)
  val sset = Array.tabulate(larges.size)(i => new mutable.BitSet(ss(larges(i)).size))
  for (i <- larges.indices) sset(i) ++= ss(larges(i))

  val isLarge = new mutable.BitSet(m)
  isLarge ++= larges

  val largeIncr = Array.fill(m)(0L)
  val largeSum = Array.fill(m)(0L)
  for (i <- larges) largeSum(i) = ss(i).map(as(_)).sum

  val overlaps = Array.tabulate(m)(i => {
    Array.tabulate(larges.size)(j => {
      var k, cnt = 0
      while (k < ss(i).size) {
        if (sset(j)(ss(i)(k))) cnt += 1
        k += 1
      }
      cnt
    }
  )})

  for (i <- 0 until q) {
    val t = tokenizeLine
    if (t.nextToken == "?") {
      val k = t.nextToken.toInt - 1
      var ans = 0L
      if (isLarge(k)) ans += largeSum(k)
      else {
        var j = 0
        while (j < ss(k).size) {
          ans += as(ss(k)(j))
          j += 1
        }
      }
      var j = 0
      while (j < larges.size) {
        ans += largeIncr(larges(j)) * overlaps(k)(j)
        j += 1
      }
	  println(ans)
    } else { // +
      val k = t.nextToken.toInt - 1
      val x = t.nextToken.toInt
      if (isLarge(k)) {
        largeIncr(k) += x
      } else {
        var j = 0
        while (j < ss(k).size) {
          as(ss(k)(j)) += x
          j += 1
        }
        j = 0
   		while (j < larges.size) {
   		  largeSum(larges(j)) += x * overlaps(k)(j)
   		  j += 1
   		}
      }
    }
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

  val LIM = 316

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

  val Array(n, m, q) = readInts(3)
  val as = readLongs(n)
  val ss = Array.fill(m){
    val t = tokenizeLine
    val sn = t.nextToken.toInt
    Array.fill(sn)(t.nextToken.toInt - 1).sorted
  }

  val larges = (0 until m).filter(ss(_).size > LIM)
  val sset = Array.tabulate(larges.size)(i => new mutable.BitSet(ss(larges(i)).size))
  for (i <- larges.indices) sset(i) ++= ss(larges(i))

  val isLarge = new mutable.BitSet(m)
  isLarge ++= larges

  val largeIncr = Array.fill(m)(0L)
  val largeSum = Array.fill(m)(0L)
  for (i <- larges) largeSum(i) = ss(i).map(as(_)).sum

  val overlaps = Array.tabulate(m)(i =>
    Array.tabulate(larges.size)(j => ss(i).count(sset(j)(_))
  ))

  for (i <- 0 until q) {
    val t = tokenizeLine
    if (t.nextToken == "?") {
      val k = t.nextToken.toInt - 1
      var ans = 0L
      if (isLarge(k)) ans += largeSum(k)
      else {
        var j = 0
        while (j < ss(k).size) {
          ans += as(ss(k)(j))
          j += 1
        }
      }
      var j = 0
      while (j < larges.size) {
        ans += largeIncr(larges(j)) * overlaps(k)(j)
        j += 1
      }
	  println(ans)
    } else { // +
      val k = t.nextToken.toInt - 1
      val x = t.nextToken.toInt
      if (isLarge(k)) {
        largeIncr(k) += x
      } else {
        var j = 0
        while (j < ss(k).size) {
          as(ss(k)(j)) += x
          j += 1
        }
        j = 0
   		while (j < larges.size) {
   		  largeSum(larges(j)) += x * overlaps(k)(j)
   		  j += 1
   		}
      }
    }
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

  val Array(n, m, q) = readInts(3)
  val as = readLongs(n)
  val ss = Array.fill(m){
    val t = tokenizeLine
    val sn = t.nextToken.toInt
    Array.fill(sn)(t.nextToken.toInt - 1).sorted
  }

  val larges = (0 until m).filter(ss(_).size > 100)

  val isLarge = new mutable.BitSet(m)
  isLarge ++= larges

  val largeIncr = Array.fill(m)(0L)
  val largeSum = Array.fill(m)(0L)
  for (i <- larges) largeSum(i) = ss(i).sum

  val overlaps = for (i <- larges)
    yield for (j <- 0 until m) yield {
      var a, b, cnt = 0
      while (a < ss(i).size && b < ss(j).size) {
        val ssa = ss(i)(a)
        val ssb = ss(j)(b)
        if (ssa == ssb) {
          cnt += 1
          a += 1
          b += 1
        } else if (ssa < ssb) a += 1
        else b += 1
      }
      cnt
    }

  for (i <- 0 until q) {
    val t = tokenizeLine
    if (t.nextToken == "?") {
      val k = t.nextToken.toInt - 1
      var ans = 0L
      if (isLarge(k)) ans += largeSum(k)
      else for (j <- ss(k)) ans += as(j)
      for (j <- larges) ans += largeIncr(j) * overlaps(k)(j)
	  println(ans)
    } else { // +
      val k = t.nextToken.toInt - 1
      val x = t.nextToken.toInt
      if (isLarge(k)) {
        largeIncr(k) += x
      } else {
        for (j <- ss(k)) as(j) += x
   		for (j <- larges) largeSum(j) += x * overlaps(k)(j)
      }
    }
  }
}

import scala.collection._

object C extends App {

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

  val Array(n, m, q) = readInts(3)
  val as = readInts(n)
  val ss = Array.fill(m){
    val t = tokenizeLine
    val sn = t.nextToken.toInt
    Array.fill(sn)(t.nextToken.toInt - 1)
  }

  val larges = (0 until m).filter(ss(_).size > 100)

  val isLarge = new mutable.BitSet(m)
  isLarge ++= larges

  val largeIncr = Array.fill(m)(0)
  val largeSum = Array.fill(m)(0)
  for (i <- larges) largeSum(i) = ss(i).sum

  val overlaps = for (i <- larges)
    yield for (j <- 0 until m; intersect = ss(i).intersect(ss(j))) yield intersect.size

  for (i <- 0 until q) {
    val t = tokenizeLine
    if (t.nextToken == "?") {
      val k = t.nextToken.toInt - 1
      var ans = 0L
      if (isLarge(k)) {
        ans += largeSum(k)
        for (j <- larges) ans += (largeIncr(j) * overlaps(k)(j))
      } else {
        for (j <- ss(k)) ans += as(j)
        for (j <- larges) ans += (largeIncr(j) * overlaps(k)(j))
      }
	  println(ans)
    } else { // +
      val k = t.nextToken.toInt - 1
      val x = t.nextToken.toInt
      if (isLarge(k)) {
        largeIncr(k) += x
      } else {
        for (j <- ss(k)) as(j) += x
   		for (j <- larges) largeSum(j) += (x * overlaps(k)(j))
      }
    }
  }
}


/**
  * @see http://codeforces.com/contest/911/problem/A
  */

object ANearestMinimums extends App {
  def distance(i: Int = 0, j: Int = 0, m: Int = Int.MaxValue, d: Int = Int.MaxValue): Int =
    if (i == n) d
    else {
      val h = a(i)
      if (h < m) distance(i + 1, i, h, Int.MaxValue)
      else if (h == m) distance(i + 1, i, m, d min (i - j))
      else distance(i + 1, j, m, d)
    }

  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  println(distance())
}

object A {
  import scala.io.StdIn
  import scala.collection.mutable

  def main(args: Array[String]): Unit = {
    StdIn.readLine() // skip the 1st line
    val lastPos = mutable.HashMap[Int, (Int, Int)]()
    for ((x, cur) <- StdIn.readLine().split(' ').toStream.map(_.toInt).zipWithIndex) {
      lastPos(x) = (cur, lastPos.get(x) match {
        case Some((prv, min)) => Math.min(cur-prv, min)
        case _ => Int.MaxValue
      })

    }
    println(lastPos(lastPos.keys.min)._2)
  }
}

import java.io.FileReader
import java.util
import java.util.Comparator

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

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val nums = readIntLine()
    val min = nums.min
    val idxs = nums.zipWithIndex.filter(_._1 == min).map(_._2)
    val diffs = idxs.sliding(2).map { case Array(a, b) => b - a}
    println(diffs.min)
  }

  def main(args: Array[String]): Unit = {
    val noCases = 1
    for (i <- 0 until noCases) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    StdIn.readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    StdIn.readLine().split(" ").map(BigInt.apply)
  }
}

object CF911A extends App {

  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val i = Array.fill(n)(sc.nextInt).iterator

  var min = Int.MaxValue
  var mindist = Int.MaxValue
  var dist = 1
  while (i.hasNext) {
    i.next match {
      case c if c < min => min = c; mindist = Int.MaxValue; dist = 1
      case c if c == min => mindist = Math.min(mindist, dist); dist = 1
      case _ => dist += 1
    }
  }
  println(mindist)
}

object A {
  import scala.io.StdIn
  import scala.collection.mutable

  def main(args: Array[String]): Unit = {
    StdIn.readLine() // skip the 1st line
    val lastPos = mutable.HashMap[Int, Int]()
    var min = Int.MaxValue
    for ((x, cur) <- StdIn.readLine().split(' ').toStream.map(_.toInt).zipWithIndex) {
      lastPos.get(x) match {
        case Some(prv) => min = Math.min(cur - prv, min)
        case _ =>
      }
      lastPos(x) = cur
    }
    println(min)
  }
}

object CF911A extends App {

  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val i = Array.fill(n)(sc.nextInt).iterator

  var min = Int.MaxValue
  var mindist = Int.MaxValue
  var dist = 1
  while (i.hasNext) {
    i.next match {
      case c if c < min => min = c; mindist = Int.MaxValue
      case c if c == min => mindist = Math.min(mindist, dist); dist = 1
      case _ => dist += 1
    }
  }
  println(mindist)
}

object CF911A extends App {

  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val i = Array.fill(n)(sc.nextInt).iterator

  var min = Int.MaxValue
  var mindist = Int.MaxValue
  var dist = 1
  while (i.hasNext) {
    i.next match {
      case c if c < min => min = c; mindist = 0
      case c if c == min => mindist = Math.min(mindist, dist); dist = 1
      case _ => dist += 1
    }
  }
  println(mindist)
}

object CF911A extends App {

  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val i = Array.fill(n)(sc.nextInt).iterator

  var min = Int.MaxValue
  var mindist = Int.MaxValue
  var dist = 1
  while (i.hasNext) {
    i.next match {
      case c if c < min => min = c; mindist = Int.MaxValue; dist = 1
      case c if c == min => mindist = Math.min(mindist, dist); dist = 1
      case _ => dist += 1
    }
    println("%d %d %d".format(min,mindist,dist))
  }
  println(mindist)
}

object CF911A extends App {

  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val i = Array.fill(n)(sc.nextInt).iterator

  var min = Int.MaxValue
  var mindist = 0
  var dist = 1
  while (i.hasNext) {
    i.next match {
      case c if c < min => min = c; mindist = 0
      case c if c == min => mindist = Math.min(mindist, dist); dist = 1
      case _ => dist += 1
    }
  }
  println(mindist)
}


import scala.collection.mutable.ArrayBuffer

object Solve extends App with fastIO{
  val n:Long = nextLong
  val aa = (for(i<-0L.until(n)) yield nextLong).toBuffer
  val a = aa.sortWith(_>_)
  var b = new ArrayBuffer[(Long,Long)]()
  var i = 0
  while(i<n-1){
    if(a(i)==a(i+1)) {
      b += ((a(i),a(i+1)))
      i+=1
    } else if(a(i)-1==a(i+1)) {
      b += ((a(i)-1,a(i+1)))
      i+=1
    }
    i+=1
  }
  i = 0
  var s = 0L
  while(i+1<b.length){
    s+=b(i)._1*b(i+1)._1
    i+=2
  }
  println(s)
  flush
}

trait fastIO {
  import java.io._
  val in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(new OutputStreamWriter(System.out))
  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }
  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }
  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }
  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

import scala.collection.mutable.ArrayBuffer

object Solve extends App{
  val n:Long = fastIO.nextLong
  val aa = (for(i<-0L.until(n)) yield fastIO.nextLong).toBuffer
  val a = aa.sortWith(_>_)
  var b = new ArrayBuffer[(Long,Long)]()
  var i = 0
  while(i<n-1){
    if(a(i)==a(i+1)) {
      b += ((a(i),a(i+1)))
      i+=1
    } else if(a(i)-1==a(i+1)) {
      b += ((a(i)-1,a(i+1)))
      i+=1
    }
    i+=1
  }
  i = 0
  var s = 0L
  while(i+1<b.length){
    s+=b(i)._1*b(i+1)._1
    i+=2
  }
  fastIO.println(s)
  fastIO.flush
}
object fastIO {
  import java.io._
  val in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(new OutputStreamWriter(System.out))
  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }
  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }
  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }
  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

import java.io._

import scala.collection.mutable.ArrayBuffer

object C {

  def main(args: Array[String]) {
    new C().run()
  }
}

class C {

  var in: StreamTokenizer = _

  var out: PrintWriter = _

  def nextInt(): Int = {
    in.nextToken()
    in.nval.toInt
  }
  def nextLong():Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble(): Double = {
    in.nextToken()
    in.nval
  }

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

  def run() {
    in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)))
    out = new PrintWriter(new OutputStreamWriter(System.out))
    solve()
    out.flush()
  }

  def solve() {
    val n:Long = nextLong()
    val aa = (for(i<-0L.until(n)) yield nextLong()).toBuffer
    val a = aa.sortWith(_>_)
    var b = new ArrayBuffer[(Long,Long)]()
    var i = 0
    while(i<n-1){
      if(a(i)==a(i+1)) {
        b += ((a(i),a(i+1)))
        i+=1
      } else if(a(i)-1==a(i+1)) {
        b += ((a(i)-1,a(i+1)))
        i+=1
      }
      i+=1
    }
    i = 0
    var s = 0L
    while(i+1<b.length){
      s+=b(i)._1*b(i+1)._1
      i+=2
    }
    out.println(s)

  }
}

object C{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val l=Array.fill(n)(0L)
    for(i<-0 until n){l(i)=nextLong}
    scala.util.Sorting.quickSort(l)
    var lastPair=0L
    var sum=0L
    var i=n-1
    while(i>0){
      if(l(i)==l(i-1)||l(i)-1==l(i-1)){

        if(lastPair==0){
          lastPair=l(i-1)

        }else{
          sum+=lastPair*l(i-1)
          lastPair=0
        }

        i-=2
      }
      else{
        i-=1
      }
    }
    out.println(sum)

    //code ends here
    out.flush
    out.close
  }
}

object CodeForces extends App {
  val n = readLine toInt
  val sticks = readLine split (' ') map (s => s.toLong)
  scala.util.Sorting.quickSort(sticks)

  val result = sticks.foldRight((0L, -1L, -1L))((stick, state) => state match {
    case (area, -1, oneside) => (area, stick, oneside)
    case (area, last, -1) => if (last - stick <= 1) (area, -1, stick) else (area, stick, -1)
    case (area, last, oneside) => {
      if (last - stick <= 1) (area + (stick * oneside), -1, -1) else (area, stick, oneside)
    }
  })

  println(result._1)
}

object Main extends App {
   println(readLine().split(" ").map(_.toInt).sum)
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt).sorted.reverse
  if (k > n)
    println(-1)
  else {
    if (k == n)
      println("0 0")
    else if (data(k - 1) == data(k))
      println(-1)
    else
      println(s"${data(k - 1)} ${data(k - 1)}")
  }

}

object Contest extends App{
  val Array(n, k) = readLine().split(" ").map(_.toInt)
  val as = readLine().split(" ").map(_.toInt)
  util.Sorting.stableSort(as)
  if (k > n) println("-1")
  else if (k == 0) println((as(n-1) + 1) + " " + (as(n-1) + 1))
  else println(as(n-k) + " " + as(n-k))
}

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

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

  val N, K = sc.nextInt
  val a = List.fill(N)(sc.nextInt).sorted.reverse
  val answer: String =
    if (K > N) "-1"
    else {
      val x = a(K - 1)
      x + " " + x
    }

  out.println(answer)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val nk = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(1)
    val a = readLine().split(" ").map(_.toInt)
    if (k > n) println("-1")
    else if (k == n) println("0 0")
    else {
      val (head, tail) = a.sorted.reverse.splitAt(k)
      if (head.last == tail.head) println("-1")
      else println(head.last + " " + head.last)
    }
  }
}

import scala.Math.pow;

object App {
    def readInts:Array[Int] = (readLine split " ") map (_.toInt)
                                                  //> readInts: => Array[Int]                              //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)

    def f1_io() = {
        val Array(n, k) = readInts
        val source = readInts.sorted
        val p = n - k
        if (p == 0) print(source(p) + " " + source(p))
        else if (p < 0) print(-1)
        else if (source(p) == source(p-1)) print(-1)
        else print(source(p) + " " + source(p))
    }
  def main(args: Array[String]): Unit = {
    f1_io
  }

}

object B{
  def main(args: Array[String]){

    val (n, k)={
      val sp=readLine.split(" ")
      (sp(0).toInt,sp(1).toInt)
    }

    val a=readLine.split(" ").map(_.toInt).sorted

    if(k>n){
      println("-1")
    }else{
      println(a(n-k)+" "+a(n-k))
    }
  }
}

import java.util.StringTokenizer

object _263B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt
  val a = (1 to n).map(i => next.toInt).groupBy(i => i).toArray.map(i => (i._1, i._2.size)).sortBy(i => -i._1)
  val b = a.unzip._2.scanLeft(0)(_ + _).drop(1)
  val index = b.indexWhere(_ == k)
  if (index == -1) println(-1)
  else println(a(index)._1 + " " + a(index)._1)
}

object B{
  def main(args: Array[String]){

    val (n, k)={
      val sp=readLine.split(" ")
      (sp(0).toInt,sp(1).toInt)
    }

    val a=readLine.split(" ").sorted

    if(k>n){
      println("-1")
    }else{
      println(a(n-k)+" "+a(n-k))
    }
  }
}


object Main extends App {

  def lexOrder(first: List[Long], second: List[Long]): Int = {
    (first, second) match {
      case (Nil, Nil) => 0
      case (Nil, _) => -1
      case (_, Nil) => 1
      case (h1 :: tail1, h2 :: tail2) =>
        if(h1 == h2) lexOrder(tail1, tail2)
        else if (h1 < h2) -1
        else 1
    }
  }

  val n = readLine.toLong
  val start = (List[Long](), List[Long](), 0L, 0L)
  val (first, second, lastFirst, lastSecond) = (1L to n).foldLeft(start)({
    case ((f, s, lf, ls), index) =>
       val next = readLine.toLong
       if(next > 0) {
         (next :: f, s, index+1, ls)
       } else {
         (f, Math.abs(next) :: s, lf, index+1)
       }
  })

  val fs = first.sum
  val ss = second.sum

  if(fs < ss) {
    println("second")
  } else if (fs > ss) {
    println("first")
  } else {
     val fr = first.reverse
     val sr = second.reverse
     val lex = lexOrder(fr, sr)
     if(lex > 0) {
       println("first")
     } else if (lex < 0) {
       println("second")
     } else {
       if(lastFirst > lastSecond) println("first") else println("second")
     }
  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).map(_ => in.next().toLong)
  val first = data.filter(_ > 0)
  val second = data.filter(_ < 0).map(-_)
  val sum1 = first.sum
  val sum2 = second.sum
  if (sum1 != sum2)
    if (sum1 > sum2)
      println("first")
    else
      println("second")
  else if (first.size != second.size || first.zip(second).exists(t => t._1 != t._2)) {
    val t = first.zip(second).find(t => t._1 != t._2)
    if (t.isEmpty)
      if (first.size > second.size)
        println("first")
      else
        println("second")
    else {
      if (t.get._1 > t.get._2)
        println("first")
      else
        println("second")
    }
  }
  else if (data.last > 0)
    println("first")
  else
    println("second")
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object B_VasyaAndWrestling {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()

    val input = for (i <- 1 to n) yield {
      scanner.nextLong()
    }

    val firstPoints = input.filter(_ > 0)
    val secondPoints = input.filter(_ < 0).map(-_)

    if (firstPoints.sum != secondPoints.sum) {
      out.println(if (firstPoints.sum > secondPoints.sum) "first" else "second")
    } else {
      val firstNotNull = firstPoints.zip(secondPoints).map(x => x._1 - x._2).find(_ != 0)
      firstNotNull match {
        case Some(x) =>
          out.println(if (x > 0) "first" else "second")
        case None =>
          out.println(if (input.last > 0) "first" else "second")
      }
    }
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).map(_ => in.next().toLong)
  val first = data.filter(_ > 0)
  val second = data.filter(_ < 0).map(-_)
  val sum1 = first.sum
  val sum2 = second.sum
  if (sum1 != sum2)
    if (sum1 > sum2)
      println("first")
    else
      println("second")
  else if (first.head != second.head)
    if (first.head > second.head)
      println("first")
    else
      println("second")
  else if (data.last > 0)
    println("first")
  else
    println("second")
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).map(_ => in.next().toInt)
  val first = data.filter(_ > 0)
  val second = data.filter(_ < 0).map(-_)
  val sum1 = first.sum
  val sum2 = second.sum
  val str = first.mkString
  val str2 = second.mkString
  if (sum1 != sum2)
    if (sum1 > sum2)
      println("first")
    else
      println("second")
  else if (str != str)
    if (str > str2)
      println("first")
    else
      println("second")
  else if (data.last > 0)
    println("first")
  else
    println("second")
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).map(_ => in.next().toLong)
  val first = data.filter(_ > 0)
  val second = data.filter(_ < 0).map(-_)
  val sum1 = first.sum
  val sum2 = second.sum
  val str = first.mkString
  val str2 = second.mkString
  if (sum1 != sum2)
    if (sum1 > sum2)
      println("first")
    else
      println("second")
  else if (str != str2)
    if (str > str2)
      println("first")
    else
      println("second")
  else if (data.last > 0)
    println("first")
  else
    println("second")
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).map(_ => in.next().toInt)
  val first = data.filter(_ > 0)
  val second = data.filter(_ < 0)
  val sum1 = first.sum
  val sum2 = second.sum
  val str = first.mkString
  val str2 = second.map(-_).mkString
  if (sum1 != sum2)
    if (sum1 > sum2)
      println("first")
    else
      println("second")
  else if (str != str)
    if (str > str2)
      println("first")
    else
      println("second")
  else if (data.last > 0)
    println("first")
  else
    println("second")
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).map(_ => in.next().toInt)
  val first = data.filter(_ > 0)
  val second = data.filter(_ < 0).map(-_)
  val sum1 = first.sum
  val sum2 = second.sum
  val str = first.mkString
  val str2 = second.mkString
  if (sum1 != sum2)
    if (sum1 > sum2)
      println("first")
    else
      println("second")
  else if (str != str2)
    if (str > str2)
      println("first")
    else
      println("second")
  else if (data.last > 0)
    println("first")
  else
    println("second")
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object B_VasyaAndWrestling {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()

    val input = for (i <- 1 to n) yield {
      scanner.nextInt()
    }

    val firstPoints = input.filter(_ > 0)
    val secondPoints = input.filter(_ < 0).map(-_)

    if (firstPoints.sum != secondPoints.sum) {
      out.println(if (firstPoints.sum > secondPoints.sum) "first" else "second")
    } else {
      val firstNotNull = firstPoints.zip(secondPoints).map(x => x._1 - x._2).find(_ != 0)
      firstNotNull match {
        case Some(x) =>
          out.println(if (x > 0) "first" else "second")
        case None =>
          out.println(if (input.last > 0) "first" else "second")
      }
    }
  }
}

object Main extends App {

  def lexOrder(first: List[Int], second: List[Int]): Int = {
    (first, second) match {
      case (Nil, Nil) => 0
      case (Nil, _) => -1
      case (_, Nil) => 1
      case (h1 :: tail1, h2 :: tail2) =>
        if(h1 == h2) lexOrder(tail1, tail2)
        else if (h1 < h2) -1
        else 1
    }
  }

  val n = readLine.toInt
  val start = (List[Int](), List[Int](), 0, 0)
  val (first, second, lastFirst, lastSecond) = (1 to n).foldLeft(start)({
    case ((f, s, lf, ls), index) =>
       val next = readLine.toInt
       if(next > 0) {
         (next :: f, s, index+1, ls)
       } else {
         (f, Math.abs(next) :: s, lf, index+1)
       }
  })

  val fs = first.sum
  val ss = second.sum

  if(fs < ss) {
    println("second")
  } else if (fs > ss) {
    println("first")
  } else {
     val fr = first.reverse
     val sr = second.reverse
     val lex = lexOrder(fr, sr)
     if(lex > 0) {
       println("first")
     } else if (lex < 0) {
       println("second")
     } else {
       if(lastFirst > lastSecond) println("first") else println("second")
     }
  }

}

object Main extends App {

  def lexOrder(first: List[Int], second: List[Int]): Int = {
    20
  }

  val n = readLine.toInt
  val start = (List[Int](), List[Int](), 0, 0)
  val (first, second, lastFirst, lastSecond) = (1 to n).foldLeft(start)({
    case ((f, s, lf, ls), index) =>
       val next = readLine.toInt
       if(next > 0) {
         (next :: f, s, index+1, ls)
       } else {
         (f, next :: s, lf, index+1)
       }
  })

  val fs = first.sum
  val ss = second.sum
  if(fs < ss) {
    println("second")
  } else if (fs > ss) {
    println("first")
  } else {
     val fr = first.reverse
     val sr = second.reverse
     val lex = lexOrder(fr, sr)
     if(lex > 0) {
       println("first")
     } else if (lex < 0) {
       println("second")
     } else {
       if(lastFirst > lastSecond) println("first") else println("second")
     }
  }

}