Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this segment as fast as possible.Each second Luba can either try moving the cursor to the left or to the right (if the cursor is currently at the tab i, then she can move it to the tab max(i - 1, a) or to the tab min(i + 1, b)) or try closing all the tabs to the left or to the right of the cursor (if the cursor is currently at the tab i, she can close all the tabs with indices from segment [a, i - 1] or from segment [i + 1, b]). In the aforementioned expressions a and b denote the minimum and maximum index of an unclosed tab, respectively. For example, if there were 7 tabs initially and tabs 1, 2 and 7 are closed, then a = 3, b = 6.What is the minimum number of seconds Luba has to spend in order to leave only the tabs with initial indices from l to r inclusive opened?

The only line of input contains four integer numbers n, pos, l, r (1 ≤ n ≤ 100, 1 ≤ pos ≤ n, 1 ≤ l ≤ r ≤ n) — the number of the tabs, the cursor position and the segment which Luba needs to leave opened.

Print one integer equal to the minimum number of seconds required to close all the tabs outside the segment [l, r].

NoteIn the first test Luba can do the following operations: shift the mouse cursor to the tab 2, close all the tabs to the left of it, shift the mouse cursor to the tab 3, then to the tab 4, and then close all the tabs to the right of it.In the second test she only needs to close all the tabs to the right of the current position of the cursor.In the third test Luba doesn't need to do anything.

object B extends App {
  val Array(n, pos, l, r) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  def seconds(i: Int, a: Int, b: Int, t: Int = 0): Int =
    if (a == l && b == r) t
    else if (a == l) seconds(r, a, r, t + (r - i).abs + 1)
    else if (b == r) seconds(l, l, b, t + (i - l).abs + 1)
    else {
      if (i <= l) seconds(l, l, b, t + l - i + 1)
      else if (i >= r) seconds(r, a, r, t + i - r + 1)
      else {
        if (r - i < i - l) seconds(r, a, b, t + r - i)
        else seconds(l, a, b, t + i - l)
      }
    }

  println(seconds(pos, 1, n))
}

object CF915B extends App{
  val sc = new java.util.Scanner(System.in)
  val n, pos, l, r = sc.nextInt
  val move = if (l == 1) {
    if (r == n) 0 else (r-pos abs) + 1
  } else {
    if (r == n) (pos-l abs) + 1 else  ((pos-l min  r-pos) abs) + (r - l) + 2
  }
  println(move)
}

object B extends App {
  val Array(n, pos, l, r) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  def seconds(i: Int, a: Int, b: Int, t: Int = 0): Int =
    if (a == l && b == r) t
    else if (a == l) seconds(r, a, r, t + r - i + 1)
    else if (b == r) seconds(l, l, b, t + i - l + 1)
    else {
      if (i <= l) seconds(l, l, b, t + l - i + 1)
      else if (i >= r) seconds(r, a, r, t + i - r + 1)
      else {
        if (r - i < i - l) seconds(r, a, b, t + r - i)
        else seconds(l, a, b, t + i - l)
      }
    }

  println(seconds(pos, 1, n))
}

object CF915B extends App{
  val sc = new java.util.Scanner(System.in)
  val n, pos, l, r = sc.nextInt
  val move = if (l == 1) {
    if (r == n) 0 else r-pos + 1
  } else {
    if (r == n) pos-l + 1 else (pos-l min  r-pos) + (r - l) + 2
  }
  println(move)
}


There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor.The game is played on a square field consisting of n × n cells. Initially all cells are empty. On each turn a player chooses and paint an empty cell that has no common sides with previously painted cells. Adjacent corner of painted cells is allowed. On the next turn another player does the same, then the first one and so on. The player with no cells to paint on his turn loses.The professor have chosen the field size n and allowed the student to choose to be the first or the second player in the game. What should the student choose to win the game? Both players play optimally.

The only line of the input contains one integer n (1 ≤ n ≤ 1018) — the size of the field.

Output number 1, if the player making the first turn wins when both players play optimally, otherwise print number 2.

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

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

    var n = readLong()
    if(n % 2 == 0) {
      println(2)
    }
    else {
      println(1)
    }

  }

}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {

  def sqr(x: Long) = x * x

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

  def C(n: Int, k: Int) = {
    var res = BigInt(1)
    for (i <- n - k + 1 to n) {
      res = res * i
    }
    for (i <- 1 to k.toInt) {
      res = res / i
    }
    res
  }

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

  def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b)

  def lcm(a: Long, b: Long) = a / gcd(a, b) * b

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

    val n = in.nextLong()

    println((n + 1) % 2 + 1)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  println(2 - in.next().last.asDigit % 2)
}

import scala.io.StdIn

object Game {

  def main(args: Array[String]) {
    val n = StdIn.readLong()
    print(2 - (n % 2))
  }

}


Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.

The first line contains a non-empty string, that contains only lowercase English letters — the user name. This string contains at most 100 letters.

If it is a female by our hero's method, print "CHAT WITH HER!" (without the quotes), otherwise, print "IGNORE HIM!" (without the quotes).

CHAT WITH HER!
IGNORE HIM!
CHAT WITH HER!

NoteFor the first example. There are 6 distinct characters in "wjmzbmr". These characters are: "w", "j", "m", "z", "b", "r". So wjmzbmr is a female and you should print "CHAT WITH HER!".

object Main {
  def main(args: Array[String]): Unit = {
      val str = readLine()
      if (str.distinct.length % 2 == 0) println("CHAT WITH HER!") else println("IGNORE HIM!")
  }
}

object Two36A extends App {
	val str = readLine
	val a = 'a'
	val arr = new Array[Int](26)
	str.foreach { x =>
		arr(x - a) += 1
	}
	val size = arr.filter(_ > 0).size
	if (size % 2 != 0) {
		println("IGNORE HIM!")
	} else {
		println("CHAT WITH HER!")
	}
}

import scala.io.StdIn._

object BoyorGirl {
  def main(args: Array[String]): Unit = {
    val name = readLine().toSet
    val ans = if (name.size % 2 == 0) "CHAT WITH HER!" else "IGNORE HIM!"
    println(ans)
  }
}

object Main extends App{
    if(readLine.distinct.size %2==0)
    println("CHAT WITH HER!")else
    println("IGNORE HIM!")
}

object BoyGirl extends App {

	val uniqueCharacters =
		scala.io.StdIn.readLine()
		.toSet.size

	if (uniqueCharacters % 2 != 0) println("IGNORE HIM!")
		else println("CHAT WITH HER!")

}

object Main extends App {
  val str = readLine()

  val r = str.toLowerCase().groupBy(_.toChar).map { case (k, v) => (k, v.size) }

  if (r.size % 2 == 0) println("CHAT WITH HER!")
  else println("IGNORE HIM!")
}

object Task236A {
  def main(args: Array[String]): Unit = {
    println(if (scala.io.StdIn.readLine().foldLeft(Set[Char]())((x, y) => x + y).size % 2 == 0) "CHAT WITH HER!" else "IGNORE HIM!")
  }
}

object CF0236A extends App {

  var str = readLine().toList

  val size = str.toSet.size

  if(size % 2 == 0) {
    println("CHAT WITH HER!")
  } else {
    println("IGNORE HIM!")
  }
}

object Solution236A extends App {

  val ans = Map(0 -> "CHAT WITH HER!", 1 -> "IGNORE HIM!")

