Jzzhu has invented a kind of sequences, they meet the following property:You are given x and y, please calculate fn modulo 1000000007 (109 + 7).

The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109).

Output a single integer representing fn modulo 1000000007 (109 + 7).

NoteIn the first sample, f2 = f1 + f3, 3 = 2 + f3, f3 = 1.In the second sample, f2 =  - 1;  - 1 modulo (109 + 7) equals (109 + 6).

import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 19.07.14.
 */
object B extends App {
  val home = true
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val x = nextLong
    val y = nextLong
    val p: Long = 1000 * 1000 * 1000 + 7
    val n = nextLong % 6
    val ans: Long = n match {
      case 0 => x - y
      case 1 => x
      case 2 => y
      case 3 => y - x
      case 4 => -x
      case 5 => - y
    }
    out.println((ans + 3 * p) % p)
  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(x, y) = in.next().split(" ").map(_.toInt)
  val mod = 1000000007
  val n = (in.next().toInt - 1) % 6
  val k = n % 3
  val res = k match {
    case 0 => x
    case 1 => y
    case 2 => y - x
  }

  if (n < 3) println((res % mod + mod) % mod) else {
    println((-res % mod + mod) % mod)
  }
}

import java.util.Scanner

/**
 * Created by kshim on 25/07/2014.
 */
object CF257B extends App {
  def Process(x:Long, y:Long, n:Long):Long = {
    val fn:Long = (n-1) % 6 match {
      case 0 => x
      case 1 => y
      case 2 => y - x
      case 3 => -x
      case 4 => -y
      case 5 => -y + x
    }
    val r = fn % (1000000000L + 7L)
    if(r < 0) {
      r + (1000000000L + 7L)
    } else {
      r
    }
  }
  val in = new Scanner(System.in)
  val x = in.nextInt()
  val y = in.nextInt()
  val n = in.nextInt()
  println(Process(x, y, n))
}

object B450 {

  import IO._
  import collection.{mutable => cu}
  val MOD = 1000000007L
  def main(args: Array[String]): Unit = {
    val Array(x, y) = readLongs(2)
    val a = Array(x, y, y-x,-x,-y,x-y).map(x => (x + 2*MOD)% MOD)
    val Array(n) = readInts(1)
    println(a((n-1)%6))
  }

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

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

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

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

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

}

object Sequences {

  def splitter(as: String) = as.split("\\s+") match {
    case Array(n, m) => List(n.toLong, m.toLong)
  }

  def solve(x: Long, y: Long, n: Long): Long = (n % 6) match {
    case 1 => x
    case 2 => y
    case 3 => y-x
    case 4 => -x
    case 5 => -y
    case 0 => x-y
  }

  def main(args: Array[String]) {
    val N = 1e9.toLong + 7
    val List(xyStr, nStr) = io.Source.stdin.getLines.take(2).toList
    val List(x, y) = splitter(xyStr)
    val n = nStr.toLong
    val f = solve(x, y, n)
    val fModN = f % N
    val res: Long = if (fModN>=0) fModN else fModN + N
    println(res)
  }
}

/**
 * @author Oleg Arshinsky
 */
object B extends App {{

  val Array(x, y) = readLine().split(" ").map(_.toInt)
  val n = readLine().toInt

  def _1 = x
  def _2 = y
  def _3 = y-x
  def _4 = -x
  def _5 = -y
  def _6 = x-y

  val functions = Array(_1, _2, _3, _4, _5, _6)

  val intermediate = n % 6

  val function_n = if (intermediate == 0) 6-1 else intermediate-1

  val f_n = functions(function_n)

  val a = f_n
  val b = 1000000007

  println((a - (a.toDouble/b).floor * b).toInt)

}}

object Main {
  def main(args: Array[String]): Unit = {
    val N = 1000000007
    val halfN = 500000003
    val xy = io.StdIn.readLine().split(" ").map { s =>
      val i = Integer.parseInt(s)
      if (i < 0 ) i + N else i
    }
    val n = (io.StdIn.readInt() -1) % 6
    def compute(k: Int): Long = {
      if (k > 2) -1 * compute(k - 3)
      else if (k ==2) xy(1) - xy(0)
      else xy(k)
    }
    val fn = compute(n) % N
    println(if (fn < 0) fn + N else fn)
  }
}

import scala.math.BigInt

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val x, y, n = sc.nextInt

  def solve( x: Int, y: Int, n: Int ): Int = {
    val M: Int = 1e9.toInt + 7

    val newN = (n-1) % 6

    def tail(a: BigInt, b: BigInt): Stream[BigInt] = a #:: tail(b, b - a)
    val res = tail(x, y)(newN)
    ( ( ( res % M ) + M ) mod M ).toInt
  }

  println( solve( x, y, n ) )
}

import scala.math.BigInt

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val x, y, n = sc.nextInt

  def solve2( x: Int, y: Int, n: Int ): Int = {
    val M: Int = 1e9.toInt + 7

    val newN = (n-1) % 6

    def tail(a: BigInt, b: BigInt): Stream[BigInt] = a #:: tail(b, b - a)
    val res = tail(x, y)(newN)
    ( ( ( res % M ) + M ) mod M ).toInt
  }

  def solve( x: Int, y: Int, n: Int ): Int = {
    val M: Int = 1e9.toInt + 7

    val newN = (n-1) % 6

    var memo = new Array[Int](6)
    memo(0) = x
    memo(1) = y
    for( i <- (2 until 6) ) {
      memo(i) = ( memo(i-1) - memo(i-2) ) % M
    }

    ( ( memo(newN) % M ) + M ) % M
  }

  println( solve( x, y, n ) )
}

object HelloWorld{
  def computeSeq(x: Int, y:Int, l:Int):List[Int] = l match {
    case 0 => List()
    case _ => (y-x)::computeSeq(y, y-x, l-1)
  }
  def main(args: Array[String]){
    val in = new java.util.Scanner(System.in)
    val x = in.nextInt
    val y = in.nextInt
    val n = in.nextInt-1
    val seq = x::y::computeSeq(x, y, 4)
    println(floorMod(1000*1000*1000+7)(seq(n%6)))
  }
  def floorMod(m: Int)(n: Int) = (((n % m) + m) % m)
}

import java.util.Scanner

/**
 * Created by kshim on 25/07/2014.
 */
object CF257B extends App {
  def Process(x:Long, y:Long, n:Long):Long = {
    val fn:Long = (n-1) % 6 match {
      case 0 => x
      case 1 => y
      case 2 => y - x
      case 3 => -x
      case 4 => -y
      case 5 => -y + x
    }
    if(fn < 0) {
      (fn % (1000000000L + 7L)) + (1000000000L + 7L)
    } else {
      fn % (1000000000L + 7L)
    }
  }
  val in = new Scanner(System.in)
  val x = in.nextInt()
  val y = in.nextInt()
  val n = in.nextInt()
  println(Process(x, y, n))
}

object B450 {

  import IO._
  import collection.{mutable => cu}
  val MOD = 100000007L
  def main(args: Array[String]): Unit = {
    val Array(x, y) = readLongs(2)
    val a = Array(x, y, y-x,-x,-y,x-y).map(x => (x + 2*MOD)% MOD)
    val Array(n) = readInts(1)
    println(a((n-1)%6))
  }

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

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

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

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

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

}

object Sequences {

  def splitter(as: String) = as.split("\\s+") match {
    case Array(n, m) => List(n.toLong, m.toLong)
  }

  def solve(x: Long, y: Long, n: Long): Long = (n % 6) match {
    case 1 => x
    case 2 => y
    case 3 => y-x
    case 4 => -x
    case 5 => -y
    case 0 => x-y
  }

  def main(args: Array[String]) {
    val N = 1e9.toLong + 7
    val List(xyStr, nStr) = io.Source.stdin.getLines.take(2).toList
    val List(x, y) = splitter(xyStr)
    val n = nStr.toLong
    val f = solve(x, y, n)
    val res: Long = if (f>=0) f % N else (f + N) % N
    println(res)
  }
}

