Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of columns.  The next n lines contain the pairs of integers li and ri (1 ≤ li, ri ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.

Print single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.

NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg — 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg — 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9.

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

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

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

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


Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, "abc" $$$\cdot~2~=$$$ "abcabc", "a" $$$\cdot~5~=$$$ "aaaaa".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \cdot x = a$$$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \le |s|, |t| \le 20$$$). Each character in each of these strings is either 'a' or 'b'.

For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

NoteIn the first test case, "baba" = "baba" $$$\cdot~1~=$$$ "ba" $$$\cdot~2$$$.In the second test case, "aaaaaa" = "aa" $$$\cdot~3~=$$$ "aaa" $$$\cdot~2$$$.

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


Gildong recently learned how to find the longest increasing subsequence (LIS) in $$$O(n\log{n})$$$ time for a sequence of length $$$n$$$. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length $$$n-1$$$, consisting of characters '<' and '>' only. The $$$i$$$-th (1-indexed) character is the comparison result between the $$$i$$$-th element and the $$$i+1$$$-st element of the sequence. If the $$$i$$$-th character of the string is '<', then the $$$i$$$-th element of the sequence is less than the $$$i+1$$$-st element. If the $$$i$$$-th character of the string is '>', then the $$$i$$$-th element of the sequence is greater than the $$$i+1$$$-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is $$$n-1$$$. It is guaranteed that the sum of all $$$n$$$ in all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print two lines with $$$n$$$ integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between $$$1$$$ and $$$n$$$, inclusive, and should satisfy the comparison results. It can be shown that at least one answer always exists.

NoteIn the first case, $$$1$$$ $$$2$$$ $$$3$$$ is the only possible answer.In the second case, the shortest length of the LIS is $$$2$$$, and the longest length of the LIS is $$$3$$$. In the example of the maximum LIS sequence, $$$4$$$ '$$$3$$$' $$$1$$$ $$$7$$$ '$$$5$$$' $$$2$$$ '$$$6$$$' can be one of the possible LIS.

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach((x) => f1)
  }

  def f1: Unit = {
    val Array(ns, s) = readLine.split(" ")
    val sa = s.toArray
    val n = ns.toInt
    var t = n
    val la = Array.ofDim[Int](n)
    val lb = Array.ofDim[Int](n)
    var i = 0;
    while (i < n - 1) {
      var l = 0;
      var r = 0;
      var tmp = 0;
      if (sa(i) == '<') {
        l = i;
        tmp = i;
        while (tmp < n - 1 && sa(tmp) == '<') tmp += 1;
        r = tmp;
        while (i < tmp) {
          la(i + 1) = t - (tmp - i - 1)
          i += 1
        }
        t -= (r - l)
      } else {
        i += 1
      }
    }
    i = 0;
    la(0) = t
    t -= 1
    while (i < n - 1) {
      if (sa(i) == '>') {
        la(i + 1) = t
        t -= 1
      }
      i += 1
    }
    i = n - 2;
    t = n
    while (i >= 0) {
      var l = 0;
      var r = 0;
      var tmp = 0;
      if (sa(i) == '<') {
        lb(i + 1) = t
        t -= 1
      }
      i -= 1
    }
    i = n - 2
    lb(0) = t
    t -= 1
    while (i >= 0) {
      var l = 0;
      var r = 0;
      var tmp = 0;
      if (sa(i) == '>') {
        r = i;
        tmp = i;
        while (tmp >= 0 && sa(tmp) == '>') tmp -= 1;
        l = tmp;
        while (i > tmp) {
          lb(i + 1) = t - (i - tmp - 1)
          i -= 1
        }
        t -= (r - l)
      } else {
        i -= 1
      }
    }

    println(la.mkString(" "))
    println(lb.mkString(" "))
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach((x) => f1)
  }

  def f1: Unit = {
    val Array(ns, s) = readLine.split(" ")
    val sa = s.toArray
    val n = ns.toInt
    var t = n
    val la = Array.ofDim[Int](n)
    var i = 0;
    while (i < n - 1) {
      var l = 0;
      var r = 0;
      var tmp = 0;
      if (sa(i) == '<') {
        l = i;
        tmp = i;
        while (tmp < n - 1 && sa(tmp) == '<') tmp += 1;
        r = tmp;
        while (i < tmp) {
          la(i + 1) = t - (tmp - i - 1)
          i += 1
        }
        t -= (r - l)
      } else {
        i += 1
      }
    }
    i = 0;
    la(0) = t
    t -= 1
    while (i < n - 1) {
      if (sa(i) == '>') {
        la(i + 1) = t
        t = t - 1
      }
      i += 1
    }
    println(la.mkString(" "))
    var a0 = la(0)
    i = 1
    var flag = true
    while (i < n - 1 && flag) {
      if (la(i - 1) < la(i) && la(i) > la(i + 1)) {
        for (j <- 0 to i - 2) la(j) = la(j + 1)
        la(i - 1) = la(i + 1)
        la(i + 1) = a0
        flag = false
      }
      i += 1
    }
    println(la.mkString(" "))
  }
}


