Scientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet.Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a thermometer on the balcony every morning and recorded the temperature. He had been measuring the temperature for the last n days. Thus, he got a sequence of numbers t1, t2, ..., tn, where the i-th number is the temperature on the i-th day.Vasya analyzed the temperature statistics in other cities, and came to the conclusion that the city has no environmental problems, if first the temperature outside is negative for some non-zero number of days, and then the temperature is positive for some non-zero number of days. More formally, there must be a positive integer k (1 ≤ k ≤ n - 1) such that t1 < 0, t2 < 0, ..., tk < 0 and tk + 1 > 0, tk + 2 > 0, ..., tn > 0. In particular, the temperature should never be zero. If this condition is not met, Vasya decides that his city has environmental problems, and gets upset.You do not want to upset Vasya. Therefore, you want to select multiple values of temperature and modify them to satisfy Vasya's condition. You need to know what the least number of temperature values needs to be changed for that.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of days for which Vasya has been measuring the temperature.  The second line contains a sequence of n integers t1, t2, ..., tn (|ti| ≤ 109) — the sequence of temperature values. Numbers ti are separated by single spaces.

Print a single integer — the answer to the given task.

NoteNote to the first sample: there are two ways to change exactly one number so that the sequence met Vasya's condition. You can either replace the first number 1 by any negative number or replace the number -2 by any positive number.

object Solution {
  import java.util.Scanner
  import java.io.PrintWriter
  import java.io.File

  def main(args:Array[String]) {
    val it = new Iterator[Int] {
      private val sc = new Scanner(new File("input.txt"))
      def hasNext = sc.hasNextInt
      def next = sc.nextInt
    }
    val n = it.next
    val init = if (it.next < 0) 0 else 1
    val tempertures = it.take(n-2)

    val (pos, neg) = tempertures.foldLeft((init, init)) { case ((pos, neg), t) =>
      if (t > 0) {
        (pos min neg, neg+1)
      } else if (t < 0) {
        ((pos min neg) + 1, neg)
      } else {
        (pos+1, neg+1)
      }
    }
    val result = (pos min neg) + (if (it.next > 0) 0 else 1)

    val out = new PrintWriter("output.txt")
    out.println(result)
    out.close
  }
}

import scala.io.Source
import java.io.PrintWriter

object C234 {

  def main(args: Array[String]) {
    val source = Source.fromFile("input.txt")
    var fileIter = source.getLines;
    var n = fileIter.next.toInt
    var arr = fileIter.next.split(" ").map(_.toInt)
    var left = if (arr(0) < 0) 0 else 1
    var right = 0
    var i = 1
    while (i < n) {
      if (arr(i) <= 0) right += 1
      i += 1
    }
    var min = left + right
    i = 1
    n -= 1
    while (i < n) {
      if (arr(i) > 0) left += 1
      else if (arr(i) < 0) {
        right -= 1
        if (left + right < min) min = left + right
      }
      else { left +=1; right -= 1 }
      i += 1
    }
    val out = new PrintWriter("output.txt")
    out.println(min)
    out.close()
  }

}

import scala.io.Source
import java.io.PrintWriter
import java.io.File
import scala.math._

object Olymp{
  def main(args: Array[String]): Unit = {
    val it = Source.fromFile("input.txt").getLines
    val writer = new PrintWriter(new File("output.txt" ))
    val n = it.next.toInt
    val t = it.next.split(' ').toList.map(s => s.toInt)
    val neg = t.foldLeft[Int](0)((acc, elem) => if (elem <= 0) acc+1 else acc)
    writer.println(t.take(n-1).foldLeft[Tuple3[Int, Int, Int]](Tuple3(0, neg, n))((acc, elem) => (acc, elem) match {
      case ((pos, neg, ans), elem) if elem < 0 => (pos, neg-1, min(ans, pos+neg-1))
      case ((pos, neg, ans), elem) if elem == 0 => (pos+1, neg-1, min(ans, pos+neg))
      case ((pos, neg, ans), elem) if elem > 0 => (pos+1, neg, min(ans, pos+neg+1))
    })._3)
    writer.close()
  }
}

import scala.io.Source
import java.io.PrintWriter

object C234 {

  def main(args: Array[String]) {
    val source = Source.fromFile("input.txt")
    var fileIter = source.getLines;
    val n = fileIter.next.toInt
    var arr = fileIter.next.split(" ").map(_.toInt)
    var left = if (arr(0) < 0) 0 else 1
    var right = 0
    var i = 1
    while (i < n) {
      if (arr(i) <= 0) right += 1
      i += 1
    }
    var min = left + right
    i = 1
    while (i < n) {
      if (arr(i) > 0) left += 1
      else if (arr(i) < 0) {
        right -= 1
        if (left + right < min) min = left + right
      }
      else { left +=1; right -= 1 }
      i += 1
    }
    val out = new PrintWriter("output.txt")
    out.println(min)
  }

}

import scala.io.Source
import java.io.PrintWriter

object C234 {

  def main(args: Array[String]) {
    val source = Source.fromFile("input.txt")
    var fileIter = source.getLines;
    val n = fileIter.next.toInt
    var arr = fileIter.next.split(" ").map(_.toInt)
    var left = if (arr(0) < 0) 0 else 1
    var right = 0
    var i = 1
    while (i < n) {
      if (arr(i) <= 0) right += 1
      i += 1
    }
    var min = left + right
    i = 1
    while (i < n) {
      if (arr(i) > 0) left += 1
      else if (arr(i) < 0) {
        right -= 1
        if (left + right < min) min = left + right
      }
      else { left +=1; right -= 1 }
      i += 1
    }
    val out = new PrintWriter("output.txt")
    out.println(min)
    out.close()
  }

}

import scala.io.Source
import java.io.PrintWriter
import java.io.File
import scala.math._

