import annotation.tailrec

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    var r = k
    for (x <- c) {
      r = gcd(r, k / gcd(k, x))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  @tailrec def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.specialized

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.specialized

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    var r = k
    for (x <- c) {
      r = gcd(r, k / gcd(k, x))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd[@specialized T](x: T, y: T)(implicit integral: Integral[T]): T = {
    import integral._
    if (y == 0)
      x
    else
      gcd(y, x % y)
  }

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

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

object D {
  def main(args: Array[String]) = {
    val sc = new MyScanner()
    val n = sc.nextInt()
    val k = sc.nextInt()
    var r = k
    for (_i <- 1 to n) {
      val x = sc.nextInt()
      r = gcd(r, k / gcd(k, x))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)

  class MyScanner {
    val br = new BufferedReader(new InputStreamReader(System.in))

    var st = new StringTokenizer(br.readLine())

    def next(): String = {
      while (!st.hasMoreElements()) {
        try {
          st = new StringTokenizer(br.readLine())
        } catch {
          case e: IOException => e.printStackTrace()
        }
      }
      st.nextToken()
    }

    def nextInt() = next().toInt
  }
}

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    var r = k
    for (x <- c) {
      r = gcd(r, k / gcd(k, x))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.specialized

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd[@specialized T](x: T, y: T)(implicit integral: Integral[T]): T =
    if (y == 0)
      x
    else
      gcd(y, integral.rem(x, y))

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import annotation.tailrec

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    if (c.map(k / gcd(k, _)).foldLeft(k)(gcd _) == 1)
      println("Yes")
    else
      println("No")
  }

  @tailrec def gcd(x: Int, y: Int): Int =
    if (y == 0)
      x
    else
      gcd(y, x % y)

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.specialized

object D {
  def main(args: Array[String]) = {
    val Seq(n, k): Seq[Int] = readInts()
    val c = readInts()
    var r = k
    for (x <- c) {
      r = gcd(r, k / gcd(k, r))
    }
    if (r == 1)
      println("Yes")
    else
      println("No")
  }

  def gcd[@specialized T](x: T, y: T)(implicit integral: Integral[T]): T = {
    import integral._
    if (y == 0)
      x
    else
      gcd(y, x % y)
  }

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}


import scala.io._
import java.util.StringTokenizer
import java.io.BufferedReader

object Main {

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

		if (n % 2 == 0)
			println(-1)
		else
		{
			val a = (0 until n)
			val b = for (i <- 0 until n) yield ((3 + i) % n)
			val c = a zip b map {case (a, b) => ((a+b) % n)}

			if (c.sorted != (0 until n))
				println("-1")
			else
			{
				println(a mkString(" "))
				println(b mkString(" "))
				println(c mkString(" "))
			}
		}
	}

	class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
	{
		private var tokenizer = new StringTokenizer("")
		def readLine() = in.readLine()
		def nextToken(): String = {
			while (!tokenizer.hasMoreTokens) {
				val line = readLine
				if (line == null) return null
				tokenizer = new StringTokenizer(line, splitOn)
			}
			tokenizer.nextToken
		}
		def next[A](f: String => A) = f(nextToken)
	}

	implicit val tokenizer = new Tokenizer(Console.in)

	def nextString()(implicit t: Tokenizer) = t.nextToken()
	def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
	def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
	def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
	def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
	def nextSeq[A](f : () => A, count: Int = nextInt()) = for (i <- 0 until count) yield f()
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()

    if (n % 2 == 0)
      println("-1")
    else {
      val a = 0 until n
      val b = a.map(k => (k + 1) % n)
      val c = a.zip(b).map { case (i, j) => (i + j) % n }

      println(a.mkString(" "))
      println(b.mkString(" "))
      println(c.mkString(" "))
    }
  }
}

import scala.io._
import java.util.StringTokenizer
import java.io.BufferedReader

object Main {

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

		//if (n % 2 == 0)
//			println(-1)
		//else
		{
			for (i <- 0 until n) print(i + " ")
			println

			for (i <- 0 until n) print((3 * i % n) + " ")
			println

			for (i <- 0 until n) print(((4 * i) % n) + " ")
			println
		}
	}

	class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
	{
		private var tokenizer = new StringTokenizer("")
		def readLine() = in.readLine()
		def nextToken(): String = {
			while (!tokenizer.hasMoreTokens) {
				val line = readLine
				if (line == null) return null
				tokenizer = new StringTokenizer(line, splitOn)
			}
			tokenizer.nextToken
		}
		def next[A](f: String => A) = f(nextToken)
	}

	implicit val tokenizer = new Tokenizer(Console.in)

	def nextString()(implicit t: Tokenizer) = t.nextToken()
	def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
	def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
	def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
	def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
	def nextSeq[A](f : () => A, count: Int = nextInt()) = for (i <- 0 until count) yield f()
}

import scala.io._
import java.util.StringTokenizer
import java.io.BufferedReader

object Main {

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

		if (n % 2 == 0)
			println(-1)
		else
		{
			for (i <- 0 until n) print(i + " ")
			println

			for (i <- 0 until n) print((3 * i % n) + " ")
			println

			for (i <- 0 until n) print(((4 * i) % n) + " ")
			println
		}
	}

	class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
	{
		private var tokenizer = new StringTokenizer("")
		def readLine() = in.readLine()
		def nextToken(): String = {
			while (!tokenizer.hasMoreTokens) {
				val line = readLine
				if (line == null) return null
				tokenizer = new StringTokenizer(line, splitOn)
			}
			tokenizer.nextToken
		}
		def next[A](f: String => A) = f(nextToken)
	}

	implicit val tokenizer = new Tokenizer(Console.in)

	def nextString()(implicit t: Tokenizer) = t.nextToken()
	def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
	def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
	def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
	def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
	def nextSeq[A](f : () => A, count: Int = nextInt()) = for (i <- 0 until count) yield f()
}


