The problem uses a simplified TCP/IP address model, please read the statement carefully.An IP address is a 32-bit integer, represented as a group of four decimal 8-bit integers (without leading zeroes), separated by commas. For example, record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In the given problem an arbitrary group of four 8-bit integers is a correct IP address.Our hero Polycarpus still works as a system administrator in some large corporation. He likes beautiful IP addresses. To check if some IP address is beautiful, he should do the following:  write out in a line four 8-bit numbers of the IP address, without the commas;  check if the resulting string is a palindrome. Let us remind you that a palindrome is a string that reads the same from right to left and from left to right.For example, IP addresses 12.102.20.121 and 0.3.14.130 are beautiful (as strings "1210220121" and "0314130" are palindromes), and IP addresses 1.20.20.1 and 100.4.4.1 are not.Polycarpus wants to find all beautiful IP addresses that have the given set of digits. Each digit from the set must occur in the IP address at least once. IP address must not contain any other digits. Help him to cope with this difficult task.

The first line contains a single integer n (1 ≤ n ≤ 10) — the number of digits in the set. The second line contains the set of integers a1, a2, ..., an (0 ≤ ai ≤ 9). It is guaranteed that all digits in the set are distinct.

In the first line print a single integer k — the number of beautiful IP addresses that contain the given set of digits. In the following k lines print the IP addresses, one per line in the arbitrary order.

import io.Source
import java.io.PrintWriter
import scala.collection.mutable.ArrayBuffer

object CF292C {

  val pow10 = Array(1, 10, 100)
  var ds = Array(0)
  var ans = ArrayBuffer.empty[Array[Int]]

  def gen2(ar: Array[Int], id: ArrayBuffer[Int], mul: ArrayBuffer[Int], i: Int, mask: Int) {
    val j = id.length - i - 1
    if (i > j) {
      if (Integer.bitCount(mask) == ds.length) {
        ans += ar.clone()
      }
    } else if (Integer.bitCount(mask) + (j - i) / 2 + 1 >= ds.length) {
      for (d <- ds if d != 0 || (i > 0 && id(i) == id(i - 1) || mul(i) == 1) && (id(j) == id(j - 1) || mul(j) == 1)) {
        ar(id(i)) += d * mul(i)
        if (i != j) {
          ar(id(j)) += d * mul(j)
        }
        if (ar(id(i)) < 256 && ar(id(j)) < 256) {
          gen2(ar, id, mul, i + 1, mask | (1 << d))
        }
        ar(id(i)) -= d * mul(i)
        if (i != j) {
          ar(id(j)) -= d * mul(j)
        }
      }
    }
  }

  def gen(lens: Array[Int], i: Int) {
    if (i == lens.length) {
      val id = ArrayBuffer.empty[Int]
      val mul = ArrayBuffer.empty[Int]
      for (i <- 0 until 4; j <- 0 until lens(i)) {
        id += i
        mul += pow10(lens(i) - j - 1)
      }
      gen2(Array.ofDim[Int](4), id, mul, 0, 0)
    } else {
      for (v <- 1 to 3) {
        lens(i) = v
        gen(lens, i + 1)
      }
    }
  }

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    ds = Array.fill(n)(in().toInt)
    gen(Array.ofDim[Int](4), 0)
    out.println(ans.size)
    for (a <- ans) {
      out.println(a.mkString("."))
    }
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      def run() {
        val in: In = new In(Source.fromInputStream(System.in))
        val out: PrintWriter = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "thread", 64000000).run()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

import io.Source
import java.io.PrintWriter
import scala.collection.mutable.ArrayBuffer

object CD292C {

  val pow10 = Array(1, 10, 100)
  var ds = Array(0)
  var ans = ArrayBuffer.empty[Array[Int]]

  def gen2(ar: Array[Int], id: ArrayBuffer[Int], mul: ArrayBuffer[Int], i: Int, mask: Int) {
    val j = id.length - i - 1
    if (i > j) {
      if (Integer.bitCount(mask) == ds.length) {
        ans += ar.clone()
      }
    } else if (Integer.bitCount(mask) + (j - i) / 2 + 1 >= ds.length) {
      for (d <- ds if d != 0 || i > 0 && id(i) == id(i - 1) && id(j) == id(j - 1)) {
        ar(id(i)) += d * mul(i)
        if (i != j) {
          ar(id(j)) += d * mul(j)
        }
        if (ar(id(i)) < 256 && ar(id(j)) < 256) {
          gen2(ar, id, mul, i + 1, mask | (1 << d))
        }
        ar(id(i)) -= d * mul(i)
        if (i != j) {
          ar(id(j)) -= d * mul(j)
        }
      }
    }
  }

  def gen(lens: Array[Int], i: Int) {
    if (i == lens.length) {
      val id = ArrayBuffer.empty[Int]
      val mul = ArrayBuffer.empty[Int]
      for (i <- 0 until 4; j <- 0 until lens(i)) {
        id += i
        mul += pow10(lens(i) - j - 1)
      }
      gen2(Array.ofDim[Int](4), id, mul, 0, 0)
    } else {
      for (v <- 1 to 3) {
        lens(i) = v
        gen(lens, i + 1)
      }
    }
  }

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    ds = Array.fill(n)(in().toInt)
    gen(Array.ofDim[Int](4), 0)
    out.println(ans.size)
    for (a <- ans) {
      out.println(a.mkString("."))
    }
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      def run() {
        val in: In = new In(Source.fromInputStream(System.in))
        val out: PrintWriter = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "thread", 64000000).run()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}


Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.  Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.

The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.

On the single line of the output print the number of groups of magnets.

NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.

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

object Main {

	def main(args: Array[String]) {
		val n = in.rdInt
		var ans = 1
		var last = in.next
		for (i <- 2 to n) {
			val cur = in.next
			if (last != cur) ans+=1
			last = cur
		}
		println(ans)
	}

	object in {
		val in = new BufferedReader(new InputStreamReader(System.in))
		var st = new StringTokenizer("")

		def next : String = {
			while (!st.hasMoreTokens) {
				val line = in.readLine
				if (line == null) return null
				eat(line)
			}
			st.nextToken
		}

		def FastReader = eat("")
		def eat(s : String) = st = new StringTokenizer(s)
		def rdInt = next.toInt
		def rdLong = next.toLong
		def rdDouble = next.toDouble
	}

}

import scala.io.StdIn

object Main extends App {
  val n = StdIn.readInt()
  var prev = StdIn.readLine()
  var count = 1

  for (_ <- 2 to n) {
    val next = StdIn.readLine()
    if (next.head == prev.last) count += 1
    prev = next
  }

  println(count)
}

object CF0344A extends App {

  val n = readInt()
  var count = 0
  var str = "\0"
  (1 to n) foreach(k => {
    val s = readLine()
    if(str == "\0" || s != str) {
      count += 1
      str = s
    }
  })

  println(count)
}

object Magnets {
    def main(arg: Array[String]) {
        val changes = (0 until readInt()).
        map(x=>readInt).
        sliding(2,1).
        map(l=>l.distinct.length).
        filter(_ > 1).
        length
        println(changes + 1)
    }
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val first = in.next()
  println(Range(0, n - 1).map(_ => in.next()).foldLeft((first, 1)) {
    case((prev, count), el) if prev == el => (el, count)
    case((prev, count), el) => (el, count + 1)
  }._2)
}

import scala.io.StdIn

object Magnets extends App {

  val count = StdIn.readLine().toInt

  val magnets = new collection.mutable.ArrayBuffer[String]()
  for (i <- 0 until count) {
    magnets += StdIn.readLine()
  }
  print(impl(magnets.toArray))