New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v.As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1.Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck.It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network.However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.

The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times.

Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6.

NoteConsider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1).

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

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

}


Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 < p_2 < \ldots < p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i < m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.

The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.

Output one integer — the maximum width of a beautiful sequence.

NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.

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

    val n, m = nextInt
    val s, t = nextLine.map(_ - 'a')
    val Z = 'z' - 'a' + 1

//    val min, max = Array.fill(Z)(-1)
    val mins, maxs = Array.ofDim[Int](m)

    var prev = 0
    for (i <- 0 until m) {
      val c = t(i)
      while (s(prev) != c) prev += 1
      mins(i) = prev
      prev += 1
//      var k = if (min(c) == -1) 0 else min(c) + 1
//      while (s(k) != c) k += 1
//      min(c) = k
//      for (c <- 0 until Z) {
//        mins(c)(i) = min(c)
//      }
    }

    prev = n - 1
    for (i <- m - 1 to 0 by -1) {
      val c = t(i)
      while (s(prev) != c) prev -= 1
      maxs(i) = prev
      prev -= 1
//      var k = if (max(c) == -1) n - 1 else max(c) - 1
//      while (s(k) != c) k -= 1
//      max(c) = k
//      for (c <- 0 until Z) {
//        maxs(c)(i) = max(c)
//      }
    }

    var res = 0
    for (i <- 1 until m) {
//      val c = t(i - 1)
//      val c2 = t(i)
      val x = mins(i - 1)
      val y = maxs(i)
//      println(c + 'a', c2 + 'a', x, y)
      if (x >= 0 && y >= 0) {
        val d = y - x
        if (d > res) res = d
      }
    }

    out.println(res)
    out.flush()
  }

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

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

    val n, m = nextInt
    val s, t = nextLine.map(_ - 'a')
    val Z = 'z' - 'a' + 1

    val min, max = Array.fill(Z)(-1)
    val mins, maxs = Array.ofDim[Int](Z, m)

    for (i <- 0 until m) {
      val c = t(i)
      var k = if (min(c) == -1) 0 else min(c) + 1
      while (s(k) != c) k += 1
      min(c) = k
      for (c <- 0 until Z) {
        mins(c)(i) = min(c)
      }
    }

    for (i <- m - 1 to 0 by -1) {
      val c = t(i)
      var k = if (max(c) == -1) n - 1 else max(c) - 1
      while (s(k) != c) k -= 1
      max(c) = k
      for (c <- 0 until Z) {
        maxs(c)(i) = max(c)
      }
    }

    var res = 0
    for (i <- 1 until m) {
      val c = t(i - 1)
      val c2 = t(i)
      val x = mins(c)(i - 1)
      val y = maxs(c2)(i)
//      println(c + 'a', c2 + 'a', x, y)
      if (x >= 0 && y >= 0) {
        val d = y - x
        if (d > res) res = d
      }
    }

    out.println(res)
    out.flush()
  }

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


A flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.Determine the maximum possible number of large bouquets Vasya can make.

The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of initial bouquets. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the number of flowers in each of the initial bouquets.

Print the maximum number of large bouquets Vasya can make.