object Main {
  def main(args: Array[String]) {
    val op = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt).sorted
    val m = op(1)
    println(-a.filter(_ < 0).take(m).sum)
  }
}

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.util.StringTokenizer;
import java.util.Arrays

object Solver {

    var st : StringTokenizer = null;
    var in : BufferedReader = null;
    var out : PrintWriter = null;

    def main(args: Array[String]){
        open();
        solve();
        close();
    }

    def open() {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
    }

    def nextToken() : String = {
        while (st == null || !st.hasMoreTokens()) {
            val line : String = in.readLine();
            if(line==null) return null;
            st = new StringTokenizer(line);
        }
        st.nextToken();
    }

    def nextInt() : Int = {
        nextToken().toInt;
    }

    def nextLong() : Long = {
        nextToken().toLong;
    }

    def nextDouble() : Double = {
        nextToken().toDouble;
    }

    def solve(){
        val n:Int = nextInt;
        val m:Int = nextInt;
        val ar:Array[Int] = new Array[Int](n);

        for(i <- 0 to n-1){
            ar(i) = nextInt;
        }

        Arrays.sort(ar);

        var sum : Int = 0;
        var i : Int = 0;
        while (i<m && ar(i)<0){
            sum -= ar(i);
            i+=1;
        }
        out println sum;
    }

    def close() {
        out.flush();
        out.close();
    }

}

object P34B extends App {
  val Array(n,m) = readLine.split(" ").map(_.toInt)
  val prices = readLine.split(" ").map(_.toInt).sorted
  print(prices.take(m).takeWhile(_<0).sum * -1)
}

object P34B extends App {
  val in = (readLine + " " + readLine).split(" ").map(_.toInt)
  print(in.slice(2,in.size).sorted.take(in(1)).takeWhile(_<0).sum * -1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val res = in.next().split(" ").map(_.toInt).filter(_ < 0).sorted.take(m).sum
  println(-res)
}

object B34 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    println(a.take(m).foldLeft(0){case (sum, i) => if(i < 0) sum - i else sum})
  }

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

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

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

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

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

}

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

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

  def solve(): Int = {
    val N, M = sc.nextInt
    List.fill(N)(sc.nextInt).sorted.takeWhile(_ < 0).take(M).sum.abs
  }

  out.println(solve)
  out.close
}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, m) = readLine.split(" ").map(_.toInt);
    var a = readLine.split(" ").toList.map(_.toInt).sorted;
    if (a(0) > 0) {
      println(0);
      return;
    }
    var result = 0;
    for (i <- 0 until n if a(i) < 0 && i < m) {
      result -= a(i);
    }
    println(result);
  }
}

  object Sales extends App {
  	val lines = io.Source.stdin.getLines.toList
  	val m = {
  		val tokens = lines.head.split(" ")
  		tokens(1).toInt
  	}

  	println(-1 * (lines.last.split(" ").toList.map(_.toInt).sorted.filter(_ <= 0).take(m).sum))
  }

object P34B extends App {
  val in = (readLine + " " + readLine).split(" ").map(_.toInt)
  print(in.slice(2,in.size-1).sorted.take(in(1)).takeWhile(_<0).sum * -1)
}

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

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

  def solve(): Int = {
    val N, M = sc.nextInt
    List.fill(N)(sc.nextInt).sorted.takeWhile(_ < 0).take(M).sum
  }

  out.println(solve)
  out.close
}

  object Sales extends App {
  	val lines = io.Source.stdin.getLines.toList
  	val m = {
  		val tokens = lines.head.split(" ")
  		tokens(1).toInt
  	}

  	println(-1 * (lines.last.split(" ").toList.map(_.toInt).sorted.take(m).sum))
  }


object Main extends App{
                    // extends App {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val cases = in.nextInt()
    val sb = new mutable.StringBuilder()
    (1 to cases).foreach{ _ =>
      val n = in.nextInt()
      val numOnes = n/2-1
      val first = if(n%2==1) '7' else '1'
      sb.append(first)
      (1 to numOnes).foreach(_ => sb.append('1'))
      sb.append(System.lineSeparator())

    }
    out.println(sb.toString())
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

import scala.io.StdIn._

object A extends App {
  /*
  0 - 6 x
  1 - 2
  2 - 5 x
  3 - 5 x
  4 - 4 x
  5 - 5 x
  6 - 6 x
  7 - 3
  8 - x
  9 - x

   */
  val t = readInt()
  1 to t foreach { _ =>
    val n = readInt()
    var sevens = n / 3
    var ones = (n % 3)

    if (ones % 2 == 0) {
      ones = ones / 2
    } else {
      ones = ones / 2 + 2
      sevens -= 1
    }

    println(("7" * sevens) + ("1" * ones))
  }
}


import scala.io.StdIn.readInt
object _1633A{
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0){
      t-=1
      var n = readInt();
      if(n % 7 == 0)println(n)
      else {
        n = (n / 10) * 10
        loop10(n)
        }
      }
    }
  def loop10 (n : Int): Any ={
    for (i <- n to n + 10) {
      if (i % 7 == 0) {
        println(i)
        return
      }
    }
  }
}

import scala.io.StdIn.readInt

object cf1633a {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var n = readInt()
      if(n % 7 == 0) println(n)
      else {
        var found = false
        for(i <- ((n / 10) * 10) to (n + 10)) {
          if(i % 7 == 0 && !found) {
            println(i)
            found = true
          }
        }
      }
    }
  }
}

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val number = readInt()
    val minNumber = number/7 * 7
    val maxNumber = minNumber + 7
    val answer = if (minNumber / 10 == number / 10) minNumber else maxNumber
    println(answer)
  }

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

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