  def impl(magnets: Array[String]): Int = {
    var groups = 1
    var prev = magnets(0)

    for (magnet <- magnets) {
      if (magnet != prev) {
        groups += 1
        prev = magnet
      }
    }

    groups
  }
}

import scala.collection.JavaConversions._
import scala.collection.mutable.ArraySeq

object Codeforces344A {
    def main(args: Array[String]) {
        val n = scala.io.StdIn.readLine().toInt
        var lastChar = scala.io.StdIn.readLine().charAt(1)
        var groups = 1
        for (i <- 0 until n-1) {
            val m = scala.io.StdIn.readLine()
            if (m.charAt(0) == lastChar)
                groups += 1
            lastChar = m.charAt(1)
        }
        println(groups)
    }
}

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

        val n = readInt()
        var pole1 = readLine()
        var res = 0
        for(i <- 1 to n){
          val pole = readLine()
          if(pole != pole1){
            res += 1
            pole1 = pole
          }
        }

        println(res)

    }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {

  def main(args: Array[String]) {

    val n = readInt().toInt
    val magnets = for(i <- 0 until n) yield readLine.trim

    var islands = 0
    for(i <- 0 until n - 1) {
      islands += (if (magnets(i)(1) == magnets(i+1)(0)) 1 else 0)
    }

    println(islands + 1)
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {

  def main(args: Array[String]) {

    val n = readInt().toInt
    var islands = 0
    var magnets = ArrayBuffer[String]()

    for(i <- 0 until n) {
      val magnet = readLine.trim
      magnets += magnet
    }

    for(i <- 0 until n - 1) {
      if (magnets(i)(1) == magnets(i+1)(0)) islands += 1
    }

    println(islands + 1)
  }
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = new Array[String](n)
    for(i <- 0 until n) {
      input(i) = scala.io.StdIn.readLine
    }
    var res = 1
    for(i <- 1 until n) {
      if(input(i)(0) == input(i-1)(1)) {
        res += 1
      }
    }
    println(res)
  }
}

import scala.collection._

object A extends App {

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

  val n = readString.toInt
  var r = 0
  var prev = ""

  for (i <- 0 until n) {
    val s = readString
    if (s != prev) {
      r += 1
      prev = s
    }
  }

  println(r)
}

import scala.collection._

object A extends App {

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

  val n = readString.toInt
  var r = 0
  var prev = ""

  var i = 0
  while (i < n) {
    i += 1
    val s = readString
    if (!s.equals(prev)) {
      r += 1
      prev = s
    }
  }

  println(r)
}

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

object P344A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt
  sc.nextLine
  val MS = List.fill(N)(sc.nextLine)

  def solve(): Unit = {

    @tailrec
    def loop(acc: Int, last: String, ms: List[String]): Int = ms match {
        case Nil     => acc
        case x :: xs => if (x == last) loop(acc, x, xs)
                        else loop(acc + 1, x, xs)
    }

    out.println(loop(0, "", MS))
  }

  solve
  out.close
}

object Magnets {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt();
	  var current = scanner.nextInt();
	  var nbGroups = 1;
		for (i <- 2 to n) {
		  val previous = current
		  current = scanner.nextInt();
		  if (current != previous)
		    nbGroups += 1
		}
		println(nbGroups)
	}
}

object Main {
  def main(args: Array[String]) {
    val num = readInt()
    var groups = 0
    var prev = "00"
    for(_ <- 1 to num) {
      val cur = readLine
      if (cur != prev) {
        groups += 1
        prev = cur
      }
    }
    println(groups)
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object Magnets {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def main(args: Array[String]) {
     val n = readInt
     val magnets = for {
       i <- 1 to n
       m = readLine
     } yield m
     println(magnets.zipWithIndex.foldLeft(0)
      { case (g,(s,i)) => if (i < n -1 && s(1) != magnets(i+1)(0)) g else g + 1})
   }

}


Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≤ ti ≤ 10). Of course, one number can be assigned to any number of customers."Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1,  - 1, 1,  - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.Of course, a client can't form a couple with him/herself.

The first line of the input data contains an integer n (1 ≤ n ≤ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 ≤ ti ≤ 10), ti — is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.

Print the number of couples of customs with opposite t. The opposite number for x is number  - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

NoteIn the first sample the couples of opposite clients are: (1,2), (1,5) и (3,4).In the second sample any couple of clients is opposite.

import java.util.Scanner
import scala.collection.mutable.Map

object Opposites {

  val scanner = new Scanner(System.in)
  val c = scanner.nextInt();

  val input = (1 to c) map {i => scanner.nextInt()}

  def main(args: Array[String]) {
    var map = Map[Long,Long]()
    for (i <- input) {
      map += (i.toLong -> (1l + ( if (map.contains(i))  map(i).toLong else 0l)))
    }

    var sum:Long = if (map contains(0)) map(0) else 0;
    sum = (0l/:(1l until sum)) {(sum:Long,i:Long) => sum+i}

    map = map.filter({entry => entry._1 != 0})

    sum += ((0l/:map) {(sum,entry)=>
      sum + {if (map.contains(-entry._1)) entry._2 * map(-entry._1) else 0 } }) / 2

      println(sum)
  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toLong
  var zeros = 0l
  val plus = Array.ofDim[Int](10)
  val minus = Array.ofDim[Int](10)
  in.next().split(' ').map(_.toInt).foreach {
    case (0) => zeros += 1
    case i if i < 0 => minus(-i - 1) += 1
    case i => plus(i - 1) += 1
  }
  val r = plus.zip(minus).foldLeft(0l) {
    case (soFar, (0, second)) => soFar
    case (soFar, (first, 0)) => soFar
    case (soFar, (first, second)) => soFar + first.toLong * second
  } + (zeros - 1) * zeros / 2

  println(r)
}

import scala.collection.mutable.HashMap;

object Main {

    def main(args: Array[String]) {
        val n = nextInt
        val a = for (i <- 1 to n) yield nextInt
        val map = HashMap[Int,Long]()
        a.foreach(x => map.put(x, map.getOrElse(x, 0L) + 1L))
        val ans = a.map(x => map.getOrElse(-x, 0L) - (if (x==0) 1 else 0)).sum
        println(ans / 2)
    }

    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
    var st = new java.util.StringTokenizer("");

    def next() = {
        while (!st.hasMoreTokens())
            st = new java.util.StringTokenizer(in.readLine());
        st.nextToken();
    }

    def nextInt() = java.lang.Integer.parseInt(next());
    def nextDouble() = java.lang.Double.parseDouble(next());
    def nextLong() = java.lang.Long.parseLong(next());
}

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

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

  val N = sc.nextInt
  val ts: Map[Long, Long] = List.fill(N)(sc.nextLong).groupBy(identity[Long]).map(x => (x._1, x._2.length.toLong)).withDefaultValue(0L)

  val n0: Long = ts(0L)
  val answer: Long = ts.keys.filter(_ > 0L).toList.map(x => ts(x) * ts(-x)).sum + n0 * (n0 - 1) / 2

  out.println(answer)
  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  val n = readInt
  val a = readInts
  val grouped = a.groupBy(x => x).mapValues(_.length)
  def ans = (a.map(x => grouped.getOrElse(-x, 0)).foldLeft(0L)(_ + _) - grouped.getOrElse(0, 0)) / 2

  def main(a: Array[String]) {
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)
    val r = (1 to 10).map(i => map.getOrElse(i, 0).toLong * map.getOrElse(-i, 0).toLong).sum + (map.getOrElse(0, 0).toLong - 1) * map.getOrElse(0, 0).toLong / 2
    println(r)
  }
}

import java.util.Scanner
import scala.collection.mutable.Map
object Opposites {

  val scanner = new Scanner(System.in)
  val c = scanner.nextInt();
  val input = (1 to c) map {i => scanner.nextInt()}

  def main(args: Array[String]) {
    var map = Map[Int,Int]()
    for (i <- input) {
      map += (i -> (1 + ( if (map.contains(i))  map(i) else 0)))
    }

    var sum = if (map contains(0)) map(0) else 0;
    sum = (0/:(1 until sum)) {(sum,i) => sum+i}

    map = map.filter({entry => entry._1 != 0})

    sum += ((0/:map) {(sum,entry)=>
      sum + {if (map.contains(-entry._1)) entry._2 * map(-entry._1) else 0 } }) / 2

      println(sum)

  }

}