NoteIn the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme. In the second example it is not possible to form a single bouquet with odd number of flowers.In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11 + 4 + 10 = 25.

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

      var d = 0
      var e = 0
      for( i <- 1 to n ) {
         val a = sc.nextInt()
         if(a % 2 == 0) d = d + 1; else e = e + 1;
      }

      var res = 0
      if(e < d) {
         res = e
      } else {
         res = d + (e - d) / 3
      }

      println(res)
  }
}

import scala.io.StdIn._

object Hello extends App {
  val n = readInt()
  val xs = readLine().split(" ").map(_.toInt)
  var o = 0;
  var e = 0;
  var i = 0
  for ( i <- xs) {
    if (i %2 == 0) {
      e = e+1
    } else {
      o = o+1
    }
  }
  var ans = 0
  if (o < e) {
    ans = o
  } else {
    ans = e
  }
  e-=ans
  o-=ans
  ans += o/3
  println(ans)
}

object CF158A {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
    var a = 0
    var b = 0
    for ( i <- 1 to n)  {
        val k = sc.nextInt()
        if(k % 2 == 0) a += 1
        else b += 1
  }
  var ans = 0;

  if(a > b) {ans += b
  a -= b;
  b = 0;
  }

  else{ ans += a
  b -= a;
  a = 0;

    ans += b / 3
  }
  println(ans)
}
}

import java.util.Scanner

object Main extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextInt()
  val arr = new Array[Int](n)
  var c = 0
  var c2 = 0

  for (i <- 0 until n) {
    arr.update(i, scanner.nextInt())
    if (arr(i) % 2 == 0)
      c += 1
    else
      c2 += 1
  }

  val mn = Integer.min(c, c2)
  c2 -= mn

  println(mn + c2 / 3)

}

object Main extends App {
  val n = readInt
  val s = readLine
  val a = s.split(" ").map(i => i.toInt)
  var n1 = 0
  for(i <- 0 until n) {
    if (a(i) % 2 == 0)
      n1 += 1
  }
  var n2 = n - n1
  if (n2 <= n1)
    println(n2)
  else
      println(n1 + (n2 - n1) / 3)
}

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

    var c1 = 0
    for ( i <- 1 to n)
    {
        var x = sc.nextInt()
        if (x % 2 == 1)
        {
            c1 = c1 + 1
        }
    }
    var c2 = n - c1

    var ans = 0

    if (c2 < c1)
    {
        ans = c2 + (c1 - c2) / 3
    }
    else
    {
        ans = c1
    }

    println(ans)
  }
}

object Main extends App {
	var i = 0
    var o = 0
    var e = 0
    var n = readLine().toLong
    val arr = readLine().split(" ").map(_.toLong)
    var k = 0

    while (i < n) {
        k = arr(i).toInt
        if (k % 2 == 1) {o += 1}
        else {e += 1}
        i += 1
    }
    if (o <= e) {print(o)}
    else {print(e + ((o-e) / 3))}
}

object CF158A {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
     var no = 0;
    for (i <- 1 to n){
        if (sc.nextInt() % 2 == 1){
            no= no + 1;
        }
    }

    var a = Math.min(no,  n /2)
    var done = false
    while(a>0 && !done){
        var nl = (no - a)/2 + (n - no);
        if (nl < a)
            a = a -1;
        else{

            done = true
        }
    }

    print(a)
}
}

import scala.io.StdIn._

object A extends App {
  readInt()

  val pairs = readLine().split(" ").map(_.toInt).dropWhile(_ == 0).reverse.dropWhile(_ == 0)

  var odd = 0
  var even = 0
  for (p <- pairs) {
    if (p % 2 == 0) {
      even += 1
    } else {
        odd += 1
    }
  }

  if (even > odd) {
      println(odd)
  } else {
      println(even + (odd - even) / 3)
  }

}

object CF158A {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
    var z = new Array[Integer](n)
    var fr = new Array[Integer](2)
    for(i <- 0 until z.length) {
        z(i) = sc.nextInt()
        fr(z(i)%2) += 1
    }
    var res = 0
    var min = math.min(fr(0), fr(1))
    res += min
    fr(0) -= min
    fr(1) -= min
    res += fr(1)/3
    println(res)
  }
}