object Sequences {

  def splitter(as: String) = as.split("\\s+") match {
    case Array(n, m) => List(n.toLong, m.toLong)
  }

  def solve(x: Long, y: Long, n: Long): Long = (n % 6) match {
    case 1 => x
    case 2 => y
    case 3 => y-x
    case 4 => -x
    case 5 => -y
    case 0 => x-y
  }

  def main(args: Array[String]) {
    val N = 1e9.toLong + 7
    val List(xyStr, nStr) = io.Source.stdin.getLines.take(2).toList
    val List(x, y) = splitter(xyStr)
    val n = nStr.toLong
    val f = solve(x, y, n)
    val res: Long = if (f>=0) f % N else (f % N) + N
    println(res)
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val N = 1000000007
    val halfN = 500000003
    val xy = io.StdIn.readLine().split(" ").map { s =>
      val i = Integer.parseInt(s)
      if (i > halfN) i - N else i
    }
    val n = (io.StdIn.readInt() -1) % 6
    def compute(k: Int): Long = {
      if (k > 2) -1 * compute(5 - k)
      else if (k == 0) xy(0)
      else if (k == 1) xy(1)
      else xy(1) - xy(0)
    }
    val fn = compute(n) % N
    println(if (fn < 0) fn + N else fn)
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val N = 1000000007
    val halfN = 500000003
    val xy = io.StdIn.readLine().split(" ").map { s =>
      val i = Integer.parseInt(s)
      if (i > halfN) i - N else i
    }
    val n = io.StdIn.readLong()
    val fn = (xy(1) - ((n - 2) % N) * xy(0)) % N
    println(if (fn < 0) fn + N else fn)
  }
}

import scala.math.BigInt

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val x, y, n = sc.nextInt

  def solve( x: Int, y: Int, n: Int ): Int = {
    val M: Int = 1e9.toInt + 7

    val newN = (n-1) % 6

    def tail(a: BigInt, b: BigInt): Stream[BigInt] = a #:: tail(b, b - a)
    val res = tail(x, y)(newN-1)
    ( ( ( res % M ) + M ) mod M ).toInt
  }

  println( solve( x, y, n ) )
}

import scala.math.BigInt

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val x, y, n = sc.nextInt

  def solve( x: Int, y: Int, n: Int ): Int = {
    val M: Int = 1e9.toInt + 7

    val newN = (n-1) % 6

    def tail(a: BigInt, b: BigInt): Stream[BigInt] = a #:: tail(b, b - a)
    val res = tail(x, y)(newN)
    ( ( ( res % M ) + M ) mod M ).toInt
  }

  def solve2( x: Int, y: Int, n: Int ): Int = {
    val M: Int = 1e9.toInt + 7

    val newN = (n-1) % 6

    var memo = new Array[Int](6)
    memo(0) = x
    memo(1) = y
    for( i <- (2 until 6) ) {
      memo(i) = ( ( ( memo(i-1) + memo(i-2) ) % M ) + M ) % M
    }

    memo(newN)
  }

  println( solve2( x, y, n ) )
}

import scala.math.BigInt

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val x, y, n = sc.nextInt

  def solve( x: Int, y: Int, n: Int ): Int = {
    val M: Int = 1e9.toInt + 7

    val newN = (n-1) % 6

    def tail(a: BigInt, b: BigInt): Stream[BigInt] = a #:: tail(b, b - a)
    val res = tail(x, y)(newN)
    ( ( ( res % M ) + M ) mod M ).toInt
  }

  def solve2( x: Int, y: Int, n: Int ): Int = {
    val M: Int = 1e9.toInt + 7

    val newN = (n-1) % 6

    var memo = new Array[Int](6)
    memo(0) = x
    memo(1) = y
    for( i <- (2 until 6) ) {
      memo(i) = ( ( ( memo(i-1) - memo(i-2) ) % M ) + M ) % M
    }

    memo(newN)
  }

  println( solve2( x, y, n ) )
}


Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.

The only line of the input file contains two natural numbers Y and W — the results of Yakko's and Wakko's die rolls.

Output the required probability in the form of irreducible fraction in format «A/B», where A — the numerator, and B — the denominator. If the required probability equals to zero, output «0/1». If the required probability equals to 1, output «1/1».

NoteDot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points.

import java.util.StringTokenizer

object _9A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val cb = 7 - (next.toInt max next.toInt)
  if (cb == 0) println("0/1")
  else if (cb == 1) println("1/6")
  else if (cb == 2) println("1/3")
  else if (cb == 3) println("1/2")
  else if (cb == 4) println("2/3")
  else if (cb == 5) println("5/6")
  else println("1/1")
}

//package me.jetblack.cf

import java.util.Scanner

object DiceRoll extends App {

  val s = new Scanner(System.in)

  val y = s.nextInt()
  val w = s.nextInt()

  val t = 6 - (math.max(y, w) - 1)
  if (t == 4) {
    println("2/3")
  } else if (t == 3) {
    println("1/2")
  } else if (t == 2) {
    println("1/3")
  } else if (t == 6) {
    println("1/1")
  } else {
    println(s"$t/6")
  }

}

object A9 {

  import IO._

  def main(args: Array[String]): Unit = {
    val score = readInts(2)
    val max = score.max
    val ans = Array("0/1", "1/1", "5/6", "2/3", "1/2", "1/3", "1/6")
    println(ans(max))
  }

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

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

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

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

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

}

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

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

  def solve(): String = {
    val target: Int = List.fill(2)(sc.nextInt).max
    List("dummy", "1/1", "5/6", "2/3", "1/2", "1/3", "1/6")(target)
  }

  out.println(solve)
  out.close
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

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

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def solve = {
    val y = nextInt
    val w = nextInt
    val x = 6 - Math.max(y, w) + 1
    if (x % 6 == 0) {
      out.println(x / 6 + "/" + 1)
    } else if (x % 3 == 0) {
      out.println(x / 3 + "/" + 2)
    } else if (x % 2 == 0) {
      out.println(x / 2 + "/" + 3)
    } else {
      out.println(x + "/" + 6)
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

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

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(y, w) = readLine.split(" ").map(_.toInt);
    var max = math.max(y, w);
    if (max == 1) {
      println("1/1");
    } else if (max == 2) {
      println("5/6");
    } else if (max == 3) {
      println("2/3");
    } else if (max == 4) {
      println("1/2");
    } else if (max == 5) {
      println("1/3");
    } else {
      println("1/6");
    }
  }

}

object Main {
  def main(args: Array[String]) {
    val max = readLine.split(" ").map(_.toInt).max
    max match {
      case 1 => println("1/1")
      case 2 => println("5/6")
      case 3 => println("2/3")
      case 4 => println("1/2")
      case 5 => println("1/3")
      case 6 => println("1/6")
      case _ => // to make scalac happy
    }
  }
}

object P9A {
    import io.StdIn._

    def main(args:Array[String]) {
        println(readLine.split(' ').map{_.toInt}.max match {
            case 1 => "1/1"
            case 2 => "5/6"
            case 3 => "2/3"
            case 4 => "1/2"
            case 5 => "1/3"
            case 6 => "1/6"
        })
    }
}

object dieroll extends App {
  val Array(a, b) = readLine split ' ' map (_.toInt)

  @scala.annotation.tailrec def gcd(a: Int, b: Int): Int = b match {
    case 0 => a
    case _ => gcd(b, a % b)
  }

  val total = 7 - math.max(a, b)
  val g = gcd(total, 6)

  println(s"${total/g}/${6/g}")
}

import java.util.StringTokenizer