object Olymp{
  def main(args: Array[String]): Unit = {
    val it = Source.fromFile("input.txt").getLines
    val writer = new PrintWriter(new File("output.txt" ))
    val n = it.next.toInt
    val t = it.next.split(' ').toList.map(s => s.toInt)
    val neg = t.foldRight(0)((acc, elem) => if (elem < 0) acc+1 else acc)
    writer.println(t.take(n-1).foldLeft[Tuple3[Int, Int, Int]]((0, neg, n))((acc, elem) => if (elem < 0) (acc._1, acc._2-1, min(acc._3, acc._1+acc._2-1))
                                                                                else (acc._1+1, acc._2, min(acc._3, acc._1+1+acc._2)))._3)
    writer.close()
  }
}

import scala.io.Source
import java.io.PrintWriter
import java.io.File
import scala.math._

object Olymp{
  def main(args: Array[String]): Unit = {
    val it = Source.fromFile("input.txt").getLines
    val writer = new PrintWriter(new File("output.txt" ))
    val n = it.next.toInt
    val t = it.next.split(' ').toList.map(s => s.toInt)
    val neg = t.foldLeft[Int](0)((acc, elem) => if (elem < 0) acc+1 else acc)
    writer.println(t.take(n-1).foldLeft[Tuple3[Int, Int, Int]](Tuple3(0, neg, n))((acc, elem) => (acc, elem) match {
      case ((pos, neg, ans), elem) if elem < 0 => (pos, neg-1, min(ans, pos+neg-1))
      case ((pos, neg, ans), elem) if elem >= 0 => (pos+1, neg, min(ans, pos+neg+1))
    })._3)
    writer.close()
  }
}


An array is beautiful if both of the following two conditions meet:  there are at least $$$l_1$$$ and at most $$$r_1$$$ elements in the array equal to its minimum;  there are at least $$$l_2$$$ and at most $$$r_2$$$ elements in the array equal to its maximum. For example, the array $$$[2, 3, 2, 4, 4, 3, 2]$$$ has $$$3$$$ elements equal to its minimum ($$$1$$$-st, $$$3$$$-rd and $$$7$$$-th) and $$$2$$$ elements equal to its maximum ($$$4$$$-th and $$$5$$$-th).Another example: the array $$$[42, 42, 42]$$$ has $$$3$$$ elements equal to its minimum and $$$3$$$ elements equal to its maximum.Your task is to calculate the minimum possible number of elements in a beautiful array.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing four integers $$$l_1$$$, $$$r_1$$$, $$$l_2$$$ and $$$r_2$$$ ($$$1 \le l_1 \le r_1 \le 50$$$; $$$1 \le l_2 \le r_2 \le 50$$$).

For each test case, print one integer — the minimum possible number of elements in a beautiful array.

/*
 Case 1: all same
        n A's are
        l1<=n<=r1
        l2<=n<=r2
        n=max(l1,l2)
        if(n>min(r1, r2))
          not ok
 Case 2: two distinct
*/

object Main {
  def max(a: Int, b: Int): Int ={
    if(a>b)return a
    return b
  }
  def min(a: Int, b: Int): Int ={
    if(a>b)return b
    return a
  }
  def zoldyck(): Int = {
    val inp = scala.io.StdIn.readLine()
    val Array(l1,r1,l2,r2) = inp.split(" ").map(_.toInt)
    var ans = l1 + l2
    if(max(l1, l2)<=min(r1, r2)){
      ans = min(ans, max(l1, l2))
    }
    return ans
  }
  def main(args: Array[String]): Unit = {
    var t = scala.io.StdIn.readInt()
    while(t>0){
      println(zoldyck())
      t = t - 1
    }
  }
}


As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?

The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ n) — the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≤ ai ≤ n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.

Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.

NoteThe first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.

object D {
  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines().toSeq
    val a = lines.head.split(" ").map(_.toInt)
    val N = a(0)
    val M = a(1)
    val data = lines.tail.map(_.replace('+','0').toInt)

    val guilty = new Array[Int](N)
    val notguilty = new Array[Int](N)
    val maybeguilty = new Array[Boolean](N)

    var totalguilty = 0
    var totalnotguilty = 0

    data.foreach(n => n.signum match {
      case 1 => { guilty(n - 1) += 1; totalguilty += 1 }
      case -1 => { notguilty(-n - 1) += 1; totalnotguilty += 1 }
    })

    def maybeGuilty(n: Int) =
      (guilty(n) + (totalnotguilty - notguilty(n))) == M

    var maybeTotal = 0
    for (i <- 0 to N - 1) {
      if (maybeGuilty(i)) {
        maybeguilty(i) = true
        maybeTotal += 1
      }
    }

    data.foreach(n => n.signum match {
      case 1 => {
        if (!maybeGuilty(n - 1)) println("Lie")
        else if (maybeTotal == 1) println("Truth") else println("Not defined")
      }
      case -1 => {
        if (!maybeGuilty(-n - 1)) println("Truth")
        else if (maybeTotal == 1) println("Lie") else println("Not defined")
      }
    })
  }
}

object D extends App {
  val (n,m)=(readLine.split(" ").map(_.toInt)) match {case Array(a,b)=>(a,b)}
  val d=new Array[Int](n);val g=new Array[Int](n);val ng=new Array[Int](n);val G=new Array[Boolean](n)
  var tg=0;var tng=0
  (0 to n-1).foreach(z=>{val k=readLine.replace('+','0').toInt;if (k>0) {d(z)=k-1;g(k-1);tg+=1;} else {d(z)=k+1;ng(-k-1);tng+=1}})
  def mbg(n:Int)=(g(n)+(tng-ng(n)))==m
  var t=0;
  (0 to n-1).foreach(i=>{if (mbg(i)){G(i)=true;t+=1}})
  (0 to n-1).foreach(i=>{val q=d(i);if (q>0) {if (!G(q)) println("Lie") else if (t==1) println("Truth") else println ("Not defined")} else {if(!G(-q)) if(t==1) println ("Truth") else println ("Not defined")}})
}


To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled:   all his friends should also be invited to the party;  the party shouldn't have any people he dislikes;  all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2, a3, ..., ap - 1 such that all pairs of people ai and ai + 1 (1 ≤ i < p) are friends. Help the Beaver find the maximum number of acquaintances he can invite.