object Div7 extends App {
  def changeToDiv7(i: Int): Int = {
    val rest7 = i % 7
    if (rest7 == 0) i
    else i - rest7 + (if (i % 10 - rest7 >= 0) 0 else 7)
  }

  val lines = io.Source.stdin.getLines
  val t = lines.next.toInt
  (1 to t).foreach(_ => println(changeToDiv7(lines.next.toInt)))
}

import scala.io.StdIn.readInt

object cf1633a {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var n = readInt()
      if(n % 7 == 0) println(n)
      else {
        var found = false
        for(i <- (n - 10) to (n + 10)) {
          if(i % 7 == 0 && !found) {
            println(i)
            found = true
          }
        }
      }
    }
  }
}

import scala.io.StdIn.readInt

object cf1633a {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var n = readInt()
      if(n % 7 == 0) println(n)
      else {
        var found = false
        for(i <- (n - 10) to (n + 10)) {
          if(i % 7 == 0 && !found) {
            println(i)
            found = false
          }
        }
      }
    }
  }
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val set = data.toSet
  var ir = -1
  var jr = -1
  var kr = -1
  val result = (0 until n - 1).foreach { i =>
    val f = (i + 1 until n).find(j => set.contains(data(i) + data(j)))
    if (f.nonEmpty) {
      ir = i + 1
      jr = f.get + 1
      kr = data.indices.find(x => data(x) == data(i) + data(f.get)).get + 1
    }

  }
  if (ir != -1)
    println(s"$kr $jr $ir")
  else
    println(-1)
}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var arr = readLine.split(" ").map(_.toInt);
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        for (k <- 0 until n) {
          if (i != j && i != k && j != k) {
            if (arr(i) == arr(j) + arr(k)) {
              println((i + 1) + " " + (j + 1) + " " + (k + 1));
              return;
            }
          }
        }
      }
    }
    println("-1");
  }

}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toLong).toArray.sorted
  println(sor.zip(sor.reverse).map(i => i._1 * i._2 % 10007).sum[Long] % 10007)
}

  import scala.io.StdIn
  import scala.util.Sorting

  object Solution extends App {
    val n = StdIn.readInt
    val a = (1 to n).map(_ => StdIn.readInt).toArray

    Sorting.quickSort(a)
    val middle = if (n % 2 == 0) n / 2 - 1 else n / 2

    var r: Long = 0
    for (i <- 0 to middle) {
      var v = a(i).toLong * a(n - i - 1)
      if (i != n - i - 1) {
        v *= 2
      }
      r += v
    }

    println(r % 10007)
  }

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toInt % 10007).toArray.sorted
  println((0 until n).foldLeft(0) {
    case (acc, i) => (acc + sor(i) * sor(n - i - 1)) % 10007
  })
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toInt).toArray.sorted
  println((0 until n / 2).foldLeft(if (n % 2 == 0) 0 else sor(n / 2)) {
    case (acc, i) => (i + 2 * sor(i) * sor(n - i - 1)) % 10007
  })
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toLong).toArray.sorted
  println((0 until n / 2).foldLeft(if (n % 2 == 0) 0l else sor(n / 2) * sor(n / 2) % 10007) {
    case (acc, i) => (i + 2 * sor(i) * sor(n - i - 1)) % 10007
  })
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toLong % 10007).toArray.sorted
  println(sor.zip(sor.reverse).map(i => i._1 * i._2 % 10007).sum[Long] % 10007)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toInt).toArray.sorted
  println((0 until n / 2).foldLeft(if (n % 2 == 0) 0 else sor(n / 2) * sor(n / 2)) {
    case (acc, i) => (i + 2 * sor(i) * sor(n - i - 1)) % 10007
  }  % 10007)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toInt % 10007).toArray.sorted
  println((0 until n / 2).foldLeft(if (n % 2 == 0) 0 else sor(n / 2) * sor(n / 2) % 10007) {
    case (acc, i) => (acc + 2 * sor(i) * sor(n - i - 1)) % 10007
  })
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toLong % 10007).toArray.sorted
  println((0 until n).foldLeft(0l) {
    case (acc, i) => (acc + sor(i) * sor(n - i - 1)) % 10007
  })
}

  import scala.io.StdIn
  import scala.util.Sorting

  object Solution extends App {
    val n = StdIn.readInt
    val a = (1 to n).map(_ => StdIn.readInt).toArray

    Sorting.quickSort(a)
    val middle = if (n % 2 == 0) n / 2 - 1 else n / 2

    var r: Long = 0
    for (i <- 0 to middle) {
      var v = a(i) * a(n - i - 1)
      if (i != n - i - 1) {
        v *= 2
      }
      r += v
    }

    println(r % 10007)
  }

  import scala.io.StdIn
  import scala.util.Sorting

  object Solution extends App {
    val n = StdIn.readInt
    val a = (1 to n).map(_ => StdIn.readInt).toArray

    Sorting.quickSort(a)
    val middle = if (n % 2 == 0) n / 2 - 1 else n / 2

    var r: Long = 0
    for (i <- 0 to middle) {
      var v: Long = a(i) * a(n - i - 1)
      if (i != n - i - 1) {
        v *= 2
      }
      r += v
    }

    println(r % 10007)
  }

  import scala.io.StdIn
  import scala.util.Sorting

  object Solution extends App {
    val n = StdIn.readInt
    val a = (1 to n).map(_ => StdIn.readInt).toArray

    Sorting.quickSort(a)
    val middle = if (n % 2 == 0) n / 2 - 1 else n / 2

    var r: Long = 0
    for (i <- 0 to middle) {
      var v = a(i) * a(n - i - 1)
      if (i != n - i - 1) {
        v *= 2
      }
      r += v
    }

    println(r)
  }


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var visited = Set.empty[Int]
  var visited2 = Set.empty[Int]
  val n = in.next().toInt
  val res = (1 to n * n).filter { i =>
    val Array(x, y) = in.next().split(" ").map(_.toInt)
    if (visited.contains(x) || visited2.contains(y))
      false
    else {
      visited += x
      visited2 += y
      true
    }
  }
  println(res.mkString(" "))
}