object _9A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val cb = 6 - next.toInt max next.toInt + 1
  if (cb == 0) println("0/1")
  else if (cb == 1) println("1/6")
  else if (cb == 2) println("1/3")
  else if (cb == 3) println("1/2")
  else if (cb == 4) println("2/3")
  else if (cb == 5) println("5/6")
  else println("1/1")
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

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

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def solve = {
    val y = nextInt
    val w = nextInt
    val x = 6 - Math.max(y, w) + 1
    if (x % 2 == 0) {
      out.println(x / 2 + "/" + 3)
    } else if (x % 3 == 0) {
      out.println(x / 3 + "/" + 2)
    } else if (x % 6 == 0) {
      out.println(x / 6 + "/" + 1)
    } else {
      out.println(x / 6)
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

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

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def solve = {
    val y = nextInt
    val w = nextInt
    val x = 6 - Math.max(y, w) + 1
    if (x % 2 == 0) {
      out.println(x / 2 + "/" + 3)
    } else if (x % 3 == 0) {
      out.println(x / 3 + "/" + 2)
    } else if (x % 6 == 0) {
      out.println(x / 6 + "/" + 1)
    } else {
      out.println(x + "/" + 6)
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

object P9A {
    import io.StdIn._

    def main(args:Array[String]) {
        println(readLine.split(' ').map{_.toInt}.max match {
            case 1 => "1/0"
            case 2 => "5/6"
            case 3 => "2/3"
            case 4 => "1/2"
            case 5 => "1/3"
            case 6 => "1/6"
        })
    }
}


Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.

The first line of the input contains four space-separated positive integer numbers not exceeding 100 — lengthes of the sticks.

Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.

object P6A {
    def main(args : Array[String]) {
        val a = readLine split ' ' map {_.toInt}
        val answer = () match {
            case _ if (a combinations 3) exists {
                case Array(u, v, w) => u + v > w && v + w > u && w + u > v
            } => "TRIANGLE"
            case _ if (a combinations 3) exists {
                case Array(u, v, w) => u + v >= w && v + w >= u && w + u >= v
            } => "SEGMENT"
            case _ => "IMPOSSIBLE"
        }
        println(answer)
    }
}

object Solution6A extends Application {

  def isTriangle(a: Int, b: Int, c: Int): Boolean = a + b > c && a + c > b && b + c > a

  def isSegment(a: Int, b: Int, c: Int): Boolean = a + b == c || a + c == b || b + c == a

  def solution() {
    val a1 = _int
    val a2 = _int
    val a3 = _int
    val a4 = _int

    if (isTriangle(a1, a2, a3)) {
      println("TRIANGLE")
      return
    }
    if (isTriangle(a1, a2, a4)) {
      println("TRIANGLE")
      return
    }
    if (isTriangle(a1, a4, a3)) {
      println("TRIANGLE")
      return
    }
    if (isTriangle(a4, a2, a3)) {
      println("TRIANGLE")
      return
    }

    if (isSegment(a1, a2, a3)) {
      println("SEGMENT")
      return
    }
    if (isSegment(a1, a2, a4)) {
      println("SEGMENT")
      return
    }
    if (isSegment(a1, a4, a3)) {
      println("SEGMENT")
      return
    }
    if (isSegment(a4, a2, a3)) {
      println("SEGMENT")
      return
    }

    println("IMPOSSIBLE")
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var data = in.next().split(" ").map(_.toInt).toList.sorted

  def triangle(list: Seq[Int]): Int = {
    val sorted = list.sorted
    if (sorted(0) + sorted(1) == sorted(2)) 1
    else if (sorted(0) + sorted(1) > sorted(2)) 2
    else 0
  }

  val max = data.combinations(3).map(triangle).max
  if (max == 2)
    println("TRIANGLE")
  else if (max == 1)
    println("SEGMENT")
  else
    println("IMPOSSIBLE")
}

import java.util.Scanner

object ATriangle extends App {

  val scanner = new Scanner(System.in)

  val in = (0 until 4).map(i => scanner.nextInt().toDouble)

  val res = (0 until 4).foldLeft("IMPOSSIBLE")((r: String, c: Int) =>
    r match {
      case "TRIANGLE" => "TRIANGLE"
      case t if t =="IMPOSSIBLE" || t == "SEGMENT"  =>
        val s = co(in.remove(c).toList)
        if (math.abs(s) == 1.0) "SEGMENT"
        else if (t == "SEGMENT" && math.abs(s) > 1.0) "SEGMENT"
        else if (math.abs(s) < 1.0) "TRIANGLE"
        else "IMPOSSIBLE"

    }
  )

  println(res)

  implicit class ListExt[T](src: Seq[T]) {
    def remove(idx: Int): Seq[T] = src.take(idx) ++ src.drop(idx + 1)
  }

  def co(a:List[Double]): Double = (math.pow(a(0), 2) + math.pow(a(1), 2) - math.pow(a(2), 2)) / (2 * a(0) * a(1))

}

object A6 {

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

  def main(args: Array[String]): Unit = {
    val in = readInts(4)
    val tri = in.permutations.exists{ arr =>
      val t = arr.take(3)
      arr(0)+arr(1) > arr(2) && arr(1)+arr(2) > arr(0) && arr(0)+arr(2) > arr(1)
    }
    if(tri) {
      println("TRIANGLE")
    } else {
      val deg = in.permutations.exists{ arr =>
        val t = arr.take(3)
        arr(0)+arr(1) >= arr(2) && arr(1)+arr(2) >= arr(0) && arr(0)+arr(2) >= arr(1)
      }
      if(deg) {
        println("SEGMENT")
      } else {
        println("IMPOSSIBLE")
      }
    }
  }

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

    @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 java.util.Scanner
import scala.util.Sorting.quickSort
import scala.math.max;

object Main {

  val TRIANGLE = 2
  val SEGMENT = 1
  val IMPOSSIBLE = 0
  val map = Array("IMPOSSIBLE", "SEGMENT", "TRIANGLE")

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

    println(map(canMakeTriangle(Array(next, next, next, next))))
  }

  def canMakeTriangle(sides: Array[Int]): Int = {
    quickSort(sides)
    max(classifyTriangle(sides(0), sides(1), sides(2)), classifyTriangle(sides(1), sides(2), sides(3)))
  }

  def classifyTriangle(s0: Int, s1: Int, s2: Int) = {
    val s = s0 + s1;
    if (s < s2) IMPOSSIBLE
    else if (s == s2) SEGMENT
    else TRIANGLE
  }
}

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF6A extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val lines = Array.ofDim[Int](4)

    (0 until 4).foreach { i =>
      lines(i) = nextInt
    }

    val combinations = lines.combinations(3)
    var c1 = 0
    var c2 = 0
    combinations.foreach { arr =>
      val sortedArr = arr.sortWith(_ > _)
      if (sortedArr(1) + sortedArr(2) > sortedArr(0)) {
        c1 += 1
      } else if (sortedArr(1) + sortedArr(2) == sortedArr(0)) {
        c2 += 1
      }
    }

    if (c1 > 0) {
      out.println("TRIANGLE")
    } else if (c2 > 0) {
      out.println("SEGMENT")
    } else {
      out.println("IMPOSSIBLE")
    }
  }

  try {
    solve
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush
    out.close
  }
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  val f: PartialFunction[List[Int], String] = {
    case List(p, q, r, s) if p + q > r || q + r > s => "TRIANGLE"
    case List(p, q, r, s) if p + q == r || q + r == s => "SEGMENT"
    case _ => "IMPOSSIBLE"
  }
  val res: String = f(List.fill(4)(sc.nextInt).sorted)

  out.println(res)
  out.close
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

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

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def solve = {
    val len = new Array[Int](4)
    for (i <- 0 until 4) {
      len(i) = nextInt
    }
    var flag = false
    for (i <- 0 until 4) {
      for (j <- 0 until 4) {
        for (k <- 0 until 4) {
          if (i != j && j != k && i != k) {
            if (len(i) < len(j) + len(k) &&
              len(j) < len(i) + len(k) &&
              len(k) < len(j) + len(i) && !flag) {
              out.println("TRIANGLE")
              flag = true
            }
          }
        }
      }
    }
    if (!flag) {
      for (i <- 0 until 4) {
        for (j <- 0 until 4) {
          for (k <- 0 until 4) {
            if (i != j && j != k && i != k) {
              if ((len(i) <= len(j) + len(k) &&
                len(j) <= len(i) + len(k) &&
                len(k) <= len(j) + len(i)) && !flag) {
                out.println("SEGMENT")
                flag = true
              }
            }
          }
        }
      }
    }
    if (!flag) {
      out.println("IMPOSSIBLE")
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

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

object HelloWorld {
  def main(args: Array[String]) = {
    var arr = readLine.split(" ").map(_.toInt);
    var result = 0;
    val buffer = ArrayBuffer[Int](arr(0), arr(1), arr(2), arr(3)).sorted;
    for (i <- 0 until buffer.length) {
      val temp = buffer.clone;
      temp.remove(i);
      if (temp(0) + temp(1) > temp(2)) {
        result = math.max(result, 2);
      } else if (temp(0) + temp(1) == temp(2)) {
        result = math.max(result, 1);
      } else {
        result = math.max(result, 0);
      }
    }
    if (result == 0) {
      println("IMPOSSIBLE");
    } else if (result ==1) {
      println("SEGMENT");
    } else {
      println("TRIANGLE");
    }
  }

}

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

object HelloWorld {
  def main(args: Array[String]) = {
    var arr = readLine.split(" ").map(_.toInt);
    val list = List(arr(0), arr(1), arr(2), arr(3)).sorted;
    var result = 0;
    val buffer = ArrayBuffer[Int](arr(0), arr(1), arr(2), arr(3)).sorted;
    for (i <- 0 until buffer.length) {
      val temp = buffer.clone;
      temp.remove(i);
//      println("LIST_LENGTH = " + buffer.length);
//      println("TEMP = " + temp.toString);
//      println("LIST = " + buffer.toString);
      if (temp(0) + temp(1) > temp(2)) {
        result = math.max(result, 2);
      } else if (temp(0) + temp(1) == temp(2)) {
    	result = math.max(result, 1);
      } else {
        result = math.max(result, 0);
      }
    }
    if (result == 0) {
      println("IMPOSSIBLE");
    } else if (result ==1) {
      println("SEGMENT");
    } else {
      println("TRIANGLE");
    }
  }

}

object Main {
  def main(args: Array[String]) {
    val a = readLine().split(" ").map(_.toInt).sorted

    var traingle = false
    var segment = false
    for{
      i <- 0 to 3
      j <- i + 1 to 3
      k <- j + 1 to 3
    } {
      if (a(i) + a(j) > a(k)) traingle = true
      else if (a(i) + a(j) == a(k)) segment = true
    }
    if (traingle ) println("TRIANGLE")
    else if (segment) println("SEGMENT")
    else println("IMPOSSIBLE")
  }
}

object Main{
  def main(args: Array[String]) {
    def solve(list: List[Int]): String ={

      (list(0), list(1), list(2), list(3)) match {
        case _ if list(0) + list(1) > list(2) => "TRIANGLE"
        case _ if list(0) + list(1) > list(3) => "TRIANGLE"
        case _ if list(0) + list(2) > list(3) => "TRIANGLE"
        case _ if list(1) + list(2) > list(3) => "TRIANGLE"

        case _ if list(0) + list(1) == list(2) => "SEGMENT"
        case _ if list(0) + list(1) == list(3) => "SEGMENT"
        case _ if list(0) + list(2) == list(3) => "SEGMENT"
        case _ if list(1) + list(2) == list(3) => "SEGMENT"

        case _ => "IMPOSSIBLE"
      }
    }

    val line = scala.io.StdIn.readLine()
    val nums = line.split(" ").map(x => x.toInt).toList.sorted

    println(solve(nums))
  }
}

object Solution6A extends Application {

  def isTriangle(a: Int, b: Int, c: Int): Boolean = a + b > c && a + c > b && b + c > a

  def isSegment(a: Int, b: Int, c: Int): Boolean = !isTriangle(a, b, c) && a + b == c && a + c == b && b + c == a

  def solution() {
    val a1 = _int
    val a2 = _int
    val a3 = _int
    val a4 = _int

    if (isTriangle(a1, a2, a3)) {
      println("TRIANGLE")
      return
    }
    if (isTriangle(a1, a2, a4)) {
      println("TRIANGLE")
      return
    }
    if (isTriangle(a1, a4, a3)) {
      println("TRIANGLE")
      return
    }
    if (isTriangle(a4, a2, a3)) {
      println("TRIANGLE")
      return
    }

    if (isSegment(a1, a2, a3)) {
      println("SEGMENT")
      return
    }
    if (isSegment(a1, a2, a4)) {
      println("SEGMENT")
      return
    }
    if (isSegment(a1, a4, a3)) {
      println("SEGMENT")
      return
    }
    if (isSegment(a4, a2, a3)) {
      println("SEGMENT")
      return
    }

    println("IMPOSSIBLE")
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF6A extends App {
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next
  def nextLine = in.nextLine

  def solve = {
    val lines = Array.ofDim[Int](4)

    (0 until 4).foreach { i =>
      lines(i) = nextInt
    }

    val combinations = lines.combinations(3)
    var c1 = 0
    var c2 = 0
    combinations.foreach { x =>
      x.permutations.foreach { y =>
        if (y(0) + y(1) > y(2) && y(0) + y(1) < y(2)) {
          c1 += 1
        } else if (y(0) + y(1) == y(2)) {
          c2 += 1
        }
      }
    }

    if (c1 > 0) {
      out.println("TRIANGLE")
    } else if (c2 > 0) {
      out.println("SEGMENT")
    } else {
      out.println("IMPOSSIBLE")
    }
  }

  try {
    solve
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush
    out.close
  }
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  val isTriangle: PartialFunction[List[Int], Boolean] = {
    case List(x, y, z) => x + y > z
  }

  val res = List.fill(4)(sc.nextInt).sorted.sliding(3).find(isTriangle) match {
      case Some(x) => "TRIANGLE"
      case None    => "SEGMENT"
    }

  out.println(res)
  out.close
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

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

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def solve = {
    val len = new Array[Int](4)
    for (i <- 0 until 4) {
      len(i) = nextInt
    }
    var flag = false
    for (i <- 0 until 4) {
      for (j <- 0 until 4) {
        for (k <- 0 until 4) {
          if (i != j && j != k && i != k) {
            if (len(i) < len(j) + len(k) &&
              len(j) < len(i) + len(k) &&
              len(k) < len(j) + len(i) && !flag) {
              out.println("TRIANGLE")
              flag = true
            }
          }
        }
      }
    }
    if (!flag) {
      for (i <- 0 until 4) {
        for (j <- 0 until 4) {
          for (k <- 0 until 4) {
            if (i != j && j != k && i != k) {
              if ((len(i) <= len(j) + len(k) &&
                len(j) <= len(i) + len(k) ||
                len(k) <= len(j) + len(i)) && !flag) {
                out.println("SEGMENT")
                flag = true
              }
            }
          }
        }
      }
    }
    if (!flag) {
      out.println("IMPOSSIBLE")
    }
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}


Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 × 3 grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the game is finished. The player who draws crosses goes first. If the grid is filled, but neither Xs, nor 0s form the required line, a draw is announced.You are given a 3 × 3 grid, each grid cell is empty, or occupied by a cross or a nought. You have to find the player (first or second), whose turn is next, or print one of the verdicts below:   illegal — if the given board layout can't appear during a valid game;  the first player won — if in the given board layout the first player has just won;  the second player won — if in the given board layout the second player has just won;  draw — if the given board layout has just let to a draw.

The input consists of three lines, each of the lines contains characters ".", "X" or "0" (a period, a capital letter X, or a digit zero).

Print one of the six verdicts: first, second, illegal, the first player won, the second player won or draw.

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach {
    i =>
      b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char): Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.zeroWon && board.count(2) > board.count(1)) {
    println("illegal")
  } else if (board.xWon && board.count(2) == board.count(1)) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int): Int = arr.flatten.count(_ == item)

    def draw: Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                      st = arr(x)(x)
                      rev = arr(x)(2 - x)} yield (st, rev)
      val res = diag.foldLeft(("", ""))((acc, t) => (acc._1 + t._1, acc._2 + t._2))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

object C3 {

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

  def wins(b: Array[Array[Char]], char: Char): Boolean = {
    b.exists(_.forall(_==char)) || {
      (0 until 3).exists(j => Array(b(0)(j), b(1)(j), b(2)(j)).forall(_==char))
    } || {
      Array(b(0)(0), b(1)(1), b(2)(2)).forall(_==char)
    } || {
      Array(b(0)(2), b(1)(1), b(2)(0)).forall(_==char)
    }
  }

  def main(args: Array[String]): Unit = {
    val b = Array.fill(3)(read.toCharArray)
    val x = b.flatten.count(_ == 'X')
    val zero = b.flatten.count(_ == '0')
    if(x != zero && x != zero+1) {
      println("illegal") //also both can't win
    } else {
      if (wins(b, 'X') && wins(b, '0')) {
        println("illegal")
      } else if (wins(b, 'X')){
        if(x == zero+1)
          println("the first player won")
        else
          println("illegal")
      } else if (wins(b, '0')){
        if(x == zero)
          println("the second player won")
        else
          println("illegal")
      } else {
        if(b.flatten.contains('.')) {
          if(x == zero) {
            println("first")
          } else {
            println("second")
          }
        } else {
          println("draw")
        }
      }
    }

  }

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

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

}

object cf3C extends App {
  val s = readLine + readLine + readLine
  val numX = s count {_ == 'X'}
  val num0 = s count {_ == '0'}
  val toX = numX== num0
  val to0 = numX== num0+1
  val filled = s forall {_!='.'}
  val lines = Array(
    Array(0, 1, 2), Array(3, 4, 5), Array(6, 7, 8),
    Array(0, 3, 6), Array(1, 4, 7), Array(2, 5, 8),
    Array(0, 4, 8), Array(2, 4, 6))
  val winX = lines exists {_ forall {s(_) == 'X'}}
  val win0 = lines exists {_ forall {s(_) == '0'}}
  val answer = () match {
    case _ if !toX && !to0 || toX && winX || to0 && win0 => "illegal"
    case _ if winX => "the first player won"
    case _ if win0 => "the second player won"
    case _ if filled => "draw"
    case _ if toX => "first"
    case _ if to0 => "second"
  }
  println(answer)
}

object P3C {
    def main(args : Array[String]) {
        val s = readLine + readLine + readLine
        val numX = s count {_ == 'X'}
        val num0 = s count {_ == '0'}
        val toX = numX == num0
        val to0 = numX == num0 + 1
        val filled = s forall {_ != '.'}
        val lines = Array(
            Array(0, 1, 2), Array(3, 4, 5), Array(6, 7, 8),
            Array(0, 3, 6), Array(1, 4, 7), Array(2, 5, 8),
            Array(0, 4, 8), Array(2, 4, 6))
        val winX = lines exists {_ forall {s(_) == 'X'}}
        val win0 = lines exists {_ forall {s(_) == '0'}}
        val answer = () match {
            case _ if !toX && !to0 || toX && winX || to0 && win0 => "illegal"
            case _ if winX => "the first player won"
            case _ if win0 => "the second player won"
            case _ if filled => "draw"
            case _ if toX => "first"
            case _ if to0 => "second"
        }
        println(answer)
    }
}

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach {
    i =>
      b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char): Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.zeroWon && board.count(2) > board.count(1)) {
    println("illegal")
  } else if (board.xWon && board.count(2) == board.count(1)) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int): Int = arr.flatten.count(_ == item)

    def draw: Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                      st = arr(x)(x)
                      rev = arr(2 - x)(2 - x)} yield (st, rev)
      val res = diag.foldLeft(("", ""))((acc, t) => (acc._1 + t._1, acc._2 + t._1))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach {
    i =>
      b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char): Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.zeroWon && board.count(2) > board.count(1)) {
    println("illegal")
  } else if (board.xWon && board.count(2) == board.count(1)) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int): Int = arr.flatten.count(_ == item)

    def draw: Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                      st = arr(x)(2 - x)
                      rev = arr(2 - x)(2)} yield (st, rev)
      val res = diag.foldLeft(("", ""))((acc, t) => (acc._1 + t._1, acc._2 + t._1))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach {
    i =>
      b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char): Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.zeroWon && board.count(2) > board.count(1)) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int): Int = arr.flatten.count(_ == item)

    def draw: Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                      st = arr(x)(x)
                      rev = arr(2 - x)(2 - x)} yield (st, rev)
      val res = diag.foldLeft(("", ""))((acc, t) => (acc._1 + t._1, acc._2 + t._1))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach { i =>
    b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char):Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int):Int = arr.flatten.count(_ == item)

    def draw:Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                        st = arr(x)(x)
                        rev = arr(2 - x)(2 - x)} yield (st, rev)
      val res = diag.foldLeft(("",""))((acc, t) => (acc._1 + t._1, acc._2 + t._1))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