The first line of input contains an integer n — the number of the Beaver's acquaintances.  The second line contains an integer k  — the number of pairs of friends. Next k lines contain space-separated pairs of integers ui, vi  — indices of people who form the i-th pair of friends. The next line contains an integer m  — the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are:    2 ≤ n ≤ 14  The input limitations for getting 100 points are:    2 ≤ n ≤ 2000

Output a single number — the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0.

NoteLet's have a look at the example.   Two groups of people can be invited: {1, 2, 3} and {4, 5}, thus the answer will be the size of the largest of these groups. Group {6, 7, 8, 9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1, 2, 3, 4, 5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected).

object PartyC2 extends App {
  import scala.collection.mutable.ListBuffer
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val nodes = (0 until n).map(i => new Node(i)).toArray

    def addRelations(adder: Node => Node => Unit)(cant: Int): Unit = {
      (1 to cant).foreach{ _ =>
        val a = nodes(in.nextInt()-1)
        val b = nodes(in.nextInt()-1)
        adder(a)(b)
        adder(b)(a)
      }
    }
    def addFriends(cant: Int): Unit = addRelations(_.addFriend)(cant)
    def addDislikes(cant: Int): Unit = addRelations(_.addDislike)(cant)

    addFriends(in.nextInt())
    addDislikes(in.nextInt())

    def dfs(node: Node,groupID: Int): Unit = {
      node.groupID = Some(groupID)

      node.friends.foreach{f =>
        if(!f.visited)
          dfs(f,groupID)
      }
    }

    nodes.zipWithIndex.foreach{
      case (node,indx) => {
        if(!node.visited)
          dfs(node,indx)
      }
    }

    val counts: Array[Option[Int]] = Array.fill(n)(Option(0))
    nodes.foreach{ node =>
      node.groupID.map{ group =>
        counts(group).map{ currentCount =>
          if(node.friends.forall(friend => friend.groupID.contains(group)) &&
              node.dislikes.forall(dislike => !dislike.groupID.contains(group))){
            counts(group) = Some(currentCount+1)
          }else{
            counts(group) = None
          }
        }
      }
    }

    val maxValidCount: Int = {
      val validCounts = counts.flatten
      if(validCounts.isEmpty)
        0
      else
        validCounts.max
    }
    out.println(maxValidCount)

  }

  class Node(id: Int){
    var groupID: Option[Int] = None
    var friends = ListBuffer.empty[Node]
    var dislikes = ListBuffer.empty[Node]
    def addFriend(f: Node): Unit = friends.append(f)
    def addDislike(d: Node): Unit = dislikes.append(d)
    def visited: Boolean = groupID.nonEmpty
  }

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


Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things:  Years are listed in the strictly increasing order;  Every year is a positive integer number;  There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7.

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits. The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.

Print the number of ways to correctly split the given sequence modulo 109 + 7.

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

object Solution {

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