object Program{
	def main(ins:Array[String]){
		var ins = new Array[Int](2);
		var n = readInt();
		var x = new Array[Int](n); var y = new Array[Int](n)
		var a = 0; var b = 0
		for (i <-1 to n*n){
			ins = readLine.split(" ").map(_.toInt)
			a = ins(0); b = ins(1)
			if (x(a - 1) == 0 && y(b - 1) == 0){
				x(a - 1) = 1; y(b - 1) = 1
				print(i+" ")
			}
		}
	}
}

object A583 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val row = Array.fill[Boolean](n)(false)
    val col = Array.fill[Boolean](n)(false)
    var res = Array.empty[Int]
    for(i <- 0 until n*n) {
      val arr = readInts(2)
      if(!row(arr(0)-1) && !col(arr(1)-1)) {
        row(arr(0)-1) = true
        col(arr(1)-1) = true
        res = res ++ Array(i+1)
      }
    }
    println(res.mkString(" "))
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _583A extends CodeForcesApp[Seq[Int]]({scanner => import scanner._
  val n = nextInt
  val vs = bag[Int]
  val hs = bag[Int]

  val ans = for {
    d <- 1 to n*n
    (i, j) = (nextInt, nextInt)
    if !(vs contains i) && !(hs contains j)
  } yield {
      vs.add(i)
      hs.add(j)
      d
   }

  ans
}) {
  override def format(result: Result) = result mkString " "
}
/********************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

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

object A extends App {

  val H = Array.ofDim[Boolean](51)
  val V = Array.ofDim[Boolean](51)

  def needWork(h: Int, v: Int) = {
    if (H(h) || V(v)) {
      false
    } else {
      H(h) = true
      V(v) = true
      true
    }
  }

  val n = readInt()
  val answer = new ArrayBuffer[Int]
  for (i <- 1 to n*n) {
    val Array(h, v) = readLine().split(" ").map(_.toInt)
    if (needWork(h, v)) answer += i
  }

  println(answer.mkString(" "))

}

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

object A_Asphalt {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

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

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    val hor = Array.fill(number+1)(false)
    val ver = Array.fill(number+1)(false)

    var res = new StringBuffer();
    for (i <- 0 until number*number) {
      val line = br.readLine().split(" ")
      val h = line(0).toInt
      val v = line(1).toInt
      if (!hor(h) && !ver(v)) {
        res.append(i+1).append(" ")
        hor(h) = true
        ver(v) = true
      }
    }

    println(res)

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

  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var visited = Set.empty[Int]
  val n = in.next().toInt
  val res = (1 to n * n).filter { i =>
    val Array(x, y) = in.next().split(" ").map(_.toInt)
    if (visited.contains(x) || visited.contains(y))
      false
    else {
      visited += x
      visited += y
      true
    }
  }
  println(res.mkString(" "))
}

object A583 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val row = Array.fill[Boolean](n)(false)
    val col = Array.fill[Boolean](n)(false)
    var res = Array.empty[Int]
    for(i <- 0 until n*n) {
      val arr = readInts(2)
      if(!row(arr(0)-1) && !row(arr(1)-1)) {
        row(arr(0)-1) = true
        row(arr(1)-1) = true
        res = res ++ Array(i+1)
      }
    }
    println(res.mkString(" "))
  }
}


import scala.io.StdIn._

//package month11.codeforces.round378

object TaskB extends App {
  val n = readInt()
  val A = Array.ofDim[(Int, Int)](n)
  var Left = 0
  var Right = 0

  0 until n foreach { i =>
    val Array(l, r) = readLine().split(" ").map(_.toInt)
    val tuple = (l, r)
    A(i) = tuple
    Left += l
    Right += r
  }

  var max = Math.abs(Left - Right)
  var maxId = -1

  0 until n foreach { i =>
    val (l, r) = A(i)
    val newLeft = Left - l + r
    val newRight = Right - r + l
    val maybeMax = Math.abs(newLeft - newRight)
    if (maybeMax > max) {
      max = maybeMax
      maxId = i
    }
  }

  println(maxId + 1)
}

import java.io._

import ProblemB.IndexedValue

import scala.io.Source
import scala.annotation.tailrec

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

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

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

  // Standard code above, custom code below
  case class IndexedValue(index: Int, value: Int) extends Ordered[IndexedValue] {
    def compare(that: IndexedValue) = math.abs(this.value).compare(math.abs(that.value))
  }

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val n = lines.next().toInt
    var minLMinusR = IndexedValue(0, 0)
    var maxLMinusR = IndexedValue(0, 0)
    var totalLMinusR = 0

    for (i <- 1 to n) {
      val column = lines.next.split(" ").map(_.toInt)
      val l = column(0)
      val r = column(1)
      val lMinusR = l - r
      totalLMinusR += lMinusR
      if (minLMinusR.value > lMinusR) minLMinusR = IndexedValue(i, lMinusR)
      if (maxLMinusR.value < lMinusR) maxLMinusR = IndexedValue(i, lMinusR)
    }

    val indexedVals = List(
      IndexedValue(0, totalLMinusR),  // Order important, so that changes aren't made unnecessarily
      IndexedValue(minLMinusR.index, totalLMinusR - 2 * minLMinusR.value),
      IndexedValue(maxLMinusR.index, totalLMinusR - 2 * maxLMinusR.value)
    )
    val bestIndVal = indexedVals.max
    bw.write(bestIndVal.index.toString)
    bw.newLine()
  }
}

object B733 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    case class Column(l: Int, r: Int)
    val input = new Array[Column](n)

    def beauty(in: Array[Column]): Int = {
      math.abs(in.map(_.l).sum - in.map(_.r).sum)
    }

    for (i <- 0 to n-1) {
      val Array(l, r) = readInts(2)
      input(i) = Column(l, r)
    }

    var ret = 0
    val L = input.map(_.l).sum
    val R = input.map(_.r).sum
    var max = math.abs(L-R)
    for (i <- 0 to n-1) {
      val beautyi = math.abs(L-input(i).l+input(i).r - (R-input(i).r+input(i).l))
      if(beautyi > max) {
        ret = i + 1
        max = beautyi
      }
    }

    println(ret)
  }
}

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

object _733B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val soldiers = read[Vector[(Int, Int)]]

    var l, r = 0
    soldiers foreach {case (i, j) =>
      l += i
      r += j
    }

    var beauty = (l - r).abs
    var ans = 0

    soldiers.zipWithIndex foreach {case ((i, j), k) =>
      val nl = l - i + j
      val nr = r - j + i
      val nb = (nl - nr).abs
      if (nb > beauty) {
        beauty = nb
        ans = k + 1
      }
    }

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def 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 maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    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): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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 Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _733B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val soldiers = read[Vector[(Int, Int)]]

    val (l, r) = {
      var _l, _r = 0
      soldiers foreach {case (i, j) =>
          _l += i
          _r += j
      }
      (_l, _r)
    }

    var beauty = (l - r).abs
    var ans = 0

    soldiers.zipWithIndex foreach {case ((i, j), k) =>
      val nl = l - i + j
      val nr = r - j + i
      val nb = (nl - nr).abs
      if (nb > beauty) {
        beauty = nb
        ans = k+1
      }
    }

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def 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 maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    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): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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 Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _733B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val soldiers = read[Vector[(Int, Int)]]

    var l, r = 0
    soldiers foreach {case (i, j) =>
      l += i
      r += j
    }

    var beauty = (l - r).abs
    var ans = 0

    soldiers.zipWithIndex foreach {case ((i, j), k) =>
      val nl = l - i + j
      val nr = r - j + i
      val nb = (nl - nr).abs
      if (nb > beauty) {
        beauty = nb
        ans = k+1
      }
    }

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def 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 maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    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): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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
      }
    }
  }
}

//package xubiker

import java.util.Scanner

/**
  * Created by xubiker on 04-Dec-16.
  */