import java.util.Scanner
import scala.collection.mutable.Map
object Opposites {

  val scanner = new Scanner(System.in)
  val c = scanner.nextInt();
  val input = (1 to c) map {i => scanner.nextInt()}

  def main(args: Array[String]) {
    var map = Map[Int,Int]()
    for (i <- input) {
      map += (i -> (1 + ( if (map.contains(i))  map(i) else 0)))
    }

    var sum:Long = if (map contains(0)) map(0) else 0;
    sum = (0l/:(1l until sum)) {(sum:Long,i:Long) => sum+i}

    map = map.filter({entry => entry._1 != 0})

    sum += ((0/:map) {(sum,entry)=>
      sum + {if (map.contains(-entry._1)) entry._2 * map(-entry._1) else 0 } }) / 2

      println(sum)

  }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toLong
  var zeros = 0
  val plus = Array.ofDim[Int](10)
  val minus = Array.ofDim[Int](10)
  in.next().split(' ').map(_.toInt).foreach {
    case (0) => zeros += 1
    case i if i < 0 => minus(-i - 1) += 1
    case i => plus(i - 1) += 1
  }
  val r = plus.zip(minus).foldLeft(0l) {
    case (soFar, (0, second)) => soFar
    case (soFar, (first, 0)) => soFar
    case (soFar, (first, second)) => soFar + first.toLong * second
  } + (zeros - 1) * zeros / 2

  println(r)
}

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

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

  val N = sc.nextInt
  val ts = List.fill(N)(sc.nextInt).groupBy(identity[Int]).map(x => (x._1, x._2.length)).withDefaultValue(0)

  val n0 = ts(0)

  val answer: Int = ts.keys.filter(_ > 0).map(x => ts(x) * ts(-x)).sum + n0 * (n0 - 1) / 2

  out.println(answer)
  out.close
}

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

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

  val N = sc.nextLong
  val ts: Map[Long, Long] = List.fill(N.toInt)(sc.nextLong).groupBy(identity[Long]).map(x => (x._1, x._2.length.toLong)).withDefaultValue(0L)

  val n0 = ts(0)

  val answer: Long = ts.keys.filter(_ > 0).map(x => ts(x) * ts(-x)).sum + n0 * (n0 - 1) / 2

  out.println(answer)
  out.close
}

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

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

  val N = sc.nextInt
  val ts = List.fill(N)(sc.nextLong).groupBy(identity[Long]).map(x => (x._1, x._2.length)).withDefaultValue(0)

  val n0 = ts(0)

  val answer: Long = ts.keys.filter(_ > 0).map(x => ts(x) * ts(-x)).sum + n0 * (n0 - 1) / 2

  out.println(answer)
  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  val n = readInt
  val a = readInts
  val grouped = a.groupBy(x => x).mapValues(_.length)
  def ans = (a.map(x => grouped.getOrElse(-x, 0)).sum - grouped.getOrElse(0, 0)) / 2

  def main(a: Array[String]) {
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)
    val r = (1 to 10).map(i => map.getOrElse(i, 0) * map.getOrElse(-i, 0)).sum + (map.getOrElse(0, 0) - 1) * map.getOrElse(0, 0) / 2
    println(r)
  }
}


Vanya is doing his maths homework. He has an expression of form , where x1, x2, ..., xn are digits from 1 to 9, and sign  represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.

The first line contains expression s (1 ≤ |s| ≤ 5001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs  +  and  * .  The number of signs  *  doesn't exceed 15.

In the first line print the maximum possible value of an expression.

NoteNote to the first sample test. 3 + 5 * (7 + 8) * 4 = 303.Note to the second sample test. (2 + 3) * 5 = 25.Note to the third sample test. (3 * 4) * 5 = 60 (also many other variants are valid, for instance, (3) * 4 * 5 = 60).

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val s=nextString.toCharArray
    var h=Array.ofDim[Long](31,3)
    var state=0
    var cs=0L
    var ch=0L
    var p=0
    for(i<-0 until s.length/2){
      var t=(s(i*2)-'0').toLong
      if(s(i*2+1)=='+'){
        if(state==0){
          cs+=t
        }
        else{
          h(p)(0)=cs*t
          h(p)(1)=ch
          h(p)(2)=t
          cs=0L
          ch=1L
          p+=1
          state=0
        }
      }
      else{
        if(state==1){
          cs*=t
        }
        else{
          if(cs!=0){
            h(p)(0)=cs
            h(p)(1)=cs
            h(p)(2)=cs
            p+=1
          }
          cs=t
          ch=t
          state=1

        }
      }
    }
    val t=(s(s.length-1)-'0').toLong
    if(state==0){
      cs+=t
      h(p)(0)=cs
      h(p)(1)=cs
      h(p)(2)=cs
    }else{
      cs*=t
      h(p)(0)=cs
      h(p)(1)=ch
      h(p)(2)=t
    }

    p+=1
    var sum0=0L
    for(i<-0 until p){
      sum0+=h(i)(0)
    }
    var max=sum0
    for(i<-0 until p-1){
      val l=h(i)(0)/h(i)(2)
      val l0=h(i)(2)
      for(j<-i+1 until p){
        val r=h(j)(0)/h(j)(1)
        val r0=h(j)(1)
        var sumc=0L
        for(k<-i+1 until j){
          sumc+=h(k)(0)
        }
        val sum=sum0-sumc-h(i)(0)-h(j)(0)+l*r*(r0+l0+sumc)

        if(sum>max){
          max=sum

        }
      }
    }
    out.println(max)
    //code ends here
    out.flush
    out.close
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val s=nextString.toCharArray
    var h=Array.ofDim[Int](31,3)
    var state=0
    var cs=0
    var ch=0
    var p=0
    for(i<-0 until s.length/2){
      var t=s(i*2)-'0'
      if(s(i*2+1)=='+'){
        if(state==0){
          cs+=t
        }
        else{
          h(p)(0)=cs*t
          h(p)(1)=ch
          h(p)(2)=t
          cs=0
          ch=1
          p+=1
          state=0
        }
      }
      else{
        if(state==1){
          cs*=t
        }
        else{
          if(cs!=0){
            h(p)(0)=cs
            h(p)(1)=cs
            h(p)(2)=cs
            p+=1
          }
          cs=t
          ch=t
          state=1

        }
      }
    }
    val t=s(s.length-1)-'0'
    if(state==0){
      cs+=t
      h(p)(0)=cs
      h(p)(1)=cs
      h(p)(2)=cs
    }else{
      cs*=t
      h(p)(0)=cs
      h(p)(1)=ch
      h(p)(2)=t
    }

    p+=1
    var sum0=0
    for(i<-0 until p){
      sum0+=h(i)(0)
    }
    var max=sum0
    for(i<-0 until p){
      val l=h(i)(0)/h(i)(2)
      val l0=h(i)(2)
      for(j<-i+1 until p){
        val r=h(j)(0)/h(j)(1)
        val r0=h(j)(1)
        var sumc=0
        for(k<-i+1 until j){
          sumc+=h(k)(0)
        }
        val sum=sum0-sumc-h(i)(0)-h(j)(0)+l*r*(r0+l0+sumc)

        if(sum>max){
          max=sum

        }
      }
    }
    out.println(max)
    //code ends here
    out.flush
    out.close
  }
}


The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times.

The only line of the input contains a pair of integers n (1000 ≤ n ≤ 10 000) and t (0 ≤ t ≤ 2 000 000 000) — the number of transistors in the initial time and the number of seconds passed since the initial time.

Output one number — the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10 - 6.

/**
  * Created by octavian on 18/02/2016.
  */