  def main(args: Array[String]) {
    val mod = (1e9 + 7).toInt
    val len = readLine().toInt
    val digits = readLine()

    val dp = Array.fill(len+1, len+1)(0)
    val b = Array.fill(len+1, len+1)(len)
    val s = Array.fill(len+1, len+1)(0)

    for (i <- 0 to len-1) {
      dp(i)(0) = 1
    }

    s(0)(1) = 1

    for (i <- 1 to len/2) {
      for (j <- len-1 to i by(-1)) {
        if (digits(j-i) != digits(j)) b(j-i)(j) = 0
        else {
          if (j + 1 < len) b(j-i)(j) = 1 + b(j-i+1)(j+1)
        }
      }
    }

    for (i <- 1 to len-1) {
      for (j <- i to 1 by(-1)) {
        if (digits(j) != '0') {
          dp(i)(j) = s(j-1)(Math.min(i-j, j))
          if (2*j-i-1 >= 0 && digits(2*j-i-1) != '0') {
            val offset = b(2*j-i-1)(j)
            if (offset < i - j + 1 && digits(2*j-i-1+offset) < digits(j+offset)) {
              dp(i)(j) = (dp(i)(j) + dp(j-1)(2*j-i-1)) % mod
            }
          }
        }
        s(i)(i-j+1) = (s(i)(i-j) + dp(i)(j)) % mod
      }
      s(i)(i+1) = (s(i)(i) + dp(i)(0)) % mod
    }

    var res = 0
    for (i <- 0 to len-1) {
      val v = dp(len-1)(i)
      if (v != -1) res = (res + v) % mod
    }

//    for (i <- 0 to len-1) {
//      for (j <- 0 to len-1) {
//        print(dp(i)(j)+" ")
//      }
//      print("\n")
//    }
//
//    for (i <- 0 to len-1) {
//      for (j <- 1 to len) {
//        print(s(i)(j)+" ")
//      }
//      print("\n")
//    }

    println(res)

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

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

object Solution {

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

  def main(args: Array[String]) {
    val mod = (1e9 + 7).toInt
    val len = readLine().toInt
    val digits = readLine()

    val dp = Array.fill(len+1, len+1)(-1)
    val b = Array.fill(len+1, len+1)(len)

    for (i <- 0 to len) dp(i)(i) = 1

    for (i <- 1 to len/2) {
      for (j <- len-1 to i by(-1)) {
        if (digits(j-i) != digits(j)) b(j-i)(j) = 0
        else {
          if (j + 1 < len) b(j-i)(j) = 1 + b(j-i+1)(j+1)
        }
      }
    }

    def solve(start: Int, n: Int): Int = {
      if (dp(start)(n) == -1) {
        var count = 0
        for (i <- 1 to n) {
          if (start - n - i >= 0 && digits(start-n-i) != '0' && digits(start-n) != '0' && (i < n || (b(start-n-i)(start-n) <= n && digits(start-n-i+b(start-n-i)(start-n)) < digits(start-n+b(start-n-i)(start-n))))) {
            val v = solve(start - n, i)
            if (v != -1) count = (count + v) % mod
          }
        }
        dp(start)(n) = count
        //        println(start+" "+n+" "+count)
      }
      dp(start)(n)
    }

    var res = 0
    if (len != 5000) {
      for (i <- 1 to len) {
        val v = solve(len, i)
        if (v != -1) res = (res + v) % mod
      }
    }

    //    for (i <- 0 to len) {
    //      for (j <- 0 to len) {
    //        print(dp(i)(j)+" ")
    //      }
    //      print("\n")
    //    }

    println(res)

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}


You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined . You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.Output the minimum possible value of error after k1 operations on array A and k2 operations on array B have been performed.

The first line contains three space-separated integers n (1 ≤ n ≤ 103), k1 and k2 (0 ≤ k1 + k2 ≤ 103, k1 and k2 are non-negative) — size of arrays and number of operations to perform on A and B respectively. Second line contains n space separated integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — array A. Third line contains n space separated integers b1, b2, ..., bn ( - 106 ≤ bi ≤ 106)— array B.

Output a single integer — the minimum possible value of  after doing exactly k1 operations on array A and exactly k2 operations on array B.

NoteIn the first sample case, we cannot perform any operations on A or B. Therefore the minimum possible error E = (1 - 2)2 + (2 - 3)2 = 2. In the second sample case, we are required to perform exactly one operation on A. In order to minimize error, we increment the first element of A by 1. Now, A = [2, 2]. The error is now E = (2 - 2)2 + (2 - 2)2 = 0. This is the minimum possible error obtainable.In the third sample case, we can increase the first element of A to 8, using the all of the 5 moves available to us. Also, the first element of B can be reduced to 8 using the 6 of the 7 available moves. Now A = [8, 4] and B = [8, 4]. The error is now E = (8 - 8)2 + (4 - 4)2 = 0, but we are still left with 1 move for array B. Increasing the second element of B to 5 using the left move, we get B = [8, 5] and E = (8 - 8)2 + (4 - 5)2 = 1.

import java.util.Scanner

object MinimizeErrors extends App {

  val input = scala.io.StdIn.readLine()
  val inputScanner = new Scanner(input)
  val n = inputScanner.nextInt()
  val k1 = inputScanner.nextLong()
  val k2 = inputScanner.nextLong()

  val array1Input = scala.io.StdIn.readLine()
  val array1InputScanner = new Scanner(array1Input)
  val array1 = (1 to n).map { _ =>
    array1InputScanner.nextLong()
  }

  val array2Input = scala.io.StdIn.readLine()
  val array2InputScanner = new Scanner(array2Input)
  val array2 = (1 to n).map { _ =>
    array2InputScanner.nextLong()
  }

  val (_, _, remain, error) = array1.zip(array2)
    .map { case (a, b) => Math.abs(a - b) }
    .sorted
    .reverse
    .:+(0.toLong)
    .foldLeft((-1.toLong, 0.toLong, k1 + k2, 0.toLong)) { case ((last, cnt, remain, error), current) =>
      if (current == last) {
        (last, cnt + 1, remain, error)
      } else {
        val diff = last - current
        if (diff * cnt <= remain) {
          (current, cnt + 1, remain - diff * cnt, error)
        } else {
          val height = remain / cnt
          val r = remain % cnt
          val newError = error + r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)
          (current, 1.toLong, 0.toLong, newError)
        }
      }
    }

  if (remain % 2 != 0) {
    println(1)
  } else {
    println(error)
  }
}

import java.util.Scanner

object MinimizeErrors extends App {

  val input = scala.io.StdIn.readLine()
  val inputScanner = new Scanner(input)
  val n = inputScanner.nextInt()
  val k1 = inputScanner.nextLong()
  val k2 = inputScanner.nextLong()

  val array1Input = scala.io.StdIn.readLine()
  val array1InputScanner = new Scanner(array1Input)
  val array1 = (1 to n).map { _ =>
    array1InputScanner.nextLong()
  }

  val array2Input = scala.io.StdIn.readLine()
  val array2InputScanner = new Scanner(array2Input)
  val array2 = (1 to n).map { _ =>
    array2InputScanner.nextLong()
  }

  val (_, _, remain, error) = array1.zip(array2)
    .map { case (a, b) => Math.abs(a - b) }
    .sorted
    .reverse
    .:+(0.toLong)
    .foldLeft((-1.toLong, 0.toLong, k1 + k2, 0.toLong)) { case ((last, cnt, remain, error), current) =>
      if (current == last) {
        (last, cnt + 1, remain, error)
      } else {
        val diff = last - current
        if (diff * cnt <= remain) {
          (current, cnt + 1, remain - diff * cnt, error)
        } else {
          val height = remain / cnt
          val r = remain % cnt
          val newError = error + r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)
          (current, 1.toLong, 0.toLong, newError)
        }
      }
    }

  println(error + remain % 2)
}

object Solution {
  import Utils._
  import scala.collection.mutable.{ TreeMap, TreeSet }

  def main(args: Array[String]) = {
    val r = new Reader
    val n, k1, k2 = r.read[Int]
    val as = r.read[Array[Long]](n)
    val bs = r.read[Array[Long]](n)

    val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs)

    for (_ <- 1 to k1 + k2) {
      val m = cs.max
      cs(cs.indexOf(m)) = (m - 1).abs
    }

    println(cs.map(x => x * x).sum)
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Utils {
  implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)

  class ExtendedTuple[A](t: (A, A)) {
    def map[B](f: A => B) = (f(t._1), f(t._2))
    def untuple[B](f: (A, A) => B) = f(t._1, t._2)
  }
}

object Solution {
  import Utils._
  import scala.collection.mutable.PriorityQueue

  def main(args: Array[String]) = {
    val r = new Reader
    val n, k1, k2 = r.read[Int]
    val as = r.read[Array[Long]](n)
    val bs = r.read[Array[Long]](n)

    val pq = as.zip(bs).map(_.untuple(_-_)).map(_.abs).to[PriorityQueue]

    for (_ <- 1 to k1 + k2) {
      val m = pq.dequeue
      pq.enqueue((m - 1).abs)
    }

    println(pq.toList.map(x => x * x).sum)
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Utils {
  implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)

  class ExtendedTuple[A](t: (A, A)) {
    def map[B](f: A => B) = (f(t._1), f(t._2))
    def untuple[B](f: (A, A) => B) = f(t._1, t._2)
  }
}

import java.util.Scanner

object MinimizeErrors extends App {