  def solution() {
    println(ans(_string.groupBy(c => c).size % 2))
  }

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

import scala.io.StdIn

object BoyAndGirlMain {
  def main(args: Array[String]): Unit = {
    val userName = StdIn.readLine().toArray
    val lol = userName.groupBy(_.charValue())

    if (lol.size % 2 == 0 )
      print ("CHAT WITH HER!")
    else print("IGNORE HIM!")
  }

}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val s = readLine
    if (s.toSeq.distinct.size % 2 == 0) println("CHAT WITH HER!") else println("IGNORE HIM!")
  }
}

object Solution extends App {
  if (readLine().distinct.size % 2 == 0)
    println("CHAT WITH HER!")
  else
    println("IGNORE HIM!")
}

object Main {
  def main(args: Array[String]) {
    val std = scala.io.StdIn
    val userName = std.readLine()
    val result = if (userName.distinct.length % 2 == 0) {
      "CHAT WITH HER!"
    }
    else {
      "IGNORE HIM!"
    }
    println(result)
  }
}

import scala.io.StdIn

object BoyOrGirl extends App {

  val name = StdIn.readLine()

  if (impl(name))
    print("CHAT WITH HER!")
  else
    print("IGNORE HIM!")

  def impl(name: String): Boolean = {
    name.distinct.length % 2 == 0
  }

}

import scala.io.StdIn.readLine
object BoyOrGirl extends App
{
    val input = readLine()
    val sort = input.distinct.length
    if(sort % 2 == 0)
    {
        println("CHAT WITH HER!")
    } else println("IGNORE HIM!")
}

object a{def main(args:Array[String]){if(readLine.distinct.size%2==0)print("CHAT WITH HER!")else print("IGNORE HIM!")}}

//2.12 | CodeForces.Com
object Solution {
    def main(args: Array[String]) {
        if(readLine.distinct.size % 2 == 0)
            print("CHAT WITH HER!")
        else
            print("IGNORE HIM!")
    }
}

//rextester.com:2.11.7--codeforces.com:2.11.8
object a extends App{
    if(readLine.distinct.size%2==0)print("CHAT WITH HER!")else print("IGNORE HIM!")
}

/**
 * Created by richard on 2015/6/10.
 */
import scala.io.StdIn
object cf236a {
  def main(args: Array[String]): Unit = {
    val name = StdIn.readLine()
    println(if (name.distinct.size%2==1) "IGNORE HIM!" else "CHAT WITH HER!")
  }
}

object I {

  def main(args : Array[String]): Unit = {
    var s = readLine
    var used=false
    var cnt = 1
    for (i <- 1 to s.length()-1; j <- i-1 to 0 by -1){
    	if (s.charAt(i)==s.charAt(j))used = true
    	if (j==0){
    	  if (!used)cnt += 1
    	 used = false
    	}
      }
//    println(cnt)
    if (cnt % 2 == 0)
      println("CHAT WITH HER!")
     else println("IGNORE HIM!")
  }

}

object A236 extends App {
  var name: String = readLine
  var count = 0;
  while (!name.isEmpty()) {
    name = name.filterNot((a: Char) => a == name.charAt(0))
    count += 1;
  }
  if (count % 2 == 0)
    println("CHAT WITH HER!")
  else println("IGNORE HIM!")
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = readLine
    if (s.toList.distinct.length % 2 == 0) {
      println("CHAT WITH HER!")
    } else {
      println("IGNORE HIM!")
    }
  }
}

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val name = sc.next()

  println(if (name.toSet.size % 2 == 0) "CHAT WITH HER!" else "IGNORE HIM!")
}

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

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

  val name = sc.nextLine

  def solve: String =
    if (name.groupBy(identity[Char]).size % 2 == 0) "CHAT WITH HER!"
    else "IGNORE HIM!"

  out.println(solve)
  out.close
}

object BoyOrGirl {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val input = scanner.nextLine;
		var theList: List[Char] = Nil
		for (c <- input) {
		  if (!theList.contains(c)) {
		    theList = c::theList;
		  }
		}
		if (theList.size % 2 == 0) {
		  println("CHAT WITH HER!")
		}
		else {
		  println("IGNORE HIM!")
		}
	}
}

object A {
  def main(args: Array[String]) {
    val input = readLine()
    val chars = input.iterator.toSet
    print(
      if ((chars.iterator.length % 2) == 0)
        "CHAT WITH HER!"
      else
        "IGNORE HIM!")
  }

}

// codeforces 236A

object DevYun extends App {
  val nm = Console.readLine()
  val sch: Set[Char] = nm toSet
  val devush = (sch.size % 2) == 0
  val answer = if (devush) "CHAT WITH HER!" else "IGNORE HIM!"
  println(answer)
}

import java.util.Scanner

object Try1 {
  def main(args: Array[String]) {
    val in = new Scanner(System.in)
    var a,b,len,x, m, k, n, j, i: Int = 0

//    val lb = "abcdefghijklmnopqrstuvwxyz"
//    val lc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    var v = new Array[Int](26)
    i=0
    while (i<26){
      v(i)=0
      i+=1
    }
//    n = in.nextInt()
//    k = in.nextInt()
//    x=0
    val la = in.nextLine()
    a=0
    b=0
    m = la.length()
    i=0
    while (i<m) {
      v(la(i)-'a')=1
      i+=1
    }
    i=0
    while (i<26){
      a+=v(i)
      i+=1
    }
    a=a%2
    if (a==0) println("CHAT WITH HER!")
    else println("IGNORE HIM!")
//    if (a>=b)
//      {
//        i=0
//        while (i<m)
//        {
//          if (la(i)>='a' && la(i)<='z') print(la(i))
//          else print(lb(la(i)-'A'))
//          i+=1
//        }
//      }
//    else
//      {
//        i=0
//        while (i<m)
//        {
//          if (la(i)>='a' && la(i)<='z') print(lc(la(i)-'a'))
//          else print(la(i))
//          i+=1
//        }
//      }
//    m = la.compareToIgnoreCase(lb)  //不区分大小写判断字符串是否相等

//    i=0
//    n=line.length()
//    while (i<n-2 && line(i)=='W' && line(i+1)=='U' && line(i+2)=='B') i+=3
//    while (n>2 && line(n-3)=='W' && line(n-2)=='U' && line(n-1)=='B') n-=3
//    while (i<n) {
//      if (line(i)=='W') {
//        if (i<n-2) {
//          if (line(i+1)=='U' && line(i+2)=='B') {
//            print(' ')
//           i+=2
//          }
//          else print(line(i))
//        }
//        else print(line(i))
//      }
//      else print(line(i))
//      i+=1
//    }

  }
}

object Codeforces236A extends App{

  def Check(quer:String):String={
    var ans:Int=1
    val nquer:String=quer.toArray.sorted.mkString
    for (i <- 0 until nquer.length-1){
      if (nquer(i) != nquer(i+1)) ans+=1
    }
    if (ans % 2 == 1) return "IGNORE HIM!"
    else return "CHAT WITH HER!"
  }

  val username:String=scala.io.StdIn.readLine
  println(Check(username))

}

import java.io._
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 ans = Array("CHAT WITH HER!", "IGNORE HIM!").apply(reader.readLine().groupBy(x => x).size % 2)

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

object test5 extends App {
    val name=readLine
    if(name.distinct.size%2==0)
    	println("CHAT WITH HER!")
    else
    	println("IGNORE HIM!")

}

object Main {
  def main(args: Array[String]) {
    val s = readLine().toSet
    if (s.size % 2 == 0) println("CHAT WITH HER!")
    else println("IGNORE HIM!")
  }
}

// Codeforces 236A