object Task_733B extends App {

  val sc = new Scanner(System.in)

  val n = sc.nextInt

  var sumL: Int = 0
  var sumR: Int = 0

  var maxDiff = -2000
  var minDiff = 2000
  var maxDiffIdx = -1
  var minDiffIdx = -1

  for (i <- 1 to n) {
    val l = sc.nextInt
    val r = sc.nextInt
    sumL += l
    sumR += r
    val diff = l - r
    if (diff > maxDiff) {
      maxDiff = diff
      maxDiffIdx = i
    }
    if (diff < minDiff) {
      minDiff = diff
      minDiffIdx = i
    }
  }

  val curr = Math.abs(sumL - sumR)
  val v1 = Math.abs((sumL - maxDiff) - (sumR + maxDiff))
  val v2 = Math.abs((sumL - minDiff) - (sumR + minDiff))

  val idx = if (v1 > v2) maxDiffIdx else minDiffIdx

  val res = if (curr < v1.max(v2)) idx else 0

  println(res)

  sc.close()
}

object _733B extends App {
  val in = io.Source.fromInputStream(System.in).getLines()
  val cols = in.take(in.next().toInt).toSeq.map {
    s =>
      val sp = s.split("\\s+")
      (sp(0).toInt, sp(1).toInt)
  }
  val ((imin, dmin), (imax, dmax), suml, sumr) = cols.zipWithIndex.foldLeft(((0, Integer.MAX_VALUE), (0, Integer.MIN_VALUE), 0, 0)) {
    case (((imin, dmin), (imax, dmax), l, r), ((cl, cr), idx)) => {
      val d = cl - cr
      (if (d < dmin) (idx, d) else (imin, dmin),
        if (d > dmax) (idx, d) else (imax, dmax),
        l + cl,
        r + cr)
    }
  }
  def b(l: Int, r: Int) = Math.abs(l - r)
  println(Seq((0, b(suml, sumr)), (imin + 1, b(suml - dmin, sumr + dmin)), (imax + 1, b(suml - dmax, sumr + dmax))).maxBy(_._2)._1)
}

import java.util.Scanner

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

    val l = new Array[Int](n)
    val r = new Array[Int](n)
    val diff = new Array[Int](n)
    var cnt = 0

    for(i <- 0 until n){
      l(i) = sc.nextInt()
      r(i) = sc.nextInt()
      diff(i) = l(i) - r(i)
      cnt += diff(i)
    }

    var ind = 0
    var now = 0
    if(cnt == 0){
      for(i <- 0 until n){
        if(now < Math.abs(diff(i))){
          ind = i + 1
          now = Math.abs(diff(i))
        }
      }
    }
    else {
      now = Math.abs(cnt)
      for(i <- 0 until n){
        if(now < Math.abs(cnt - 2 * diff(i))){
          ind = i + 1
          now = Math.abs(cnt - 2 * diff(i))
        }
      }
    }

    println(ind)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lr = in.take(n).map(l => l.split(' ').map(_.toInt)).toList
  val l = lr.map(_.head).sum
  val r = lr.map(_.last).sum
  val diff = Math.abs(l - r)

  val res = lr.map(e => Math.abs(l - 2 * e.head + 2 * e.last - r)).zipWithIndex.filter(_._1 > diff)

  if (res.isEmpty)
    println(0)
  else
    println(res.maxBy(_._1)._2 + 1)
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    input.next()
    val lrs = input.toSeq.map(line => line.split(' ').map(_.toInt))
    val lness = lrs.map(arr => arr(0) - arr(1)).sum
    val change = lrs.map(arr => (lness + arr(1) * 2 - arr(0) * 2).abs).zipWithIndex.maxBy(_._1)
    val k = if (change._1 > lness.abs) change._2 + 1 else 0
    print(k)
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    input.next()
    val lrs = input.toSeq.map(line => line.split(' ').map(_.toInt))
    val lness = lrs.map(arr => arr(0) - arr(1)).sum
    val change = lrs.map(arr => lness + arr(1) * 2 - arr(0) * 2).zipWithIndex.maxBy(_._1.abs)
    val k = if (change._1 > lness.abs) change._2 + 1 else 0
    print(k)
  }
}