object C3 {

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

  def wins(b: Array[Array[Char]], char: Char): Boolean = {
    b.exists(_.forall(_==char)) || {
      (0 until 3).exists(j => Array(b(0)(j), b(1)(j), b(2)(j)).forall(_==char))
    } || {
      Array(b(0)(0), b(1)(1), b(2)(2)).forall(_==char)
    } || {
      Array(b(0)(2), b(1)(1), b(2)(0)).forall(_==char)
    }
  }

  def main(args: Array[String]): Unit = {
    val b = Array.fill(3)(read.toCharArray)
    val x = b.flatten.count(_ == 'X')
    val zero = b.flatten.count(_ == '0')
    if(x != zero || x != zero+1) {
      println("illegal") //also both can't win
    } else {
      if (wins(b, 'X') && wins(b, '0')) {
        println("illegal")
      } else if (wins(b, 'X')){
        if(x == zero+1)
          println("the first player won")
        else
          println("illegal")
      } else if (wins(b, '0')){
        if(x == zero)
          println("the second player won")
        else
          println("illegal")
      } else {
        if(b.flatten.contains('.')) {
          if(x == zero) {
            println("first")
          } else {
            println("second")
          }
        } else {
          println("draw")
        }
      }
    }

  }

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

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

}

object C3 {

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

