In the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2 × 2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed. Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2 × 2 square, consisting of cells of the same color.

Four lines contain four characters each: the j-th character of the i-th line equals "." if the cell in the i-th row and the j-th column of the square is painted white, and "#", if the cell is black.

Print "YES" (without the quotes), if the test can be passed and "NO" (without the quotes) otherwise.

NoteIn the first test sample it is enough to repaint the first cell in the second row. After such repainting the required 2 × 2 square is on the intersection of the 1-st and 2-nd row with the 1-st and 2-nd column.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = (1 to 4).map(_ => in.next().map{t => if (t == '#') 1 else 0}).toArray
  val r = (1 to 3).map(i =>
    (1 to 3).map{
      j =>
        val sum = data(i)(j) + data(i - 1)(j) + data(i)(j - 1) + data(i - 1)(j - 1)
        Math.max(sum, 4 - sum)
    }.max
  ).max
  if (r < 3)
    println("NO")
  else
    println("YES")
}

object IQ {

  def main (args : Array[String]){
    var a = new Array[String](4)
    for (i <- 0 to 3)
      a(i) = readLine
     for (i <- 1 to 3; j <- 1 to 3){
         var ans = 0
         if (a(i).charAt(j)=='.')ans +=1
         if (a(i-1).charAt(j-1)=='.')ans +=1
         if (a(i).charAt(j-1)=='.')ans +=1
         if (a(i-1).charAt(j)=='.')ans +=1
         if (ans!=2){
        	 println("YES");return
        	 }
         }
     println("NO")
  }

}

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

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

  type Grid = Array[Array[Char]]
  val grid: Grid = Array.fill(4)(sc.nextLine.toArray)

  def solve(): String = {
    def test(i: Int, j: Int): Boolean = {
      val cells = List(List(i, j), List(i + 1, j), List(i, j + 1), List(i + 1, j + 1))
      cells.count {
        case List(x, y) => grid(x)(y) == '#'
      } != 2
    }

    if ((for (i <- 0 until 3; j <- 0 until 3) yield test(i, j)).exists(_ == true)) "YES"
    else "NO"
  }

  out.println(solve)
  out.close
}

object A {
  def R = readLine().split(" ") map(_.toInt)

  def main(args: Array[String]) {
    var a = Array.ofDim[Boolean](4,4)
    def check(b:Boolean):Boolean = {
      for (x <- 0 until 3; y <- 0 until 3 if (a(x)(y) == b &&a(x+1)(y) ==b &&a(x)(y+1) == b &&a(x+1)(y+1) == b)) return true;
      return false;
    }
    for (i <- 0 until 4)
      a(i) = readLine().toCharArray() map(x => if (x == '#') true else false)

    if (check(true) || check(false)) {
      println("YES")
      return;
    }
    for (b <- List(false, true); i <- 0 until 4; j <- 0 until 4 if (a(i)(j) != b)) {
      a(i)(j) = b;
      if (check(b)) {
        println("YES")
        return;
      }
      a(i)(j) = !b;
    }
    println("NO")

  }

}

import annotation.tailrec
import java.io._

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

  val board = for(_ <- 1 to 4) yield reader.readLine().map {
    case '.' => 0
    case _ => 1
  }
  def ans = (for(i <- 0 to 2) yield (for(j <- 0 to 2) yield {
    val sum = board(i)(j) + board(i + 1)(j) + board(i)(j + 1) + board(i + 1)(j + 1)
    sum != 2
  }).contains(true)).contains(true)
  def yesNoAns = Map(true -> "YES", false -> "NO")

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

object A
{
	def main(args: Array[String]) {
		val sz = 4
		val maze = Array.ofDim[Int](sz, sz)
		for (i <- 0 until sz) {
			maze(i) = readLine.split("").tail.map( x => if(x == "#") 1 else 0 )
		}
		val result = (for (i <- 0 until sz - 1; j <- 0 until sz - 1) yield(i, j)).map( pos => {
							val (x, y) = pos
							val ss = maze(x)(y) + maze(x+1)(y) + maze(x)(y+1) + maze(x+1)(y+1)
							if(ss >= 3 || ss<=1) true else false
						}) reduceLeft(_ || _)
		println(if(result) "YES" else "NO")
	}
}

object Main {
  def main(args: Array[String]) {
    val al = new Array[String](4)
    al(0) = readLine()
    al(1) = readLine()
    al(2) = readLine()
    al(3) = readLine()

    val sqs = for {
      i <- 0 to 2
      j <- 0 to 2
    } yield(Seq(al(i)(j), al(i)(j + 1), al(i + 1)(j), al(i + 1)(j + 1)))
    if (sqs.count{ s =>
      val bl = s.count(_ == '#')
      bl <= 1 || bl >= 3
    } >= 1) println("YES")
    else println("NO")
  }
}

object CFContest176Div2A {
  def main(args: Array[String]){
    var inp = new Array[Array[Char]](4);
    inp = inp.map(_ => readLine().toCharArray())
    var result = false;
    var i =0; var j = 0;
    for(i <- 0 to 2; j <- 0 to 2){
      var b=0;
      for(k<- 0 to 1; l<- 0 to 1){
        if(inp(i+k)(j+l) == '#') b+=1;

      }
      result = result || (b<=1 || b>=3)
    }
    if(result) println("YES") else println("NO")

  }
}

object CFContest176Div2A {
  def main(args: Array[String]){
    var inp = new Array[Array[Char]](4);
    inp = inp.map(_ => readLine().toCharArray())
    var result = false;
    var i =0; var j = 0;
    for(i <- 0 to 2; j <- 0 to 2){
      var b=0;
      for(k<- 0 to 1; l<- 0 to 1){
        if(inp(i+k)(j+l) == '#') b+=1;

      }
      result = result || (b==1 || b==3)
    }
    if(result) println("YES") else println("NO")

  }
}

object IQ {

  def main (args : Array[String]){
    var a = new Array[String](4)
    for (i <- 0 until 4)
      a(i) = readLine
     var ans = 0
     for (i <- 1 to 3; j <- 1 to 3){
         if (a(i).charAt(j)=='.')ans +=1
         if (a(i-1).charAt(j-1)=='.')ans +=1
         if (a(i-1).charAt(j+1)=='.')ans +=1
         if (a(i+1).charAt(j-1)=='.')ans +=1
         if (ans!=2){
        	 println("YES");return}
         }
     println("No")
  }

}

object IQ {

  def main (args : Array[String]){
    var a = new Array[String](4)
    for (i <- 0 until 4)
      a(i) = readLine
     var ans = 0
     for (i <- 0 to 1)
       for (j <- 0 to 1)
         if (a(i).charAt(j)=='.')ans +=1
     if (ans==3 || ans==1){
       println("YES");return}
     ans = 0
     for (i <- 2 to 3)
       for (j <- 0 to 1)
         if (a(i).charAt(j)=='.')ans +=1
      if (ans==3 || ans==1){
       println("YES");return}
     ans = 0
     for (i <- 2 to 3)
       for (j <- 2 to 3)
         if (a(i).charAt(j)=='.')ans +=1
      if (ans==3 || ans==1){
       println("YES");return}
     ans = 0
     for (i <- 0 to 1)
       for (j <- 2 to 3)
         if (a(i).charAt(j)=='.')ans +=1
      if (ans==3 || ans==1){
       println("YES");return}
     println("NO")

  }

}

object A {
  def R = readLine().split(" ") map(_.toInt)

  def main(args: Array[String]) {
    var a = Array.ofDim[Boolean](4,4)
    def check:Boolean = {
      for (x <- 0 until 3; y <- 0 until 3 if (a(x)(y)&&a(x+1)(y)&&a(x)(y+1)&&a(x+1)(y+1))) return true;
      return false;
    }
    for (i <- 0 until 4)
      a(i) = readLine().toCharArray() map(x => if (x == '#') true else false)

    for (i <- 0 until 4; j <- 0 until 4 if (!a(i)(j))) {
      a(i)(j) = true;
      if (check) {
        println("YES")
        return;
      }
      a(i)(j) = false;
    }
    println("NO")

  }

}

object A {
  def R = readLine().split(" ") map(_.toInt)

  def main(args: Array[String]) {
    var a = Array.ofDim[Boolean](4,4)
    def check(b:Boolean):Boolean = {
      for (x <- 0 until 3; y <- 0 until 3 if (a(x)(y) == b &&a(x+1)(y) ==b &&a(x)(y+1) == b &&a(x+1)(y+1) == b)) return true;
      return false;
    }
    for (i <- 0 until 4)
      a(i) = readLine().toCharArray() map(x => if (x == '#') true else false)

    for (b <- List(false, true); i <- 0 until 4; j <- 0 until 4 if (a(i)(j) != b)) {
      a(i)(j) = b;
      if (check(b)) {
        println("YES")
        return;
      }
      a(i)(j) = !b;
    }
    println("NO")

  }

}

object CFContest176Div2A {
  def main(args: Array[String]){
    var inp = new Array[Array[Char]](4);
    inp = inp.map(_ => readLine().toCharArray())
    var result = false;
    var i =0; var j = 0;
    for(i <- 0 to 2; j <- 0 to 2){
      var b=0;
      for(k<- 0 to 1; l<- 0 to 1){
        if(inp(i+k)(j+l) == '#') b+=1;

      }
      result = result || (b<1 || b>3)
    }
    if(result) println("YES") else println("NO")

  }
}