object _236A extends App {
  val scanner = new java.util.Scanner(System.in)
  val user_name = scanner.next
  println(
    if (user_name.distinct.size % 2 == 0) "CHAT WITH HER!"
    else "IGNORE HIM!"
  )
}

import scala.io.StdIn._

object A_236 extends App {
  println(if (readLine().toCharArray.toSet.size % 2 == 1) "IGNORE HIM!" else "CHAT WITH HER!")
}

import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
  val s = readLine
    println(if(s.distinct.size%2 ==0) "CHAT WITH HER!" else "IGNORE HIM!")
  }
}

object JuanDavidRobles236A {

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

    import scala.io.StdIn
    import java.util

    var string: String = StdIn.readLine()
    var words: Array[Char] = new Array[Char](30)
    var count: Int = 0

    for (i <- 0 until string.length){
      if (!arrayContains(words, string.charAt(i))){
        words(count) = string.charAt(i)
        count += 1
      }
    }

    if (count%2 == 0){
      println("CHAT WITH HER!")
    } else {
      println("IGNORE HIM!")
    }

  }

  def arrayContains(myString: Array[Char], char: Char): Boolean ={
    var boolean: Boolean = false
    for (i <- 0 until myString.length){

      if (myString.charAt(i) == char){
        boolean = true
      }
    }

    boolean
  }
}

import scala.io.StdIn.readLine

object BoyOrGirl {
  def main(args: Array[String]) {
    if (readLine.toSet.size % 2 == 0)
      println("CHAT WITH HER!")
    else
      println("IGNORE HIM!")
  }

}

import scala.collection.immutable.Set
object TEST extends App{
    var al = Set[Char]()
    readLine.foreach(i => al += i)
    print (if(al.size%2==0) "CHAT WITH HER!" else "IGNORE HIM!")
}

object Main {

  def distinct(x: List[Char]): List[Char] = {
    x.foldLeft(List.empty[Char])((acc, c) => if (acc.contains(c)) acc else c :: acc)
  }

  def gender(nick: String): String = {
    val chars = distinct(nick.toList)
    if (chars.size % 2 == 0) "CHAT WITH HER!"
    else "IGNORE HIM!"
  }

  def main(args: Array[String]) = {
    print (gender(readLine))
  }
}

import scala.io.StdIn._

object Task extends App{
	val name = readLine.toSet

	if(name.size % 2 == 0)
	  println("CHAT WITH HER!")
	else
	  println("IGNORE HIM!")
}

object A00236 extends App {
  val str = Console.readLine()
  val message = if (str.distinct.length % 2 == 1) "IGNORE HIM!" else "CHAT WITH HER!"
  println(message)
}

object Main {
  def main(args: Array[String]): Unit = {
      val str = readLine()
      println(str.distinct.length)
  }
}

object BoyGirl extends App {

	val uniqueCharacters =
		scala.io.StdIn.readLine()
		.toSet.size

	if (uniqueCharacters % 2 == 0) println("IGNORE HIM!")
		else println("CHAT WITH HER!")

}

object Main extends App {
  val str = readLine()

  val r = str.toLowerCase().groupBy(_.toChar).map { case (k, v) => (k, v.size) }.
    filter { case (k, v) => v == 1 }.filterNot { case (k, v) => k == ' ' }.size

  if (r % 2 == 0) println("IGNORE HIM!")
  else println("CHAT WITH HER!")
}

import scala.io.StdIn

object BoyAndGirlMain {
  def main(args: Array[String]): Unit = {
    val userName = StdIn.readLine().toArray
    val lol = userName.groupBy(_.charValue())

    println(lol .size)
    if (lol.size % 2 == 0 )
      print ("CHAT WITH HER!")
    else print("IGNORE HIM!")
  }

}

/**
 * Created by richard on 2015/6/10.
 */
import scala.io.StdIn
object cf236a {
  def main(args: Array[String]): Unit = {
    val name = StdIn.readLine()
    println(if (name.size%2==1) "IGNORE HIM!" else "CHAT WITH HER!")
  }
}

object Main {
  def main(args: Array[String]) {
    val s = readLine().toSet
    println(s)
    if (s.size % 2 == 0) println("CHAT WITH HER!")
    else println("IGNORE HIM!")
  }
}

// Codeforces 236A

object _236A extends App {
  val scanner = new java.util.Scanner(System.in)
  val user_name = scanner.next
  println(
    if (user_name.distinct.size % 2 == 0) "CHAT WITH HER"
    else "IGNORE HIM"
  )
}

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

    import scala.io.StdIn

    var string: String = StdIn.readLine()
    var words: Array[Char] = new Array[Char](30)

    var count: Int = 0

    for (i <- 0 until string.length; j <- 0 until words.length()){

      if (words(j).equals(string.charAt(i))){
        words(count) = string.charAt(i)
        count = count + 1
      }
    }

    if (count%2 == 0){
      println("CHAT WITH HER!")
    } else {
      println("IGNORE HIM!")
    }

  }
}


You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of B - C?

The first line contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line contains n integers a1, a2, ..., an ( - 100 ≤ ai ≤ 100) — the elements of sequence a.

Print the maximum possible value of B - C, where B is the sum of elements of sequence b, and C is the sum of elements of sequence c.

NoteIn the first example we may choose b = {1, 0}, c = { - 2}. Then B = 1, C =  - 2, B - C = 3.In the second example we choose b = {16, 23, 16, 15, 42, 8}, c = {} (an empty sequence). Then B = 120, C = 0, B - C = 120.

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 xs = readInts(n)
  val sum = xs.sum
  var max = Int.MinValue

  for (d <- -101 to 101) {
    max = Math.max(max, Math.abs(xs.filter(_ <= d).sum - xs.filter(_ > d).sum))
  }

  println(max)

  Console.flush
}

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

  val t = a.foldLeft(0)(_ + _.abs)

  println(t)
}

object A extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val t = a.foldLeft((0, 0))((t, i) => {
    if (i < 0 ) (t._1, t._2 + i)
    else if (i > 0) (t._1 + i, t._2)
    else t
  })

  println(t._1 - t._2)
}

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

  override def apply(io: IO): io.type = {
    val a = io.read[Seq[Int]]
    val (b, c) = a.partition(_ > 0)
    io.write(b.sum - c.sum)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  type Point = java.awt.geom.Point2D.Double
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p._1, ev(p._2))
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    //def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def getBit(i: Int): Int = (x >> i) & 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def getBit(i: Int): Long = (x >> i) & 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative.getOrElse(f)   //e.g. students.indexOf("Greg").whenNegative(Int.MaxValue)
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new Point(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def isPrime(n: Int): Boolean = BigInt(n).isProbablePrime(31)
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

  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 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: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object CF946A extends App {
  import scala.io.StdIn._
  readLine()

  val nums: List[Int] = readLine().split(" ").map(Integer.parseInt(_)).toList

  val (pos, neg) = nums.partition(_ > 0)

  val res = pos.sum - neg.sum

  println(res)

}

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

  val t = a.reduce(_.abs + _.abs)

  println(t)
}


Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from $$$1$$$ to $$$9$$$). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, $$$\ldots$$$, 9m, 1p, 2p, $$$\ldots$$$, 9p, 1s, 2s, $$$\ldots$$$, 9s.In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.Do you know the minimum number of extra suited tiles she needs to draw so that she can win?Here are some useful definitions in this game:  A mentsu, also known as meld, is formed by a koutsu or a shuntsu;  A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;  A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu. Some examples:   [2m, 3p, 2s, 4m, 1s, 2s, 4s] — it contains no koutsu or shuntsu, so it includes no mentsu;  [4s, 3m, 3p, 4s, 5p, 4s, 5p] — it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;  [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] — it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu. Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.