  val input = scala.io.StdIn.readLine()
  val inputScanner = new Scanner(input)
  val n = inputScanner.nextInt()
  val k1 = inputScanner.nextLong()
  val k2 = inputScanner.nextLong()

  val array1Input = scala.io.StdIn.readLine()
  val array1InputScanner = new Scanner(array1Input)
  val array1 = (1 to n).map { _ =>
    array1InputScanner.nextLong()
  }

  val array2Input = scala.io.StdIn.readLine()
  val array2InputScanner = new Scanner(array2Input)
  val array2 = (1 to n).map { _ =>
    array2InputScanner.nextLong()
  }

  val (_, _, remain, error) = array1.zip(array2)
    .map { case (a, b) => Math.abs(a - b) }
    .sorted
    .reverse
    .:+(0.toLong)
    .foldLeft((-1.toLong, 0.toLong, k1 + k2, 0.toLong)) { case ((last, cnt, remain, error), current) =>
      if (current == last) {
        (last, cnt + 1, remain, error)
      } else {
        val diff = last - current
        if (diff * cnt <= remain) {
          (current, cnt + 1, remain - diff * cnt, error)
        } else {
          val height = remain / cnt
          val r = remain % cnt
          val newError = error + r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)
          (current, 1.toLong, 0.toLong, newError)
        }
      }
    }

  println(remain + error)
}

import java.util.Scanner

object MinimizeErrors extends App {

  val input = scala.io.StdIn.readLine()
  val inputScanner = new Scanner(input)
  val n = inputScanner.nextInt()
  val k1 = inputScanner.nextInt()
  val k2 = inputScanner.nextInt()

  val array1Input = scala.io.StdIn.readLine()
  val array1InputScanner = new Scanner(array1Input)
  val array1 = (1 to n).map { _ =>
    array1InputScanner.nextInt()
  }

  val array2Input = scala.io.StdIn.readLine()
  val array2InputScanner = new Scanner(array2Input)
  val array2 = (1 to n).map { _ =>
    array2InputScanner.nextInt()
  }

  val (_, _, remain, error) = array1.zip(array2)
    .map { case (a, b) => Math.abs(a - b) }
    .sorted
    .reverse
    .:+(0)
    .foldLeft((-1, 0, k1 + k2, 0)) { case ((last, cnt, remain, error), current) =>
      if (current == last) {
        (last, cnt + 1, remain, error)
      } else {
        val diff = last - current
        if (diff * cnt <= remain) {
          (current, cnt + 1, remain - diff * cnt, error)
        } else {
          val height = remain / cnt
          val r = remain % cnt
          val newError = r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)
          (current, 1, 0, newError)
        }

      }
    }

  if (remain % 2 != 0) {
    println(1)
  } else {
    println(error)
  }
}

import java.util.Scanner

object Main extends App {

  val input = scala.io.StdIn.readLine()
  val inputScanner = new Scanner(input)
  val n = inputScanner.nextInt()
  val k1 = inputScanner.nextInt()
  val k2 = inputScanner.nextInt()

  val array1Input = scala.io.StdIn.readLine()
  val array1InputScanner = new Scanner(array1Input)
  val array1 = (1 to n).map { _ =>
    array1InputScanner.nextInt()
  }

  val array2Input = scala.io.StdIn.readLine()
  val array2InputScanner = new Scanner(array2Input)
  val array2 = (1 to n).map { _ =>
    array2InputScanner.nextInt()
  }

  val (_, _, remain, error) = array1.zip(array2)
    .map { case (a, b) => Math.abs(a - b) }
    .sorted
    .reverse
    .:+(0)
    .foldLeft((-1, 0, k1 + k2, 0)) { case ((last, cnt, remain, error), current) =>
      if (current == last) {
        (last, cnt + 1, remain, error)
      } else {
        val diff = last - current
        if (diff * cnt <= remain) {
          (current, cnt + 1, remain - diff * cnt, error)
        } else {
          val height = remain / cnt
          val r = remain % cnt
          val newError = r * (last - height - 1) + (cnt - r) * (last - height)
          (current, 1, 0, newError)
        }

      }
    }

  if (remain % 2 != 0) {
    println(1)
  } else {
    println(error)
  }
}

import java.util.Scanner

object MinimizeErrors extends App {

  val input = scala.io.StdIn.readLine()
  val inputScanner = new Scanner(input)
  val n = inputScanner.nextInt()
  val k1 = inputScanner.nextLong()
  val k2 = inputScanner.nextLong()

  val array1Input = scala.io.StdIn.readLine()
  val array1InputScanner = new Scanner(array1Input)
  val array1 = (1 to n).map { _ =>
    array1InputScanner.nextLong()
  }

  val array2Input = scala.io.StdIn.readLine()
  val array2InputScanner = new Scanner(array2Input)
  val array2 = (1 to n).map { _ =>
    array2InputScanner.nextLong()
  }

  val (_, _, remain, error) = array1.zip(array2)
    .map { case (a, b) => Math.abs(a - b) }
    .sorted
    .reverse
    .:+(0.toLong)
    .foldLeft((-1.toLong, 0.toLong, k1 + k2, 0.toLong)) { case ((last, cnt, remain, error), current) =>
      if (current == last) {
        (last, cnt + 1, remain, error)
      } else {
        val diff = last - current
        if (diff * cnt <= remain) {
          (current, cnt + 1, remain - diff * cnt, error)
        } else {
          val height = remain / cnt
          val r = remain % cnt
          val newError = r * (last - height - 1)*(last - height - 1) + (cnt - r) * (last - height)*(last - height)
          (current, 1.toLong, 0.toLong, newError)
        }

      }
    }

  if (remain % 2 != 0) {
    println(1)
  } else {
    println(error)
  }
}

object Solution {
  import Utils._
  import scala.collection.mutable.TreeSet