Alice and Bob are decorating a Christmas Tree. Alice wants only $$$3$$$ types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have $$$y$$$ yellow ornaments, $$$b$$$ blue ornaments and $$$r$$$ red ornaments.In Bob's opinion, a Christmas Tree will be beautiful if:  the number of blue ornaments used is greater by exactly $$$1$$$ than the number of yellow ornaments, and  the number of red ornaments used is greater by exactly $$$1$$$ than the number of blue ornaments. That is, if they have $$$8$$$ yellow ornaments, $$$13$$$ blue ornaments and $$$9$$$ red ornaments, we can choose $$$4$$$ yellow, $$$5$$$ blue and $$$6$$$ red ornaments ($$$5=4+1$$$ and $$$6=5+1$$$).Alice wants to choose as many ornaments as possible, but she also wants the Christmas Tree to be beautiful according to Bob's opinion.In the example two paragraphs above, we would choose $$$7$$$ yellow, $$$8$$$ blue and $$$9$$$ red ornaments. If we do it, we will use $$$7+8+9=24$$$ ornaments. That is the maximum number.Since Alice and Bob are busy with preparing food to the New Year's Eve, they are asking you to find out the maximum number of ornaments that can be used in their beautiful Christmas Tree! It is guaranteed that it is possible to choose at least $$$6$$$ ($$$1+2+3=6$$$) ornaments.

The only line contains three integers $$$y$$$, $$$b$$$, $$$r$$$ ($$$1 \leq y \leq 100$$$, $$$2 \leq b \leq 100$$$, $$$3 \leq r \leq 100$$$) — the number of yellow, blue and red ornaments.  It is guaranteed that it is possible to choose at least $$$6$$$ ($$$1+2+3=6$$$) ornaments.

Print one number — the maximum number of ornaments that can be used.

NoteIn the first example, the answer is $$$7+8+9=24$$$.In the second example, the answer is $$$2+3+4=9$$$.

//package codeforces.contest1091

object NewYearAndTheChristmasOrnament {
  def main(args: Array[String]): Unit = {
    val Array(y, b, r) = io.StdIn.readLine.split(" ").map(_.toInt)
    println(sumOfMaxPossibleIncrementalSequence(y, b, r))
  }

  def sumOfMaxPossibleIncrementalSequence(y: Int, b: Int, r: Int): Int = {
    if (!requiresFix(y, b) && !requiresFix(b, r)) y + b + r
    else {
      if (requiresFix(b, r)) {
        val f = fix(b, r)
        sumOfMaxPossibleIncrementalSequence(y, f._1, f._2)
      } else {
        val f = fix(y, b)
        sumOfMaxPossibleIncrementalSequence(f._1, f._2, r)
      }
    }
  }

  def requiresFix(x: Int, y: Int): Boolean = x + 1 != y

  def fix(x: Int, y: Int): (Int, Int) = {
    if (x < y) (x, x + 1)
    else (y - 1, y)
  }
}

import scala.io.StdIn

object A1091 {
  def main(args: Array[String]): Unit = {
    val Array (y_, b_, r_) = StdIn.readLine().split(' ').map{_.toInt}
    println(
      (for { y <-  y_ to 1 by -1
             b <-  b_  to 2 by -1
             r <-  r_ to 3 by -1
             if r == b+1 && b == y+1 }
        yield y+b+r).take(1).head
    )
  }
}

import scala.io.StdIn

object NewYearAndTheChristmasOrnament extends App {

  val line = StdIn.readLine().split(" ").map(_.toInt)

  val (y, b, r) = (line(0), line(1), line(2))

  val resY = Iterator
    .iterate(y)(_ - 1)
    .takeWhile(_ >= 1)
    .find(y1 => {
      val b1 = y1 + 1
      val r1 = b1 + 1

      b1 <= b && r1 <= r
    })
    .get

  println(resY + resY + 1 + resY + 2)
}

object A 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(y, b, r) = readInts(3)

  val y2 = y min (b - 1) min (r - 2)
  val b2 = y2 + 1
  val r2 = b2 + 1

  println(y2 + b2 + r2)

  Console.flush
}


Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.The term is coming to an end and students start thinking about their grades. Today, a professor told his students that the grades for his course would be given out automatically  — he would calculate the simple average (arithmetic mean) of all grades given out for lab works this term and round to the nearest integer. The rounding would be done in favour of the student — $$$4.5$$$ would be rounded up to $$$5$$$ (as in example 3), but $$$4.4$$$ would be rounded down to $$$4$$$.This does not bode well for Vasya who didn't think those lab works would influence anything, so he may receive a grade worse than $$$5$$$ (maybe even the dreaded $$$2$$$). However, the professor allowed him to redo some of his works of Vasya's choosing to increase his average grade. Vasya wants to redo as as few lab works as possible in order to get $$$5$$$ for the course. Of course, Vasya will get $$$5$$$ for the lab works he chooses to redo.Help Vasya — calculate the minimum amount of lab works Vasya has to redo.

The first line contains a single integer $$$n$$$ — the number of Vasya's grades ($$$1 \leq n \leq 100$$$). The second line contains $$$n$$$ integers from $$$2$$$ to $$$5$$$ — Vasya's grades for his lab works.

Output a single integer — the minimum amount of lab works that Vasya has to redo. It can be shown that Vasya can always redo enough lab works to get a $$$5$$$.

NoteIn the first sample, it is enough to redo two lab works to make two $$$4$$$s into $$$5$$$s.In the second sample, Vasya's average is already $$$4.75$$$ so he doesn't have to redo anything to get a $$$5$$$.In the second sample Vasya has to redo one lab work to get rid of one of the $$$3$$$s, that will make the average exactly $$$4.5$$$ so the final grade would be $$$5$$$.

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object Task2 extends App {
  val n = readLine().split(' ').map(_.toInt).head

  val marks = readLine().split(' ').map(_.toInt).toList.sorted

  @tailrec
  def sol(n: Int, marks: List[Int], index: Int = 0, res: Int = 0): Int =
    if (marks.sum.toDouble / n >= 4.5) res else sol(n, marks.updated(index, 5), index + 1, res + 1)

  println(sol(n, marks))

}

object Main{
  def main(arr: Array[String]): Unit ={
    val n = readInt()
    val a = readLine.split(" ").map(_.toInt).map(_ * 10)

    val totReq = n * 45

    val as = a.sorted
    var ctot = as.sum
    var changes = 0
    var i = 0
    while(totReq > ctot && i < n){
      ctot += (50 - as(i))
      changes += 1
      i += 1
    }

    println(changes)
  }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine
import scala.math.ceil

object Main extends App {
  def read(): List[Int] = readLine().split(' ').map(_.toInt).toList
  @tailrec def f(marks: List[Int], need: Int, ans: Int = 0): Int = {
    if (need > 0) marks match {
      case _ :: Nil => ans + 1
      case x :: xs => f(xs, need - 5 + x, ans + 1)
    } else ans
  }
  val List(n) = read()
  val marks = read().sorted
  val need = ceil(n * 4.5).toInt - marks.sum
  println(f(marks, need))
}

import math._
object Main extends App {
    val n = readInt
    val m = ceil(4.5 * n).toInt
    val array = readLine.split(" ").map(_.toInt).sorted
    val dif = m - array.sum
    if (dif <= 0) println(0)
    else {
        val a_2 = array.count(_ == 2)
        if (dif <= a_2 * 3) {
            println(ceil(dif / 3.0).toInt)
        } else {
            val r = dif - 3 * a_2
            val a_3 = array.count(_ == 3)
            if (r <= a_3 * 2) {
                println(ceil(r / 2.0).toInt + a_2)
            } else {
                println(dif - 2 * a_2 - a_3)
            }
        }
    }
}

import math._
object Main extends App {
    val n = readInt
    val m = 5 * n - n / 2
    val array = readLine.split(" ").map(_.toInt).sorted
    val dif = m - array.sum
    if (dif <= 0) println(0)
    else {
        val a_3 = array.count(_ == 3)
        if (dif <= a_3 * 2){
            println(ceil(dif / 2))
        } else {
            println(dif - a_3)
        }
    }
}

import math._
object Main extends App {
    val n = readInt
    val m = 5 * n - n / 2
    val array = readLine.split(" ").map(_.toInt).sorted
    val dif = m - array.sum
    if (dif <= 0) println(0)
    else {
        val a_3 = array.count(_ == 3)
        if (dif <= a_3 * 2){
            println(ceil(dif / 2).toInt)
        } else {
            println(dif - a_3)
        }
    }
}

import math._
object Main extends App {
    val n = readInt
    val m = ceil(4.5 * n).toInt
    val array = readLine.split(" ").map(_.toInt).sorted
    val dif = m - array.sum
    if (dif <= 0) println(0)
    else {
        val a_3 = array.count(_ == 3)
        if (dif <= a_3 * 2){
            println(ceil(dif / 2).toInt)
        } else {
            println(dif - a_3)
        }
    }
}

import math._
object Main extends App {
    val n = readInt
    val m = ceil(4.5 * n).toInt
    val array = readLine.split(" ").map(_.toInt).sorted
    val dif = m - array.sum
    if (dif <= 0) println(0)
    else {
        val a_3 = array.count(_ == 3)
        if (dif <= a_3 * 2){
            println(ceil(dif / 2.0).toInt)
        } else {
            println(dif - a_3)
        }
    }
}

import math._
object Main extends App {
    val n = readInt
    val m = 5 * n - n / 2
    val array = readLine.split(" ").map(_.toInt).sorted
    val dif = m - array.sum
    if (dif <= 0) println(0)
    else {
        val a_3 = array.count(_ == 3)
        if (dif <= a_3 * 2){
            println(dif / 2)
        } else {
            println(dif - a_3)
        }
    }
}


Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).

The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).

Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).

NoteTwo sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.Notes to the samples:  In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.  In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.  In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.

import scala.collection._

object C extends App {

  val M = 1000000007