object Moore {

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("src/moore.in"))
    //System.setOut(new PrintStream(new FileOutputStream("src/moore.out")))

    var Array(n, t): Array[Long] = readLine().split(" ").map(_.toLong)
    var basis: Double = 1.000000011

    println(raise(basis, t) * n)

  }

  def raise(basis: Double, power: Long): Double = {
    var res: Double = 1
    var acc = basis
    var c_power = power
    while(c_power > 0) {
      if(c_power % 2 == 1) {
        c_power -= 1
        res *= acc
      }
      if(c_power > 0) {
        c_power /= 2
        acc = Math.pow(acc, 2)
      }
    }

    return res
  }

}

import java.util.Scanner

object Main {

  def sqr(x: Long) = x * x

  def powmod(x: Long, n: Long, p: Long): Long = {
    if (n == 1) x
    else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p
    else sqr(powmod(x, n / 2, p)) % p
  }

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

    val n = in.nextInt()

    val t = in.nextInt()

    println("%.9f".format(Math.pow(1.000000011, t) * n))
  }
}

import scala.io.StdIn

object MooresLaw {

  def main(args: Array[String]) {
    val Array(n, t) = StdIn.readLine().split("\\s+").map(_.toInt)
    print(n * Math.pow(1.000000011, t))
  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer
//import java.math.BigDecimal

object Bitz_B {

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

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

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val t = line1.int

//    val bd = BigDecimal(1.000000011)
//    val res = bd.pow(t) * n
//
////    val res = Math.pow(pp, t) * n

    def pow(arg:Double, pp:Int):Double = {
      if (pp == 0) return 1
      if (pp == 1) return arg
      val half = pow(arg, pp/2)
      if (pp % 2 == 0) {
        return  half * half
      } else {
        return half * half * arg
      }
    }

    val res = pow(1.000000011, t) * n

    println(res.toDouble)

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

  }

  //---------------------------- service code ----------------------------------

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

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

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

val sa1 = """
1000 1000000
"""

}

}


New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $$$h$$$ hours and $$$m$$$ minutes, where $$$0 \le hh < 24$$$ and $$$0 \le mm < 60$$$. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $$$0$$$ hours and $$$0$$$ minutes.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1439$$$) — the number of test cases. The following $$$t$$$ lines describe test cases. The $$$i$$$-th line contains the time as two integers $$$h$$$ and $$$m$$$ ($$$0 \le h < 24$$$, $$$0 \le m < 60$$$). It is guaranteed that this time is not a midnight, i.e. the following two conditions can't be met at the same time: $$$h=0$$$ and $$$m=0$$$. It is guaranteed that both $$$h$$$ and $$$m$$$ are given without leading zeros.

For each test case, print the answer on it — the number of minutes before the New Year.

case class Trap(l: Int, r: Int, d: Int)

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()

  val t = stdin.next().toInt
  println(stdin.take(t).map(_.split(" ").map(_.toInt)).map(arr => calc(arr(0), arr(1))).mkString(" "))

  def calc(hours: Int, minutes: Int): Int = (23 - hours) * 60 + (60 - minutes)
}

object CF611A extends App {

  import scala.io.StdIn

  val t = StdIn.readInt
  for (_ <- 0 until t) {
    val Array(h, m) = StdIn.readLine.split(' ').map(_.toInt)
    println((23-h)*60 + 60-m)
  }
}


Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 × 5 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3 × 5 table is 15 + 8 + 3 = 26.

The first line of the input contains a single integer x (1 ≤ x ≤ 1018) — the number of squares inside the tables Spongebob is interested in.

First print a single integer k — the number of tables with exactly x distinct squares inside. Then print k pairs of integers describing the tables. Print the pairs in the order of increasing n, and in case of equality — in the order of increasing m.

NoteIn a 1 × 2 table there are 2 1 × 1 squares. So, 2 distinct squares in total.  In a 2 × 3 table there are 6 1 × 1 squares and 2 2 × 2 squares. That is equal to 8 squares in total.

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val x=nextLong
    val a=ArrayBuffer.empty[(Long,Long)]
    for(n:Long<-1L to (math.pow(3*x,1.0/3.0) toLong )){
      val u=6*x+n*(n+1)*(n-1)
      val d=3*n*(n+1)
      if(u%d==0){

          a+=((n,u/d))

      }
    }
    val last=a(a.length-1)
    if(last._1!=last._2){
      out.println(a.length*2)
    }else{
      out.println(a.length*2-1)
    }
    for(i<-0 until a.length){
      out.println(a(i)._1+" "+a(i)._2)
    }
    if(last._1!=last._2){
      out.println(last._2+" "+last._1)
    }
    for(i<-a.length-2 to 0 by -1){
      out.println(a(i)._2+" "+a(i)._1)
    }

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


Ivan unexpectedly saw a present from one of his previous birthdays. It is array of $$$n$$$ numbers from $$$1$$$ to $$$200$$$. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally:$$$a_{1} \le a_{2}$$$,$$$a_{n} \le a_{n-1}$$$ and$$$a_{i} \le max(a_{i-1}, \,\, a_{i+1})$$$ for all $$$i$$$ from $$$2$$$ to $$$n-1$$$.Ivan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from $$$1$$$ to $$$200$$$. Since the number of ways can be big, print it modulo $$$998244353$$$.

First line of input contains one integer $$$n$$$ ($$$2 \le n \le 10^{5}$$$) — size of the array. Second line of input contains $$$n$$$ integers $$$a_{i}$$$ — elements of array. Either $$$a_{i} = -1$$$ or $$$1 \le a_{i} \le 200$$$. $$$a_{i} = -1$$$ means that $$$i$$$-th element can't be read.

Print number of ways to restore the array modulo $$$998244353$$$.

NoteIn the first example, only possible value of $$$a_{2}$$$ is $$$2$$$.In the second example, $$$a_{1} = a_{2}$$$ so there are $$$200$$$ different values because all restored elements should be integers between $$$1$$$ and $$$200$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val dp = Array.ofDim[Long](2, 201, 2)

    // i = 1 から始めたいので初期化するxorは1の方になる
    if (A(0) == -1) {
      rep(200, 1) { a => dp(1)(a)(0) = 1 }
    } else {
      dp(1)(A(0))(0) = 1
    }

    rep(N - 1, 1) { i =>
      val x = i % 2

      // flag = 0, { x < a; Σ(x, 0) + Σ(x, 1) }
      rep(200, 1) { a =>
        if (a > 0) {
          val cum = dp(x ^ 1)(a - 1)(0) // a - 2 までの累積
          dp(x ^ 1)(a)(0) = (cum + dp(x)(a - 1)(0) + dp(x)(a - 1)(1)) % MOD // a - 1 の分
        }
      }

      // flag = 1, { x > a; Σ(x, 1) + (a, 0) + (a, 1) }
      rep_r(200, 1) { a =>
        if (a < 200) {
          val cum = dp(x ^ 1)(a + 1)(1) // a + 2 までの累積
          dp(x ^ 1)(a)(1) = (cum + dp(x)(a + 1)(1)) % MOD // a + 1 の分
        }
      }

      rep(200, 1) { a =>
        dp(x ^ 1)(a)(1) += dp(x)(a)(0) + dp(x)(a)(1)
        dp(x ^ 1)(a)(1) %= MOD
      }

      // aが固定のときはa以外の値を消す
      // if-elseで処理分けるよりシンプル
      if (A(i) != -1) {
        rep(200, 1) { a =>
          if (a != A(i)) {
            dp(x ^ 1)(a)(0) = 0
            dp(x ^ 1)(a)(1) = 0
          }
        }
      }

      rep(200, 1) { a =>
        dp(x)(a)(0) = 0
        dp(x)(a)(1) = 0
      }
    }

    val ans = map(200)(i => dp(N % 2)(i + 1)(1)).sum % MOD
    out.println(ans)
  }

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

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

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

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

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