  def wins(b: Array[Array[Char]], char: Char): Boolean = {
    b.exists(_.forall(_==char)) || {
      (0 until 3).exists(j => Array(b(0)(j), b(1)(j), b(2)(j)).forall(_==char))
    } || {
      Array(b(0)(0), b(1)(1), b(2)(2)).forall(_==char)
    } || {
      Array(b(0)(2), b(1)(1), b(2)(0)).forall(_==char)
    }
  }

  def main(args: Array[String]): Unit = {
    val b = Array.fill(3)(read.toCharArray)
    val x = b.flatten.count(_ == 'X')
    val zero = b.flatten.count(_ == '0')
    if(x < zero) {
      println("illegal") //also both can't win
    } else {
      if (wins(b, 'X') && wins(b, '0')) {
        println("illegal")
      } else if (wins(b, 'X')){
        if(x == zero+1)
          println("the first player won")
        else
          println("illegal")
      } else if (wins(b, '0')){
        if(x == zero)
          println("the second player won")
        else
          println("illegal")
      } else {
        if(b.flatten.contains('.')) {
          if(x == zero) {
            println("first")
          } else {
            println("second")
          }
        } else {
          println("draw")
        }
      }
    }

  }

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

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

}

object C3 {

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

  def wins(b: Array[Array[Char]], char: Char): Boolean = {
    b.exists(_.forall(_==char)) || {
      (0 until 3).exists(j => Array(b(0)(j), b(1)(j), b(2)(j)).forall(_==char))
    } || {
      Array(b(0)(0), b(1)(1), b(2)(2)).forall(_==char)
    } || {
      Array(b(0)(2), b(1)(1), b(2)(0)).forall(_==char)
    }
  }