object Main {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
    var a1 = 0
    var a0 = 0
    for (a <- 1 to n) {
        val x = sc.nextInt()
        if (x % 2 == 0) a0 = a0 + 1
        else a1 = a1 + 1
    }
    var x = math.min(a1,a0)
    a1 = a1 - x
    x = x + a1 / 3

    println(x)
  }
}

object CF928A extends App {
    val sc = new java.util.Scanner(System.in)
    var n: Int = sc.nextInt()
    var o: Int = 0
    var e: Int = 0
    while (n != 0) {
        val x: Int = sc.nextInt()
        if (x % 2 == 0) e = e + 1
        else o = o + 1
        n = n - 1
    }
    var ans: Int = 0
    if (o > e) ans = e
    else ans = o
    e -= ans
    o -= ans
    ans += o / 3
    println(ans)
  }

object CF158A {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
    var a = 0
    var b = 0
    for ( i <- 1 to n)  {
        val k = sc.nextInt()
        if(k % 2 == 0) a += 1
        else b += 1
  }
  if(a > b) println(b)
  else println(a)
}
}

object Main extends App {
  val n = readInt
  val s = readLine
  val a = s.split(" ").map(i => i.toInt)
  var n1 = 0
  for(i <- 0 until n) {
    if (a(i) % 2 == 0)
      n1 += 1
  }
  var n2 = n - n1
  if (n2 <= n1)
    println(n2)
  else
    if ((n2 - n1) % 3 == 1)
      println(math.max(0, n1 + (n2 - n1) / 3 - 1))
    else
      println(n1 + (n2 - n1) / 3)
}

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

    var c1 = 0
    for ( i <- 1 to n)
    {
        var x = sc.nextInt()
        if (x % 2 == 1)
        {
            c1 = c1 + 1
        }
    }

    val c2 = n - c1

    var ans = c1
    if (c2 < c1)
    {
        ans = c2
    }

    println(ans)
  }
}

object CF158A {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
    val a: List[Int] = (1 to n).toList.foldLeft(List.empty[Int]){case (list, _) => list :+ sc.nextInt()}

    println(a.count(
      x => x % 2 == 1
    ))
  }
}

object Main extends App {
	var i = 0
    var o = 0
    var e = 0
    var n = readLine().toInt
    val arr = readLine().split(" ").map(_.toInt)
    var k = 0

    while (i < n) {
        k = arr(i)
        if (k % 2 == 1) {o += 1}
        else {e += 1}
        i += 1
    }
    if (o <= e) {print(o)}
    else {print(e + ((o-e) % 3))}
}

object CF158A {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
     var no = 0;
    for (i <- 1 to n){
        if (sc.nextInt() % 2 == 0){
            no= no + 1;
        }
    }
    print(Math.min(no,  n /2))
}
}

object CF158A {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
     var no = 0;
    for (i <- 1 to n){
        if (sc.nextInt() % 2 == 1){
            no= no + 1;
        }
    }
    if (n == 2 && no == 2)
        print(0); else
    print(Math.min(no,  n /2))
}
}

object CF158A {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
     var no = 0;
    for (i <- 1 to n){
        if (sc.nextInt() % 2 == 1){
            no= no + 1;
        }
    }
    print(Math.min(no,  n /2))
}
}

object Main {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
    var a1 = 0
    var a0 = 0
    for (a <- 1 to n) {
        val x = sc.nextInt()
        if (x % 2 == 0) a0 = a0 + 1
        else a1 = a1 + 1
    }
    // val a = Array.fromFunction(_ => sc.nextInt())(n)

    // val a1 = a.count(x => x % 2 == 1)
    // val a0 = a.count(x => x % 2 == 0)

    println(math.min(a1,a0))
  }
}


ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after.ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1, A2, ..., Ak (k > 1) such that for every 1 ≤ i < k there is a road from town Ai to town Ai + 1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns.Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing.Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.

The first line of the input contains single integer n (2 ≤ n ≤ 2·105) — the number of towns in Udayland. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n, ai ≠ i), ai denotes a road going from town i to town ai.

Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109 + 7.