The only line contains three strings — the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from $$$1$$$ to $$$9$$$ and the second character is m, p or s.

Print a single integer — the minimum number of extra suited tiles she needs to draw.

NoteIn the first example, Tokitsukaze already has a shuntsu.In the second example, Tokitsukaze already has a koutsu.In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile — 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].

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[Long]]): 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 = map(3)(_ => ns())
    val C = Array.ofDim[Int](3, 9)
    A.foreach { s =>
      val c = s.last match {
        case 's' => 0
        case 'm' => 1
        case 'p' => 2
      }
      val n = s.head - '1'
      C(c)(n) += 1
    }
    var ans = 3
    // koutsu
    REP(3) { i =>
      REP(9) { j =>
        ans = min(ans, 3 - C(i)(j))
      }
    }

    // shuntsu
    REP(3) { i =>
      REP(7) { j =>
        var c = 0
        if (C(i)(j) > 0) c += 1
        if (C(i)(j + 1) > 0) c += 1
        if (C(i)(j + 2) > 0) c += 1
        ans = min(ans, 3 - c)
      }
    }

    out.println(ans)
  }
}


A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?

The first and only input line contains two positive integers — n and m (2 ≤ n < m ≤ 50). It is guaranteed that n is prime. Pretests contain all the cases with restrictions 2 ≤ n < m ≤ 4.

Print YES, if m is the next prime number after n, or NO otherwise.

object Flask {

  def isPrime(n: Int): Boolean = List.range(2, n / 2 + 1).forall(n % _ != 0)

  def main(args: Array[String]): Unit = {
    var input = Console.readLine.split(" ").map(_.toInt)
    var n = input(0); var m = input(1)
    var result = isPrime(m) && List.range(n + 1, m).forall(x => !isPrime(x))
    println(if (result) "YES" else "NO")
  }
}

import scala.io.Source

object a11 {
  def main(args: Array[String]): Unit = {
    val a =  Seq.iterate((List[Int](),(2 to 50).toArray),5)(a=>(((a._2.head)::a._1), a._2.filter(b => b % (a._2.head) != 0))).last
    val primes = a._1.reverse.toArray ++ a._2
    val line = Source.stdin.getLines().take(1).map(_.split(' ').map(_.toInt)).toArray.head
    val (b,c) = (line(0), line(1))
    println(if (!primes.contains(c) || primes(primes.indexOf(b)+1) != c)
      "NO"
    else
      "YES")
  }
}

object Solution extends App {
  def simple(a: Int) =
    a % 2 != 0 && (3 to Math.sqrt(a).toInt by 2).forall(a % _ != 0) || a == 2

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  if (simple(m) && (n + 1 until m).forall(t => !simple(t)))
    println("YES")
  else
    println("NO")
}

object A80 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val primes = genPrimes(100)
    if(primes.contains(n) && primes.contains(m)) {
      val nPos = primes.indexOf(n)
      val mPos = primes.indexOf(m)
      if(mPos == nPos+1) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else {
      out.println("NO")
    }
    out.close()
  }

  def genPrimes(till: Int): Array[Int] = {
    val isPrime = Array.fill[Boolean](till+1)(true)
    isPrime(0) = false
    isPrime(1) = true // not composite
    for(i <- 4 to till by 2) {
      isPrime(i) = false
    }
    for(i <- 3 to till by 2 if isPrime(i)) {
      for(j <- i+i to till by i) isPrime(j) = false
    }
    isPrime.zipWithIndex.filter(_._1).map(_._2)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

    @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 java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

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

  def nextPrime(n: Int): Int = {
    def isPrime(x: Int): Boolean = (2 until x).forall(x % _ > 0)

    @tailrec
    def loop(i: Int): Int =
      if (isPrime(i)) i
      else loop(i + 1)

    loop(n + 1)
  }

  val N, M = sc.nextInt
  val answer = if (M == nextPrime(N)) "YES" else "NO"

  out.println(answer)
  out.close
}

object APanoramixsPrediction extends App {
  import scala.io.StdIn._

  lazy val primes: Stream[Int] =
    2 #:: Stream.iterate(3)(_ + 2).filter(isPrime)

  def isPrime(number: Int): Boolean =
    primes.takeWhile(prime => prime * prime <= number).forall(number % _ != 0)

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

  val ans = isPrime(m) && primes.indexOf(n) + 1 == primes.indexOf(m) match {
    case true => "YES"
    case _    => "NO"
  }

  println(ans)
}

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)

  def sqStream(current: Int, ceil: Int): Stream[Int] = if(current * current > ceil) Stream.Empty else current #:: sqStream(current + 1, ceil)
  def isPrime(x: Int) = sqStream(2, x).filter(x % _ == 0).isEmpty
  @tailrec
  def nextPrime(n: Int): Int = if(isPrime(n)) n else nextPrime(n + 1)
  val Array(m, n) = readInts
  def ans = nextPrime(m + 1) == n
  val yesNoAns = Map(true -> "YES", false -> "NO")

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

object Main {
  def sieve(n: Int) = {
    val primes = scala.collection.mutable.BitSet.empty ++ (2 to n)
    for {
      candidate <- 2 until Math.sqrt(n).ceil.toInt
      if primes contains candidate
    } primes --= candidate * candidate to n by candidate
    primes
  }

  val primes = sieve(51).zipWithIndex

  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val n = nm(0)
    val m = nm(1)
    val i = primes.find(_._1 == n).get._2
    val j = primes.find(_._1 == m).map(_._2)
    if (j.map(_ - i).getOrElse(0) == 1) println("YES")
    else println("NO")
  }
}

object Panoramix extends App {

  val Array(n, m) = readLine.split(' ').map(_.toInt)

  val primes: Array[Int] = Array(
    2, 3, 5, 7, 11, 13,
    17, 19, 23, 29, 31,
    37, 41, 43, 47
  )

  val result: Boolean =
    primes.contains(n) && primes.contains(m) &&
      primes.indexOf(m) - primes.indexOf(n) == 1
  println(if (result) "YES" else "NO")

}

object Solution extends App {
  def simple(a: Int) = {
    a % 2 == 0 && (a == 2 || (3 to Math.sqrt(a).toInt).forall(a % _ != 0))
  }

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  if (simple(m) && (n + 1 until m).forall(t => !simple(t)))
    println("YES")
  else
    println("NO")
}

object Main {
  def sieve(n: Int) = {
    val primes = scala.collection.mutable.BitSet.empty ++ (2 to n)
    for {
      candidate <- 2 until Math.sqrt(n).toInt
      if primes contains candidate
    } primes --= candidate * candidate to n by candidate
    primes
  }

  val primes = sieve(50).zipWithIndex

  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val n = nm(0)
    val m = nm(1)
    val i = primes.find(_._1 == n).get._2
    val j = primes.find(_._1 == m).map(_._2)
    if (j.map(_ - i).getOrElse(0) == 1) println("YES")
    else println("NO")
  }
}

object Main {
  def sieve(n: Int) = {
    val primes = scala.collection.mutable.BitSet.empty ++ (2 to n)
    for {
      candidate <- 2 until Math.sqrt(n).ceil.toInt
      if primes contains candidate
    } primes --= candidate * candidate to n by candidate
    primes
  }