  @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, a, _b, k) = readInts(4)
  val b = _b - 1

  val counts = Array.fill(n){ 1L }
  val pSums = Array.ofDim[Long](n + 1)

  for (step <- 0 until k) {
    var s = 0L
    for (i <- 0 until n) {
      pSums(i) = s
      s += counts(i)
    }
    pSums(n) = s

    for (i <- 0 until n) if (i != b) {
      val delta = math.abs(b - i) - 1
      val l = if (i < b) 0 max (i - delta) else (b + 1) max (i - delta)
      val r = if (i > b) (n - 1) min (i + delta) else (b - 1) min (i + delta)
      counts(i) = (pSums(r + 1) - pSums(l) - counts(i)) % M
    }
  }

  println(counts(a - 1))
}


Nowadays, most of the internet advertisements are not statically linked to a web page. Instead, what will be shown to the person opening a web page is determined within 100 milliseconds after the web page is opened. Usually, multiple companies compete for each ad slot on the web page in an auction. Each of them receives a request with details about the user, web page and ad slot and they have to respond within those 100 milliseconds with a bid they would pay for putting an advertisement on that ad slot. The company that suggests the highest bid wins the auction and gets to place its advertisement. If there are several companies tied for the highest bid, the winner gets picked at random.However, the company that won the auction does not have to pay the exact amount of its bid. In most of the cases, a second-price auction is used. This means that the amount paid by the company is equal to the maximum of all the other bids placed for this ad slot.Let's consider one such bidding. There are n companies competing for placing an ad. The i-th of these companies will bid an integer number of microdollars equiprobably randomly chosen from the range between Li and Ri, inclusive. In the other words, the value of the i-th company bid can be any integer from the range [Li, Ri] with the same probability. Determine the expected value that the winner will have to pay in a second-price auction.

The first line of input contains an integer number n (2 ≤ n ≤ 5). n lines follow, the i-th of them containing two numbers Li and Ri (1 ≤ Li ≤ Ri ≤ 10000) describing the i-th company's bid preferences. This problem doesn't have subproblems. You will get 8 points for the correct submission.

Output the answer with absolute or relative error no more than 1e - 9.

NoteConsider the first example. The first company bids a random integer number of microdollars in range [4, 7]; the second company bids between 8 and 10, and the third company bids 5 microdollars. The second company will win regardless of the exact value it bids, however the price it will pay depends on the value of first company's bid. With probability 0.5 the first company will bid at most 5 microdollars, and the second-highest price of the whole auction will be 5. With probability 0.25 it will bid 6 microdollars, and with probability 0.25 it will bid 7 microdollars. Thus, the expected value the second company will have to pay is 0.5·5 + 0.25·6 + 0.25·7 = 5.75.

import java.util.StringTokenizer

object _513C extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val l = Array.fill(n)(0)
  val r = Array.fill(n)(0)
  for (i <- 0 until n) {
    l(i) = next.toInt
    r(i) = next.toInt
  }
  val mask = (1 to n).toArray
  val denominator = (l zip r).map(p => 1.0 * (p._2 - p._1 + 1)).reduce(_ * _)

  def calc(l: Int, r: Int, ll: Int, rr: Int): Double = {
    val lll = l max ll
    val rrr = r min rr
    if (lll <= rrr) rrr - lll + 1 else 0
  }

  var second = 1
  var numerator = 0.0
  def dfs(t: Int) {
    if (t >= n) {
      val sorted = mask.sorted
      if (sorted(n - 2) == 0) {
        var tmp = 1.0
        for (i <- 0 until n) {
          if (mask(i) == 1) tmp *= calc(l(i), r(i), second + 1, Int.MaxValue)
          else if (mask(i) == 0) tmp *= calc(l(i), r(i), second, second)
          else tmp *= calc(l(i), r(i), 0, second - 1)
        }
        numerator += second * tmp
      }
    } else {
      for (i <- -1 to 1) {
        mask(t) = i; dfs(t + 1)
      }
    }
  }
  while (second <= 10000) {
    dfs(0)
    second += 1
  }
  println("%.10f".format(numerator / denominator))
}

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)
  var ls, rs = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val Array(l, r) = readInts(2)
    ls(i) = l
    rs(i) = r
  }

  var ev1, ev2 = 0d

  def probWin(x: Int, l: Int, r: Int): Double = {
    if (x < l) 0d
    else if (x > r) 1d
    else (x - l + 0d) / (r - l + 1d)
  }

  def probLose(x: Int, l: Int, r: Int): Double = {
    if (x < l) 1d
    else if (x > r) 0d
    else (r - x + 0d) / (r - l + 1d)
  }

  def probEq(x: Int, l: Int, r: Int): Double = {
    if (x < l) 0d
    else if (x > r) 0d
    else 1d / (r - l + 1d)
  }

  val maxMask = (1 << (n - 2)) - 1

  for (p1 <- 0 until n) {
    for (p2 <- 0 until n) if (p2 != p1) {
      var sumProb1 = 0d
      var sumProb2 = 0d
      for (x2 <- ls(p2) to rs(p2)) {
        for (mask <- 0 to maxMask) {
          var prob = 1d
          var i = 1
          var eqCnt = 2
          for (px <- 0 until n) if (px != p2 && px != p1) {
            if ((mask & i) == 0) prob *= probWin(x2, ls(px), rs(px))
            else {
              prob *= probEq(x2, ls(px), rs(px))
              eqCnt += 1
            }
            i *= 2
          }
         // println(p1, p2, x2, mask, prob, probLose(x2, ls(p1), rs(p1)), probEq(x2, ls(p1), rs(p1)))
          sumProb1 += x2 * prob * probLose(x2, ls(p1), rs(p1)) / (eqCnt - 1d)
          sumProb2 += x2 * prob * probEq(x2, ls(p1), rs(p1)) / (eqCnt - 1d) / eqCnt
          //sumProb2 += x2 * 0.5d * prob * probEq(x2, ls(p1), rs(p1))
        }
      }
      ev1 += sumProb1 / (rs(p2) - ls(p2) + 1d)
      ev2 += sumProb2 / (rs(p2) - ls(p2) + 1d)
    }
  }
  //println(ev1, ev2)
  println(ev1 + ev2)
}

import java.util.Scanner
import java.io.FileInputStream

object DoubleSolution {

  def main(args: Array[String]) {
    val sc = new Scanner(if (args.length > 0) new FileInputStream(args(0)) else System.in)
    val n = sc.nextInt
    val arr = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt()))
    //val start = System.nanoTime()
    println(new DoubleAuction(n, arr).expectationOfSecond())
    //val end = System.nanoTime()
    //println("Time = " + (end - start) / 1000000L)
  }
}

class DoubleAuction(n: Int, r: Array[(Int, Int)]) {
  def low(i: Int): Int = r(i)._1
  def hi(i: Int): Int = r(i)._2
  def length(i: Int): Int = r(i)._2 - r(i)._1 + 1

  val ZERO = BigInt(0)
  val ONE = BigInt(0)
  def gcd(a: BigInt, b: BigInt): BigInt = if (b == ZERO) a else gcd(b, a % b)

  def simplify(a: BigInt, b: BigInt): (BigInt, BigInt) = {
    val g = gcd(a, b)
    if (g == ONE) (a, b) else (a / g, b / g)
  }

  def expectationOfSecond(): Double = {
    val secondFrom = (0 until n).map(low).sortWith(_ > _)(1)
    val secondTo = (0 until n).map(hi).sortWith(_ > _)(1)
    var value = 0.0
    var second = secondFrom
    while (second<=secondTo) {
      var si = 0
      while (si < n) {
        if (low(si) <= second && second <= hi(si)) {
          var fi = 0
          while (fi<n) {
            if (fi != si && (if (fi < si) second + 1 else second) <= hi(fi)) {
              var exists = true
              var k = 0
              while (exists && k < n) {
                if (k != si && k != fi) {
                  if (!(low(k) <= (if (k < si) second + 1 else second))) exists = false
                }
                k += 1
              }
              if (exists) {
                var a0 = second * (hi(fi) - math.max(if (fi < si) second + 1 else second, low(fi)) + 1) / length(si).toDouble / length(fi)
                var i = 0
                while (i < n) {
                  if (i != si && i != fi && hi(i) > (if (i < si) second else second - 1)) {
                    a0 *= ((if (i < si) second else second - 1) - low(i) + 1)
                    a0 /= length(i)
                  }
                  i += 1
                }
                value = value + a0
              }
            }
            fi += 1
          }
        }
        si += 1
      }
      second += 1
    }
    value
  }
}

import java.util.Scanner
import java.io.FileInputStream

object DoubleSolution {

  def main(args: Array[String]) {
    val sc = new Scanner(if (args.length > 0) new FileInputStream(args(0)) else System.in)
    val n = sc.nextInt
    val arr = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt()))
    println(new DoubleAuction(n, arr).expectationOfSecond())
  }
}

class DoubleAuction(n: Int, r: Array[(Int, Int)]) {
  def low(i: Int): Int = r(i)._1
  def hi(i: Int): Int = r(i)._2
  def length(i: Int): Int = r(i)._2 - r(i)._1 + 1

  val ZERO = BigInt(0)
  val ONE = BigInt(0)
  def gcd(a: BigInt, b: BigInt): BigInt = if (b == ZERO) a else gcd(b, a % b)

  def simplify(a: BigInt, b: BigInt): (BigInt, BigInt) = {
    val g = gcd(a, b)
    if (g == ONE) (a, b) else (a / g, b / g)
  }