A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordinary sorting problem, but we can make it more interesting by adding nondeterministic element. There are n people, each person will use either his/her first name or last name as a handle. Can the lexicographical order of the handles be exactly equal to the given permutation p?More formally, if we denote the handle of the i-th person as hi, then the following condition must hold: .

The first line contains an integer n (1 ≤ n ≤ 105) — the number of people. The next n lines each contains two strings. The i-th line contains strings fi and si (1 ≤ |fi|, |si| ≤ 50) — the first name and last name of the i-th person. Each string consists only of lowercase English letters. All of the given 2n strings will be distinct. The next line contains n distinct integers: p1, p2, ..., pn (1 ≤ pi ≤ n).

If it is possible, output "YES", otherwise output "NO".

3
gennady korotkevich
petr mitrichev
gaoyuan chen
1 2 3

3
gennady korotkevich
petr mitrichev
gaoyuan chen
3 1 2

2
galileo galilei
nicolaus copernicus
2 1

10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
1 2 3 4 5 6 7 8 9 10

10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
2 4 9 6 5 7 1 3 8 10

NoteIn example 1 and 2, we have 3 people: tourist, Petr and me (cgy4ever). You can see that whatever handle is chosen, I must be the first, then tourist and Petr must be the last.In example 3, if Copernicus uses "copernicus" as his handle, everything will be alright.

import java.util.StringTokenizer

object _472C extends App {
  var token = new StringTokenizer("")

  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val a = (1 to n).map(i => {
    val s = next; val ss = next; if (s < ss) (s, ss) else (ss, s)
  }).toArray
  val b = (1 to n).map(i => next.toInt - 1).map(i => a(i))

  def doit(i: Int, pre: String): Boolean = {
    if (i >= n) true
    else {
      if (b(i)._1 >= pre) doit(i + 1, b(i)._1)
      else if (b(i)._2 >= pre) doit(i + 1, b(i)._2)
      else return false
    }
  }

  if (doit(1, b(0)._1)) println("YES")
  else println("NO")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next())
  val indices = in.next().split(" ").map(_.toInt - 1)
  val sorted = indices.map(i => data(i))
  if (sorted.foldLeft(("", true)) {
    case ((prev, false), el) => (prev, false)
    case ((prev, true), el) =>
      val Array(a, b) = el.split(" ")
      if (prev > a && prev > b) {
        (prev, false)
      }
      else if (prev < a && prev < b) {
        if (a < b)
          (a, true)
        else
          (b, true)
      } else {
        if (prev > a)
          (b, true)
        else
          (a, true)
        }
      }._2)
    println("YES")
  else
    println("NO")
}

import scala.annotation.tailrec

/**
 * Created by antonk on 29.09.14.
 */
object TaskA {
  def main(args: Array[String]) {
    val n = readInt
    val handles = {for (_ <- (1 to n)) yield {readLine split ' ' toList}} toArray
    val permutation = readLine split ' ' map(_.toInt - 1)
//    val inverse_permutation = Array.fill(n)(0)
  //  for ((x, i) <- permutation.view.zipWithIndex) inverse_permutation(x) = i
    @tailrec def isContinued(i: Int, max: Int, currentHandle: String = handles(permutation.head) min): String = {
      if (i == max) "YES"
      else ((currentHandle :: handles(permutation(i))) sorted) match {
        case List(x, r, _) if x == currentHandle => isContinued(i + 1, max, r)
        case List(_, x, r) if x == currentHandle => isContinued(i + 1, max, r)
        case _ => "NO"
      }
    }
    println(isContinued(1, n))
//    println(inverse_permutation map(_.toString) reduceLeft(_ + ' ' +  _))
  }
}

object C472 {
  import IO._
  import collection.{mutable => cu}
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val names = Array.fill(n)(read.split(" ").sorted)
    val expected = readInts(n)
    def result(): Boolean = {
      var curr = names(expected.head-1).head
      var res = true
      for(i <- 1 until n if res) {
        if(names(expected(i)-1).head > curr) {
          curr = names(expected(i)-1).head
        } else if(names(expected(i)-1).last > curr) {
          curr = names(expected(i)-1).last
        } else {
          res = false
        }
      }
      res
    }
    if(result()) {
      println("YES")
    } else {
      println("NO")
    }
  }

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

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)

  val ss = Array.ofDim[(String, String)](n)

  for (i <- 0 until n) {
    val s = readLine.split(" ")
    ss(i) = (s(0), s(1))
  }

  val ps = readInts(n)

  var prev = ""

  for (p <- ps) {
    val (l, r) = ss(p - 1)
    val (min, max) = if (l < r) (l, r) else (r, l)
    if (min > prev) {
      prev = min
    } else if (max > prev) {
      prev = max
    } else {
      //println(min, max, prev)
      println("NO")
      System.exit(0)
    }
  }

  println("YES")
}

object C {
   def READ: Array[Int] = readLine() split (" ") map (_.toInt);

   def main(args: Array[String]) {
     val Array(n) = READ;
     var w = Array.ofDim[String](n, 2)
     for (i <- 0 until n) w(i) = readLine() split (" ") sorted
     val p = READ;
     w = p.map(x => w(x-1))
     var min = w(0) min;
     for (i <- 1 until n)
       if (min <= w(i)(0)) min = w(i)(0)
       else if (min <= w(i)(1)) min = w(i)(1)
       else {
         println("NO")
         return;
       }
     println("YES")
   }
 }

import scala.annotation.tailrec

/**
 * Created by antonk on 29.09.14.
 */
object TaskA {
  def main(args: Array[String]) {
    val n = readInt
    val handles = {for (_ <- (1 to n)) yield {readLine split ' ' toList}} toArray
    val permutation = readLine split ' ' map(_.toInt - 1)
//    val inverse_permutation = Array.fill(n)(0)
  //  for ((x, i) <- permutation.view.zipWithIndex) inverse_permutation(x) = i
    @tailrec def isContinued(i: Int, max: Int, currentHandle: String = handles(permutation.head) min): String = {
      if (i == max) "YES"
      else ((currentHandle :: handles(i)) sorted) match {
        case List(x, r, _) if x == currentHandle => isContinued(i + 1, max, r)
        case List(_, x, r) if x == currentHandle => isContinued(i + 1, max, r)
        case _ => "NO"
      }
    }
    println(isContinued(1, n))
//    println(inverse_permutation map(_.toString) reduceLeft(_ + ' ' +  _))
  }
}

import scala.annotation.tailrec

object TaskA {
  def main(args: Array[String]) {
    val n = readInt
    val handles = {for (_ <- (1 to n)) yield {readLine split ' ' toList}} toArray
    val permutation = readLine split ' ' map(_.toInt - 1)
    val inverse_permutation = Array.fill(n)(0)
    for ((x, i) <- permutation.view.zipWithIndex) inverse_permutation(x) = i
    @tailrec def isContinued(i: Int, max: Int, currentHandle: String = handles(inverse_permutation.head) min): String = {
      if (i == max) "YES"
      else ((currentHandle :: handles(i)) sorted) match {
        case List(x, r, _) if x == currentHandle => isContinued(i + 1, max, r)
        case List(_, x, r) if x == currentHandle => isContinued(i + 1, max, r)
        case _ => "NO"
      }
    }
    println(isContinued(1, n))
//    println(inverse_permutation map(_.toString) reduceLeft(_ + ' ' +  _))
  }
}