object Main {

  def main(args: Array[String]) = {
    val input = scala.io.Source.stdin.getLines()
    input.next()
    val lrs = input.toSeq.map(line => line.split(' ').map(_.toInt))
    val lness = lrs.map(arr => arr(0) - arr(1)).sum
    val change = lrs.map(arr => lness + arr(1) * 2 - arr(0) * 2).zipWithIndex.minBy(_._1.abs)
    val k = if (change._1 < lness.abs) change._2 + 1 else 0
    print(k)
  }
}


object StringLCM {

  import scala.io.{StdIn => in}
  import scala.util.control._

  def main(args: Array[String]) = {
    var t = in.readInt()
    while (t > 0) {
      var a = in.readLine()
      var b = in.readLine()
      var c = a
      var d = b;
      while (c.length <= 400)
        c += a
      while (d.length <= 400)
        d += b
      var x, y: String = ""
      var ans: Int = -1
      var ansString: String = ""
      val loop = new Breaks
      loop.breakable {
        for (i <- 0 to 400) {
          x += c(i)
          y += d(i)
          if (x == y && (i + 1) % a.length == 0 && (i + 1) % b.length == 0) {
            ans = i
            ansString = x
            loop.break
          }
        }
      }
      if (ans == -1)
        println(ans)
      else println(ansString)
      t -= 1;
    }
  }

}

object StringLCM {

  import scala.io.{StdIn => in}
  import scala.util.control._

  def gcd(a: Int, b: Int): Int = {
    if(b ==0) a else gcd(b, a % b)
  }

  def main(args: Array[String]) = {
    var t = in.readInt()
    while (t > 0) {
      var a = in.readLine()
      var b = in.readLine()
      var c = a
      var d = b;
      while (c.length <= 400)
        c += a
      while (d.length <= 400)
        d += b
      var jump = a.length * b.length / gcd(a.length, b.length)
      var x, y: String = ""
      var ans: Int = -1
      var ansString: String = ""
      val loop = new Breaks
      loop.breakable {
        for (i <- 0 to 400) {
          x += c(i)
          y += d(i)
          if (x == y && (i + 1) % a.length == 0 && (i + 1) % b.length == 0) {
            ans = i
            ansString = x
            loop.break
          }
        }
      }
      if (ans == -1)
        println(ans)
      else println(ansString)
      t -= 1;
    }
  }

}

object firstdemo extends  App {

  def readString() : String = {
    val yo = scala.io.StdIn.readLine()
    yo
  }
  def readInt() : Int = {
    val yo = scala.io.StdIn.readInt();
    yo
  }

  def gcd(a: Int, b: Int): Int =
    if (b == 0) a else gcd(b, a % b)

     var t = readInt()

      while(t > 0) {

        val s = readString()
        val s1 = readString()

        val x = s.length
        val y = s1.length

        val lcm = x * y / gcd(x , y)

        val temp = lcm / x

        var actual = ""
        for(i <- 0 until temp) {
          actual += s
        }
        var flag = 0

        for(i <- 0 until actual.length by x) {
          val temp = actual.substring(i , i + x)
          if(temp != s) {
            flag = 1
          }
        }

        for(i <- 0 until actual.length by y) {
          val temp = actual.substring(i , i + y)
          if(temp != s1) {
            flag = 1
          }
        }
        if(flag == 0) {
          println(actual)
        }
        else {
          println("-1")
        }
       // print(actual)

        t = t - 1
      }

}

/*import org.apache.spark.sql.sources.LessThanOrEqual
package com.spark.demo
import org.apache.spark.sql.SparkSession
import org.apache.spark.{SparkConf, SparkContext}*/


import scala.collection._

object D extends App {

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

  val Array(n) = readInts(1)
  val rLens = Array.fill(n - 1)(0)
  val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)
  val abToRoad = mutable.Map.empty[(Int, Int), Int]

  for (i <- 0 until n - 1) {
    val Array(_a, _b, l) = readInts(3)
    val a = _a - 1
    val b = _b - 1
    adjBuilders(a) += b
    adjBuilders(b) += a
    abToRoad += (a, b) -> i
    abToRoad += (b, a) -> i
    rLens(i) = l
  }

  val adjs = adjBuilders.map(_.result)
  val incoming, outgoing = Array.fill(n - 1)(0)

  def dfs(u: Int, cnt: Int, parent: Int): Int = {
    var add = 1
    for (v <- adjs(u)) {
      if (v != parent) {
        val c = dfs(v, cnt + 1, u)
        val r = abToRoad((u, v))
        incoming(r) = n - c
        outgoing(r) = c
        add += c
      }
    }
    add
  }

  dfs(0, 1, -1)

  var total = 0d
  for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)

  val Array(q) = readInts(1)

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

  for (i <- 0 until q) {
    val Array(_r, w) = readInts(2)
    val r = _r - 1
    val delta = rLens(r) - w
    rLens(r) = w
    total -= delta.toDouble * incoming(r) * outgoing(r)
    println(total * 3 / n / (n - 1) * 2)
  }

  Console.flush
}