  def expectationOfSecond(): Double = {
    val secondFrom = (0 until n).map(low).sortWith(_ > _)(1)
    val secondTo = (0 until n).map(hi).sortWith(_ > _)(1)
    //val summands =
    (for {
      second <- secondFrom to secondTo
      si <- 0 until n if low(si) <= second && second <= hi(si)
      fi <- 0 until n if fi != si && (if (fi < si) second + 1 else second) <= hi(fi)
      if (0 until n).filter(i => i != si && i != fi).forall(i => low(i) <= (if (i < si) second + 1 else second))

    } yield {
      val a0: Double = second * (hi(fi) - math.max(if (fi < si) second + 1 else second, low(fi)) + 1) / length(si).toDouble / length(fi)
      (0 until n).filter(i => i != si && i != fi && hi(i) > (if (i < si) second else second - 1)).
        foldLeft(a0) ((p, i) => p * ((if (i < si) second else second - 1) - low(i) + 1) / length(i))
    }).sum
  }
}

import java.io.FileInputStream
import java.util.Scanner
import scala.collection.mutable

object Solution {
  def main(args: Array[String]) {
    val sc = new Scanner(if (args.length > 0) new FileInputStream(args(0)) else System.in)
    val n = sc.nextInt

    val arr = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt()))
    //val start = System.nanoTime()
    println(new Auction(n, arr).expectationOfSecond())
    //val end = System.nanoTime()
    //println("Time = " + (end - start) / 1000000L)
  }
}

class Auction(n: Int, r: Array[(Int, Int)]) {
  def low(i: Int): Int = r(i)._1
  def hi(i: Int): Int = r(i)._2
  def length(i: Int): Int = r(i)._2 - r(i)._1 + 1

  val ZERO = BigInt(0)
  val ONE = BigInt(0)
  def gcd(a: BigInt, b: BigInt): BigInt = if (b == ZERO) a else gcd(b, a % b)

  def simplify(a: BigInt, b: BigInt): (BigInt, BigInt) = {
    val g = gcd(a, b)
    if (g == ONE) (a, b) else (a / g, b / g)
  }

  def expectationOfSecond(): Double = {
    val secondFrom = (0 until n).map(low).sortWith(_ > _)(1)
    val secondTo = (0 until n).map(hi).sortWith(_ > _)(1)
    val map = new mutable.OpenHashMap[BigInt, BigInt](200000)
    //val summands =
      for {
        second <- secondFrom to secondTo
        si <- 0 until n if low(si) <= second && second <= hi(si)
        fi <- 0 until n if fi != si && (if (fi < si) second + 1 else second) <= hi(fi)
        if (0 until n).filter(i => i != si && i != fi).forall(i => low(i) <= (if (i < si) second + 1 else second))
      } {
        val a0: BigInt = second * (hi(fi) - math.max(if (fi < si) second + 1 else second, low(fi)) + 1)
        val b0: BigInt = length(si) * length(fi)
        val is = (0 until n).filter(i => i != si && i != fi && hi(i) > (if (i < si) second else second - 1))
        val a = is.map(i => (if (i < si) second else second - 1) - low(i) + 1).foldLeft(a0)(_ * _)
        val b = is.map(i => length(i)).foldLeft(b0)(_ * _)
        val x = simplify(a, b)
        map += (x._2 -> (map.getOrElse(x._2, ZERO) + x._1))
      }
      val grouped = map.toIterator.map(p => simplify(p._2, p._1))
//    val grouped = summands.foldLeft(Map[BigInt, BigInt]())((m, x) => m + (x._2 -> (m.getOrElse(x._2, ZERO) + x._1))).
//      toList.map(p => simplify(p._2, p._1))

    //println(  summands.foldLeft(Map[BigInt, BigInt]()) ( (m, x) => m + (x._2 -> (m.getOrElse(x._2, ZERO) + x._1)) )  )

    //val grouped = summands.groupBy(_._2).mapValues(_.map(_._1).sum).toList.map(p=>simplify(p._2,p._1))
    //val grouped = summands.agroupBy(_._2).map(p => (p._1,p._2.map(_._1).sum)).map(p=>simplify(p._2,p._1))
    grouped.map(p => BigDecimal(p._1) / BigDecimal(p._2)).sum.toDouble
  }
}

import java.util.StringTokenizer

object _513C extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val l = Array.fill(n)(0)
  val r = Array.fill(n)(0)
  for (i <- 0 until n) {
    l(i) = next.toInt
    r(i) = next.toInt
  }
  val mask = (1 to n).toArray
  val denominator = (l zip r).map(p => 1.0 * (p._2 - p._1 + 1)).reduce(_ * _)

  def calc(l: Int, r: Int, ll: Int, rr: Int): Double = {
    val lll = l max ll
    val rrr = r min rr
    if (lll <= rrr) rrr - lll + 1 else 0
  }

  val numerators = for (second <- 1 to 50) yield {
    def dfs(t: Int): Double =
      if (t >= n) {
        val sorted = mask.sorted
        if (sorted(n - 2) == 0) {
          val cand = for (i <- 0 until n) yield {
            if (mask(i) == 1) calc(l(i), r(i), second + 1, Int.MaxValue)
            else if (mask(i) == 0) calc(l(i), r(i), second, second)
            else calc(l(i), r(i), 0, second - 1)
          }
          cand.reduce(_ * _) * second
        } else 0
      } else {
        val hehe = for (i <- -1 to 1) yield { mask(t) = i; dfs(t + 1) }
        hehe.sum
      }
    dfs(0)
  }
  val numerator = numerators.sum
  println("%.10f".format(numerator / denominator))
}

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)
  var ls, rs = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val Array(l, r) = readInts(2)
    ls(i) = l
    rs(i) = r
  }

  var ev1, ev2 = 0d

  def probWin(x: Int, l: Int, r: Int): Double = {
    if (x < l) 0d
    else if (x > r) 1d
    else (x - l + 0d) / (r - l + 1d)
  }

  def probLose(x: Int, l: Int, r: Int): Double = {
    if (x < l) 1d
    else if (x > r) 0d
    else (r - x + 0d) / (r - l + 1d)
  }

  def probEq(x: Int, l: Int, r: Int): Double = {
    if (x < l) 0d
    else if (x > r) 0d
    else 1d / (r - l + 1d)
  }

  val maxMask = (1 << (n - 2)) - 1

  for (p1 <- 0 until n) {
    for (p2 <- 0 until n) if (p2 != p1) {
      var sumProb1 = 0d
      var sumProb2 = 0d
      for (x2 <- ls(p2) to rs(p2)) {
        for (mask <- 0 to maxMask) {
          var prob = 1d
          var i = 1
          var eqCnt = 2
          for (px <- 0 until n) if (px != p2 && px != p1) {
            if ((mask & i) == 0) prob *= probWin(x2, ls(px), rs(px))
            else {
              prob *= probEq(x2, ls(px), rs(px))
              eqCnt += 1
            }
            i *= 2
          }
         // println(p1, p2, x2, mask, prob, probLose(x2, ls(p1), rs(p1)), probEq(x2, ls(p1), rs(p1)))
          sumProb1 += x2 * prob * probLose(x2, ls(p1), rs(p1)) / (eqCnt - 1d)
          sumProb2 += x2 * prob * probEq(x2, ls(p1), rs(p1)) / (eqCnt - 1d) / eqCnt
          //sumProb2 += x2 * 0.5d * prob * probEq(x2, ls(p1), rs(p1))
        }
      }
      ev1 += sumProb1 / (rs(p2) - ls(p2) + 1d)
      ev2 += sumProb2 / (rs(p2) - ls(p2) + 1d)
    }
  }
  println(ev1, ev2)
  println(ev1 + ev2)
}

import java.util.Scanner
import java.io.FileInputStream

object DoubleSolution {

  def main(args: Array[String]) {
    val sc = new Scanner(if (args.length > 0) new FileInputStream(args(0)) else System.in)
    val n = sc.nextInt
    val arr = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt()))
    println(new DoubleAuction(n, arr).expectationOfSecond())
  }
}

class DoubleAuction(n: Int, r: Array[(Int, Int)]) {
  def low(i: Int): Int = r(i)._1
  def hi(i: Int): Int = r(i)._2
  def length(i: Int): Int = r(i)._2 - r(i)._1 + 1

  val ZERO = BigInt(0)
  val ONE = BigInt(0)
  def gcd(a: BigInt, b: BigInt): BigInt = if (b == ZERO) a else gcd(b, a % b)

  def simplify(a: BigInt, b: BigInt): (BigInt, BigInt) = {
    val g = gcd(a, b)
    if (g == ONE) (a, b) else (a / g, b / g)
  }

  def expectationOfSecond(): Double = {
    val secondFrom = (0 until n).map(low).sortWith(_ > _)(1)
    val secondTo = (0 until n).map(hi).sortWith(_ > _)(1)
    var value = 0.0
    var second = secondFrom
    while (second<=secondTo) {
      var si = 0
      while (si < n) {
        if (low(si) <= second && second <= hi(si)) {
          var fi = 0
          while (fi < n) {
            if (fi != si && (if (fi < si) second + 1 else second) <= hi(fi)) {
              var v = second * (hi(fi) - math.max(if (fi < si) second + 1 else second, low(fi)) + 1) / length(si).toDouble / length(fi)
              var i = 0
              while (i < n) {
                if (i != si && i != fi && hi(i) > (if (i < si) second else second - 1)) {
                  v *= ((if (i < si) second else second - 1) - low(i) + 1) / length(i).toDouble
                }
                i += 1
              }
              value += v
            }
            fi += 1
          }
        }
        si += 1
      }
      second += 1
    }
    value
  }
}

import Fraction._
import java.io.FileInputStream
import java.util.Scanner

object Solution {
  def main(args: Array[String]) {
    // assert(new Auction(3, Array((4, 7), (8, 10), (5, 5))).expectationOfSecond().toDouble == 5.75)
    // assert(new Auction(3, Array((2,5), (3,4), (1,6))).expectationOfSecond().toDouble == 3.5)
    val sc = new Scanner(if (args.length > 0) new FileInputStream(args(0)) else System.in)
    val n = sc.nextInt
    val arr = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt()))
    val expectation = new Auction(3, arr).expectationOfSecond().toDouble
    println(expectation)
  }
}