Let $$$s$$$ be some string consisting of symbols "0" or "1". Let's call a string $$$t$$$ a substring of string $$$s$$$, if there exists such number $$$1 \leq l \leq |s| - |t| + 1$$$ that $$$t = s_l s_{l+1} \ldots s_{l + |t| - 1}$$$. Let's call a substring $$$t$$$ of string $$$s$$$ unique, if there exist only one such $$$l$$$. For example, let $$$s = $$$"1010111". A string $$$t = $$$"010" is an unique substring of $$$s$$$, because $$$l = 2$$$ is the only one suitable number. But, for example $$$t = $$$"10" isn't a unique substring of $$$s$$$, because $$$l = 1$$$ and $$$l = 3$$$ are suitable. And for example $$$t =$$$"00" at all isn't a substring of $$$s$$$, because there is no suitable $$$l$$$.Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.You are given $$$2$$$ positive integers $$$n$$$ and $$$k$$$, such that $$$(n \bmod 2) = (k \bmod 2)$$$, where $$$(x \bmod 2)$$$ is operation of taking remainder of $$$x$$$ by dividing on $$$2$$$. Find any string $$$s$$$ consisting of $$$n$$$ symbols "0" or "1", such that the length of its minimal unique substring is equal to $$$k$$$.

The first line contains two integers $$$n$$$ and $$$k$$$, separated by spaces ($$$1 \leq k \leq n \leq 100\,000$$$, $$$(k \bmod 2) = (n \bmod 2)$$$).

Print a string $$$s$$$ of length $$$n$$$, consisting of symbols "0" and "1". Minimal length of the unique substring of $$$s$$$ should be equal to $$$k$$$. You can find any suitable string. It is guaranteed, that there exists at least one such string.

NoteIn the first test, it's easy to see, that the only unique substring of string $$$s = $$$"1111" is all string $$$s$$$, which has length $$$4$$$.In the second test a string $$$s = $$$"01010" has minimal unique substring $$$t =$$$"101", which has length $$$3$$$.In the third test a string $$$s = $$$"1011011" has minimal unique substring $$$t =$$$"110", which has length $$$3$$$.

object B extends App {

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

  val Array(n, k) = readInts(2)

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

//  if (n >= 2 * k || n == k) {
//    println("0" * k + "1" * (n - k))
//  } else /*if (n % 2 == 1) */{
    val l = (n - k) / 2
    val s0 = "0" * l + "1"
//    val d = n - k
//    val s0 = "0" * (d - 1) + "1"
    val s = s0 * (n / s0.length + 1)
    println(s.take(n))
//  }
  Console.flush

//  for (b <- 0 until (1 << n)) {
//    val bb = b.toBinaryString
//    val s = "0" * (n - bb.length) + bb
//    var bad = false
//    for (i <- 1 to n) {
//      for (j <- 0 to n - i) {
//        val ss = s.substring(j, j + i)
//        //println(ss)
//        if (s.indexOf(ss) == j && s.lastIndexOf(ss) == j) {
//          if (!bad && i == k) {
//            println(s, ss)
//            System.exit(0)
//          }
//          bad = true
//        }
//      }
//    }
//  }
//  Console.flush

}

object B extends App {

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

  val Array(n, k) = readInts(2)

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

  if (n >= 2 * k || n == k) {
    println("0" * k + "1" * (n - k))
  } else /*if (n % 2 == 1) */{
//    val l = (n - k) / 2
//    val s0 = "0" * l + "1" * l
    val d = n - k
    val s0 = "0" * (d - 1) + "1"
    val s = s0 * (n / s0.length + 1)
    println(s.take(n))
  }

  Console.flush
}

object B extends App {

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

  val Array(n, k) = readInts(2)

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

  if (n >= 2 * k || n == k) {
    println("0" * k + "1" * (n - k))
  } else /*if (n % 2 == 1) */{
    val l = (n - k) / 2
    val s0 = "0" * l + "1"
//    val d = n - k
//    val s0 = "0" * (d - 1) + "1"
    val s = s0 * (n / s0.length + 1)
    println(s.take(n))
  }

//  for (b <- 0 until (1 << n)) {
//    val bb = b.toBinaryString
//    val s = "0" * (n - bb.length) + bb
//    var bad = false
//    for (i <- 1 to n) {
//      for (j <- 0 to n - i) {
//        val ss = s.substring(j, j + i)
//        if (s.indexOf(ss) == j && s.lastIndexOf(ss) == j) {
//          if (!bad && i == k) {
//            println(s, ss)
//            System.exit(0)
//          }
//          bad = true
//        }
//      }
//    }
//  }
//
  Console.flush
}

object B extends App {

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

  val Array(n, k) = readInts(2)

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

  if (n >= 2 * k || n == k) {
    println("0" * k + "1" * (n - k))
  } else /*if (n % 2 == 1) */{
    val l = (n - k) / 2
    val s0 = "0" * l + "1" * l
    val s = s0 * (n / s0.length + 1)
    println(s.take(n))
  }

  Console.flush
}


There are n balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the i-th ball is ci and the value of the i-th ball is vi.Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence.The value of the sequence is defined as the sum of following values for each ball (where a and b are given constants):  If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball)  ×  a.  Otherwise, add (the value of the ball)  ×  b. You are given q queries. Each query contains two integers ai and bi. For each query find the maximal value of the sequence she can make when a = ai and b = bi.Note that the new sequence can be empty, and the value of an empty sequence is defined as zero.

The first line contains two integers n and q (1 ≤ n ≤ 105; 1 ≤ q ≤ 500). The second line contains n integers: v1, v2, ..., vn (|vi| ≤ 105). The third line contains n integers: c1, c2, ..., cn (1 ≤ ci ≤ n). The following q lines contain the values of the constants a and b for queries. The i-th of these lines contains two integers ai and bi (|ai|, |bi| ≤ 105). In each line integers are separated by single spaces.