import scala.collection._

object D extends App {

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

  val Array(n) = readInts(1)
  val rLens = Array.fill(n - 1)(0)
  val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)
  val abToRoad = mutable.Map.empty[(Int, Int), Int]

  for (i <- 0 until n - 1) {
    val Array(_a, _b, l) = readInts(3)
    val a = _a - 1
    val b = _b - 1
    adjBuilders(a) += b
    adjBuilders(b) += a
    abToRoad += (a, b) -> i
    abToRoad += (b, a) -> i
    rLens(i) = l
  }

  val adjs = adjBuilders.map(_.result)
  val incoming, outgoing = Array.fill(n - 1)(0)

  def dfs(u: Int, parent: Int): Int = {
    var add = 1
    for (v <- adjs(u)) {
      if (v != parent) {
        val cnt = dfs(v, u)
        val r = abToRoad((u, v))
        incoming(r) = n - cnt
        outgoing(r) = cnt
        add += cnt
      }
    }
    add
  }

  dfs(0, -1)

  var total = 0d
  for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)

  val Array(q) = readInts(1)

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

  for (i <- 0 until q) {
    val Array(_r, w) = readInts(2)
    val r = _r - 1
    val delta = rLens(r) - w
    rLens(r) = w
    total -= delta.toDouble * incoming(r) * outgoing(r)
    println(total * 3 / n / (n - 1) * 2)
  }

  Console.flush
}

import scala.collection._

object D extends App {

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

  val Array(n) = readInts(1)
  val rLens = Array.fill(n - 1)(0)
  val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)
  val abToRoad = mutable.Map.empty[(Int, Int), Int]

  for (i <- 0 until n - 1) {
    val Array(_a, _b, l) = readInts(3)
    val a = _a - 1
    val b = _b - 1
    adjBuilders(a) += b
    adjBuilders(b) += a
    abToRoad += (a, b) -> i
    abToRoad += (b, a) -> i
    rLens(i) = l
  }

  val adjs = adjBuilders.map(_.result)
  val visited = new mutable.BitSet(n)
  val incoming, outgoing = Array.fill(n - 1)(0)

  def dfs(u: Int, cnt: Int): Int = {
    visited += u
    var add = 1
    val ne = new mutable.ArrayBuilder.ofInt
    val cs = new mutable.ArrayBuilder.ofInt
    for (i <- adjs(u).indices) {
      val v = adjs(u)(i)
      ne += v
      if (!visited(v)) {
        val c = dfs(v, cnt + 1)
        cs += c
        add += c
      } else cs += 0
    }
    val nes = ne.result
    val css = cs.result
    for (i <- nes.indices) {
      val v = nes(i)
      val r = abToRoad((u, v))
      incoming(r) = n - css(i)
      outgoing(r) = css(i)
    }
    add
  }

  dfs(0, 1)

  var total = 0d
  for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)

  val Array(q) = readInts(1)

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

  for (i <- 0 until q) {
    val Array(_r, w) = readInts(2)
    val r = _r - 1
    val delta = rLens(r) - w
    rLens(r) = w
    total -= delta.toDouble * incoming(r) * outgoing(r)
    println(total * 3 / n / (n - 1) * 2)
  }

  Console.flush
}

import scala.collection._

object D extends App {

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

  val Array(n) = readInts(1)
  val rLens = Array.fill(n - 1)(0)
  //val adjs = Array.fill(n)(0)
  val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)
  val as = Array.fill(n)(0)
  val bs = Array.fill(n)(0)
  val isLeaf = Array.fill(n - 1)(true)
  val abToRoad = mutable.Map.empty[(Int, Int), Int]
  for (i <- 0 until n - 1) {
    val Array(_a, _b, l) = readInts(3)
    val a = _a - 1
    val b = _b - 1
    //adjs(a - 1) += 1
    //adjs(b - 1) += 1
    adjBuilders(a) += b
    adjBuilders(b) += a
    abToRoad += (a, b) -> i
    abToRoad += (b, a) -> i
    as(i) = a - 1
    bs(i) = b - 1
    rLens(i) = l
  }

  val adjs = adjBuilders.map(_.result)
  val visited = new mutable.BitSet(n)
  val incoming, outgoing = Array.fill(n - 1)(0)

  def dfs(u: Int, cnt: Int): Int = {
    visited += u
    var add = 1
    val ne = new mutable.ArrayBuilder.ofInt
    val cs = new mutable.ArrayBuilder.ofInt
    for (i <- adjs(u).indices) {
      val v = adjs(u)(i)
      ne += v
      if (!visited(v)) {
        val c = dfs(v, cnt + 1)
        cs += c
        add += c
      } else cs += 0
    }
    val nes = ne.result
    val css = cs.result
    for (i <- nes.indices) {
      val v = nes(i)
      val r = abToRoad((u, v))
      incoming(r) = n - css(i)
      outgoing(r) = css(i)
    }
    add
  }

  dfs(0, 1)

  //for (i <- 0 until n - 1)
  //if (adjs(as(i)) > 1 && adjs(bs(i)) > 1) isLeaf(i) = false
  def c(k: Int, n: Int): Long = {
    var result = 1L
    var i = 1
    var lim = math.min(k, n - k)
    while (i <= lim) {
      result = result * (n - i + 1)
      result = result / i
      i += 1
    }
    result
  }

  def fib(n: Int): Double = {
    var i1 = 1d
    var i2 = 1d
    for (i <- 2 until n) {
      val x = i1 + i2
      i1 = i2
      i2 = x
    }
    i2
  }
  val f = fib(n - 1)

  var total = 0d
  for (i <- 0 until n - 1) total += rLens(i) * incoming(i) * outgoing(i)
  //println(incoming.mkString(" "))
  //println(outgoing.mkString(" "))
  val Array(q) = readInts(1)
  for (i <- 0 until q) {
    val Array(_r, w) = readInts(2)
    val r = _r - 1
    val delta = rLens(r) - w
    rLens(r) = w
    total -= delta * incoming(r) * outgoing(r)
    println(total / f)// * (n - 1) / (n - 2) / (n - 2) / 2))
  }
}