class Fraction(val a:Long, val b:Long) {
  def toDouble: Double = if (a == 0) 0.0 else a.toDouble / b

  def *(that: Fraction): Fraction = mul(this, that)

  override def toString: String =
    if (a == 0) "0"
    else if (b == 1) a.toString
    else a + "/" + b
}

object Fraction {
  val ZERO = new Fraction(0L, 1L)
  val ONE = new Fraction(1L, 1L)
  def gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
  def fract(a: Long, b: Long): Fraction =
    if (a == 0L) ZERO
    else if (a == b) ONE
    else {
      val d = gcd(a, b)
      new Fraction(a / d, b / d)
    }

  def mul(x: Fraction, y: Fraction): Fraction =
    if (x == ZERO || y == ZERO) ZERO
    else if (x == ONE) y
    else if (y == ONE) x
    else fract(x.a * y.a, x.b * y.b)

  def mul(x: Long, y: Fraction): Fraction =
    if (x == 0 || y == ZERO) ZERO
    else if (x == 1) y
    else if (y == ONE) new Fraction(x, 1L)
    else fract(x * y.a, y.b)

  def sum(x: Fraction, y: Fraction): Fraction =
    if (x == ZERO) y
    else if (y == ZERO) x
    else if (x.b == y.b) fract(x.a + y.a, x.b)
    else fract(x.a * y.b + y.a * x.b, x.b * y.b)
}

class Auction(n: Int, r: Array[(Int, Int)]) {
  @inline def low(i: Int): Int = r(i)._1
  @inline def hi(i: Int): Int = r(i)._2
  @inline def length(i: Int): Int = r(i)._2 - r(i)._1 + 1

  def pFirst(firstFrom: Int, excluded: Int): Fraction = {
    @inline def from(i: Int) = if (i < excluded) firstFrom + 1 else firstFrom
    @inline def till(i: Int) = if (i < excluded) firstFrom else firstFrom - 1
    val fs = (0 until n).filter(i => i != excluded && from(i) <= hi(i))
    if (fs.isEmpty) ZERO
    else
      fs.map(f =>
        (0 until n).filter(i => i != excluded && i != f).
          map(i => if (hi(i) <= till(i)) ONE
                   else if (till(i) < low(i)) ZERO
                   else fract(till(i) - low(i) + 1, length(i))).
          foldLeft(fract(hi(f) - math.max(from(f), low(f)) + 1, length(f)))(mul)
      ).reduce(sum)
  }

  def expectationOfSecond(): Fraction = {
    val secondFrom = (0 until n).map(low).sortWith(_ > _)(1)
    val secondTo = (0 until n).map(hi).sortWith(_ > _)(1)
    (for {
      second <- secondFrom to secondTo
      i <- 0 until n if low(i) <= second && second <= hi(i)
    } yield fract(second, length(i)) * pFirst(second, i)) reduce sum
  }

}

import java.io.FileInputStream
import java.util.Scanner

object Solution {
  def main(args: Array[String]) {
    val sc = new Scanner(if (args.length > 0) new FileInputStream(args(0)) else System.in)
    val n = sc.nextInt
    val arr = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt()))
    println(new Auction(n, arr).expectationOfSecond())
  }
}
class Auction(n: Int, r: Array[(Int, Int)]) {
  def low(i: Int): Int = r(i)._1
  def hi(i: Int): Int = r(i)._2
  def length(i: Int): Int = r(i)._2 - r(i)._1 + 1

  val ZERO = BigInt(0)
  val ONE = BigInt(0)
  def gcd(a: BigInt, b: BigInt): BigInt = if (b == ZERO) a else gcd(b, a % b)

  def simplify(a: BigInt, b: BigInt): (BigInt, BigInt) = {
    val g = gcd(a, b)
    if (g == ONE) (a, b) else (a / g, b / g)
  }

  def expectationOfSecond(): Double = {
    val secondFrom = (0 until n).map(low).sortWith(_ > _)(1)
    val secondTo = (0 until n).map(hi).sortWith(_ > _)(1)
    val summands =
      for {
        second <- secondFrom to secondTo
        si <- 0 until n if low(si) <= second && second <= hi(si)
        fi <- 0 until n if fi != si && (if (fi < si) second + 1 else second) <= hi(fi)
        if (0 until n).filter(i => i != si && i != fi).forall(i => low(i) <= (if (i < si) second + 1 else second))
      } yield {
        val a0: BigInt = second * (hi(fi) - math.max(if (fi < si) second + 1 else second, low(fi)) + 1)
        val b0: BigInt = length(si) * length(fi)
        val is = (0 until n).filter(i => i != si && i != fi && hi(i) > (if (i < si) second else second - 1))
        val a = is.map(i => (if (i < si) second else second - 1) - low(i) + 1).foldLeft(a0)(_ * _)
        val b = is.map(i => length(i)).foldLeft(b0)(_ * _)
        simplify(a, b)
      }
    //val optimized = summands
    val grouped = summands.groupBy(_._2).mapValues(_.map(_._1).sum).map(p => simplify(p._2, p._1))
    grouped.map(p => BigDecimal(p._1) / BigDecimal(p._2)).sum.toDouble
  }
}

import Fraction._
import java.io.FileInputStream
import java.util.Scanner

object Solution {
  def main(args: Array[String]) {
    val sc = new Scanner(if (args.length > 0) new FileInputStream(args(0)) else System.in)
    val n = sc.nextInt
    val arr = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt()))
    val expectation = new Auction(n, arr).expectationOfSecond().toDouble
    println(expectation)
  }
}

class Fraction(val a:Long, val b:Long) {
  def toDouble: Double = if (a == 0) 0.0 else a.toDouble / b

  def *(that: Fraction): Fraction = mul(this, that)

  override def toString: String =
    if (a == 0) "0"
    else if (b == 1) a.toString
    else a + "/" + b
}

object Fraction {
  val ZERO = new Fraction(0L, 1L)
  val ONE = new Fraction(1L, 1L)
  def gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
  def fract(a: Long, b: Long): Fraction =
    if (a == 0L) ZERO
    else if (a == b) ONE
    else {
      val d = gcd(a, b)
      new Fraction(a / d, b / d)
    }

  def mul(x: Fraction, y: Fraction): Fraction =
    if (x == ZERO || y == ZERO) ZERO
    else if (x == ONE) y
    else if (y == ONE) x
    else fract(x.a * y.a, x.b * y.b)

  def mul(x: Long, y: Fraction): Fraction =
    if (x == 0 || y == ZERO) ZERO
    else if (x == 1) y
    else if (y == ONE) new Fraction(x, 1L)
    else fract(x * y.a, y.b)

  def sum(x: Fraction, y: Fraction): Fraction =
    if (x == ZERO) y
    else if (y == ZERO) x
    else if (x.b == y.b) fract(x.a + y.a, x.b)
    else fract(x.a * y.b + y.a * x.b, x.b * y.b)
}

class Auction(n: Int, r: Array[(Int, Int)]) {
  @inline def low(i: Int): Int = r(i)._1
  @inline def hi(i: Int): Int = r(i)._2
  @inline def length(i: Int): Int = r(i)._2 - r(i)._1 + 1

  def pFirst(firstFrom: Int, excluded: Int): Fraction = {
    @inline def from(i: Int) = if (i < excluded) firstFrom + 1 else firstFrom
    @inline def till(i: Int) = if (i < excluded) firstFrom else firstFrom - 1
    val fs = (0 until n).filter(i => i != excluded && from(i) <= hi(i))
    if (fs.isEmpty) ZERO
    else
      fs.map(f =>
        (0 until n).filter(i => i != excluded && i != f).
          map(i => if (hi(i) <= till(i)) ONE
                   else if (till(i) < low(i)) ZERO
                   else fract(till(i) - low(i) + 1, length(i))).
          foldLeft(fract(hi(f) - math.max(from(f), low(f)) + 1, length(f)))(mul)
      ).reduce(sum)
  }

  def expectationOfSecond(): Fraction = {
    val secondFrom = (0 until n).map(low).sortWith(_ > _)(1)
    val secondTo = (0 until n).map(hi).sortWith(_ > _)(1)
    (for {
      second <- secondFrom to secondTo
      i <- 0 until n if low(i) <= second && second <= hi(i)
    } yield fract(second, length(i)) * pFirst(second, i)) reduce sum
  }

}

import Fraction._
import java.io.FileInputStream
import java.util.Scanner

object Solution {
  def main(args: Array[String]) {
    // assert(new Auction(3, Array((4, 7), (8, 10), (5, 5))).expectationOfSecond().toDouble == 5.75)
    // assert(new Auction(3, Array((2,5), (3,4), (1,6))).expectationOfSecond().toDouble == 3.5)
    val sc = new Scanner(if (args.length > 0) new FileInputStream(args(0)) else System.in)
    val n = sc.nextInt
    val arr = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt()))
    val start = System.nanoTime()
    val expectation = new Auction(n, arr).expectationOfSecond().toDouble
    val end = System.nanoTime()
    println(expectation)
    println("Time = " + (end - start) / 1000000L)
  }
}

class Fraction(val a:Long, val b:Long) {
  def toDouble: Double = if (a == 0) 0.0 else a.toDouble / b

  def *(that: Fraction): Fraction = mul(this, that)

  override def toString: String =
    if (a == 0) "0"
    else if (b == 1) a.toString
    else a + "/" + b
}