  val primes = sieve(51).zipWithIndex

  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val n = nm(0)
    val m = nm(1)
    val i = primes.find(_._1 == n).get._2
    val j = primes.find(_._1 == m).map(_._2)
    println("i = " + i)
    println("j = " + j)
    if (j.map(_ - i).getOrElse(0) == 1) println("YES")
    else println("NO")
  }
}


n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.

The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively.

The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively.

NoteIn the first sample all the participants get into one team, so there will be exactly ten pairs of friends.In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one.In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people.

import java.util.StringTokenizer

object _478B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toLong
  val m = next.toLong
  def choose(a: Long) = a * (a - 1) / 2
  val max = choose(n - (m - 1))
  val min = (m - n % m) * choose(n / m) + (n % m) * choose(n / m + 1)
  println(min + " " + max)
}

object Solution extends App {
  def f(n: Long) = n * (n - 1) / 2

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toLong)
  val c = n / m
  val min = (n % m) * f(c + 1) + (m - n % m) * f(c)
  val max = f(n - m + 1)
  println(min + " " + max)
}

object B478 {
  @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 Array(n, m) = readLongs(2)
    val min = {
      val mod = n%m
      mod * ((n/m + 1) *(n/m)) /2 + (m-mod) * ((n/m) * (n/m -1 )) / 2
    }
    val max = ((n-m+1) * (n-m))/2
    println(s"$min $max")
  }
}

import java.util.Scanner

object R273_RandomTeams {
  def main(args: Array[String]) = {
    val in = new Scanner(System.in).nextLine().split(" ").map(_.toInt)
    val (n, m) = (in(0), in(1))
    val (p, q) = (n / m, n % m)

    val min = combination2(p) * (m - q) + combination2(p + 1) * q
    val max = combination2(n - m + 1)
    println(min + " " + max)
   }

  def combination2(n: Long): Long = {
    (n * (n - 1)) / 2
  }
}

object P478B {
	def edges(n: Int) : BigInt = ((BigInt(n) * n) - n) / 2

	def main(args: Array[String]) {
		val Array(n, m) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
		val min = (n % m) * edges((n / m) + 1) + (m - (n % m)) * edges(n / m)
		val max = edges(n - m + 1)
		println(List(min, max).mkString(" "))
	}
}

import java.util.Scanner

object Solution {
    def countPairs(n: Long): Long = n * (n - 1) / 2

    def main(args: Array[String]) = {
	val in = new Scanner(System.in)
	val people = in.nextLong()
	val teams = in.nextLong()
	val max = countPairs(people - teams + 1)
	val size = people / teams
	val bigCount = people - size * teams
	val smallCount = teams - bigCount
	val min = countPairs(size + 1) * bigCount + countPairs(size) * smallCount
	println(min + " " + max)
    }
}

import java.util.Scanner

object Main extends App {
  val in = (new Scanner(System.in)).nextLine().split(" ").map(_.toInt)
  val n = in(0)
  val m = in(1)

  def nC2(n: Int): Long = {
    if(n == 1) 0
    else
      n.toLong * (n-1) / 2
  }

  val mi = n/m
  val mi2_count = if( mi*m != n ) n - mi*m else 0
  val mi_count = m - mi2_count
  val ans1 = (nC2(mi)*mi_count + nC2(mi+1)*mi2_count)

  val mx = n - (m-1)
  val ans2 = nC2(mx)

  println(ans1.toString + " " + ans2.toString)
}

import java.util.StringTokenizer

object _478B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toLong
  val m = next.toLong
  def choose(a: Long) = a * (a - 1) / 2
  val max = choose(n - (m - 1))
  val min = {
    if (n % m == 0) m * choose(n / m)
    else (m - 1) * choose(n / m) + choose(n - n / m * (m - 1))
  }
  println(min + " " + max)
}

object Solution extends App {
  def f(n: Int) = n * (n - 1) / 2

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val c = n / m
  val min = (n % m) * f(c + 1) + (m - n % m) * f(c)
  val max = f(n - m + 1)
  println(max + " " + min)
}

object Solution extends App {
  def f(n: Int) = n * (n - 1) / 2

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val c = n / m
  val min = (n % m) * f(c + 1) + (m - n % m) * f(c)
  val max = f(n - m + 1)
  println(min + " " + max)
}

object Solution extends App {
  def f(n: Int) = n * (n + 1) / 2

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val c = n / m
  val min = (n % m) * f(c + 1) + (m - n % m) * f(c)
  val max = f(n - m)
  println(max + " " + min)
}

import java.util.Scanner

object R273_RandomTeams {
  def main(args: Array[String]) = {
    val in = new Scanner(System.in).nextLine().split(" ").map(_.toInt)
    val (n, m) = (in(0), in(1))
    val (p, q) = (n / m, n % m)

    val min = combination2(p) * (m - q) + (combination2(p) + 1) * q
    val max = combination2(n - m + 1)
    println(min + " " + max)
   }

  def combination2(n: Long): Long = {
    (n * (n - 1)) / 2
  }
}

import java.util.Scanner

object R273_RandomTeams {
  def main(args: Array[String]) = {
    val in = new Scanner(System.in).nextLine().split(" ").map(_.toInt)
    val n = in(0)
    val m = in(1)
    val p = n / m
    val q = n % m

    val min = combination2(p) * (m - q) + (combination2(p) + 1) * q
    val max = combination2(n - m + 1)
    println(min + " " + max)
   }

  def combination2(n: Int): Int = {
    (n / 2) * (n - 1)
  }

  def fact(n: Int): Int = {
    Range(1, n + 1).toList.product
  }
}

import java.util.Scanner

object R273_RandomTeams {
  def main(args: Array[String]) = {
    val in = new Scanner(System.in).nextLine().split(" ").map(_.toInt)
    val n = in(0)
    val m = in(1)
    val p = n / m
    val q = n % m

    val min = combination2(p) * (m - q) + (combination2(p) + 1) * q
    val max = combination2(n - m + 1)
    println(min + " " + max)
   }

  def combination2(n: Int): Int = {
    (n * (n - 1)) / 2
  }

  def fact(n: Int): Int = {
    Range(1, n + 1).toList.product
  }
}

object P478B {
	def edges(n: Int) : BigInt = ((BigInt(n) * n) - n) / 2

	def main(args: Array[String]) {
		val Array(n, m) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
		val min = (n % m) * edges((n / m) + 1) + (m - (n % m)) * edges(n / m)
		val max = edges(n - m + 1)
		println(min, max)
	}
}

import java.util.Scanner

object Solution {
    def countPairs(n: Long): Long = n * (n - 1) / 2

    def main(args: Array[String]) = {
	val in = new Scanner(System.in)
	val people = in.nextLong()
	val teams = in.nextLong()
	val max = countPairs(people - teams + 1) + teams - 1
	val size = people / teams
	val bigCount = people - size * teams
	val smallCount = teams - bigCount
	val min = countPairs(size + 1) * bigCount + countPairs(size) * smallCount
	println(min + " " + max)
    }
}

import java.util.Scanner

object Main extends App {
  val in = (new Scanner(System.in)).nextLine().split(" ").map(_.toInt)
  val n = in(0)
  val m = in(1)

  def nCm(n: Int, m: Int): Long = {
    if(n == 1) 0
    else {
      val nt = (1 to n).reverse.take(m).product
      val mt = (1 to m).reverse.product
      (nt / mt).toLong
    }
  }

  val mi = n/m
  val mi2_count = if( mi*m != n ) n - mi*m else 0
  val mi_count = m - mi2_count
  val ans1 = (nCm(mi,2)*mi_count + nCm(mi+1,2)*mi2_count)