NoteConsider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are , ,  initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip.The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.

import scala.collection.mutable.ArrayBuffer

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 as = readInts(n).map(_ - 1)
  val MOD = 1000000007L
  val TWO = BigInt(2)

  val cycleSizes = ArrayBuffer.empty[Int]
  val gens = Array.fill(n){ -1 }
  var gen = 0

  def dfs(u: Int, gen0: Int): Unit = {
    gen += 1
    if (gens(u) >= gen0) cycleSizes += gen - gens(u)
    else if (gens(u) == -1) {
      gens(u) = gen
      dfs(as(u), gen0)
    }
  }

  for (u <- 0 until n) {
    if (gens(u) == -1) dfs(u, gen)
  }

  val nonCycleCount = n - cycleSizes.sum

  var res = TWO.modPow(nonCycleCount, MOD)

  for (cs <- cycleSizes) {
    res = res * (TWO.modPow(cs, MOD) - 2 + MOD) % MOD
  }

  println(res)
}


You are given an undirected connected weighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges. Let's denote the length of the shortest path from vertex $$$1$$$ to vertex $$$i$$$ as $$$d_i$$$. You have to erase some edges of the graph so that at most $$$k$$$ edges remain. Let's call a vertex $$$i$$$ good if there still exists a path from $$$1$$$ to $$$i$$$ with length $$$d_i$$$ after erasing the edges.Your goal is to erase the edges in such a way that the number of good vertices is maximized.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$1 \le m \le 3 \cdot 10^5$$$, $$$n - 1 \le m$$$, $$$0 \le k \le m$$$) — the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively. Then $$$m$$$ lines follow, each containing three integers $$$x$$$, $$$y$$$, $$$w$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$, $$$1 \le w \le 10^9$$$), denoting an edge connecting vertices $$$x$$$ and $$$y$$$ and having weight $$$w$$$. The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).

In the first line print $$$e$$$ — the number of edges that should remain in the graph ($$$0 \le e \le k$$$). In the second line print $$$e$$$ distinct integers from $$$1$$$ to $$$m$$$ — the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.

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

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

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

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

  def solve(): Unit = {
    val N, M, K = ni()
    val from, to, weight = Array.ofDim[Int](M)
    rep(M) { i =>
      from(i) = ni() - 1
      to(i) = ni() - 1
      weight(i) = ni()
    }

    val g = packWUGraph(N, from, to, weight)
    val edges = dijk(g, 0, K)
    out.println(edges.length)
    out.println(edges.map(_.id + 1).mkString(" "))
  }

  def dijk(g: WUGraph, start: Int, K: Int): ArrayBuffer[Edge] = {
    val d = Array.fill[Long](g.length)(Long.MaxValue / 2)
    case class Visit(node: Int, cost: Long, edge: Option[Edge]) extends Comparable[Visit] {
      override def compareTo(o: Visit): Int = java.lang.Long.compare(cost, o.cost)
    }
    val queue = new java.util.PriorityQueue[Visit]()
    queue.add(Visit(start, 0, None))

    val res = ArrayBuffer[Edge]()

    while(!queue.isEmpty) {
      val v = queue.poll()
      if (d(v.node) > v.cost) {
        d(v.node) = v.cost
        res ++= v.edge
        if (res.length == K) return res

        if (d(v.node) == v.cost) {
          rep(g(v.node).length) { i =>
            val e = g(v.node)(i)
            val next = v.cost + e.weight
            if (d(e.to) > next) {
              queue.add(Visit(e.to, next, Some(e)))
            }
          }
        }
      }
    }

    res
  }

  case class Edge(to: Int, weight: Int, id: Int)
  type WUGraph = Array[Array[Edge]]
  /**
    * uwiのぱくり
    */
  def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Int]): WUGraph = {
    val g = new Array[Array[Edge]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => g(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      g(from(i))(p(from(i))) = Edge(to(i), w(i), i)
      p(to(i)) -= 1
      g(to(i))(p(to(i))) = Edge(from(i), w(i), i)
    }
    g
  }

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

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

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

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

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

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