object Fraction {
  val ZERO = new Fraction(0L, 1L)
  val ONE = new Fraction(1L, 1L)
  def gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
  def fract(a: Long, b: Long): Fraction =
    if (a == 0L) ZERO
    else if (a == b) ONE
    else {
      val d = gcd(a, b)
      new Fraction(a / d, b / d)
    }

//  def mul(x: Fraction, y: Fraction): Fraction =
//    if (x == ZERO || y == ZERO) ZERO
//    else if (x == ONE) y
//    else if (y == ONE) x
//    else {
//      val gcd1 = gcd(x.a, y.b)
//      val gcd2 = gcd(x.b, y.a)
//      fract((x.a / gcd1) * (y.a / gcd2), (x.b / gcd2) * (y.b / gcd1))
//      if (x.a * y.a < x.a || x.a * y.a < y.a) println(x.a, y.a, x.a * y.a)
//      fract( x.a * y.a, x.b * y.b)
//    }

  def mul(x: Fraction, y: Fraction): Fraction = mulUnsafe(reduce(x), reduce(y))
  def mulUnsafe(x: Fraction, y: Fraction): Fraction =
    if (x == ZERO || y == ZERO) ZERO
    else if (x == ONE) y
    else if (y == ONE) x
    else {
      val gcd1 = gcd(x.a, y.b)
      val gcd2 = gcd(x.b, y.a)
      fract((x.a / gcd1) * (y.a / gcd2), (x.b / gcd2) * (y.b / gcd1))
      if (x.a * y.a < x.a || x.a * y.a < y.a) println(x.a, y.a, x.a * y.a)
      fract( x.a * y.a, x.b * y.b)
    }

  def mul(x: Long, y: Fraction): Fraction =
    if (x == 0 || y == ZERO) ZERO
    else if (x == 1) y
    else if (y == ONE) new Fraction(x, 1L)
    else fract(x * y.a, y.b)

//  def sum(x: Fraction, y: Fraction): Fraction =
//    if (x == ZERO) y
//    else if (y == ZERO) x
//    else if (x.b == y.b) fract(x.a + y.a, x.b)
//    else {
//      val g = gcd(x.b, y.b)
//      if (g == 1) fract(x.a * y.b + y.a * x.b, x.b * y.b)
//      else fract(x.a * (y.b / g) + y.a * (x.b / g), x.b / g * y.b)
//    }

  def sumUnsafe(x: Fraction, y: Fraction): Fraction =
    if (x == ZERO) y
    else if (y == ZERO) x
    else if (x.b == y.b) fract(x.a + y.a, x.b)
    else {
      val g = gcd(x.b, y.b)
      if (g == 1) fract(x.a * y.b + y.a * x.b, x.b * y.b)
      else fract(x.a * (y.b / g) + y.a * (x.b / g), x.b / g * y.b)
    }

  def sum(x: Fraction, y: Fraction): Fraction = sumUnsafe(reduce(x),reduce(y))

  val MAX: Long = Integer.MAX_VALUE
  def reduce(x: Fraction): Fraction =
    if (x.a < MAX && x.b < MAX) x
    else {
      var a = x.a
      var b = x.b
      while (a > MAX || b > MAX) {
        a >>= 1
        b >>= 1
      }
      fract(a, b)
    }
}

//class BigFraction(val a:BigInt, val b:BigInt) {
//
//}
//
//object BigFraction {
//  def sum(x: BigFraction, y: Fraction): BigFraction = {
//
//  }
//}

class Auction(n: Int, r: Array[(Int, Int)]) {
  @inline def low(i: Int): Int = r(i)._1
  @inline def hi(i: Int): Int = r(i)._2
  @inline def length(i: Int): Int = r(i)._2 - r(i)._1 + 1

  def pFirst(firstFrom: Int, excluded: Int): Fraction = {
    @inline def from(i: Int) = if (i < excluded) firstFrom + 1 else firstFrom
    @inline def till(i: Int) = if (i < excluded) firstFrom else firstFrom - 1
    val fs = (0 until n).filter(i => i != excluded && from(i) <= hi(i))
    if (fs.isEmpty) ZERO
    else
      fs.map(f =>
        (0 until n).filter(i => i != excluded && i != f).
          map(i => if (hi(i) <= till(i)) ONE
                   else if (till(i) < low(i)) ZERO
                   else fract(till(i) - low(i) + 1, length(i))).
          foldLeft(fract(hi(f) - math.max(from(f), low(f)) + 1, length(f)))(mul)
      ).reduce(sum)
  }

  def expectationOfSecond(): Fraction = {
    val secondFrom = (0 until n).map(low).sortWith(_ > _)(1)
    val secondTo = (0 until n).map(hi).sortWith(_ > _)(1)
    val summands =
      for {
        second <- secondFrom to secondTo
        i <- 0 until n if low(i) <= second && second <= hi(i)
      } yield fract(second, length(i)) * pFirst(second, i)
    val optimized = summands.groupBy(_.b).mapValues(_.map(_.a).sum).map(p => fract(p._2, p._1))
    optimized.reduce(sum)
  }

}

import Fraction._
import java.io.FileInputStream
import java.util.Scanner

object Solution {
  def main(args: Array[String]) {
    // assert(new Auction(3, Array((4, 7), (8, 10), (5, 5))).expectationOfSecond().toDouble == 5.75)
    // assert(new Auction(3, Array((2,5), (3,4), (1,6))).expectationOfSecond().toDouble == 3.5)
    val sc = new Scanner(if (args.length > 0) new FileInputStream(args(0)) else System.in)
    val n = sc.nextInt
    val arr = Array.tabulate(n)(_ => (sc.nextInt(), sc.nextInt()))
//    val start = System.nanoTime()
    val expectation = new Auction(n, arr).expectationOfSecond().toDouble
//    val end = System.nanoTime()
    println(expectation)
//    println("Time = " + (end - start) / 1000000L)
  }
}

class Fraction(val a:Long, val b:Long) {
  def toDouble: Double = if (a == 0) 0.0 else a.toDouble / b

  def *(that: Fraction): Fraction = mul(this, that)

  override def toString: String =
    if (a == 0) "0"
    else if (b == 1) a.toString
    else a + "/" + b
}

object Fraction {
  val ZERO = new Fraction(0L, 1L)
  val ONE = new Fraction(1L, 1L)
  def gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
  def fract(a: Long, b: Long): Fraction =
    if (a == 0L) ZERO
    else if (a == b) ONE
    else {
      val d = gcd(a, b)
      new Fraction(a / d, b / d)
    }

//  def mul(x: Fraction, y: Fraction): Fraction =
//    if (x == ZERO || y == ZERO) ZERO
//    else if (x == ONE) y
//    else if (y == ONE) x
//    else {
//      val gcd1 = gcd(x.a, y.b)
//      val gcd2 = gcd(x.b, y.a)
//      fract((x.a / gcd1) * (y.a / gcd2), (x.b / gcd2) * (y.b / gcd1))
//      if (x.a * y.a < x.a || x.a * y.a < y.a) println(x.a, y.a, x.a * y.a)
//      fract( x.a * y.a, x.b * y.b)
//    }

  def mul(x: Fraction, y: Fraction): Fraction = mulUnsafe(reduce(x), reduce(y))
  def mulUnsafe(x: Fraction, y: Fraction): Fraction =
    if (x == ZERO || y == ZERO) ZERO
    else if (x == ONE) y
    else if (y == ONE) x
    else {
      //val gcd1 = gcd(x.a, y.b)
      //val gcd2 = gcd(x.b, y.a)
      // fract((x.a / gcd1) * (y.a / gcd2), (x.b / gcd2) * (y.b / gcd1))
      // if (x.a * y.a < x.a || x.a * y.a < y.a) println(x.a, y.a, x.a * y.a)
      fract( x.a * y.a, x.b * y.b)
    }

  def mul(x: Long, y: Fraction): Fraction =
    if (x == 0 || y == ZERO) ZERO
    else if (x == 1) y
    else if (y == ONE) new Fraction(x, 1L)
    else fract(x * y.a, y.b)

//  def sum(x: Fraction, y: Fraction): Fraction =
//    if (x == ZERO) y
//    else if (y == ZERO) x
//    else if (x.b == y.b) fract(x.a + y.a, x.b)
//    else {
//      val g = gcd(x.b, y.b)
//      if (g == 1) fract(x.a * y.b + y.a * x.b, x.b * y.b)
//      else fract(x.a * (y.b / g) + y.a * (x.b / g), x.b / g * y.b)
//    }

  def sumUnsafe(x: Fraction, y: Fraction): Fraction =
    if (x == ZERO) y
    else if (y == ZERO) x
    else if (x.b == y.b) fract(x.a + y.a, x.b)
    else {
      val g = gcd(x.b, y.b)
      if (g == 1) fract(x.a * y.b + y.a * x.b, x.b * y.b)
      else fract(x.a * (y.b / g) + y.a * (x.b / g), x.b / g * y.b)
    }

  def sum(x: Fraction, y: Fraction): Fraction = sumUnsafe(reduce(x),reduce(y))

  val MAX: Long = Integer.MAX_VALUE
  def reduce(x: Fraction): Fraction =
    if (x.a < MAX && x.b < MAX) x
    else {
      var a = x.a
      var b = x.b
      while (a > MAX || b > MAX) {
        a >>= 1
        b >>= 1
      }
      fract(a, b)
    }
}

//class BigFraction(val a:BigInt, val b:BigInt) {
//
//}
//
//object BigFraction {
//  def sum(x: BigFraction, y: Fraction): BigFraction = {
//
//  }
//}

class Auction(n: Int, r: Array[(Int, Int)]) {
  @inline def low(i: Int): Int = r(i)._1
  @inline def hi(i: Int): Int = r(i)._2
  @inline def length(i: Int): Int = r(i)._2 - r(i)._1 + 1