import scala.collection._

object D extends App {

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

  val Array(n) = readInts(1)
  val rLens = Array.fill(n - 1)(0)
  val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)
  val abToRoad = mutable.Map.empty[(Int, Int), Int]

  for (i <- 0 until n - 1) {
    val Array(_a, _b, l) = readInts(3)
    val a = _a - 1
    val b = _b - 1
    adjBuilders(a) += b
    adjBuilders(b) += a
    abToRoad += (a, b) -> i
    abToRoad += (b, a) -> i
    rLens(i) = l
  }

  val adjs = adjBuilders.map(_.result)
  val incoming, outgoing = Array.fill(n - 1)(0)

  def dfs(u: Int, cnt: Int, parent: Int): Int = {
    var add = 1
    for (v <- adjs(u)) {
      if (v != parent) {
        val c = dfs(v, cnt + 1, u)
        val r = abToRoad((u, v))
        incoming(r) = n - c
        outgoing(r) = c
        add += c
      }
    }
    add
  }

  dfs(0, 1, -1)

  var total = 0d
  for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)

  val Array(q) = readInts(1)

  Console.withOut(new java.io.BufferedOutputStream(Console.out)) {

    for (i <- 0 until q) {
      val Array(_r, w) = readInts(2)
      val r = _r - 1
      val delta = rLens(r) - w
      rLens(r) = w
      total -= delta.toDouble * incoming(r) * outgoing(r)
      println(total * 3 / n / (n - 1) * 2)
    }

  }
}

import scala.collection._

object D extends App {

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

  val Array(n) = readInts(1)
  val rLens = Array.fill(n - 1)(0)
  val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)
  val abToRoad = mutable.Map.empty[(Int, Int), Int]

  for (i <- 0 until n - 1) {
    val Array(_a, _b, l) = readInts(3)
    val a = _a - 1
    val b = _b - 1
    adjBuilders(a) += b
    adjBuilders(b) += a
    abToRoad += (a, b) -> i
    abToRoad += (b, a) -> i
    rLens(i) = l
  }

  val adjs = adjBuilders.map(_.result)
  val visited = new mutable.BitSet(n)
  val incoming, outgoing = Array.fill(n - 1)(0)

  def dfs(u: Int, cnt: Int): Int = {
    visited += u
    var add = 1
    val ne = new mutable.ArrayBuilder.ofInt
    val cs = new mutable.ArrayBuilder.ofInt
    for (i <- adjs(u).indices) {
      val v = adjs(u)(i)
      ne += v
      if (!visited(v)) {
        val c = dfs(v, cnt + 1)
        cs += c
        add += c
      } else cs += 0
    }
    val nes = ne.result
    val css = cs.result
    for (i <- nes.indices) {
      val v = nes(i)
      val r = abToRoad((u, v))
      incoming(r) = n - css(i)
      outgoing(r) = css(i)
    }
    add
  }

  dfs(0, 1)

  var total = 0d
  for (i <- 0 until n - 1) total += rLens(i).toDouble * incoming(i) * outgoing(i)

  val Array(q) = readInts(1)
  for (i <- 0 until q) {
    val Array(_r, w) = readInts(2)
    val r = _r - 1
    val delta = rLens(r) - w
    rLens(r) = w
    total -= delta * incoming(r) * outgoing(r)
    println(total * 3 / n / (n - 1) * 2)
  }

}

import scala.collection._

object D extends App {

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

  val Array(n) = readInts(1)
  val rLens = Array.fill(n - 1)(0)
  val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)
  val abToRoad = mutable.Map.empty[(Int, Int), Int]

  for (i <- 0 until n - 1) {
    val Array(_a, _b, l) = readInts(3)
    val a = _a - 1
    val b = _b - 1
    adjBuilders(a) += b
    adjBuilders(b) += a
    abToRoad += (a, b) -> i
    abToRoad += (b, a) -> i
    rLens(i) = l
  }

  val adjs = adjBuilders.map(_.result)
  val visited = new mutable.BitSet(n)
  val incoming, outgoing = Array.fill(n - 1)(0)

  def dfs(u: Int, cnt: Int): Int = {
    visited += u
    var add = 1
    val ne = new mutable.ArrayBuilder.ofInt
    val cs = new mutable.ArrayBuilder.ofInt
    for (i <- adjs(u).indices) {
      val v = adjs(u)(i)
      ne += v
      if (!visited(v)) {
        val c = dfs(v, cnt + 1)
        cs += c
        add += c
      } else cs += 0
    }
    val nes = ne.result
    val css = cs.result
    for (i <- nes.indices) {
      val v = nes(i)
      val r = abToRoad((u, v))
      incoming(r) = n - css(i)
      outgoing(r) = css(i)
    }
    add
  }

  dfs(0, 1)

  var total = 0d
  for (i <- 0 until n - 1) total += rLens(i) * incoming(i) * outgoing(i)

  val Array(q) = readInts(1)
  for (i <- 0 until q) {
    val Array(_r, w) = readInts(2)
    val r = _r - 1
    val delta = rLens(r) - w
    rLens(r) = w
    total -= delta * incoming(r) * outgoing(r)
    println(total * 3 / n / (n - 1) * 2)
  }

}