For each query, output a line containing an integer — the answer to the query. The i-th line contains the answer to the i-th query in the input order. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first example, to achieve the maximal value:  In the first query, you should select 1st, 3rd, and 4th ball.  In the second query, you should select 3rd, 4th, 5th and 6th ball.  In the third query, you should select 2nd and 4th ball. Note that there may be other ways to achieve the maximal value.

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)
    val mc2=new Array[Int](2)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        (0 to n-1).foreach{i=>dp(i)=Long.MinValue/2}
        dp(n)=0

        mc2(0)=n;mc2(1)=n

        (0 to n-1).foreach{i=>
          dp(c(i))=
            Math.max(Math.max(dp(c(i)),dp(c(i))+v(i)*a),dp(
              if(mc2(0)!=c(i)) mc2(0) else mc2(1)
            )+v(i)*b)

          //sort
          var tmp=c(i)
          if(dp(c(i))>dp(mc2(1))){
            mc2(1)^=tmp
            tmp^=mc2(1)
            mc2(1)^=tmp
          }
          if(dp(mc2(1))>dp(mc2(0))){
            mc2(0)^=mc2(1)
            mc2(1)^=mc2(0)
            mc2(0)^=mc2(1)
          }
          if(mc2(0)==mc2(1)){
            mc2(1)=tmp
          }
        }

        dp(mc2(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)
    val mc2=new Array[Int](2)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }

        loop(n){dp(_)=Long.MinValue/2}

        mc2(0)=n;mc2(1)=n

        loop(n){i=>
          dp(c(i))=
            Math.max(Math.max(dp(c(i)),dp(c(i))+v(i)*a),dp(
              if(mc2(0)!=c(i)) mc2(0) else mc2(1)
            )+v(i)*b)

          //sort
          var tmp=c(i)
          if(dp(c(i))>dp(mc2(1))){
            mc2(1)^=tmp
            tmp^=mc2(1)
            mc2(1)^=tmp
          }
          if(dp(mc2(1))>dp(mc2(0))){
            mc2(0)^=mc2(1)
            mc2(1)^=mc2(0)
            mc2(0)^=mc2(1)
          }
          if(mc2(0)==mc2(1)){
            mc2(1)=tmp
          }
        }

        dp(mc2(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }

  def loop(n:Int)(f:Int=>Unit){
    var i=0
    while(i<n){
      f(i)
      i+=1
    }
  }

  def getTime(f:()=>Unit):Long={
    val now=System.currentTimeMillis
    f()
    System.currentTimeMillis-now
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)
    val mc2=new Array[Int](2)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        {
          var i=0
          while(i<n){
            dp(i)=Long.MinValue/2
            i+=1
          }
          dp(n)=0
        }

        mc2(0)=n;mc2(1)=n

        var i=0
        while(i<n){
          dp(c(i))=
            Math.max(Math.max(dp(c(i)),dp(c(i))+v(i)*a),dp(
              if(mc2(0)!=c(i)) mc2(0) else mc2(1)
            )+v(i)*b)

          //sort
          var tmp=c(i)
          if(dp(c(i))>dp(mc2(1))){
            mc2(1)^=tmp
            tmp^=mc2(1)
            mc2(1)^=tmp
          }
          if(dp(mc2(1))>dp(mc2(0))){
            mc2(0)^=mc2(1)
            mc2(1)^=mc2(0)
            mc2(0)^=mc2(1)
          }
          if(mc2(0)==mc2(1)){
            mc2(1)=tmp
          }
          i+=1
        }

        dp(mc2(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }

  def loop(n:Int)(f:Int=>Unit){
    var i=0
    while(i<n){
      f(i)
      i+=1
    }
  }

  def getTime(f:()=>Unit):Long={
    val now=System.currentTimeMillis
    f()
    System.currentTimeMillis-now
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        val dp= new Array[Long](n+1).map(i=>Long.MinValue/2)

        val maxc0=
          (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>
            dp(c(i))=
              dp(c(i)) max (v(i)*b) max maxc2.map{cm=>
                if(cm==c(i)){
                  dp(cm)+v(i)*a
                }else{
                  dp(cm)+v(i)*b
                }
              }.max

            (c(i)::maxc2).distinct.sortWith{(c1,c2)=>
              dp(c1)>dp(c2)
            }.take(2)//->foldLeft
          }.head//->maxc0

        dp(maxc0)//->map
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        };
        (0 to n-1).foreach(dp(_)=Long.MinValue/2)
        dp(n)=0

        val maxc=Array(n,n);
        (0 to n-1).foreach{i=>
          dp(c(i))=
            dp(c(i)) max dp(c(i))+v(i)*a max dp(
              if(c(i)==maxc(0)) maxc(1) else maxc(0)
            )+v(i)*b

          if(c(i)!=maxc(0)||c(i)!=maxc(1)){
            if(dp(c(i))>dp(maxc(0))){
              maxc(1)=maxc(0)
              maxc(0)=c(i)
            }else if(dp(c(i))>dp(maxc(1))){
              maxc(1)=c(i)
            }
          }else{
            if(dp(maxc(1))>dp(maxc(0))){
              maxc(0)^=maxc(1)
              maxc(1)^=maxc(0)
            }
          }
        }
        dp(maxc(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)

    val ansList=
      (1 to q).map{ii=>
        val (a,b)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        val dp= new Array[Long](n+1)

        val maxc0=
          (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>
            dp(c(i))=
              dp(c(i)) max (v(i)*b) max maxc2.map{cm=>
                if(cm==c(i)){
                  dp(cm)+v(i)*a
                }else{
                  dp(cm)+v(i)*b
                }
              }.max

            (c(i)::maxc2).distinct.sortWith{(c1,c2)=>
              dp(c1)>dp(c2)
            }.take(2)//->foldLeft
          }.head//->maxc0

        dp(maxc0)//->map
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)
    val mc2=new Array[Int](2)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        dp.map(i=>Long.MinValue/2)
        dp(n)=0

        mc2(0)=n;mc2(1)=n

        0 to n-1 foreach{i=>
          dp(c(i))=
            Math.max(Math.max(dp(c(i)),dp(c(i))+v(i)*a),dp(
              if(mc2(0)!=c(i)) mc2(0) else mc2(1)
            )+v(i)*b)

          //sort
          var tmp=c(i)
          if(dp(c(i))>dp(mc2(1))){
            mc2(1)^=tmp
            tmp^=mc2(1)
            mc2(1)^=tmp
          }
          if(dp(mc2(1))>dp(mc2(0))){
            mc2(0)^=mc2(1)
            mc2(1)^=mc2(0)
            mc2(0)^=mc2(1)
          }
          if(mc2(0)==mc2(1)){
            mc2(1)=tmp
          }
        }

        dp(mc2(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        val dp= new Array[Long](n+1).map(i=>Long.MinValue/2)
        dp(n)=0

        val maxc0=
          (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>
            dp(c(i))=
              dp(c(i)) max (v(i)*b) max maxc2.map{cm=>
                if(cm==c(i)){
                  dp(cm)+v(i)*a
                }else{
                  dp(cm)+v(i)*b
                }
              }.max

            (c(i)::maxc2).distinct.sortWith{(c1,c2)=>
              dp(c1)>dp(c2)
            }.take(2)//->foldLeft
          }.head//->maxc0

        dp(maxc0)//->map
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        };
        (0 to n-1).foreach(dp(_)=Long.MinValue/2)
        dp(n)=0

        val maxc=Array(n,n);
        (0 to n-1).foreach{i=>
          dp(c(i))=
            dp(c(i)) max dp(c(i))+v(i)*a max dp(
              if(c(i)==maxc(0)) maxc(1) else maxc(0)
            )+v(i)*b

          if(c(i)!=maxc(0)||c(i)!=maxc(1)){
            if(dp(c(i))>dp(maxc(0))){
              maxc(1)=maxc(0)
              maxc(0)=c(i)
            }else if(dp(c(i))>dp(maxc(1))){
              maxc(1)=c(i)
            }
          }else{
            if(dp(maxc(1))>dp(maxc(0))){
              maxc(0)^=maxc(1)
              maxc(1)^=maxc(0)
              maxc(0)^=maxc(1)
            }
          }
        }
        dp(maxc(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        (0 to n-1).foreach(dp(_)=Long.MinValue/2)
        dp(n)=0

        val maxc2=Array[Int](n,n)

        (0 to n-1).foreach{i=>
          dp(c(i))=
            dp(c(i)) max dp(c(i))+v(i)*a max dp(
              maxc2.find(_!=c(i)).get
            )+v(i)*b

          val tmp=Array(c(i),maxc2(0),maxc2(1))
          tmp.sortWith{(c1,c2)=>dp(c1)>dp(c2)}
          maxc2(0)=tmp(0)
          maxc2(1)=tmp.find(_!=maxc2(0)).get
        }

        dp(maxc2(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toInt)
    val c=readLine.split(" ").map(_.toInt -1)

    val ansList=
      (1 to q).map{ii=>
        val (a,b)={
          val sp=readLine.split(" ")
          (sp(0).toInt,sp(1).toInt)
        }
        val dp= new Array[Long](n+1)

        val maxc0=
          (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>
            dp(c(i))=
              dp(c(i)) max (v(i)*b) max maxc2.map{cm=>
                if(cm==c(i)){
                  dp(cm)+v(i)*a
                }else{
                  dp(cm)+v(i)*b
                }
              }.max

            (c(i)::maxc2).distinct.sortWith{(c1,c2)=>
              dp(c1)>dp(c2)
            }.take(2)//->foldLeft
          }.head//->maxc0

        dp(maxc0)//->map
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        val dp= new Array[Long](n+1).map(i=>Long.MinValue/2)
        dp(n)=0

        val maxc0=
          (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>
            dp(c(i))=
              dp(c(i)) max maxc2.map{cm=>
                if(cm==c(i)){
                  dp(cm)+v(i)*a
                }else{
                  dp(cm)+v(i)*b
                }
              }.max

            (c(i)::maxc2).distinct.sortWith{(c1,c2)=>
              dp(c1)>dp(c2)
            }.take(2)//->foldLeft
          }.head//->maxc0

        dp.max
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
          (0 to n-1).foreach(dp(_)=Long.MinValue/2)
        dp(n)=0

        val maxc=Array(n,n);
        (0 to n-1).foreach{i=>
          dp(c(i))=
            dp(c(i)) max dp(c(i))+v(i)*a max dp(
              if(c(i)==maxc(0)) maxc(1) else maxc(0)
            )+v(i)*b

          if(c(i)!=maxc(0)||c(i)!=maxc(1)){
            if(dp(c(i))>dp(maxc(0))){
              maxc(1)=maxc(0)
              maxc(0)=c(i)
            }else if(dp(c(i))>dp(maxc(1))){
              maxc(1)=c(i)
            }
          }
        }
        dp(maxc(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)
    val mc2=new Array[Int](2)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        (0 to n-1).foreach(dp(_)=Long.MinValue/2)
        dp(n)=0

        mc2(0)=n;mc2(1)=n

        (0 to n-1).foreach{i=>
          dp(c(i))=
            dp(c(i)) max dp(c(i))+v(i)*a max dp(
              try{
                mc2.find(_!=c(i)).get
              }catch{
                case(e:Exception) =>
                  println(mc2(0)+","+mc2(1)+","+c(i)+","+i)
                  0
              }

            )+v(i)*b

          //sort
          var tmp=c(i)
          if(dp(c(i))>dp(mc2(1))){
            mc2(1)^=tmp
            tmp^=mc2(1)
            mc2(1)^=tmp
          }
          if(dp(mc2(1))>dp(mc2(0))){
            mc2(0)^=mc2(1)
            mc2(1)^=mc2(0)
            mc2(0)^=mc2(1)
          }
          if(mc2(0)==mc2(1)){
            mc2(1)=c(i)
          }

        }

        dp(mc2(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        val dp= new Array[Long](n+1).map(i=>Long.MinValue/2)
        dp(n)=0

        val maxc0=
          (0 to n-1).foldLeft(List[Int](n)){(maxc2,i)=>
            dp(c(i))=
              dp(c(i)) max (v(i)*b) max maxc2.map{cm=>
                if(cm==c(i)){
                  dp(cm)+v(i)*a
                }else{
                  dp(cm)+v(i)*b
                }
              }.max

            (c(i)::maxc2).distinct.sortWith{(c1,c2)=>
              dp(c1)>dp(c2)
            }.take(2)//->foldLeft
          }.head//->maxc0

        dp.max
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        };
        (0 to n-1).foreach(dp(_)=Long.MinValue/2)
        dp(n)=0

        val maxc=Array(n,n);
        (0 to n-1).foreach{i=>
          dp(c(i))=
            dp(c(i)) max dp(c(i))+v(i)*a max dp(
              if(c(i)==maxc(0)) maxc(1) else maxc(0)
            )+v(i)*b

          if(c(i)!=maxc(0)||c(i)!=maxc(1)){
            if(dp(c(i))>dp(maxc(0))){
              maxc(1)=maxc(0)
              maxc(0)=c(i)
            }else if(dp(c(i))>dp(maxc(1))){
              maxc(1)=c(i)
            }else if(maxc(0)==maxc(1)){
              maxc(1)=c(i)
            }
          }else{
            if(dp(maxc(1))>dp(maxc(0))){
              maxc(0)^=maxc(1)
              maxc(1)^=maxc(0)
              maxc(0)^=maxc(1)
            }
          }
        }
        dp(maxc(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }
}

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

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

    val v=readLine.split(" ").map(_.toLong)
    val c=readLine.split(" ").map(_.toInt -1)
    val dp=new Array[Long](n+1)

    val ansList=
      (1 to q).map{ii=>
        val (a:Long,b:Long)={
          val sp=readLine.split(" ")
          (sp(0).toLong,sp(1).toLong)
        }
        (0 to n-1).foreach(dp(_)=Long.MinValue/2)
        dp(n)=0

        val maxc2=Array[Int](n,n)

        (0 to n-1).foreach{i=>
          dp(c(i))=
            dp(c(i)) max dp(c(i))+v(i)*a max dp(
              maxc2.find(_!=c(i)).get
            )+v(i)*b

          val tmp=Array(c(i),maxc2(0),maxc2(1)).sortWith{(c1,c2)=>dp(c1)>dp(c2)}
          maxc2(0)=tmp(0)
          maxc2(1)=tmp.find(_!=maxc2(0)).get

          println(maxc2.mkString(","))
        }

        dp(maxc2(0))
      }//->ansList

    println(ansList.mkString("\n"))
  }
}


Codeforces separates its users into $$$4$$$ divisions by their rating:  For Division 1: $$$1900 \leq \mathrm{rating}$$$  For Division 2: $$$1600 \leq \mathrm{rating} \leq 1899$$$  For Division 3: $$$1400 \leq \mathrm{rating} \leq 1599$$$  For Division 4: $$$\mathrm{rating} \leq 1399$$$ Given a $$$\mathrm{rating}$$$, print in which division the $$$\mathrm{rating}$$$ belongs.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of testcases. The description of each test consists of one line containing one integer $$$\mathrm{rating}$$$ ($$$-5000 \leq \mathrm{rating} \leq 5000$$$).

For each test case, output a single line containing the correct division in the format "Division X", where $$$X$$$ is an integer between $$$1$$$ and $$$4$$$ representing the division for the corresponding rating.

Division 4
Division 4
Division 4
Division 4
Division 3
Division 2
Division 1

NoteFor test cases $$$1-4$$$, the corresponding ratings are $$$-789$$$, $$$1299$$$, $$$1300$$$, $$$1399$$$, so all of them are in division $$$4$$$.For the fifth test case, the corresponding rating is $$$1400$$$, so it is in division $$$3$$$.For the sixth test case, the corresponding rating is $$$1679$$$, so it is in division $$$2$$$.For the seventh test case, the corresponding rating is $$$2300$$$, so it is in division $$$1$$$.

object qa {
  def main(args: Array[String]) {
    val n = scala.io.StdIn.readInt()
    for (_ <- 0 until n) {
      val i = scala.io.StdIn.readInt()
      val str = {
        if (i >= 1900) "Division 1"
        else if (i >= 1600) "Division 2"
        else if (i >= 1400) "Division 3"
        else "Division 4"
      }
      println(str)
    }
  }
}

import scala.io.StdIn

/**
 * На Codeforces пользователи разделены на 4 дивизиона по их рейтингу:
 *
 * Для 1-го дивизиона: 1900≤rating
 * Для 2-го ивизиона: 1600≤rating≤1899
 * Для 3-го дивизиона: 1400≤rating≤1599
 * Для 4-го дивизиона: rating≤1399
 * Учитывая rating, выведите, к какому дивизиону относится rating.
 *
 * Входные данные
 * Первая строка ввода содержит целое число 𝑡 (1≤𝑡≤104) — количество наборов входных данных в тесте.
 *
 * Описание каждого набора состоит из одной строки, содержащей одно целое число rating (−5000≤rating≤5000).
 *
 * Выходные данные
 * Для каждого набора входных данных выведите единственную строку, содержащую дивизион в формате «Division X», где 𝑋 — целое число от 1 до 4, представляющее дивизион для соответствующего рейтинга.
 */

object Task1 extends App {
  def getNextNum: Int = StdIn.readLine().toInt

  val inputSize = getNextNum

  for (_ <- 0 until inputSize) {
    val rating = getNextNum

    if (rating <= 1399) {
      println("Division 4")
    } else {
      if (rating <= 1599) {
        println("Division 3")
      } else {
        if (rating <= 1899) {
          println("Division 2")
        } else {
          println("Division 1")
        }
      }
    }
  }

}

import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)
  // ======================================

  def solve(n: Int) = {
    "Division " + (n match {
      case i if (i >= 1900) => 1
      case i if (i >= 1600) => 2
      case i if (i >= 1400) => 3
      case i => 4
    })
  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt

    for (
      i <- 0 until cases;
      n = readLine().toInt
    ) println(solve(n))
  }
}