  def pFirst(firstFrom: Int, excluded: Int): Fraction = {
    @inline def from(i: Int) = if (i < excluded) firstFrom + 1 else firstFrom
    @inline def till(i: Int) = if (i < excluded) firstFrom else firstFrom - 1
    val fs = (0 until n).filter(i => i != excluded && from(i) <= hi(i))
    if (fs.isEmpty) ZERO
    else
      fs.map(f =>
        (0 until n).filter(i => i != excluded && i != f).
          map(i => if (hi(i) <= till(i)) ONE
                   else if (till(i) < low(i)) ZERO
                   else fract(till(i) - low(i) + 1, length(i))).
          foldLeft(fract(hi(f) - math.max(from(f), low(f)) + 1, length(f)))(mul)
      ).reduce(sum)
  }

  def expectationOfSecond(): Fraction = {
    val secondFrom = (0 until n).map(low).sortWith(_ > _)(1)
    val secondTo = (0 until n).map(hi).sortWith(_ > _)(1)
    val summands =
      for {
        second <- secondFrom to secondTo
        i <- 0 until n if low(i) <= second && second <= hi(i)
      } yield fract(second, length(i)) * pFirst(second, i)
    val optimized = summands.groupBy(_.b).mapValues(_.map(_.a).sum).map(p => fract(p._2, p._1))
    optimized.reduce(sum)
  }

}


Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption.Spinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one):  After the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in.Slastyona managed to have spinner rotating for exactly n seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.

There are two characters in the first string – the starting and the ending position of a spinner. The position is encoded with one of the following characters: v (ASCII code 118, lowercase v), < (ASCII code 60), ^ (ASCII code 94) or > (ASCII code 62) (see the picture above for reference). Characters are separated by a single space. In the second strings, a single number n is given (0 ≤ n ≤ 109) – the duration of the rotation. It is guaranteed that the ending position of a spinner is a result of a n second spin in any of the directions, assuming the given starting position.

Output cw, if the direction is clockwise, ccw – if counter-clockwise, and undefined otherwise.

object A 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 s = readLine
  val Array(n) = readInts(1)

  val dir = Map('v' -> 0, '<' -> 1, '^' -> 2, '>' -> 3)

  val rot = (dir(s(2)) - dir(s(0)) + 4) % 4

  val res = if (rot == 2 || rot == 0) "undefined" else
    if (n % 4 == rot) "cw"
  else "ccw"

  println(res)
}


Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown.

The first input line contains the name of the gesture that Uncle Fyodor showed, the second line shows which gesture Matroskin showed and the third line shows Sharic’s gesture.

Print "F" (without quotes) if Uncle Fyodor wins. Print "M" if Matroskin wins and "S" if Sharic wins. If it is impossible to find the winner, print "?".

object RockPaperScissors48A extends App {
    import java.io.{InputStream, PrintStream}
    import java.util.Scanner
    solve(System.in,System.out)

    trait Gesture {
      val user: String
      def against(gesture: Gesture): Gesture
    }
    case class Rock(user: String) extends Gesture {
      override def against(gesture: Gesture): Gesture = gesture match {
        case Rock(other) => if(other.equals(user)) this else Rock("?")
        case s: Scissors => this
        case p: Paper => p
      }
    }
    case class Scissors(user: String) extends Gesture {
      override def against(gesture: Gesture): Gesture = gesture match {
        case r: Rock => r
        case Scissors(other) =>if(other.equals(user)) this else  Scissors("?")
        case p: Paper => this
      }
    }
    case class Paper(user: String) extends Gesture {
      override def against(gesture: Gesture): Gesture = gesture match {
        case r: Rock => this
        case s: Scissors => s
        case Paper(other) => if(other.equals(user)) this else Paper("?")
      }
    }
  def build(s: String,user: String): Gesture = {
    s match {
      case "rock" => Rock(user)
      case "paper" => Paper(user)
      case _ => Scissors(user)
    }
  }
    def solve(in: InputStream, out: PrintStream): Unit = {
        val scanner = new Scanner(in)
      val a = build(scanner.next(),"F")
      val b = build(scanner.next(),"M")
      val c = build(scanner.next(),"S")
      val winner1 = a against b against c
      val winner2 = a against c against b
      if(winner1 == winner2)
        out.println(winner1.user)
      else
        out.println("?")
    }
}


The Little Elephant loves chess very much. One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8 × 8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doesn't have any side-adjacent cells with the same color and the upper left cell is white. To play chess, they want to make the board they have a proper chessboard. For that the friends can choose any row of the board and cyclically shift the cells of the chosen row, that is, put the last (rightmost) square on the first place in the row and shift the others one position to the right. You can run the described operation multiple times (or not run it at all).For example, if the first line of the board looks like that "BBBBBBWW" (the white cells of the line are marked with character "W", the black cells are marked with character "B"), then after one cyclic shift it will look like that "WBBBBBBW".Help the Little Elephant and his friend to find out whether they can use any number of the described operations to turn the board they have into a proper chessboard.

The input consists of exactly eight lines. Each line contains exactly eight characters "W" or "B" without any spaces: the j-th character in the i-th line stands for the color of the j-th cell of the i-th row of the elephants' board. Character "W" stands for the white color, character "B" stands for the black color. Consider the rows of the board numbered from 1 to 8 from top to bottom, and the columns — from 1 to 8 from left to right. The given board can initially be a proper chessboard.

In a single line print "YES" (without the quotes), if we can make the board a proper chessboard and "NO" (without the quotes) otherwise.

WBWBWBWB
BWBWBWBW
BWBWBWBW
BWBWBWBW
WBWBWBWB
WBWBWBWB
BWBWBWBW
WBWBWBWB

WBWBWBWB
WBWBWBWB
BBWBWWWB
BWBWBWBW
BWBWBWBW
BWBWBWWW
BWBWBWBW
BWBWBWBW

NoteIn the first sample you should shift the following lines one position to the right: the 3-rd, the 6-th, the 7-th and the 8-th.In the second sample there is no way you can achieve the goal.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val d = (1 to 8).map(_ => in.next())
  if (d.forall(t => t == "WBWBWBWB" || t == "BWBWBWBW"))
    println("YES")
  else
    println("NO")
}

object Main{

    def different(a: String, b: String, pos: Int = 0): Boolean = {
        if (pos >= a.length) true else{
            if (a(pos) == b(pos)) false else different(a, b, pos+1)
        }
    }                                         //> different: (a: String, b: String, pos: Int)Boolean

    def validPair(a: String, b: String, remainTry: Int = 0): Boolean = {
        if (remainTry == a.length) false else{
            if (different(a, b)) true else{
                val nextA = a.substring(1) + a(0)
                validPair(nextA, b, remainTry+1)
            }
        }
    }                                         //> validPair: (a: String, b: String, remainTry: Int)Boolean

    def alterChar(s: String, pos: Int = 1): Boolean = {
        if (pos == s.length) true else{
            if (s(pos) == s(pos-1)) false else alterChar(s, pos+1)
        }
    }                                         //> alterChar: (s: String, pos: Int)Boolean

    def validRow(s: String, remainTry: Int = 0): Boolean = {
        if (remainTry == s.length) false else{
            if (alterChar(s)) true else{
                val nextS = s.substring(1) + s(0)
                validRow(nextS, remainTry + 1)
            }
        }
    }                                         //> validRow: (s: String, remainTry: Int)Boolean

    def validBoard(board: Array[String])={
        var ret = true
        if (!validRow(board(0))) ret = false
        for (i <- 1 until board.length){
            if (!validPair(board(i-1), board(i))) ret = false
        }
        ret
    }                                         //> validBoard: (board: Array[String])Boolean

    def main(args: Array[String]) = {
        val board = new Array[String](8)
        for (i <- 0 until 8){
            board(i) = readLine()
        }
        if (validBoard(board)) println("YES") else println("NO")

    }                                         //> main: (args: Array[String])Unit
}

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

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

  val B = List.fill(8)(sc.nextLine)

  def solve(): String = if (B forall (s => s == "WBWBWBWB" || s == "BWBWBWBW")) "YES"
                        else "NO"

  out.println(solve)
  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 bw = "(BW)*"
  val wb = "(WB)*"
  val ans = (for(_ <- 1 to 8) yield reader.readLine()).forall(s => s.matches(bw) || s.matches(wb))
  val yesNoAns = Map(true -> "YES", false -> "NO")

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

object Main {
  def correct(row: String): Boolean = {
    val sum = row.zipWithIndex.map{ t =>
      if (t._1 == 'W') 1 << t._2
      else 0
    }.sum
    if (sum == 0x55 || sum == 0xAA) true
    else false
  }

  def main(args: Array[String]) {
    val cor = (1 to 8).map(_ => readLine()).map(correct(_)).foldLeft(true)(_ & _)
    if (cor) println("YES")
    else println("NO")
  }
}

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

    val s1="WBWBWBWB"
    val s2="BWBWBWBW"
    (1 to 8).foreach{i=>
      val str=readLine
      if(str!=s1 && str!=s2){
        println("NO")
        return
      }
    }
    println("YES")
  }
}

object Ches {
     def main(args:Array[String]):Unit={
       var list=List[String]()
       for(i<-0 until 8){
          list=list:+readLine()
       }
       if(solve(list)) println("YES")
       else println("NO")
     }
  def solve(list:List[String]):Boolean={
    def isNormal(str:String):Boolean={
      def strIter(str:String, c:Char):Boolean={
        if(str.length==0) true
        else if(c==str.head) false
        else strIter(str.tail, str.head)
      }
      strIter(str, str.last)
    }
    if(list.length==0) true
    else if(!isNormal(list.head)) false
    else solve(list.tail)
  }
}

object Main{