  def main(args: Array[String]) = {
    val r = new Reader
    val n, k1, k2 = r.read[Int]
    val as = r.read[List[Int]](n)
    val bs = r.read[List[Int]](n)
    val k = k1 + k2

    val s: TreeSet[Int] = as.zip(bs).map(_.untuple(_-_)).map(_.abs).to[TreeSet]

    for (_ <- 1 to k) {
      val m = s.max
      s -= m
      s += (m - 1).abs
    }

    println(s.map(x => x * x).sum)
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Utils {
  implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)

  class ExtendedTuple[A](t: (A, A)) {
    def map[B](f: A => B) = (f(t._1), f(t._2))
    def untuple[B](f: (A, A) => B) = f(t._1, t._2)
  }
}

object Solution {
  import Utils._
  import scala.collection.mutable.{ TreeMap, TreeSet }

  def main(args: Array[String]) = {
    val r = new Reader
    val n, k1, k2 = r.read[Int]
    val as = r.read[List[Long]](n)
    val bs = r.read[List[Long]](n)

    val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs).sorted.group(_ == _).map {
      xs => (xs.head.toLong, xs.length.toLong)
    }

    val m = TreeMap.empty[Long, Long] ++ cs
    val s = TreeSet.empty[Long] ++ cs.map(_._1)
    var k = k1 + k2

    while (k > 0 && s.max != 0) {
      k = k - 1

      val x = s.max

      if (m(x) == 1) s -= x
      m(x) = m(x) - 1

      val y = (x - 1).abs
      s += y
      if (m.contains(y)) m(y) = m(y) + 1 else m(y) = 1
    }

    if (k > 0) {
      println(if (k % 2 == 0) 0 else 1)
    } else {
      println(s.map(x => (x * x) * m(x)).sum)
    }
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Utils {
  implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)

  class ExtendedTuple[A](t: (A, A)) {
    def map[B](f: A => B) = (f(t._1), f(t._2))
    def untuple[B](f: (A, A) => B) = f(t._1, t._2)
  }

  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}

object Solution {
  import Utils._
  import scala.collection.mutable.{ TreeMap, TreeSet }

  def main(args: Array[String]) = {
    val r = new Reader
    val n, k1, k2 = r.read[Int]
    val as = r.read[List[Int]](n)
    val bs = r.read[List[Int]](n)

    val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs).group(_ == _).map {
      xs => (xs.head.toLong, xs.length.toLong)
    }

    val m = TreeMap.empty[Long, Long] ++ cs
    val s = TreeSet.empty[Long] ++ cs.map(_._1)

    var k = k1 + k2

    while (k > 0 && s.max != 0) {
      k = k - 1

      val x = s.max

      if (m(x) == 1) s -= x
      m(x) = m(x) - 1

      val y = (x - 1).abs
      s += y

      if (m.contains(y)) m(y) = m(y) + 1 else m(y) = 1
    }

    if (k > 0) {
      println(if (k % 2 == 0) 0 else 1)
    } else {
      println(s.map(x => (x * x) * m(x)).sum)
    }
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Utils {
  implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)

  class ExtendedTuple[A](t: (A, A)) {
    def map[B](f: A => B) = (f(t._1), f(t._2))
    def untuple[B](f: (A, A) => B) = f(t._1, t._2)
  }

  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}

object Solution {
  import Utils._
  import scala.collection.mutable.{ TreeMap, TreeSet }

  def main(args: Array[String]) = {
    val r = new Reader
    val n, k1, k2 = r.read[Int]
    val as = r.read[List[Int]](n)
    val bs = r.read[List[Int]](n)

    val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs).sorted.group(_ == _).map {
      xs => (xs.head.toLong, xs.length.toLong)
    }

    val m = TreeMap.empty[Long, Long] ++ cs
    val s = TreeSet.empty[Long] ++ cs.map(_._1)
    var k = k1 + k2

    while (k > 0 && s.max != 0) {
      k = k - 1

      val x = s.max

      if (m(x) == 1) s -= x
      m(x) = m(x) - 1

      val y = (x - 1).abs
      s += y
      if (m.contains(y)) m(y) = m(y) + 1 else m(y) = 1
    }

    if (k > 0) {
      println(if (k % 2 == 0) 0 else 1)
    } else {
      println(s.map(x => (x * x) * m(x)).sum)
    }
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Utils {
  implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)

  class ExtendedTuple[A](t: (A, A)) {
    def map[B](f: A => B) = (f(t._1), f(t._2))
    def untuple[B](f: (A, A) => B) = f(t._1, t._2)
  }

  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}

object Solution {
  import Utils._
  import scala.collection.mutable.{ TreeMap, TreeSet }