  def main(args: Array[String]): Unit = {
    val b = Array.fill(3)(read.toCharArray)
    if(b.flatten.count(_ == 'X') < b.flatten.count(_ == '0') || (wins(b, 'X') && wins(b, '0')) ) {
      println("illegal") //also both can't win
    } else if (wins(b, 'X')){
      println("the first player won")
    } else if (wins(b, 'X')){
      println("the second player won")
    } else {
      if(b.flatten.contains('.')) {
        if(b.flatten.count(_ == 'X') == b.flatten.count(_ == '0')) {
          println("first")
        } else {
          println("second")
        }
      } else {
        println("draw")
      }
    }
  }

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

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

}

object P3C {
    def main(args : Array[String]) {
        val s = readLine + readLine + readLine
        val numX = s count {_ == 'X'}
        val num0 = s count {_ == '0'}
        val filled = s forall {_ != '.'}
        val lines = Array(
            Array(0, 1, 2), Array(3, 4, 5), Array(6, 7, 8),
            Array(0, 3, 6), Array(1, 4, 7), Array(2, 5, 8),
            Array(0, 4, 8), Array(2, 4, 6))
        val winX = lines exists {_ forall {s(_) == 'X'}}
        val win0 = lines exists {_ forall {s(_) == '0'}}
        val answer = () match {
            case _ if numX < num0 || num0 + 1 < numX => "Illegal"
            case _ if winX && win0 => "Illegal"
            case _ if winX => "the first player won"
            case _ if win0 => "the second player won"
            case _ if filled => "draw"
            case _ if numX == num0 => "first"
            case _ => "second"
        }
        println(answer)
    }
}

object P3C {
    def main(args : Array[String]) {
        val s = readLine + readLine + readLine
        val numX = s count {_ == 'X'}
        val num0 = s count {_ == '0'}
        val filled = s forall {_ != '.'}
        val lines = Array(
            Array(0, 1, 2), Array(3, 4, 5), Array(6, 7, 8),
            Array(0, 3, 6), Array(1, 4, 7), Array(2, 5, 8),
            Array(0, 4, 8), Array(2, 4, 6))
        val winX = lines exists {_ forall {s(_) == 'X'}}
        val win0 = lines exists {_ forall {s(_) == '0'}}
        val answer = () match {
            case _ if numX < num0 || num0 + 1 < numX => "illegal"
            case _ if winX && win0 => "illegal"
            case _ if winX => "the first player won"
            case _ if win0 => "the second player won"
            case _ if filled => "draw"
            case _ if numX == num0 => "first"
            case _ => "second"
        }
        println(answer)
    }
}


The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.   The event coordinator has a list of k participants who should be picked up at the airport. When a participant gets on the bus, he will sit in the last row with an empty seat. If there is more than one empty seat in that row, he will take the leftmost one. In order to keep track of the people who are on the bus, the event coordinator needs a figure showing which seats are going to be taken by k participants. Your task is to draw the figure representing occupied seats.

The only line of input contains integer k, (0 ≤ k ≤ 34), denoting the number of participants.

Print the figure of a bus with k passengers as described in sample tests. Character '#' denotes an empty seat, while 'O' denotes a taken seat. 'D' is the bus driver and other characters in the output are for the purpose of beautifying the figure. Strictly follow the sample test cases output format. Print exactly six lines. Do not output extra space or other characters.

import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 05.10.14.
 */
object A extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val k = nextInt
    var r1 = "+------------------------+"
    var r2 = "|#.#.#.#.#.#.#.#.#.#.#.|D|)"
    var r3 = "|#.#.#.#.#.#.#.#.#.#.#.|.|"
    var r4 = "|#.......................|"
    var r5 = "|#.#.#.#.#.#.#.#.#.#.#.|.|)"
    var r6 = "+------------------------+"

    if (k >= 1) {
      r2 = r2.updated(1, 'O')
    }
    if (k >= 2) {
      r3 = r3.updated(1, 'O')
    }
    if (k >= 3) {
      r4 = r4.updated(1, 'O')
    }
    if (k >= 4) {
      r5 = r5.updated(1, 'O')
    }
    if (k >= 5) {
      val m = (k - 4) / 3
      for (i <- 0 until m) {
        r2 = r2.updated((i + 1) * 2 + 1, 'O')
        r3 = r3.updated((i + 1) * 2 + 1, 'O')
        r5 = r5.updated((i + 1) * 2 + 1, 'O')
      }
      val t = (k - 4) % 3
      if (t >= 1) {
       r2 = r2.updated(2 * m + 3, 'O')
      }
      if (t >= 2) {
        r3 = r3.updated(2 * m + 3, 'O')
      }
    }

    out.println(r1)
    out.println(r2)
    out.println(r3)
    out.println(r4)
    out.println(r5)
    out.println(r6)

  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}

import scala.collection._

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 Array(n) = readInts(1)

  val seats = Array.fill(4, 11)(false)
  var used = 0

  for (r <- 0 until 11) {
    for (c <- 0 until 4 if r == 0 || c != 2) {
      if (used < n) {
        seats(c)(r) = true
        used += 1
      }
    }
  }

  println("+------------------------+")

  print("|")
  for (s <- seats(0)) print(if (s) "O." else "#.")
  println("|D|)")

  print("|")
  for (s <- seats(1)) print(if (s) "O." else "#.")
  println("|.|")

  print("|")
  if (seats(2)(0)) print("O") else print("#")
  println(".......................|")

  print("|")
  for (s <- seats(3)) print(if (s) "O." else "#.")
  println("|.|)")

  println("+------------------------+")

//|O.O.O.#.#.#.#.#.#.#.#.|D|)
//|O.O.O.#.#.#.#.#.#.#.#.|.|
//|O.......................|
//|O.O.#.#.#.#.#.#.#.#.#.|.|)
//+------------------------+
}

import java.util._
import java.io._
import java.util

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

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

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    var k = nextInt
    out.println("+------------------------+")
    val ans = new Array[util.ArrayList[Char]](4)
    for (i <- 0 until 4) {
      ans(i) = new util.ArrayList[Char]()
      ans(i).add('|')
    }
    for (j <- 0 until 11) {
      for (i <- 0 until 4) {
        if (k > 0) {
          if (i == 2) {
            if (j == 0) {
              ans(i).add('O')
              ans(i).add('.')
              k -= 1
            } else {
              ans(i).add('.')
              ans(i).add('.')
            }
          }
          else {
            ans(i).add('O')
            ans(i).add('.')
            k -= 1
          }
        }
        else {
          if (i == 2 && j > 0) {
            ans(i).add('.')
            ans(i).add('.')
          } else {
            ans(i).add('#')
            ans(i).add('.')
          }
        }
      }
    }
    ans(0).add('|')
    ans(0).add('D')
    ans(0).add('|')
    ans(0).add(')')
    ans(1).add('|')
    ans(1).add('.')
    ans(1).add('|')
    ans(2).add('.')
    ans(2).add('.')
    ans(2).add('|')
    ans(3).add('|')
    ans(3).add('.')
    ans(3).add('|')
    ans(3).add(')')
    for (i <- 0 until 4) {
      for (j <- 0 until ans(i).size()) {
        out.print(ans(i).get(j))
      }
      out.println
    }
    out.println("+------------------------+")
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}


Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.Each command is one of the following two types:   Go 1 unit towards the positive direction, denoted as '+'  Go 1 unit towards the negative direction, denoted as '-' But the Wi-Fi condition is so poor that Dreamoon's smartphone reports some of the commands can't be recognized and Dreamoon knows that some of them might even be wrong though successfully recognized. Dreamoon decides to follow every recognized command and toss a fair coin to decide those unrecognized ones (that means, he moves to the 1 unit to the negative or positive direction with the same probability 0.5). You are given an original list of commands sent by Drazil and list received by Dreamoon. What is the probability that Dreamoon ends in the position originally supposed to be final by Drazil's commands?