    def different(a: String, b: String, pos: Int = 0): Boolean = {
        if (pos >= a.length) true else{
            if (a(pos) == b(pos)) false else different(a, b, pos+1)
        }
    }                                         //> different: (a: String, b: String, pos: Int)Boolean

    def validPair(a: String, b: String, remainTry: Int = 0): Boolean = {
        if (remainTry == a.length) false else{
            if (different(a, b)) true else{
                val nextA = a.substring(1) + a(0)
                validPair(nextA, b, remainTry+1)
            }
        }
    }                                         //> validPair: (a: String, b: String, remainTry: Int)Boolean

    def validBoard(board: Array[String])={
        var ret = true
        for (i <- 1 until board.length){
            if (!validPair(board(i-1), board(i))) ret = false
        }
        ret
    }                                         //> validBoard: (board: Array[String])Boolean

    def main(args: Array[String]) = {
        val board = new Array[String](8)
        for (i <- 0 until 8){
            board(i) = readLine()
        }
        if (validBoard(board)) println("YES") else println("NO")

    }                                         //> main: (args: Array[String])Unit
}


n hobbits are planning to spend the night at Frodo's house. Frodo has n beds standing in a row and m pillows (n ≤ m). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have. Frodo will sleep on the k-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt?

The only line contain three integers n, m and k (1 ≤ n ≤ m ≤ 109, 1 ≤ k ≤ n) — the number of hobbits, the number of pillows and the number of Frodo's bed.

Print single integer — the maximum number of pillows Frodo can have so that no one is hurt.

NoteIn the first example Frodo can have at most two pillows. In this case, he can give two pillows to the hobbit on the first bed, and one pillow to each of the hobbits on the third and the fourth beds.In the second example Frodo can take at most four pillows, giving three pillows to each of the others.In the third example Frodo can take three pillows, giving two pillows to the hobbit in the middle and one pillow to the hobbit on the third bed.

object Solution extends App {

  val arr = io.StdIn.readLine().split(" ").map(_.toLong);
  val n = arr(0)
  var m = arr(1)
  val k = arr(2)

  def calcPillows(x: Long, y: Long) = {
    def maxBed(x: Long, y: Long) = (x - 1) * x / 2 + y - (x - 1)

    def maxPillow(x: Long, y: Long) = (x - 1 + x - y) * y / 2

    if (y >= x - 1) maxBed(x, y) else maxPillow(x, y)
  }

  def binSearch(start: Long, end: Long): Long = {
    val mid = (end + start) / 2
    val calc = calcPillows(mid, k - 1)
    val calcAnother = calcPillows(mid, n - k)
    if (end - start <= 1) mid
    else if (calc + calcAnother + mid <= m) binSearch(mid, end) else binSearch(start, mid)
  }

  print(binSearch(1, m + 1))

}

object Solution extends App {

  val arr = io.StdIn.readLine().split(" ").map(_.toLong);
  val n = arr(0)
  val m = arr(1)
  val k = arr(2)

  def calcPillows(x: Long, y: Long) = {
    def maxBed(x: Long, y: Long) = (x - 1) * x / 2 + y - x + 1

    def maxPillow(x: Long, y: Long) = (x - 1 + x - y) * y / 2

    if (y > x - 1) maxBed(x, y) else maxPillow(x, y)
  }

  def binSearch(start: Long, end: Long): Long = {
    val mid = (end + start) / 2
    val calc = calcPillows(mid, k - 1)
    val calcAnother = calcPillows(mid, n - k - 1)
    if (end - start <= 1) mid
    else if (calc + calcAnother + mid <= m) binSearch(mid, end) else binSearch(start, mid)
  }

  print(binSearch(1, m + 1))

}

object Solution extends App {

  val arr = io.StdIn.readLine().split(" ").map(_.toLong);
  val n = arr(0)
  val m = arr(1)
  val k = arr(2)

  def calcPillows(x: Long, y: Long) = {
    def maxBed(x: Long, y: Long) = (x - 1) * x / 2 + y - x + 1

    def maxPillow(x: Long, y: Long) = (x - 1 + x - y) * y / 2

    if (y > x - 1) maxBed(x, y) else maxPillow(x, y)
  }

  def binSearch(start: Long, end: Long): Long = {
    val mid = (end + start) / 2
    val calc = calcPillows(mid, k)
    val calcAnother = calcPillows(mid, n - k + 1)
    if (end - start <= 1) mid
    else if (calc + calcAnother <= m) binSearch(mid, end) else binSearch(start, mid)
  }

  print(binSearch(1, m + 1))

}


Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions $$$a$$$, $$$b$$$ and $$$c$$$ respectively. At the end of the performance, the distance between each pair of ropewalkers was at least $$$d$$$.Ropewalkers can walk on the rope. In one second, only one ropewalker can change his position. Every ropewalker can change his position exactly by $$$1$$$ (i. e. shift by $$$1$$$ to the left or right direction on the rope). Agafon, Boniface and Konrad can not move at the same time (Only one of them can move at each moment). Ropewalkers can be at the same positions at the same time and can "walk past each other".You should find the minimum duration (in seconds) of the performance. In other words, find the minimum number of seconds needed so that the distance between each pair of ropewalkers can be greater or equal to $$$d$$$.Ropewalkers can walk to negative coordinates, due to the rope is infinite to both sides.

The only line of the input contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$1 \le a, b, c, d \le 10^9$$$). It is possible that any two (or all three) ropewalkers are in the same position at the beginning of the performance.

Output one integer — the minimum duration (in seconds) of the performance.

NoteIn the first example: in the first two seconds Konrad moves for 2 positions to the right (to the position $$$8$$$), while Agafon and Boniface stay at their positions. Thus, the distance between Agafon and Boniface will be $$$|5 - 2| = 3$$$, the distance between Boniface and Konrad will be $$$|2 - 8| = 6$$$ and the distance between Agafon and Konrad will be $$$|5 - 8| = 3$$$. Therefore, all three pairwise distances will be at least $$$d=3$$$, so the performance could be finished within 2 seconds.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val A, B, C, D = ni()
    val V = Array(A, B, C)
    sort(V)
    val ans = max(0, D - (V(1) - V(0))) + max(0, D - (V(2) - V(1)))
    out.println(ans)
  }
}

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

  override def apply(io: IO): io.type = {
    val Seq(a, b, c) = io.read[Seq, Int](3).sorted
    val d = io.read[Int]
    val ans = ((d - b + a) max 0) + ((d - c + b) max 0)
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[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 Main {

  import java.io.{PrintWriter, _}
  import java.util._

  def main(args: Array[String]): Unit = {
    val inputStream = System.in
    val outputStream = System.out
    val in = new InputReader(inputStream)
    val out = new PrintWriter(outputStream)
    val solver = new Task
    solver.solve(1, in, out)
    out.close()
  }

  def ?(item: Boolean, first: Any, second: Any): Any = if (item) first else second

  class Task {
    def solve(testNumber: Int, in: InputReader, out: PrintWriter): Unit = {
      var arr = new Array[Int](3)
      arr(0) = in.nextInt
      arr(1) = in.nextInt
      arr(2) = in.nextInt
      arr = arr.sorted
      val d = in.nextInt
      val a = math.max(arr(1) + d - arr(2), 0)
      val b = math.min(arr(1) - d - arr(0), 0)
      out.println(a - b)
    }

  }

  class InputReader(val stream: InputStream) extends AutoCloseable {
    //reader = new BufferedReader(new FileReader(stream), 32768);
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer = new 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 nextLine: String = {
      try
        return reader.readLine
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      ""
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    override def close(): Unit = {
    }
  }

}

object Main {

  import java.io.{PrintWriter, _}
  import java.util._

  def main(args: Array[String]): Unit = {
    val inputStream = System.in
    val outputStream = System.out
    val in = new InputReader(inputStream)
    val out = new PrintWriter(outputStream)
    val solver = new Task
    solver.solve(1, in, out)
    out.close()
  }

  def ?(item: Boolean, first: Any, second: Any): Any = if (item) first else second

  class Task {
    def solve(testNumber: Int, in: InputReader, out: PrintWriter): Unit = {
      var arr = new Array[Int](3)
      arr(0) = in.nextInt
      arr(1) = in.nextInt
      arr(2) = in.nextInt
      arr = arr.sorted
      val d = in.nextInt
      val a = math.max(arr(1) + d - arr(2), 0)
      val b = math.max(math.abs(arr(1) - d - arr(0)), 0)
      out.println(a + b)
    }

  }

  class InputReader(val stream: InputStream) extends AutoCloseable {
    //reader = new BufferedReader(new FileReader(stream), 32768);
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer = new 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 nextLine: String = {
      try
        return reader.readLine
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      ""
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    override def close(): Unit = {
    }
  }

}


The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:    Elements of the main diagonal.   Elements of the secondary diagonal.   Elements of the "middle" row — the row which has exactly  rows above it and the same number of rows below it.   Elements of the "middle" column — the column that has exactly  columns to the left of it and the same number of columns to the right of it.    The figure shows a 5 × 5 matrix.   The good elements are marked with green.  Help the Smart Beaver count the sum of good elements of the given matrix.

The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are:    1 ≤ n ≤ 5  The input limitations for getting 100 points are:   1 ≤ n ≤ 101

Print a single integer — the sum of good matrix elements.

NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.

import scala.io.Source

object Cf177a1 extends App {
  val a = Source.stdin.getLines.drop(1).map(_.split(" ").map(_.toInt)).toArray
  var rez = 0
  val n = a.length
  for (i <- 0 until n) {
    for (j <- 0 until n) {
      if (i == j || i == n - j - 1 || i == n / 2 || j == n / 2) rez = rez + a(i)(j)
    }
  }
  println(rez)
}