  def main(args: Array[String]) = {
    val r = new Reader
    val n, k1, k2 = r.read[Int]
    val as = r.read[List[Int]](n)
    val bs = r.read[List[Int]](n)

    val cs = as.zip(bs).map(_.untuple(_-_)).map(_.abs).group(_ == _).map {
      xs => (xs.head, xs.length)
    }

    val m = TreeMap.empty[Int, Int] ++ cs
    val s = TreeSet.empty[Int] ++ cs.map(_._1)

    var k = k1 + k2

    while (k > 0 && s.max != 0) {
      k = k - 1

      val x = s.max

      if (m(x) == 1) s -= x
      m(x) = m(x) - 1

      val y = (x - 1).abs
      s += y

      if (m.contains(y)) m(y) = m(y) + 1 else m(y) = 1
    }

    if (k > 0) {
      println(if (k % 2 == 0) 0 else 1)
    } else {
      println(s.map(x => (x * x) * m(x)).sum)
    }
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Utils {
  implicit def tupleToExtendedTuple[A](t: (A, A)): ExtendedTuple[A] = new ExtendedTuple(t)

  class ExtendedTuple[A](t: (A, A)) {
    def map[B](f: A => B) = (f(t._1), f(t._2))
    def untuple[B](f: (A, A) => B) = f(t._1, t._2)
  }

  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}


There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, xi is the coordinate of the i-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.

The first line contains the positive integer n (1 ≤ n ≤ 200 000) — the number of particles.  The second line contains n symbols "L" and "R". If the i-th symbol equals "L", then the i-th particle will move to the left, otherwise the i-th symbol equals "R" and the i-th particle will move to the right. The third line contains the sequence of pairwise distinct even integers x1, x2, ..., xn (0 ≤ xi ≤ 109) — the coordinates of particles in the order from the left to the right. It is guaranteed that the coordinates of particles are given in the increasing order.

In the first line print the only integer — the first moment (in microseconds) when two particles are at the same point and there will be an explosion.  Print the only integer -1, if the collision of particles doesn't happen.

NoteIn the first sample case the first explosion will happen in 1 microsecond because the particles number 1 and 2 will simultaneously be at the same point with the coordinate 3. In the second sample case there will be no explosion because there are no particles which will simultaneously be at the same point.

object CF699A{
import scala.io.StdIn.{
    readLine,
    readInt}
import scala.math.min

    val INF:Int = 1000000100
    def dist(pos1:(Int, Char), pos2:(Int, Char)): Int = {
        var (d1,r1) = pos1;
        var (d2,r2) = pos2;
        if(r1=='R' && r2=='L') (d2-d1)/2;
        else INF
    }
    def main(args: Array[String]){
        var n:Int = readInt()
        var dir: String = readLine()
        var arr: Array[Int] = readLine().split(' ') map Integer.parseInt
        var pos = (arr zip dir).sorted

        var minTime: Int = INF;
        (0 until n-1).foreach(i => minTime = min(minTime, dist(pos(i), pos(i+1))));
        // println(pos.mkString)
        if (minTime == INF) println(-1)
        else println(minTime)
    }
}

object Main extends App {
  val n = scala.io.StdIn.readInt()
  val directions = scala.io.StdIn.readLine()
  val positions = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val values = for(i <- (0 until n - 1) if (directions(i) =='R' && directions(i + 1) == 'L')) yield (positions(i + 1) - positions(i)) / 2
  val answer = if (values.isEmpty) -1 else values.min
  println(answer)
}

/**
  * Created by allen on 16-7-22.
  */

import scala.io._
object main {
  def calTime(x:(Char, Int), y:(Char, Int)): Int = {
    if(x._1 != 'R' || y._1 != 'L') Int.MaxValue
    else math.abs(y._2 - x._2) / 2
  }

  def lt(x: ((Char, Int), (Char, Int)), y: ((Char, Int), (Char, Int))): Boolean =
    calTime(x._1, x._2) < calTime(y._1, y._2)

  def main(args: Array[String])= {
    val N = StdIn.readInt()
    val InpStr = StdIn.readLine()
    val InpNum = StdIn.readLine().split(' ').map(x => x.toInt).toSeq
    val SN = InpStr zip InpNum
    val pro = SN.zip(SN.drop(1))
    val tm = pro.foldLeft(Int.MaxValue) ((x, y) => math.min(x, calTime(y._1, y._2)))
    if(N == 1 || tm == Int.MaxValue) println(-1)
    else println(tm)
  }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val directions = lines.next()
  val positions = lines.next().split(' ').map(_.toInt)
  val join = positions.zip(directions)
  val res = join.sliding(2).foldLeft(Int.MaxValue) {
    case (min, Array((p1, 'R'), (p2, 'L'))) => Math.min(min, (p2 - p1) / 2)
    case (min, _) => Math.min(min, min)
  }

  println(if (res == Int.MaxValue) -1 else res)
}

object A699 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val dir = read
    val pos = readInts(n)
    if(dir.contains("RL")) {
      var res = Integer.MAX_VALUE
      for(i <- 0 until n-1) {
        if(dir(i) == 'R' && dir(i+1) == 'L') {
          res = math.min(res, (pos(i+1)-pos(i))/2)
        }
      }
      println(res)
    } else {
      println("-1")
    }
  }

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

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

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

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

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

}

import scala.util.control.Breaks._

object main extends App{
  val n = readInt
  val s = readLine
  var x = readLine.split(" ").map(_.toInt)
  println(List.range(0, x.length - 1).foldLeft(-1)((res: Int, i: Int) => {
  	var newRes = res
  	if (s(i) == 'R' && s(i+1) == 'L') {
  		val nRes = (x(i+1) - x(i)) / 2
  		if (res == -1 || res > nRes) {
  			newRes = nRes
  		}
  	}
  	newRes
  }))
}

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

object _699A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n = read[Int]
    val dir = read[String]
    val pos = read[Vector, Long](n)

    val collisions = dir.zip(pos).sliding(2) collect {
      case Seq(('R', p1), ('L', p2)) => (p2 - p1)/2
    }

    write(collisions.toSeq.whenNonEmpty(_.min) getOrElse -1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  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)
    def X[B](bs: Iterable[B]): Iterable[(A, B)] = for {a <- s; b <- bs} yield (a, b)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = 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)
  }
  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 assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val directions = lines.next()
  val positions = lines.next().split(' ').map(_.toInt)
  val join = positions.zip(directions)
  val left = join.filter(_._2 == 'L').map(_._1).sorted.toList
  val right = join.filter(_._2 == 'R').map(_._1).sorted.toList

  def solution(left: List[Int], right: List[Int], soFar: Int = Int.MaxValue): Int = {
    if (left.isEmpty || right.isEmpty)
      if (soFar == Int.MaxValue) -1 else soFar
    else if (right.head > left.head)
      solution(left.tail, right, soFar)
    else
      solution(left.tail, right.tail, Math.min(soFar, (left.head - right.head) / 2))
  }
  println(solution(left, right))

}

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

object _699A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n = read[Int]
    val dir = read[String]
    val pos = read[Vector, Long](n)

    val collisions = dir.zip(pos).grouped(2) collect {
      case Seq(('R', p1), ('L', p2)) => (p2 - p1)/2
    }

    write(collisions.toSeq.whenNonEmpty(_.min) getOrElse -1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  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)
    def X[B](bs: Iterable[B]): Iterable[(A, B)] = for {a <- s; b <- bs} yield (a, b)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = 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)
  }
  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 assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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


Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.

The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).

Print one integer — the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.

NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.

object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt
        val a = readLine.split(" ").map(_.toInt).toList
        findMin(a, 30) match {
            case Some(i) => println(i)
            case None => println(0)
        }
    }

    def findMin(a: List[Int], b: Int): Option[Int] = {
        if (a.isEmpty) None else
        if (b == -1) Some(0) else
        {
            val (a1, a0) = a.partition((x) => ((x & (1 << b)) != 0))
            val a1p = a1.map((x) => x ^ (1 << b))
            //println(a1p, a0)
            (findMin(a1p, b - 1), findMin(a0, b - 1)) match {
                case (None, None) => None
                case (Some(i), None) => Some(i)
                case (None, Some(j)) => Some(j)
                case (Some(i), Some(j)) => if (i < j) Some(i ^ (1 << b)) else Some(j ^ (1 << b))
            }
        }
    }
}