The first line contains a string s1 — the commands Drazil sends to Dreamoon, this string consists of only the characters in the set {'+', '-'}.  The second line contains a string s2 — the commands Dreamoon's smartphone recognizes, this string consists of only the characters in the set {'+', '-', '?'}. '?' denotes an unrecognized command. Lengths of two strings are equal and do not exceed 10.

Output a single real number corresponding to the probability. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9.

NoteFor the first sample, both s1 and s2 will lead Dreamoon to finish at the same position  + 1. For the second sample, s1 will lead Dreamoon to finish at position 0, while there are four possibilites for s2: {"+-++", "+-+-", "+--+", "+---"} with ending position {+2, 0, 0, -2} respectively. So there are 2 correct cases out of 4, so the probability of finishing at the correct position is 0.5. For the third sample, s2 could only lead us to finish at positions {+1, -1, -3}, so the probability to finish at the correct position  + 3 is 0.

import scala.io.StdIn

object DW extends App {

  val required = StdIn.readLine().toCharArray.map {
    case '+' => 1
    case '-' => -1
  }.sum
  val (actual, uncertain) = StdIn.readLine().toCharArray.map {
    case '+' => (1, 0)
    case '-' => (-1, 0)
    case '?' => (0, 1)
  }.fold(0,0) {
    case ((a1, b1), (a2, b2)) => (a1 + a2, b1 + b2)
  }
  val miss = math.abs(required - actual)
  if (
    required > (actual + uncertain) ||
    required < (actual - uncertain) ||
    miss == 0 && uncertain % 2 != 0
  ) println(0.0d)
  else {

    val pluses = miss + (uncertain - miss) / 2
    println(
      math.pow(0.5f, uncertain) * factorial(uncertain) / (factorial(pluses) * factorial(math.abs(uncertain - pluses)))
    )
  }

  def factorial(n: Int): Int = {
    var res = 1
    for (i  <- 1 to n) {
      res *= i
    }
    res
  }
}

import scala.io.StdIn._

object Wifi
{
	var original, total, correct: Int = 0

	def main(args: Array[String])
	{
		val a, b = readLine

		for (c <- a) c match
		{
			case '+' => original += 1
			case '-' => original -= 1
		}

		parse(b, 0)
		printf("%1$.12f", correct.toDouble / total)
	}

	def parse(str: String, _pos: Int)
	{
		if (str isEmpty)
		{
			if (_pos == original) correct += 1
			total += 1
			return
		}
		var pos = _pos

		for (i <- 0 until str.size) str(i) match
		{
			case '+' => pos += 1
			case '-' => pos -= 1
			case '?' => {
							parse(str.substring(i + 1), pos + 1)
							parse(str.substring(i + 1), pos - 1)
							return
						}
		}

		if (pos == original) correct += 1
		total += 1
	}
}

object B476 {
  @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 s1 = scala.io.StdIn.readLine
    val s2 = scala.io.StdIn.readLine
    val total = math.pow(2.0, s2.count(_ == '?'))
    val count = gen(0, s2.toCharArray, calc(s1.toCharArray))
    println(count.toDouble/total)
  }

  def calc(str: Array[Char]): Int = {
    val ret = str.foldLeft(0) { case (sum, ch) =>
      if(ch == '+') {
        sum + 1
      } else {
        sum - 1
      }
    }
    ret
  }

  def gen(ind: Int, str: Array[Char], finalPos: Int): Int = {
    if(ind == str.length) {
      if(calc(str) == finalPos) 1 else 0
    } else if (str(ind) != '?'){
      gen(ind + 1, str, finalPos)
    } else {
      var score = 0

      str(ind) = '+'
      score = gen(ind + 1, str, finalPos)

      str(ind) = '-'
      score += gen(ind + 1, str, finalPos)

      str(ind) = '?'

      score
    }
  }
}

object Main extends App {
  def step(acc: Array[Int], op: Char): Array[Int] =
    if (op == '+') acc.map(_ + 1)
    else if (op == '-') acc.map(_ - 1)
    else acc.flatMap(x => Array(x - 1, x + 1))

  val orig = readLine
  val endPos = orig.foldLeft(Array(0))(step)(0)

  val recieved = readLine
  val sampleSpace = recieved.foldLeft(Array(0))(step)

  println(sampleSpace.count(_ == endPos) / sampleSpace.size.toDouble)
}

object B476 {
  @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 s1 = scala.io.StdIn.readLine
    val s2 = scala.io.StdIn.readLine
    val total = s2.count(_ == '?').toDouble
    if(total == 0) {
      println(1.0d)
    } else {
      val count = gen(0, s2.toCharArray, calc(s1.toCharArray))
      println(count.toDouble/total)
    }
  }

  def calc(str: Array[Char]): Int = {
    str.foldLeft(0) { case (sum, ch) =>
      if(ch == '+') {
        sum + 1
      } else {
        sum - 1
      }
    }
  }

  def gen(ind: Int, str: Array[Char], finalPos: Int): Int = {
    if(ind == str.length) {
      if(calc(str) == finalPos) 1 else 0
    } else if (str(ind) != '?'){
      gen(ind + 1, str, finalPos)
    } else {
      var score = 0

      str(ind) = '+'
      score = gen(ind + 1, str, finalPos)

      str(ind) = '-'
      score += gen(ind + 1, str, finalPos)

      score
    }
  }
}

object B476 {
  @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 s1 = scala.io.StdIn.readLine
    val s2 = scala.io.StdIn.readLine
    val total = math.pow(2.0, s2.count(_ == '?'))
    val count = gen(0, s2.toCharArray, calc(s1.toCharArray))
    println(count.toDouble/total)
  }

  def calc(str: Array[Char]): Int = {
    str.foldLeft(0) { case (sum, ch) =>
      if(ch == '+') {
        sum + 1
      } else {
        sum - 1
      }
    }
  }

  def gen(ind: Int, str: Array[Char], finalPos: Int): Int = {
    if(ind == str.length) {
      if(calc(str) == finalPos) 1 else 0
    } else if (str(ind) != '?'){
      gen(ind + 1, str, finalPos)
    } else {
      var score = 0

      str(ind) = '+'
      score = gen(ind + 1, str, finalPos)

      str(ind) = '-'
      score += gen(ind + 1, str, finalPos)

      score
    }
  }
}


Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.Limak wants to prove how responsible a bear he is. He is going to regularly save candies for the entire year 2016! He considers various saving plans. He can save one candy either on some fixed day of the week or on some fixed day of the month.Limak chose one particular plan. He isn't sure how many candies he will save in the 2016 with his plan. Please, calculate it and tell him.

The only line of the input is in one of the following two formats:    "x of week" where x (1 ≤ x ≤ 7) denotes the day of the week. The 1-st day is Monday and the 7-th one is Sunday.  "x of month" where x (1 ≤ x ≤ 31) denotes the day of the month.

Print one integer — the number of candies Limak will save in the year 2016.

NotePolar bears use the Gregorian calendar. It is the most common calendar and you likely use it too. You can read about it on Wikipedia if you want to – https://en.wikipedia.org/wiki/Gregorian_calendar. The week starts with Monday.In the first sample Limak wants to save one candy on each Thursday (the 4-th day of the week). There are 52 Thursdays in the 2016. Thus, he will save 52 candies in total.In the second sample Limak wants to save one candy on the 30-th day of each month. There is the 30-th day in exactly 11 months in the 2016 — all months but February. It means that Limak will save 11 candies in total.