  val mx = n - (m-1)
  val ans2 = nCm(mx,2)

  print(Math.min(ans1, ans2))
  print(" ")
  println(Math.max(ans1, ans2))
}

import java.util.Scanner

object Main extends App {
  val in = (new Scanner(System.in)).nextLine().split(" ").map(_.toInt)
  val n = in(0)
  val m = in(1)

  def nCm(n: Int, m: Int): Long = {
    if(n == 1) 1
    else {
      val nt = (1 to n).reverse.take(m).product
      val mt = (1 to m).reverse.product
      (nt / mt).toLong
    }
  }

  val mi = n/m
  val mi2_count = if( mi*m != n ) n - mi*m else 0
  val mi_count = m - mi2_count
  val ans1 = (nCm(mi,2)*mi_count + nCm(mi+1,2)*mi2_count)

  val mx = n - (m-1)
  val ans2 = nCm(mx,2)

  print(Math.min(ans1, ans2))
  print(" ")
  println(Math.max(ans1, ans2))
}


You are given names of two days of the week.Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong to one year.In this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31.Names of the days of the week are given with lowercase English letters: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".

The input consists of two lines, each of them containing the name of exactly one day of the week. It's guaranteed that each string in the input is from the set "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".

Print "YES" (without quotes) if such situation is possible during some non-leap year. Otherwise, print "NO" (without quotes).

NoteIn the second sample, one can consider February 1 and March 1 of year 2015. Both these days were Sundays.In the third sample, one can consider July 1 and August 1 of year 2017. First of these two days is Saturday, while the second one is Tuesday.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val first = in.next() match {
    case "monday" => 0
    case "tuesday" => 1
    case "wednesday" => 2
    case "thursday" => 3
    case "friday" => 4
    case "saturday" => 5
    case "sunday" => 6
  }
  val second = in.next() match {
    case "monday" => 0
    case "tuesday" => 1
    case "wednesday" => 2
    case "thursday" => 3
    case "friday" => 4
    case "saturday" => 5
    case "sunday" => 6
  }
  val candidates = List(first + 28, first + 30, first + 31).map(_ % 7)
  if (candidates.contains(second))
    println("YES")
  else
    println("NO")
}

import java.io._

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

  def processStdInOut(): Unit = {
    val src = io.Source.fromInputStream(System.in)
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
        bw.close()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val day1 = lines.next()
    val day2 = lines.next()
    val hasSolution = solve(day1, day2)
    if (hasSolution) { bw.write("YES") } else {bw.write("NO") };
    bw.newLine()
  }

  def solve(day1: String, day2: String): Boolean = {
    val dayNames = List("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")
    def getDayIndex(dayName: String): Int = dayNames.indexOf(dayName)
    val day1Index = getDayIndex(day1)
    val day2Index = getDayIndex(day2)
    val dayOffset = (7 + day2Index - day1Index) % 7  // Add 7 to prevent negative remainders
    val monthLengths = List(28, 30, 31)
    monthLengths.exists(dayOffset == _ % 7)
  }
}

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

  val dows = Array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")
  val ms = Array(28, 30, 31)

  val s1, s2 = readLine

  val d1 = dows.indexWhere(_ == s1)
  val d2 = dows.indexWhere(_ == s2)

  val can = ms.exists(d => (d1 + d) % 7 == d2)

  println(if (can) "YES" else "NO")
}

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