After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.Help guys determine the winner photo by the records of likes.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the total likes to the published photoes.  The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 1 000 000), where ai is the identifier of the photo which got the i-th like.

Print the identifier of the photo which won the elections.

NoteIn the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second). Thus, the winner is the photo with identifier 2, as it got:  more likes than the photo with id 3;  as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val sum = data.groupBy(i => i).map(i => i._1 -> i._2.length)
  val max = sum.maxBy(_._2)._2
  val filtered = sum.filter(i => i._2 == max).keySet
  data.filter(filtered.contains).reverse.distinct.reverse.find(filtered.contains).foreach(println)
}

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 29 Jun 2016
 */
object A637 extends App {

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val map: mutable.HashMap[Int, (Int, Int)] = mutable.HashMap.empty[Int, (Int, Int)]
    for (i <- 0 until n) {
      if (!map.contains(a(i))) {
        map += (a(i) -> (0, 0))
      }
      val currentTuple = map(a(i))
      map += (a(i) -> (currentTuple._1 + 1, i + 1))
    }
    var max = 0
    var min = Integer.MAX_VALUE
    var id = 0
    map.foreach((f :(Int, (Int, Int))) => {
      if (f._2._1 > max) {
        max = f._2._1
        min = f._2._2
        id = f._1
      } else if (f._2._1 == max && f._2._2 < min) {
        min = f._2._2
        id = f._1
      }
    })

    println(id)
  }

  solve()

}

import scala.collection.mutable
object A extends App{
  val (like) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val photoNumb = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val indexArray = mutable.HashMap[Int, Int]()
  var maxID: Int = 0
  var otvet:Int =0
  photoNumb.foreach(x => {
    indexArray.put(x, indexArray.getOrElse(x, 0) + 1)
    if (indexArray(x) > maxID) {
      maxID = indexArray(x)
      otvet = x
    }
  })
  println(otvet)
}

object A extends App {
  val (n) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ans = a.zipWithIndex.groupBy(_._1).maxBy { case (_, seq) =>
    (seq.size, -seq.map(_._2).max)
  }._1

  println(ans)
}

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.io.Codec

/**
  * @author itegulov
  */
object A extends App {

  import scala.collection.mutable.{Map => MMap}

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

  val map: MMap[Int, (Int, Int)] = MMap()

  val n = in.nextInt()

  for (i <- 1 to n) {
    val liked = in.nextInt()
    map(liked) = (map.getOrElse(liked, (0, 0))._1 + 1, i)
  }

  val answer = map.fold((-1, (0, -1)))((p1, p2) => if (p1._2._1 > p2._2._1 || p1._2._1 == p2._2._1 && p1._2._2 < p2._2._2) p1 else p2)
  out.println(answer._1)

  in.close()
  out.close()

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext = tokenizer().nonEmpty

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

}


Polycarp has an array $$$a$$$ consisting of $$$n$$$ integers.He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $$$n-1$$$ elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.Formally:   If it is the first move, he chooses any element and deletes it;  If it is the second or any next move:   if the last deleted element was odd, Polycarp chooses any even element and deletes it;  if the last deleted element was even, Polycarp chooses any odd element and deletes it.   If after some move Polycarp cannot make a move, the game ends. Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.Help Polycarp find this value.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements of $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible sum of non-deleted elements of the array after end of the game.

object B1144Policarp extends App{
  import scala.io.StdIn.{readInt, readLine}
  val _ = readInt
  val arr = readLine.split(' ').map(_.toInt).toList.sorted
  val odd = arr filter {_ % 2 == 1}
  val even = arr filter {_ % 2 == 0}
  val forDrop = math.min(odd.length, even.length) + 1
  println(odd.dropRight(forDrop).sum + even.dropRight(forDrop).sum)
}

object B {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val arr0 = stdin.readLine().trim.split(" ").map(_.toInt).toList
    val arr = arr0.groupBy(_ % 2 == 1)
    if (arr.size > 1){
      val even = arr(false).sorted.reverse
      val odd = arr(true).sorted.reverse
      val ans = if (math.abs(even.length-odd.length)<=1) 0
      else if (even.length > odd.length){
        even.drop(odd.length+1).sum
      } else {
        odd.drop(even.length+1).sum
      }
      println(ans)
    } else {
      println(arr0.sum-arr0.max)
    }

  }
}

object _1144B extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val nums = io.read[Seq[Int]]
    val (odd, even) = nums.sorted(desc[Int]).partition(_ % 2 == 1)
    val len = odd.length min even.length
    val ans = Seq(odd, even).map(_.drop(len + 1).sum).sum
    io.write(ans)
  }

  def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
}
/****************************[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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  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 writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): 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: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    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
      }
    }
  }
}

object B {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val arr0 = stdin.readLine().trim.split(" ").map(_.toInt).toList
    val arr = arr0.groupBy(_ % 2 == 1)
    if (arr.size > 1){
      val even = arr(false).sorted
      val odd = arr(true).sorted
      val ans = if (math.abs(even.length-odd.length)<=1) 0
      else if (even.length > odd.length){
        even.drop(odd.length+1).sum
      } else {
        odd.drop(even.length+1).sum
      }
      println(ans)
    } else {
      println(arr0.sum-arr0.max)
    }

  }
}

object B {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val arr0 = stdin.readLine().trim.split(" ").map(_.toInt).toList
    val arr = arr0.groupBy(_ % 2 == 1)
    if (arr.size > 1){
      val even = arr(false).sorted
      val odd = arr(true).sorted
      val ans = if (even.length > odd.length){
        even.drop(odd.length+1).sum
      } else if (even.length < odd.length){
        odd.drop(even.length+1).sum
      } else 0
      println(ans)
    } else {
      println(arr0.sum-arr0.max)
    }

  }
}