import scala.math._
import scala.collection.immutable.Range
import scala.io.Source

object a8 {
  def main(args: Array[String]): Unit = {
    val a = Array.iterate(4,366)(a=>(a + 1)%7).map(_+1)
    val b = Array(31,29,31,30,31,30,31,31,30,31,30,31).map(a=>(1 to a ).toArray)
    val line = Source.stdin.getLines().toArray.head.split(' ')
    val x = line(0).toInt
    println(line(2) match {
      case  "week" => a.count(_ == x)
      case "month" => b.map(_.count(_ == x)).sum
    })
    //a.foreach(println)
  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(day, of, period) = in.next().split(' ')
  val d = day.toInt
  if (period == "week") {
    d match {
      case 6 => println(53)
      case 5 => println(53)
      case _ => println(52)
    }
  } else {
    d match {
      case 31 => println(7)
      case 30 => println(11)
      case _ => println(12)
    }
  }
}

object A611 {
  @inline def read = scala.io.StdIn.readLine

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

  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 t1 = tokenizeLine
    val input = Array.fill(3)(t1.nextToken)
    if(input.contains("week")) {
      val day = input(0).toInt
      if(Array(1,2,3,4,7).contains(day))
        println("52")
      else
        println("53")
    } else {
      val day = input(0).toInt
      if(day <= 29) {
        println("12")
      } else if (day == 30) {
        println("11")
      } else {
        println("7")
      }
    }
  }
}

import scala.collection._

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 ss = readLine.split(" ")

  val n = ss(0).toInt
  if (ss(2) == "week") {
    val w = Seq(0, 52, 52, 52, 52, 53, 53, 52)
    println(w(n))
  } else {
    val x = if (n <= 29) 12
    else if (n <= 30) 11
    else 7
    println(x)
  }
}

/**
 * @author pvasilyev
 * @since 05 May 2016
 */
object A611 extends App {

  val Array(x, y, z) = scala.io.StdIn.readLine().split(" ")
  val n = x.toInt
  var answer = 0
  if ("month".equals(z)) {
    if (n < 30) {
      answer = 12
    } else if (n == 30) {
      answer = 11
    } else {
      answer = 7
    }
  } else {
    if (n == 5 || n == 6) {
      answer = 53
    } else {
      answer = 52
    }
  }

  println(answer)

}

import java.util.Scanner

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

    if(span == "week"){
      if(n == 7)
        println(52)
      else if(n >= 5)
        println(53)
      else
        println(52)
    }
    else if(span == "month"){
      if(n <= 29)
        println(12)
      else if(n == 30)
        println(11)
      else  // n == 31
        println(7)
    }
  }
}

import scala.math._
import scala.collection.immutable.Range
import scala.io.Source

object a8 {
  def main(args: Array[String]): Unit = {
    val a = Array.iterate(4,365)(a=>(a + 1)%7).map(_+1)
    val b = Array(31,28,31,30,31,30,31,31,30,31,30,31).map(a=>(1 to a ).toArray)
    val line = Source.stdin.getLines().toArray.head.split(' ')
    val x = line(0).toInt
    println(line(2) match {
      case  "week" => a.count(_ == x)
      case "month" => b.map(_.count(_ == x)).sum
    })
    //b.foreach(println)
  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(day, of, period) = in.next().split(' ')
  val d = day.toInt
  if (period == "week") {
    d match {
      case 6 => println(53)
      case 5 => println(53)
      case _ => println(52)
    }
  } else {
    d match {
      case 31 => println(7)
      case 30 => println(11)
      case 29 => println(11)
      case _ => println(12)
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(day, of, period) = in.next().split(' ')
  val d = day.toInt
  if (period == "week") {
    d match {
      case 7 => println(53)
      case 6 => println(53)
      case _ => println(52)
    }
  } else {
    d match {
      case 31 => println(7)
      case 30 => println(11)
      case 29 => println(11)
      case _ => println(12)
    }
  }
}

import java.util.Scanner

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

    if(span == "week"){
      if(n >= 5)
        println(53)
      else
        println(52)
    }
    else if(span == "month"){
      if(n <= 29)
        println(12)
      else if(n == 30)
        println(11)
      else  // n == 31
        println(7)
    }
  }
}


Everybody knows of spaghetti sort. You decided to implement an analog sorting algorithm yourself, but as you survey your pantry you realize you're out of spaghetti! The only type of pasta you have is ravioli, but you are not going to let this stop you...You come up with the following algorithm. For each number in the array ai, build a stack of ai ravioli. The image shows the stack for ai = 4.  Arrange the stacks in one row in the order in which the corresponding numbers appear in the input array. Find the tallest one (if there are several stacks of maximal height, use the leftmost one). Remove it and add its height to the end of the output array. Shift the stacks in the row so that there is no gap between them. Repeat the procedure until all stacks have been removed.At first you are very happy with your algorithm, but as you try it on more inputs you realize that it doesn't always produce the right sorted array. Turns out when two stacks of ravioli are next to each other (at any step of the process) and differ in height by two or more, the top ravioli of the taller stack slides down on top of the lower stack.Given an input array, figure out whether the described algorithm will sort it correctly.

The first line of input contains a single number n (1 ≤ n ≤ 10) — the size of the array. The second line of input contains n space-separated integers ai (1 ≤ ai ≤ 100) — the elements of the array.

Output "YES" if the array can be sorted using the described procedure and "NO" if it can not.

NoteIn the second example the array will change even before the tallest stack is chosen for the first time: ravioli from stack of height 3 will slide on the stack of height 1, and the algorithm will output an array {2, 2, 2}.

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n = r.read[Int]

    import scala.collection.mutable.ListBuffer

    var xs = r.read[List[Int]](n).to[ListBuffer]
    var noSlides = true

    while (!xs.isEmpty && noSlides) {
      if (xs.zip(xs.tail).map{ case (x, y) => scala.math.abs(x - y) > 1 }.exists(_ == true)) {
        noSlides = false
      } else {
        xs.remove(xs.zipWithIndex.max._2)
      }
    }
    println(if (noSlides) "YES" else "NO")
  }
}

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

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

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

  val tokenizer = new Tokenizer(br)
}

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

  object Read {
    implicit val int: Read[Int] = new Read(_.tokenizer.next.toInt)
    implicit val double: Read[Double] = new Read(_.tokenizer.next.toDouble)

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

    implicit def list[A: Read](n: Int): Read[List[A]] = new Read(r => List.range(0, n).map(_ => r.read[A]))
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

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

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

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

object Utils {
  import scala.math._

  type Point = (Double, Double)

  def distance(p: Point, q: Point) = sqrt(pow(q._1 - p._1, 2) + pow(q._2 - p._2, 2))
}

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n = r.read[Int]
    import scala.collection.mutable.ListBuffer

    var xs = r.read[List[Int]](n).zipWithIndex.to[ListBuffer]
    var noSlides = true
    while (!xs.isEmpty && noSlides) {
      if (xs.zip(xs.tail).map{ case ((x, y), _) => scala.math.abs(x - y) > 1 }.exists(_ == true)) {
        noSlides = false
      } else {
        xs.remove(xs.max._2)
      }
    }
    println(if (noSlides) "YES" else "NO")
  }
}

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

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

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

  val tokenizer = new Tokenizer(br)
}

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

  object Read {
    implicit val int: Read[Int] = new Read(_.tokenizer.next.toInt)
    implicit val double: Read[Double] = new Read(_.tokenizer.next.toDouble)

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

    implicit def list[A: Read](n: Int): Read[List[A]] = new Read(r => List.range(0, n).map(_ => r.read[A]))
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

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

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

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

object Utils {
  import scala.math._

  type Point = (Double, Double)

  def distance(p: Point, q: Point) = sqrt(pow(q._1 - p._1, 2) + pow(q._2 - p._2, 2))
}