object _724A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val d1, d2 = read[String]

    val months = Seq(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    val firstDayOfMonth = months.init.scanLeft(0)(_ + _)

    val days = IndexedSeq("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")

    val ans = days.zipWithIndex exists {case (start, k) =>
      val calendar = Seq.tabulate(365)(i => days((i + k)%days.length))
      firstDayOfMonth.sliding(2) exists {
        case Seq(m1, m2) => calendar(m1) == d1 && calendar(m2) == d2
      }
    }

    write(ans.toEnglish)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

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

//package me.code4fun

import scala.io.StdIn

object A {

  def dayOfWeek(dayStr: String): Int =
    dayStr match {
      case "monday" => 0
      case "tuesday" => 1
      case "wednesday" => 2
      case "thursday" => 3
      case "friday" => 4
      case "saturday" => 5
      case "sunday" => 6
      case _ => throw new IllegalArgumentException(s"$dayStr is not a day of week")
    }

  val nbDaysInWeek = 7

  val possibleOffsets = Seq(28, 30, 31).map(_ % nbDaysInWeek)

  def posMod(a: Int, b: Int): Int = {
    val mod = a % b
    if (mod >= 0) mod else (mod + b)
  }

  def areConsecutiveDays(firstDay: String, secondDay: String): Boolean = {
    val fst = dayOfWeek(firstDay)
    val snd = dayOfWeek(secondDay)
    val diff = posMod(snd - fst, nbDaysInWeek)
    possibleOffsets.contains(diff)
  }

  def main(args: Array[String]): Unit = {
    val fst = StdIn.readLine()
    val snd = StdIn.readLine()
    if (areConsecutiveDays(fst, snd))
      Console.out.println("YES")
    else
      Console.out.println("NO")
  }
}


In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terrible Game Cubes fall down on the city, bringing death to those modules, who cannot win the game...For sure, as guard Bob appeared in Mainframe many modules stopped fearing Game Cubes. Because Bob (as he is alive yet) has never been defeated by User, and he always meddles with Game Cubes, because he is programmed to this.However, unpleasant situations can happen, when a Game Cube falls down on Lost Angles. Because there lives a nasty virus — Hexadecimal, who is... mmm... very strange. And she likes to play very much. So, willy-nilly, Bob has to play with her first, and then with User.This time Hexadecimal invented the following entertainment: Bob has to leap over binary search trees with n nodes. We should remind you that a binary search tree is a binary tree, each node has a distinct key, for each node the following is true: the left sub-tree of a node contains only nodes with keys less than the node's key, the right sub-tree of a node contains only nodes with keys greater than the node's key. All the keys are different positive integer numbers from 1 to n. Each node of such a tree can have up to two children, or have no children at all (in the case when a node is a leaf).In Hexadecimal's game all the trees are different, but the height of each is not lower than h. In this problem «height» stands for the maximum amount of nodes on the way from the root to the remotest leaf, the root node and the leaf itself included. When Bob leaps over a tree, it disappears. Bob gets the access to a Cube, when there are no trees left. He knows how many trees he will have to leap over in the worst case. And you?

The input data contains two space-separated positive integer numbers n and h (n ≤ 35, h ≤ n).

Output one number — the answer to the problem. It is guaranteed that it does not exceed 9·1018.

//package me.jetblack.cf

import java.util.Scanner

object TreesCount extends App {

  val s = new Scanner(System.in)

  val maxn = s.nextInt()
  val maxh = s.nextInt()

  val dp = Array.ofDim[Long](maxn + 1, maxn + 1)
  dp(0)(0) = 1
  for {
    h <- (1 until maxn + 1)
    i <- (1 until maxn + 1)
    j <- (1 to i)
  } yield {
    val left1 = dp(h - 1)(j - 1)
    val right1 = (0 until h).map(h1 => dp(h1)(i - j)).sum
    val left2 = (0 until h - 1).map(h1 => dp(h1)(j - 1)).sum
    val right2 = dp(h - 1)(i - j)
    dp(h)(i) += (left1 * right1) + left2 * right2
  }

  val result = (maxh to maxn).map(dp(_)(maxn)).sum
  println(result)

}

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

object D {

  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 sumOfTrees(dp: Array[Array[Long]], h: Int, n: Int): Long = {
    var temp: Long = 0
    for (i <- 0 to h) {
      temp += dp(i)(n)
    }
    temp
  }

  def solve = {
    val n = nextInt
    val h = nextInt
    val dp = new Array[Array[scala.Long]](36)
    for (i <- 0 to 35) {
      dp(i) = new Array[scala.Long](36)
      Arrays.fill(dp(i), 0)
    }
    dp(0)(0) = 1L
    for (i <- 1 to h) {
      dp(i)(0) = 0L
    }
    for (i <- 1 to n) {
      dp(0)(i) = 0L
    }
    for (i <- 1 to 35) {
      for (j <- 1 to 35) {
        var temp: Long = 0
        for (m <- 1 to j) {
          temp += dp(i - 1)(m - 1) * sumOfTrees(dp, i - 1, j - m) + dp(i - 1)(j - m) * sumOfTrees(dp, i - 2, m - 1)
        }
        dp(i)(j) = temp
      }
    }
    var ans: Long = 0
    for (i <- h to n) {
      ans += dp(i)(n)
    }
    out.println(ans)
  }

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

//package me.jetblack.cf

import java.util.Scanner

object TreesCount extends App {

  val s = new Scanner(System.in)

  val maxn = s.nextInt()
  val maxh = s.nextInt()

  val dp = Array.ofDim[Int](maxn + 1, maxn + 1)
  dp(0)(0) = 1
  for {
    h <- (1 until maxn + 1)
    i <- (1 until maxn + 1)
    j <- (1 to i)
  } yield {
    val left1 = dp(h - 1)(j - 1)
    val right1 = (0 until h).map(h1 => dp(h1)(i - j)).sum
    val left2 = (0 until h - 1).map(h1 => dp(h1)(j - 1)).sum
    val right2 = dp(h - 1)(i - j)
    dp(h)(i) += (left1 * right1) + left2 * right2
  }

  val result = (maxh to maxn).map(dp(_)(maxn)).sum
  println(result)

}


Alice and Bob play 5-in-a-row game. They have a playing field of size 10 × 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts.In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately.Alice wins if some crosses in the field form line of length not smaller than 5. This line can be horizontal, vertical and diagonal.

You are given matrix 10 × 10 (10 lines of 10 characters each) with capital Latin letters 'X' being a cross, letters 'O' being a nought and '.' being an empty cell. The number of 'X' cells is equal to the number of 'O' cells and there is at least one of each type. There is at least one empty cell. It is guaranteed that in the current arrangement nobody has still won.

Print 'YES' if it's possible for Alice to win in one turn by putting cross in some empty cell. Otherwise print 'NO'.

import scala.io.StdIn._

object Main extends App {
  val a =
    (for (_ <- 0 until 10)
      yield readLine()).toArray

  if (check((0, 1)) || check((1, 0)) || check((1, 1)) || check((1, -1)))
    println("YES")
  else
    println("NO")

  def good(x: Int): Boolean = x >= 0 && x < 10

  def check(diff: (Int, Int)): Boolean = {
    for (i <- 0 until 10; j <- 0 until 10) {
      var (x, y, cnt, free) = (j, i, 0, 0)
      for (z <- 0 until 5) {
        if (good(x) && good(y))
          if (a(y)(x) == 'X')
            cnt += 1
          else if (a(y)(x) == '.')
            free += 1
        y += diff._1
        x += diff._2
      }
      if (cnt == 4 && free == 1)
        return true
    }
    false
  }
}

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

object Main extends App {
  val a = ArrayBuffer[ArrayBuffer[Char]]()
  for (i <- 0 until 10) {
    a.append(readLine().toCharArray.to[ArrayBuffer])
  }

  if (check(a, (0, 1)) || check(a, (1, 0)) || check(a, (1, 1)) || check(a, (1, -1)))
    println("YES")
  else
    println("NO")

  def good(x: Int): Boolean = x >= 0 && x < 10

  def check(a: ArrayBuffer[ArrayBuffer[Char]], diff: (Int, Int)): Boolean = {
    for (i <- 0 until 10) {
      for (j <- 0 until 10) {
        var x = j
        var y = i
        var cnt = 0
        var free = 0
        for (z <- 0 until 5) {
          if (good(x) && good(y))
            if (a(y)(x) == 'X')
              cnt += 1
            else if (a(y)(x) == '.')
              free += 1
          y += diff._1
          x += diff._2
        }
        if (cnt == 4 && free == 1)
          return true
      }
    }
    false
  }
}

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

object Main extends App {
  val a = ArrayBuffer[ArrayBuffer[Char]]()
  for (i <- 0 until 10) {
    a.append(readLine().toCharArray.to[ArrayBuffer])
  }

  if (check(a) || check(a.transpose) || check2(a, (1, 1)) || check2(a, (1, -1)))
    println("YES")
  else
    println("NO")

  def check(a: ArrayBuffer[ArrayBuffer[Char]]): Boolean = {
    for (i <- 0 until 10) {
      for (j <- 0 to 5) {
        var cnt = 0
        for (z <- j until j + 5) {
          if (a(i)(z) == 'X')
            cnt += 1
          else if (a(i)(z) == 'O')
            cnt = -5
        }
        if (cnt == 4)
          return true
      }
    }
    false
  }

  def good(x: Int): Boolean = x >= 0 && x < 10

  def check2(a: ArrayBuffer[ArrayBuffer[Char]], diff: (Int, Int)): Boolean = {
    for (i <- 0 until 10) {
      for (j <- 0 until 10) {
        var x = j
        var y = i
        var cnt = 0
        for (z <- 0 until 5) {
          y += diff._1
          x += diff._2
          if (good(x) && good(y))
            if (a(y)(x) == 'X')
              cnt += 1
            else if (a(y)(x) == 'O')
              cnt = -5
        }
        if (cnt == 4)
          return true
      }
    }
    false
  }
}

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

object Main extends App {
  val a = ArrayBuffer[ArrayBuffer[Char]]()
  for (i <- 0 until 10) {
    a.append(readLine().toCharArray.to[ArrayBuffer])
  }

  if (check(a, (0, 1)) || check(a, (1, 0)) || check(a, (1, 1)) || check(a, (1, -1)))
    println("YES")
  else
    println("NO")

  def good(x: Int): Boolean = x >= 0 && x < 10

  def check(a: ArrayBuffer[ArrayBuffer[Char]], diff: (Int, Int)): Boolean = {
    for (i <- 0 until 10) {
      for (j <- 0 until 10) {
        var x = j
        var y = i
        var cnt = 0
        var free = 0
        for (z <- 0 until 5) {
          y += diff._1
          x += diff._2
          if (good(x) && good(y))
            if (a(y)(x) == 'X')
              cnt += 1
            else if (a(y)(x) == '.')
              free += 1
        }
        if (cnt == 4 && free == 1)
          return true
      }
    }
    false
  }
}


An n × n table a is defined as follows:  The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.  Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula ai, j = ai - 1, j + ai, j - 1. These conditions define all the values in the table.You are given a number n. You need to determine the maximum value in the n × n table defined by the rules above.

The only line of input contains a positive integer n (1 ≤ n ≤ 10) — the number of rows and columns of the table.

Print a single line containing a positive integer m — the maximum value in the table.

NoteIn the second test the rows of the table look as follows: {1, 1, 1, 1, 1},  {1, 2, 3, 4, 5},  {1, 3, 6, 10, 15},  {1, 4, 10, 20, 35},  {1, 5, 15, 35, 70}.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var n = in.next().toInt
  var previous = Array.fill(n){1}
  Range(0, n - 1).foreach { i =>
    val current = Array.ofDim[Int](n)
    current(0) = 1
    Range(1, n).foreach {
      i => current(i) = current(i - 1) + previous(i)
    }
    previous = current
  }
  print(previous.max)
}

object S509A {
    def main(args: Array[String]) {
        var i: Int = 0
        var j: Int = 0
        var n = readInt()
        val a = Array.ofDim[Int](n, n)
        for (i <- 0 until n) {
            a(i)(0) = 1
            a(0)(i) = 1
        }
        for (i <- 1 until n) {
            for (j <- 1 until n)
                a(i)(j) = a(i - 1)(j) + a(i)(j - 1)
        }
        println(a(n - 1)(n - 1))
    }
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val res = Array.ofDim[Int](n, n)
    for(i <- 0 until n; j <- 0 until n) {
      if(i == 0 || j == 0) {
        res(i)(j) = 1
      } else {
        res(i)(j) = res(i-1)(j) + res(i)(j-1)
      }
    }
    println(res(n-1)(n-1))
  }
}

import Array._
import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
  val n = readLine.toInt
    var A = ofDim[Int](n + 1, n + 1)
      for(i <- 1 to n) A(1)(i) = 1
    for(i <- 2 to n){
      for(j <- 1 to n) A(i)(j) = A(i - 1)(j) + A(i)(j - 1)
    }
//    for(i <- 1 to n){
//      for(j <- 1 to n) print(A(i)(j) + " "); println()
//    }
        for(i <- n to n){
          for(j <- n to n) print(A(i)(j) + " "); println()
        }
  }
}

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

object MaximumInTable {

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

   def readLongs() : Array[Long] =
      readLine.split(' ').map(_.toLong)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def solve(n : Int) : Int = {
     def go(r: Int, c: Int) : Int = {
       if (r == 1 || c == 1) 1
       else go(r-1,c)+go(r,c-1)
     }
     go(n,n)
   }

   def main(args: Array[String]) {
     val n = readInt
     println(solve(n))
   }

}

object main extends App with fastIO {

  def C(n: Int, m: Int): Int = {
    (n, m) match {
      case (1, m) => 1
      case (n, 1) => 1
      case (n, m) => C(n - 1, m) + C(n, m - 1)
    }
  }

  val n = nextInt

  println(C(n, n))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val n = StdIn.readInt()
    val A = Array.ofDim[Array[Int]](n)
    for (i <- 0 to n - 1) {
      A(i) = new Array[Int](n)
      A(i)(0) = 1
      A(0)(i) = 1
    }

    for (i <- 1 to n - 1) {
      for (j <- 1 to n - 1) {
        A(i)(j) = A(i-1)(j) + A(i)(j-1)
      }
    }

    println(A(n-1)(n-1))
  }

}


Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.

The single line contains a single integer n (1 ≤ n ≤ 1017). Please, do not use the %lld specifier to read or write 64 bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with.

NoteIn the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change.In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives.

object CF333A {
    def main(argv: Array[String]) {
        def calc(n: Long): Long = {
            if (n % 3 == 0) calc(n / 3)
            else (n + 2) / 3
        }
        println(calc(readLine.toLong))
    }
}

import scala.collection.mutable._
import scala.math._
import scala.util._
import scala.util.control.Breaks.break
import scala.util.control.Breaks.breakable
import java.util._
import java.math.BigInteger
object Main extends App {
  val sc = new Scanner(System.in)
  def count3(n: BigInt): BigInt = {
    if(n % 3 != 0) return 0
    return 1 + count3(n / 3)
  }
  def pow(a: BigInt, b: BigInt): BigInt = {
    if(b == 0) return 1
    else return a * pow(a, b-1)
  }
  val n = new BigInt(sc.nextBigInteger)
  val m = pow(3, count3(n)+1)
  println(n / m + (if((n % m) == 0) 0 else 1))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toLong

  def findK(n: Long): Long = {
    var k = 3l
    while (n % k == 0) {
      k *= 3
    }
    k
  }

  val k = findK(n)
  println( n / k + (if (n % k != 0) 1 else 0))

}

/**
 * Created by Notebook on 14.02.2015.
 */
object AplusB extends App{
      var a =readLong()
      while(a%3==0) a /= 3
      println(a/3+1)
}

object A extends App {

  def readString = Console.readLine

  val n = BigInt(readString)

  var i = BigInt(3)

  while (i <= n && n % i == 0) i *= 3

  println(n / i + 1)
}

object Main extends App {

        def calc(n: Long): Long = {
            if (n % 3 == 0) calc(n / 3)
            else (n + 2) / 3
        }
        println(calc(readLine.toLong))
    }

/**
 * User: Oleg Nizhnik
 * Date: 29.07.13
 * Time: 1:49
 */
object C_Secrets extends App {
  def find(n: Long, k: Long = 1): Long = if (n % k == 0) find(n, k * 3) else (n + k - 1) / k
  println(find(readLine().toLong))

}

/**
 * User: Oleg Nizhnik
 * Date: 29.07.13
 * Time: 1:49
 */
object C_Secrets {
  def find(n: Long, k: Long = 1): Long = if (n % k == 0) find(n, k * 3) else (n + k - 1) / k
  def main(args: Array[String]) = println(find(readLine().toLong))
}

import scala.collection.mutable._
import scala.math._
import scala.util._
import scala.util.control.Breaks.break
import scala.util.control.Breaks.breakable
import java.util._
import java.math.BigInteger
object Main extends App {
  val sc = new Scanner(System.in)
  val v = new BigInt(sc.nextBigInteger)
  println(v / 3 + (if((v % 3) == 0) 0 else 1))
}

import scala.collection.mutable._
import scala.math._
import scala.util._
import scala.util.control.Breaks.break
import scala.util.control.Breaks.breakable
import java.util._
object Main extends App {
  val sc = new Scanner(System.in)
  println(ceil(readLong/3.0).toLong)
}

import scala.collection.mutable._
import scala.math._
import scala.util._
import scala.util.control.Breaks.break
import scala.util.control.Breaks.breakable
import java.util._
import java.math.BigInteger
object Main extends App {
  val sc = new Scanner(System.in)
  val v = new BigInt(sc.nextBigInteger)
  println(v / 3 + ceil((v % 3).toInt * 0.1).toInt)
}

/**
 * Author: Odomontois
 * Date: 29.07.13
 * Time: 9:53
 * To change this template use File | Settings | File Templates.
 */
object C_Secrets extends App {
  val in = java.lang.Long.toString(readLine().toLong, 3).reverse
  println((in(0) match {
    case '1' => in.drop(1).dropWhile(_ == '2')
    case '0' | '2' => in.dropWhile(_ == '0').dropWhile(_ == '2')
  }).map(Map('0' -> 0, '1' -> 1, '2' -> 2)).sum + 1)
}

/**
 * Author: Odomontois
 * Date: 29.07.13
 * Time: 9:53
 * To change this template use File | Settings | File Templates.
 */
object C_Secrets extends App {
  val in = java.lang.Long.toString(readLine().toLong, 3).reverse.dropWhile(_ == '0')
  println((in(0) match {
    case '1' => in.drop(1)
    case '2' => in
  }).dropWhile(_ == '2').map(Map('0' -> 0, '1' -> 1, '2' -> 2)).sum + 1)
}