Stepan has n pens. Every day he uses them, and on the i-th day he uses the pen number i. On the (n + 1)-th day again he uses the pen number 1, on the (n + 2)-th — he uses the pen number 2 and so on.On every working day (from Monday to Saturday, inclusive) Stepan spends exactly 1 milliliter of ink of the pen he uses that day. On Sunday Stepan has a day of rest, he does not stend the ink of the pen he uses that day. Stepan knows the current volume of ink in each of his pens. Now it's the Monday morning and Stepan is going to use the pen number 1 today. Your task is to determine which pen will run out of ink before all the rest (that is, there will be no ink left in it), if Stepan will use the pens according to the conditions described above.

The first line contains the integer n (1 ≤ n ≤ 50 000) — the number of pens Stepan has. The second line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of milliliters of ink which the pen number i currently has.

Print the index of the pen which will run out of ink before all (it means that there will be no ink left in it), if Stepan will use pens according to the conditions described above.  Pens are numbered in the order they are given in input data. The numeration begins from one.  Note that the answer is always unambiguous, since several pens can not end at the same time.

NoteIn the first test Stepan uses ink of pens as follows:   on the day number 1 (Monday) Stepan will use the pen number 1, after that there will be 2 milliliters of ink in it;  on the day number 2 (Tuesday) Stepan will use the pen number 2, after that there will be 2 milliliters of ink in it;  on the day number 3 (Wednesday) Stepan will use the pen number 3, after that there will be 2 milliliters of ink in it;  on the day number 4 (Thursday) Stepan will use the pen number 1, after that there will be 1 milliliters of ink in it;  on the day number 5 (Friday) Stepan will use the pen number 2, after that there will be 1 milliliters of ink in it;  on the day number 6 (Saturday) Stepan will use the pen number 3, after that there will be 1 milliliters of ink in it;  on the day number 7 (Sunday) Stepan will use the pen number 1, but it is a day of rest so he will not waste ink of this pen in it;  on the day number 8 (Monday) Stepan will use the pen number 2, after that this pen will run out of ink. So, the first pen which will not have ink is the pen number 2.

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val xs = readLine().split(" ").map(_.toInt)
    if (n % 7 == 0) {
        var mi = -1
        xs.zipWithIndex.foreach({ case (x, i) =>
            if ((i + 1) % 7 != 0 && (mi == -1 || xs(mi) > x)) mi = i else ()
        })
        println(mi + 1)
    } else {
        val mx = (xs.min - 1) / 6 * 6
        var ys = xs.map(_ - mx)
        var (i, d) = (0, 1)
        while (d != 8) {
            if (d == 7) d = 0 else {
                ys(i) = ys(i) - 1
                if (ys(i) == 0) d = 7 else ()
            }
            d += 1
            i = (i + 1) % n
        }
        println(if (i == 0) n else i)
    }
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
var mn = 0;
                var i = 0;
		while(i<n) {
			if (a(i) < a(mn)) {
                                if (n%7!=0 || i%7!=6) {
				     mn = i;
                                }
			}
                        i+=1;
		}

	        var del = (a(mn) - 1) / 7 * 7;
                i = 0;
	        while(i<n) {
			a(i) -= del;

                        i+=1;
		}
	        var day = 0;
		while (i<=n) {
                        i = 0;
			while(i<n) {
			        day+=1;
				if (day % 7 != 0) {
					a(i)-=1;
				}
				if (a(i) == 0) {

                                    if (n%7!=0 || i%7!=6) {
					println(i + 1);
					i = n+5;
                                    }
				}
                                i += 1;
			}
		}
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
var mn = 0;
                var i = 0;
		while(i<n) {
			if (a(i) < a(mn) && (n%7!=0 || i%7!=6)) {
				mn = i;
			}
                        i+=1;
		}

	        var del = (a(mn) - 1) / 7 * 7;
                i = 0;
	        while(i<n) {
			a(i) -= del;

                        i+=1;
		}
	        var day = 0;
		while (i<=n) {
                        i = 0;
			while(i<n) {
			        day+=1;
				if (day % 7 != 0) {
					a(i)-=1;
				}
				if (a(i) == 0 && (i%7!=6 || n%7!=0)) {
					println(i + 1);
					i = n+5;
				}
                                i += 1;
			}
		}
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
  	if (n % 7 == 0) {
		var mn = 0;
                var i = 0;
		while(i<n) {
			if (i % 7 != 6 && a(i) < a(mn)) {
				mn = i;
                        }
                        i+=1;
		}
		println(mn+1);
	}
	else {
		var mn = 0;
                var i = 0;
		while(i<n) {
			if (a(i) < a(mn)) {
				mn = i;
			}
                        i+=1;
		}
	        var del = (a(mn) - 1) / 7 * 7;
                i = 0;
	        while(i<n) {
			a(i) -= del;
                        i+=1;
		}
	        var day = 0;
		while (i<=n) {
                        i = 0;
			while(i<n) {
			        day+=1;
				if (day % 7 != 0) {
					a(i)-=1;
				}
				if (a(i) == 0) {
					println(i + 1);
					i = n+5;
				}
                                i += 1;
			}
		}
	}
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    var mx = 2e9;
    var d = 1;
    var i = 0;
    while(i<n) {
        var x = a(i);
	var l = 1.toLong;
        var r = 2e9.toLong;
	var pv = 0;
        var nxt = 0;
	var j = 1;
        while (j<=21) {
	    if ((i + 1 + n*(j-1)) % 7 == 0) {
		if (pv > 0) {
           		nxt = j;
                        j = 25;
		} else {
		        pv = j;
                }
	    }
            j += 1;
	}
	while (l != r) {
	    var m = ((l + r) / 2).toInt;
	    var emptyC = 0;
	    if (m >= pv && pv > 0) {
		emptyC = (m - pv) / (nxt - pv);
		emptyC += 1;
       	    }
	    if (m - emptyC > x) {
		r = m.toLong;
     	    }
            else {
		l = (m + 1).toLong;
	    }
	}
	if (l - 1 < mx) {
 	    mx = (l - 1).toInt;
	    d = i + 1;
	}
        i+=1;
    }
    println(d)
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    var mx = 4e9.toLong;
    var d = 1;
    var i = 0;
    while(i<n) {
        var x = a(i);
	var l = 1.toLong;
        var r = 4e9.toLong;
	var pv = 0;
        var nxt = 0;
	var j = 1;
        while (j<=21) {
	    if ((i + 1 + n*(j-1)) % 7 == 0) {
		if (pv > 0) {
           		nxt = j;
                        j = 25;
		} else {
		        pv = j;
                }
	    }
            j += 1;
	}
	while (l != r) {
	    var m = ((l + r) / 2+1e-5).toLong;
	    var emptyC = 0.toLong;
	    if (m >= pv && pv > 0) {
		emptyC = ((m - pv) / (nxt - pv) + 1e-5).toLong;
		emptyC += 1;
       	    }
	    if (m - emptyC > x) {
		r = m.toLong;
     	    }
            else {
		l = (m + 1).toLong;
	    }
	}
	if (l - 1 < mx) {
 	    mx = (l - 1).toInt;
	    d = i + 1;
	}
        i+=1;
    }
    println(d)
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    var mx = 4e9.toLong;
    var d = 1;
    var i = 0;
    while(i<n) {
        var x = a(i);
	var l = 1.toLong;
        var r = 4e9.toLong;
	var pv = 0;
        var nxt = 0;
	var j = 1;
        while (j<=21) {
	    if ((i + 1 + n*(j-1)) % 7 == 0) {
		if (pv > 0) {
           		nxt = j;
                        j = 25;
		} else {
		        pv = j;
                }
	    }
            j += 1;
	}
	while (l != r) {
	    var m = ((l + r) / 2).toLong;
	    var emptyC = 0.toLong;
	    if (m >= pv && pv > 0) {
		emptyC = (m - pv) / (nxt - pv);
		emptyC += 1;
       	    }
	    if (m - emptyC > x) {
		r = m.toLong;
     	    }
            else {
		l = (m + 1).toLong;
	    }
	}
	if (l - 1 < mx) {
 	    mx = (l - 1).toInt;
	    d = i + 1;
	}
        i+=1;
    }
    println(d)
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    var mx = 2e9;
    var d = 1;
    var i = 0;
    while(i<n) {
        var x = a(i);
	var l = 1;
        var r = (x*1.5).toInt;
	var pv = 0;
        var nxt = 0;
	var j = 1;
        while (j<=21) {
	    if ((i + 1 + n*(j-1)) % 7 == 0) {
		if (pv > 0) {
           		nxt = j;
                        j = 25;
		} else {
		        pv = j;
                }
	    }
            j += 1;
	}
	while (l != r) {
	    var m = ((l + r) / 2).toInt;
	    var emptyC = 0;
	    if (m >= pv && pv > 0) {
		emptyC = (m - pv) / (nxt - pv);
		emptyC += 1;
       	    }
	    if (m - emptyC > x) {
		r = m;
     	    }
            else {
		l = m + 1;
	    }
	}
	if (l - 1 < mx) {
 	    mx = l - 1;
	    d = i + 1;
	}
        i+=1;
    }
    println(d)
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
  	if (n % 7 == 0) {
		var mn = 0;
                var i = 0;
		while(i<n) {
			if (i % 7 == 6 && a(i) < a(mn)) {
				mn = i;
                        }
                        i+=1;
		}
		println(mn+1);
	}
	else {
		var mn = 0;
                var i = 0;
		while(i<n) {
			if (a(i) < a(mn)) {
				mn = i;
			}
                        i+=1;
		}
	        var del = (a(mn) - 1) / 7 * 7;
                i = 0;
	        while(i<n) {
			a(i) -= del;
                        i+=1;
		}
	        var day = 0;
		while (i<=n) {
                        i = 0;
			while(i<n) {
			        day+=1;
				if (day % 7 != 0) {
					a(i)-=1;
				}
				if (a(i) == 0) {
					println(i + 1);
					i = n+5;
				}
                                i += 1;
			}
		}
	}
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    var mx = 1e9;
    var d = 1;
    var i = 0;
    while(i<n) {
        var x = a(i);
	var l = 1;
        var r = 1e9;
	var pv = 0;
        var nxt = 0;
	var j = 1;
        while (j<=21) {
	    if ((i + 1 + n*(j-1)) % 7 == 0) {
		if (pv > 0) {
           		nxt = j;
                        j = 25;
		} else {
		        pv = j;
                }
	    }
            j += 1;
	}
	while (l != r) {
	    var m = ((l + r) / 2).toInt;
	    var emptyC = 0;
	    if (m >= pv && pv > 0) {
		emptyC = (m - pv) / (nxt - pv);
		emptyC += 1;
       	    }
	    if (m - emptyC > x) {
		r = m;
     	    }
            else {
		l = m + 1;
	    }
	}
	if (l - 1 < mx) {
 	    mx = l - 1;
	    d = i + 1;
	}
        i+=1;
    }
    println(d)
}

import scala.io.StdIn._

object F extends App {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    var mx = 4e9.toLong;
    var d = 1;
    var i = 0;
    while(i<n) {
        var x = a(i);
	var l = 1.toLong;
        var r = 4e9.toLong;
	var pv = 0;
        var nxt = 0;
	var j = 1;
        while (j<=21) {
	    if ((i + 1 + n*(j-1)) % 7 == 0) {
		if (pv > 0) {
           		nxt = j;
                        j = 25;
		} else {
		        pv = j;
                }
	    }
            j += 1;
	}
	while (l != r) {
	    var m = ((l + r) / 2).toLong;
	    var emptyC = 0.toLong;
	    if (m >= pv && pv > 0) {
		emptyC = ((m - pv) / (nxt - pv)).toLong;
		emptyC += 1;
       	    }
	    if (m - emptyC > x) {
		r = m.toLong;
     	    }
            else {
		l = (m + 1).toLong;
	    }
	}
	if (l - 1 < mx) {
 	    mx = (l - 1).toInt;
	    d = i + 1;
	}
        i+=1;
    }
    println(d)
}


There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies.Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm:  Give m candies to the first child of the line.  If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home.  Repeat the first two steps while the line is not empty. Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?

The first line contains two integers n, m (1 ≤ n ≤ 100; 1 ≤ m ≤ 100). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100).

Output a single integer, representing the number of the last child.

NoteLet's consider the first sample. Firstly child 1 gets 2 candies and go home. Then child 2 gets 2 candies and go to the end of the line. Currently the line looks like [3, 4, 5, 2] (indices of the children in order of the line). Then child 3 gets 2 candies and go home, and then child 4 gets 2 candies and goes to the end of the line. Currently the line looks like [5, 2, 4]. Then child 5 gets 2 candies and goes home. Then child 2 gets two candies and goes home, and finally child 4 gets 2 candies and goes home.Child 4 is the last one who goes home.

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

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

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

  def solve() = {
    val n = nextInt
    val m = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      val t = nextInt
      a(i) = t / m
      if (t % m != 0) {
       a(i) = a(i) + 1
      }
    }
    //println(a.toList)
    var max = 0
    for (i <- 0 until n) {
      if (a(i) >= a(max)) {
        max = i
      }
    }
    out.println(max + 1)
  }

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

import java.util.StringTokenizer

import scala.collection.mutable.Queue

object _450A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val m = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray

  def f(q: Queue[Int]): Int = {
    if (q.tail == Nil) q.head + 1
    else {
      val i = q.head
      if (a(i) <= m) f(q.tail)
      else {
        a(i) = a(i) - m
        f(q.tail :+ i)
      }
    }
  }
  println(f(Queue[Int]() ++ (0 until n)))
}

import java.util.Scanner

/**
 * Created by kshim on 25/07/2014.
 */
object CF257A extends App {
  def Process(m:Int, a:Seq[Int]):Int = {
    val dvd = a.map(v => math.ceil(v / m.toDouble).toInt)
    var maxi = -1
    var max = -1
    for(i <- 0 until dvd.length){
      if(dvd(i) >= max){
        max = dvd(i)
        maxi = i
      }
    }
    maxi + 1
  }
  val in = new Scanner(System.in)
  val n = in.nextInt()
  val m = in.nextInt()
  val ai = (1 to n).map(_=>in.nextInt())
  println(Process(m,ai.toArray))
}

object A450 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val in = readInts(n).zipWithIndex
    val q = collection.mutable.Queue[(Int, Int)]()
    in.foreach(q.enqueue(_))
    while(q.size > 1) {
      var (cand, pos) = q.dequeue()
      cand -= m
      if(cand > 0)
        q.enqueue((cand, pos))
    }
    println(q.dequeue._2 + 1)
  }

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

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

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

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

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

}

object Children {

  def splitter(as: String) = as.split("\\s+") match {
    case Array(n, m) => List(n.toInt, m.toInt)
    case arr: Array[String] => arr.map(_.toInt).toList
  }

  def solve(l: List[(Int, Int)], m: Int): Int = l match {
    case h :: Nil => h._2
    case h :: t if (h._1 <= m) => solve(t, m)
    case h :: t => solve(t :+ (h._1 - m, h._2), m)
  }

  def main(args: Array[String]) {
    val List(nmStr, asStr) = io.Source.stdin.getLines.take(2).toList
    val List(n, m) = splitter(nmStr)
    val as = splitter(asStr).zipWithIndex
    println(solve(as, m) + 1)
  }
}

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

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

  val as: Array[Int] = readLine()
    .split(" ")
    .map(_.toInt)

  val max: Int = as.max

  val res: Int =
    if (max > m) {val bs = as.map(a => (a.toDouble / m).ceil.toInt); bs.lastIndexOf(bs.max)+1}

    else
      as.length

  println(res)

}}

object Main {
  def main(args: Array[String]): Unit = {
    val nm = io.StdIn.readLine().split(" ").map(x => Integer.parseInt(x))
    val nums = io.StdIn.readLine().split(" ").map { x=>
      val i = Integer.parseInt(x)
      if  (i % nm(1) != 0) i/nm(1) + 1 else i/nm(1)
    }

    def indexOfMax( maxIndex: Int, index: Int): Int = {
      if (index < 0) maxIndex
      else indexOfMax(if (nums(index) > nums(maxIndex)) index else maxIndex, index - 1)
    }

    println(indexOfMax(nm(0)-1, nm(0)-1) + 1)
  }
}

import scala.annotation.tailrec

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n,m = sc.nextInt
  val input = List.fill(n)(sc.nextInt)

  def solve( m: Int, input: List[Int] ): Int = {

    @tailrec
    def dist(children: List[(Int, Int)]): Int = {
      children match {

        case List(x) =>  // size == 1
          x._2 + 1

        case x :: xs =>
          val diff = x._1 - m
          if (diff <= 0)
            dist(xs)
          else
            dist( ( (diff, x._2) :: xs.reverse ).reverse )
      }
    }

    dist( input.zipWithIndex )
  }

  println( solve( m, input ) )
}

import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n,m = sc.nextInt
  val children = List.fill(n)(sc.nextInt).zipWithIndex

  @tailrec
  def dist(children: List[(Int,Int)]): Unit = {
    children match {
      case Nil =>
      case List(x) => println(x._2 + 1)
      case x::xs =>
        val diff = x._1 - m
        if( diff <= 0 )
          dist(xs)
        else
          dist( xs :+ (diff, x._2) )
    }
  }

  dist(children)
}

object HelloWorld{
  def giveCandies(xs: List[(Int, Int)], m:Int, lastSatisfied:Int):Int = xs match {
    case Nil => lastSatisfied
    case x::xs => if (x._1<=m) giveCandies(xs, m, x._2) else giveCandies(xs++List((x._1-m, x._2)), m, lastSatisfied)
  }
  def main(args: Array[String]){
    val in = new java.util.Scanner(System.in)
    val n = in.nextInt
    val m = in.nextInt
    in.nextLine
    val q = in.nextLine.split(" ").map(_.toInt).zipWithIndex.toList
    print(giveCandies(q, m, -1)+1)
  }
}

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

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

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

  def solve() = {
    val n = nextInt
    val m = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
       a(i) = Math.max(nextInt / m, 1)
    }
    var max = 0
    for (i <- 0 until n) {
      if (a(i) >= a(max)) {
        max = i
      }
    }
    out.println(max + 1)
  }

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

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

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

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

  def solve() = {
    val n = nextInt
    val m = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
       a(i) = (nextInt) / m
    }
    var max = 0
    for (i <- 0 until n) {
      if (a(i) >= a(max)) {
        max = i
      }
    }
    out.println(max + 1)
  }

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

import java.util.Scanner

/**
 * Created by kshim on 25/07/2014.
 */
object CF257A extends App {
  def Process(m:Int, a:Seq[Int]):Int = {
    val dvd = a.map(_ / m)
    var maxi = -1
    var max = -1
    for(i <- 0 until dvd.length){
      if(dvd(i) >= max){
        max = dvd(i)
        maxi = i
      }
    }
    maxi + 1
  }
  val in = new Scanner(System.in)
  val n = in.nextInt()
  val m = in.nextInt()
  val ai = (1 to n).map(_=>in.nextInt())
  println(Process(m,ai))
}

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

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

  val as: Array[Int] = readLine()
    .split(" ")
    .map(_.toInt)

  val max: Int = as.max

  val res: Int =
    if (max > m) {val bs = as.map(_ / m); bs.lastIndexOf(bs.max)+1}

    else
      as.length

  println(res)

}}

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

  val line: String = readLine()

  val asString: String = readLine()
  val as: Array[Int] = asString.split(" ")
    .map(_.toInt)

  val of: Int = as.lastIndexOf(as.max)

  println(of+1)

}}

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

  val line: String = readLine()

  val asString: String = readLine()
  val as: Array[Int] = asString.split(" ")
    .map(_.toInt)

  val of: Int = as.lastIndexOf(as.max)

  println(of)

}}

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

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

  val asString: String = readLine()
  val as: Array[Int] = asString.split(" ")
    .map(_.toInt)

  val max: Int = as.max
  val of: Int =
    if (max > m)
      as.lastIndexOf(max)
    else
      as.length-1

  println(of+1)

}}

object Main {
  def main(args: Array[String]): Unit = {
    val nm = io.StdIn.readLine().split(" ").map(x => Integer.parseInt(x))
    val nums = io.StdIn.readLine().split(" ")
    def indexOfMax( maxIndex: Int, index: Int): Int = {
      if (index < 0) maxIndex
      else indexOfMax(if (nums(index) > nums(maxIndex)) index else maxIndex, index - 1)
    }
    println(indexOfMax(nm(0)-1, nm(0)-1) + 1)
  }
}

import scala.annotation.tailrec

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n,m = sc.nextInt
  val children = List.fill(n)(sc.nextInt).zipWithIndex

  @tailrec
  def dist(children: List[(Int,Int)]): Unit = {
    children match {
      case Nil =>
      case List(x) => println(x._2 + 1)
      case x::xs =>
        val diff = x._1 - m
        if( diff < 0 )
          dist(xs)
        else
          dist( ( (diff, x._2) :: xs).reverse )
    }
  }

  dist(children)
}


There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the troupe are considered different.Perform all calculations in the 64-bit type: long long for С/С++, int64 for Delphi and long for Java.

The only line of the input data contains three integers n, m, t (4 ≤ n ≤ 30, 1 ≤ m ≤ 30, 5 ≤ t ≤ n + m).

Find the required number of ways. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

object P131C extends App {
  val Array(n,m,t) = readLine.split(" ").map(_.toInt)
  def f(a:BigInt, n:Int):BigInt = if (n<=2) a*math.max(n,1) else f(a*n, n-1)
  def m(m:Int, n:Int) = f(1,n)/f(1,n-m)/f(1,m)
  val c = (for(b <- 4 to n; g <- 1 to m) yield((b,g))) filter ((x)=>x._1+x._2==t)
  println(c.map((x) => m(x._1,n) * m(x._2,m)).sum)
}

object P131C extends App {

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

  def fac(a:BigInt,n:Int):BigInt = if (n<=2) a*math.max(n,1) else fac(a*n,n-1)
  def mofn(m:Int,n:Int) = fac(1,n) / fac(1,n-m) / fac(1,m)

  val combs = (for(boys <- 4 to n; girls <- 1 to m) yield((boys,girls))) filter ((x) => x._1 + x._2 == t)

  println(combs.map((x) => mofn(x._1,n) * mofn(x._2,m)).sum)

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val arr@Array(n, m, t) = in.next().split(' ').map(_.toInt)
  val max = arr.max
  val binom = Array.ofDim[Long](max + 1, max + 1)
  (0 to max).foreach { i =>
    binom(i)(0) = 1
    (1 to i).foreach {j =>
      binom(i)(j) = binom(i - 1)(j) + binom(i - 1)(j - 1)
    }
  }
//  println(binom.map(_.mkString(" ")).mkString("\n"))

  println((1 to t - 4).foldLeft(0l) {
    case(sum, i) =>
      sum + binom(m)(i) * binom(n)(t - i)
  })
}

object Main {

    def mkComb(n:Int) = {
        val a = Array.ofDim[Long](n, n)
        for (i <- 0 until n) {
            a(i)(0) = 1L
            a(i)(i) = 1L
            for (j <- 1 until i)
                a(i)(j) = a(i-1)(j) + a(i-1)(j-1)
        }
        a
    }

    def main(args: Array[String]) {
        val comb = mkComb(31)
        val n = nextInt()
        val m = nextInt()
        val actors = nextInt()
        val ans = for ( boys <- 0 to actors;
                        girls = actors - boys
                        if boys >= 4 && boys <= n
                        if girls >= 1 && girls <= m
                      ) yield (comb(n)(boys) * comb(m)(girls))
        println(ans.sum)
    }

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

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

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

object C131 {
	def fact(t: Int): BigInt = if (t <= 1) BigInt(1) else t * fact(t - 1)
	implicit def implfact(t: Int) = new { def ! = fact(t)}

	def c(n: Int, k: Int): BigInt = (n!)/((k!) * ((n - k)!))

	def main(args: Array[String]) {
		val s = readLine.split(" ")
		val n = Integer.parseInt(s(0))
		val m = Integer.parseInt(s(1))
		val t = Integer.parseInt(s(2))
		var res = BigInt(0)
		for (i <- 4 to n)
			for (j <- 1 to m)
				if (i + j == t)
					res += c(n, i) * c(m, j)
		println(res)
	}
}

object Main {
  val cache: Array[Array[Long]] = (1 to 61).map(_ => (1L to 61L).toArray).toArray
  for{
    i <- 0 to 60
    j <- 0 to 60
  } {
    (i, j) match {
      case (n, 0) => cache(n)(0) = 1
      case (0, k) => cache(0)(k) = 0
      case (n, k) => cache(n)(k) = cache(n - 1)(k - 1) + cache(n - 1)(k)
    }
  }

  def main(args: Array[String]) {
    val Array(n, m, k) = readLine().split(" ").map(_.toInt)
    val sum = (4 to n.min(k - 1)).map(i => cache(n)(i) * cache(m)(k - i)).sum
    println(sum)
  }
}

import scala.io.Source

object Solution extends App {

  def factorial(n: Int) = (1 to n).foldLeft(1l) { case(acc, i) => acc * i }

  def combinations(k: Int, n: Int) = factorial(n) / (factorial(k) * factorial(n - k))

  val in = Source.stdin.getLines()
  val Array(n, m, t) = in.next().split(' ').map(_.toInt)
  println((1 to t - 4).foldLeft(0l) {
    case(sum, i) => sum + combinations(i, m) * combinations(t - i, n)
  })
}


It is known that fleas in Berland can jump only vertically and horizontally, and the length of the jump is always equal to s centimeters. A flea has found herself at the center of some cell of the checked board of the size n × m centimeters (each cell is 1 × 1 centimeters). She can jump as she wishes for an arbitrary number of times, she can even visit a cell more than once. The only restriction is that she cannot jump out of the board.The flea can count the amount of cells that she can reach from the starting position (x, y). Let's denote this amount by dx, y. Your task is to find the number of such starting positions (x, y), which have the maximum possible value of dx, y.

The first line contains three integers n, m, s (1 ≤ n, m, s ≤ 106) — length of the board, width of the board and length of the flea's jump.

Output the only integer — the number of the required starting positions of the flea.

object P032C extends App {
  val a = readLine.split(' ').map(_.toLong)
  val f = (n: Long, s: Long) => ((n-1)%s+1) * ((n-1)/s+1)
  println(f(a(0), a(2)) * f(a(1), a(2)))
}

object P032C extends App {
  val a = readLine.split(' ').map(_.toInt)
  val f = (n: Int, s: Int) => ((n-1)%s+1) * ((n-1)/s+1)
  println(f(a(0), a(2)) * f(a(1), a(2)))
}


Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the circle by numbers from 0 to 3n - 1, let the gnome sitting on the i-th place have ai coins. If there is an integer i (0 ≤ i < n) such that ai + ai + n + ai + 2n ≠ 6, then Tanya is satisfied. Count the number of ways to choose ai so that Tanya is satisfied. As there can be many ways of distributing coins, print the remainder of this number modulo 109 + 7. Two ways, a and b, are considered distinct if there is index i (0 ≤ i < 3n), such that ai ≠ bi (that is, some gnome got different number of coins in these two ways).

A single line contains number n (1 ≤ n ≤ 105) — the number of the gnomes divided by three.

Print a single number — the remainder of the number of variants of distributing coins that satisfy Tanya modulo 109 + 7.

Note20 ways for n = 1 (gnome with index 0 sits on the top of the triangle, gnome 1 on the right vertex, gnome 2 on the left vertex):

/**
 * @author netman
 */

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

object HelloWorld {

  class InputReader(reader: BufferedReader) {

    var tokenizer: StringTokenizer = null;

    def this(stream: InputStream) = {
      this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));
    }

    def this(f: File) = {
      this(new BufferedReader(new FileReader(f), (1 << 20)));
    }

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

    def nextInt(): Int = next().toInt

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

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

  class OutputWriter(writer: PrintWriter) {
    def this(stream: OutputStream) {
      this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));
    }

    def this(f: File) = {
      this(new PrintWriter(new BufferedWriter(new FileWriter(f))));
    }

    def print(x: Any) = writer.print(x);

    def println(x: Any) = writer.println(x);

    def close() = writer.close();
  }

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

  val P = 1000 * 1000 * 1000L + 7

  def main(args: Array[String]): Unit = {
    val n = in.nextInt

    var f = new Array[Long](2)
    var fn = new Array[Long](2)

    f(0) = 1

    val coef = 7L
    val all = 3 * 3 * 3L

    for (i <- 0 until n) {
      fn(0) = f(0) * coef
      fn(1) = f(1) * all + f(0) * (all - coef)
      fn(0) %= P
      fn(1) %= P
      var tmp = f
      f = fn
      fn = tmp
    }

    out.println(f(1))

    out.close
  }
}

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

  val n = in.next().toInt
  var ans = (BigInt(3).pow(3 * n) - BigInt(7).pow(n)) % 1000000007
  println(ans.toLong)
}

import scala.io.StdIn._

object B extends App {
  val Array(n) = readLine().split(" ").map(_.toInt)

  val M = 1000000007

  def countMod(base: Int, power: Int): Long = {
    var curr: Long = base
    for (i <- 2 to power) {
      curr *= base
      if (curr > M) curr %= M
    }
    curr
  }

//  def countMod2(base: Int, power: Int): Long = {
//    BigInt(base).modPow(power, M).toLong
//  }

  val answer = countMod(27, n) - countMod(7, n)
  println(if (answer < 0) M + answer else answer)

}

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

  val n = in.next().toLong
  println((Math.pow(3, 3 * n) - Math.pow(7, n)).toLong % 1000000007)
}

import scala.io.StdIn._

object B extends App {
  val Array(n) = readLine().split(" ").map(_.toInt)

  val M = 1000000007

  def countMod(base: Int, power: Int): Long = {
    var curr: Long = base
    for (i <- 2 to power) {
      curr *= base
      if (curr > M) curr %= M
    }
    curr
  }

  println(countMod(27, n) - countMod(7, n))

}

import scala.io.StdIn._

object B extends App {
  val Array(n) = readLine().split(" ").map(_.toInt)

  val M = 1000000007

  def countMod(base: Int, power: Int): Long = {
    var curr: Long = base
    for (i <- 2 to power) {
      curr *= base
      if (curr > M) curr %= M
    }
    curr
  }

  val answer = countMod(27, n) - countMod(7, n)
  println(if (answer < 0) M - answer else answer)

}

import scala.io.StdIn._

object B extends App {
  val Array(n) = readLine().split(" ").map(_.toInt)

  val M = 1000000007

  def countMod(base: Int, power: Int): Long = {
    var curr: Long = base
    for (i <- 2 to power) {
      curr *= base
      if (curr > M) curr %= M
    }
    curr
  }

  def countMod2(base: Int, power: Int): Long = {
    BigInt(base).modPow(power, M).toLong
  }

  val answer = countMod2(27, n) - countMod2(7, n)
  println(if (answer < 0) M - answer else answer)

}


Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm:  Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones).  Digits are written one by one in order corresponding to number and separated by single '0' character. Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number.

The first line contains one integer number n (1 ≤ n ≤ 89) — length of the string s. The second line contains string s — sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 109. The string always starts with '1'.

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

object Main extends App {
  readLine()
  val a = readLine().split("0", -1)
  var res = ""
  a.foreach(x => res += x.length)
  println(res)
}

object Main extends App {
  val n = io.StdIn.readInt()
  var s: String = io.StdIn.readLine()

  var result = ""
  while(!s.isEmpty){
    if (s.head == '0') s = s.tail
    val (head, tail) = s.span(_ == '1')
    result += head.length.toString
    s = tail
  }
  println(result)
}

object Main extends App {
  scala.io.StdIn.readLine()
  print(scala.io.StdIn.readLine().split("0", -1).map(_.length).mkString(""))
}

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

object Main extends App {
  readLine()
  val a = readLine().split('0')
  var res = ""
  a.foreach(x => res += x.length)
  println(res)
}

object Main extends App {
  scala.io.StdIn.readLine()
  print(scala.io.StdIn.readLine().split("0").map(_.length).mkString(""))
}


Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).The University works in such a way that every day it holds exactly n lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks).The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the n pairs she knows if there will be a class at that time or not.Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university.Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home.Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair.

The first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of lessons at the university.  The second line contains n numbers ai (0 ≤ ai ≤ 1). Number ai equals 0, if Alena doesn't have the i-th pairs, otherwise it is equal to 1. Numbers a1, a2, ..., an are separated by spaces.

Print a single number — the number of pairs during which Alena stays at the university.

NoteIn the first sample Alena stays at the university from the second to the fifth pair, inclusive, during the third pair she will be it the university waiting for the next pair. In the last sample Alena doesn't have a single pair, so she spends all the time at home.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).dropWhile(_ == 0).reverse.dropWhile(_ == 0).reverse
  val res = data.foldLeft((0, 0)){
    case((soFar, zeros), 1) if zeros < 2 => (soFar + zeros + 1, 0)
    case((soFar, zeros), 1) => (soFar + 1, 0)
    case((soFar, zeros), 0) => (soFar, zeros + 1)
  }

  println(res._1)

}

object A586 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n).dropWhile(_ == 0).reverse.dropWhile(_ == 0).reverse
    var res = 0
    var curr = 0
    for(i <- in.indices) {
      if(in(i) == 0) {
        curr += 1
        res += 1
      } else {
        res += 1
        if(curr > 1)
          res -= curr
        curr = 0
      }
    }
    println(res)
  }

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

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

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

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

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

}

import scala.io.StdIn._

object A extends App {
  readInt()

  val pairs = readLine().split(" ").map(_.toInt).dropWhile(_ == 0).reverse.dropWhile(_ == 0)

  var lastlast = 1
  var last = 1
  var zeros = 0
  for (p <- pairs) {
    if (p == 0) {
      if (last == 0 && lastlast == 0) zeros += 1
      else if (last == 0) zeros += 2
    }

    lastlast = last
    last = p
  }

  println(pairs.length - zeros)
}

import java.io._

//32A, 586A
object A_AlenaSchedule {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val number = br.readLine().trim().toInt
    val pairsSrc = br.readLine().trim().split(" ")

//    val number = 5
//    val pairsSrc = "0 1 0 1 1".split(" ")

//    val number = 7
//    val pairsSrc = "1 0 1 0 0 1 0".split(" ")

    var pairs = List[Int]()
    var break = true
    var breakCandidate = false;

    for (i <- 0 until number) {
      val value = pairsSrc(i).toInt
      if (breakCandidate && value == 0) {
        break = true
        breakCandidate = false
      } else if (break && value == 0) {
        //skip
      } else if (value == 1) {
        break = false
        if (breakCandidate) {
          pairs = 0 :: pairs
          breakCandidate = false
        }
        pairs = value :: pairs
      } else if (!break && value == 0) {
        if(!breakCandidate) {
          breakCandidate = true
        }
      }
    }

    println(pairs.size)

  }
}


It is a balmy spring afternoon, and Farmer John's n cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through n, are arranged so that the i-th cow occupies the i-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has formed the Mischievous Mess Makers and is plotting to disrupt this beautiful pastoral rhythm. While Farmer John takes his k minute long nap, Elsie and the Mess Makers plan to repeatedly choose two distinct stalls and swap the cows occupying those stalls, making no more than one swap each minute.Being the meticulous pranksters that they are, the Mischievous Mess Makers would like to know the maximum messiness attainable in the k minutes that they have. We denote as pi the label of the cow in the i-th stall. The messiness of an arrangement of cows is defined as the number of pairs (i, j) such that i < j and pi > pj.

The first line of the input contains two integers n and k (1 ≤ n, k ≤ 100 000) — the number of cows and the length of Farmer John's nap, respectively.

Output a single integer, the maximum messiness that the Mischievous Mess Makers can achieve by performing no more than k swaps.

NoteIn the first sample, the Mischievous Mess Makers can swap the cows in the stalls 1 and 5 during the first minute, then the cows in stalls 2 and 4 during the second minute. This reverses the arrangement of cows, giving us a total messiness of 10.In the second sample, there is only one cow, so the maximum possible messiness is 0.

import scala.collection._

object B 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, k) = readInts(2)

  var res = 0L

  val lim = math.min(k, n / 2)
  for (i <- 1 to lim) {
    val x = n - 2 * i
    res += 2 * x + 1
  }

  println(res)
}

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

object _645B extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, k = io[Long]
    io += solve(n, k, 0)
  }

  @tailrec
  def solve(n: Long, k: Long, acc: Long): Long = {
    //debug(n, k)
    (n, k) match {
      case (_, 0) => acc
      case (1, _) | (0, _) => acc
      case _ =>  solve(n - 2, k - 1, acc + (n - 2) + (n - 1))
    }
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates: Traversable[A] = {
      val elems = mutable.Set.empty[A]
      t collect {case i if !elems.add(i) => i}
    }
    def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}
    def mapTo[B](f: 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
  }
  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 IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {
    def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s
  }
  implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))
    def swap: Traversable[(B, A)] = t.map(_.swap)
  }
  implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.swap.toMultiMap.mapValues(_.toSet)
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  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 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(n.min(x, y), n.max(x, y), n.one)
  }
  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] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer, scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def appendNewLine(): this.type = {
    println()
    this
  }

  override def print(obj: Any) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]): Read[C[A]]            = new Read(r => r[C, A](r[Int]))
    implicit val string                                                  : Read[String]          = new Read(_.next())
    implicit val char                                                    : Read[Char]            = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                                 : Read[Boolean]         = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                       : Read[(A, B, C)]       = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]              : Read[(A, B, C, D)]    = new Read(r => (r[A], r[B], r[C], r[D]))
    implicit def tuple5[A: Read, B: Read, C: Read, D: Read, E: Read]     : Read[(A, B, C, D, E)] = new Read(r => (r[A], r[B], r[C], r[D], r[E]))
  }
  class Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit = out.print(x)
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = new Write[A]
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}


Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number n is almost lucky.

The single line contains an integer n (1 ≤ n ≤ 1000) — the number that needs to be checked.

In the only line print "YES" (without the quotes), if number n is almost lucky. Otherwise, print "NO" (without the quotes).

NoteNote that all lucky numbers are almost lucky as any number is evenly divisible by itself.In the first sample 47 is a lucky number. In the second sample 16 is divisible by 4.

object a {
	def main(args: Array[String]) {
	    val a = scala.io.StdIn.readInt()
        var ans = List(4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777).
            map(arg => a%arg).
	        exists(arg => arg == 0)

        print(if (ans) "YES" else "NO")
	}
}

import scala.io.StdIn
import scala.util.control.Breaks

/**
  * @author traff
  */

object Main extends App {
  val n = StdIn.readLine().toInt

  Breaks.breakable {
    for (i <- 2 to n) {
      if (n % i == 0 && !i.toString.exists(!"47".contains(_))) {
        println("YES")
        Breaks.break()
      }
    }
    println("NO")
  }
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  if (List(4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777).exists(t => n % t == 0))
    println("YES") else println("NO")
}

import scala.collection.mutable.ArrayBuffer

object Main {

  def generateLuckyMumbers(buf: ArrayBuffer[Int], maxValue: Int, currentValue: Int): Unit = {
    if (currentValue <= maxValue) {
      buf.append(currentValue)
      generateLuckyMumbers(buf, maxValue, currentValue * 10 + 4)
      generateLuckyMumbers(buf, maxValue, currentValue * 10 + 7)
    }
  }

  def main(args: Array[String]) {
    val std = scala.io.StdIn
    val number = std.readLine().toInt

    val luckyNumbers = ArrayBuffer.empty[Int]
    generateLuckyMumbers(luckyNumbers, number, 4)
    generateLuckyMumbers(luckyNumbers, number, 7)
    val result = luckyNumbers.exists(x => number % x == 0)
    if (result) {
      println("YES")
    }
    else {
      println("NO")
    }
  }
}

import scala.io.StdIn

/**
 * Created by richard on 2015/6/10.
 */
object cf112a {
  def main(args: Array[String]): Unit = {
    val num = Array(4,7,47,74,447,474,477,744,747,774,777)
    val n = StdIn.readInt()
    println(if (num.exists(n%_==0)) "YES" else "NO")
  }
}

object A122 {
  @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(num) = readBigs(1)
    val lucky = Array("4", "7", "44", "47", "74", "77", "444", "447", "474", "477", "744", "747", "774", "777").map(BigInt.apply)
    if(lucky.exists{n => (num % n) == 0}) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

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

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

  val luckyNumbers = (1 to 1000).filter { n =>
      n.toString.forall(c => c == '4' || c == '7')
    }

  def isAlmostLucky(i: Int): Boolean =
    luckyNumbers.find(i % _ == 0) match {
      case None => false
      case Some(_) => true
    }

  def solve: String =
    if (isAlmostLucky(sc.nextInt)) "YES"
    else "NO"

  out.println(solve)
  out.close
}

object LuckyDivision {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val input = scanner.nextInt();
		if (isLucky(input)) {
			println("YES")
			System.exit(0)
		}
		for (i <- 1 to input / 2) {
			if (input % i == 0 && isLucky(i)) {
				println("YES")
				System.exit(0)
			}
		}
		println("NO")
	}

	def isLucky(in: Int) : Boolean = {
			var lucky = true;
			var tmp = in;
			while (lucky && tmp > 0) {
				val rem = tmp % 10;
				if (rem != 4 && rem != 7) {
					lucky = false
				}
				tmp /= 10
			}
			lucky
	}
}

import scala.io.StdIn._

object LuckyDivision extends App {

  def isLucky(i: Int): Boolean = i match {
    case 0 => true
    case _ => (i%10 == 4 || i%10 == 7) && isLucky(i / 10)
  }

  def isAlmostLucky(i: Int, d: Int): Boolean = d match {
    case 0 => false
    case _ => (i%d == 0 && isLucky(d)) || isAlmostLucky(i, d-1)
  }

  val s = readInt
  println(if(isAlmostLucky(s, s)) "YES" else "NO")
}

object Codeforces122A extends App{

  def CreateLuckyNumberSet:List[Int] = {
    var luckyset:List[Int] = List()
    luckyset = List(4,7,44,47,74,77,444,447,474,477,744,747,774,777)
    return luckyset
  }
  def TestAlmostLuckyNumber(query:Int):Boolean={
    val luckyset:List[Int] = CreateLuckyNumberSet
    for (i <- luckyset){
      if (query%i == 0){
        return true
      }
    }
    return false
  }
  var query:Int=scala.io.StdIn.readInt
  var ans:Boolean = TestAlmostLuckyNumber(query)
  if (ans == true){
    println("YES")
  }
  else {
    println("NO")
  }
}

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 limitedStream(cur: Int, sqr: Int): Stream[Int] = if(cur * cur > sqr) Stream.Empty else cur #:: limitedStream(cur + 1, sqr)
  def dividersStream(n: Int) = limitedStream(1, n).filter(n % _ == 0)
  def allDividersStream(n: Int) = dividersStream(n).flatMap { x =>
    Stream(x, n / x)
  }
  def beautifulInt(x: Int) = x.toString.forall("47".contains(_))
  def beautifulDividersStream(n: Int) = allDividersStream(n).filter(beautifulInt)

  def main(a: Array[String]) {
    println(if(beautifulDividersStream(readInt).isEmpty) "NO" else "YES")
  }
}

object Main {
  val happy: Stream[Int] = {
    def nextGen(ls: List[Int], gen: Int): Stream[Int] = {
      val nextLs = List(4, 7).flatMap(e => ls.map(e * gen +))
      nextLs.toStream #::: nextGen(nextLs, gen * 10)
    }
    nextGen(List(0), 1)
  }

  def main(args: Array[String]) {
    val num = readInt()
    var isHappy = false
    for(h <- happy.takeWhile(_ <= num)) {
      if (num % h == 0) isHappy |= true
    }
    if (isHappy) println("YES")
    else println("NO")
  }
}

// Codeforces 122A

object _122A extends App {
  val scanner = new java.util.Scanner(System.in)
  val lucky_numbers = List(4, 7, 47, 74, 447, 474, 477, 747)
  val n = scanner.nextInt
  println(
    if (lucky_numbers.exists(n%_ == 0)) "YES" else "NO"
  )
}

import scala.io.StdIn._

object A_122 extends App {
  val n = readInt()

  def isLucky(x: Int) = x.toString.toCharArray.toSet.forall(x => x == '4' || x == '7')

  val L = 1 to 1000 filter isLucky

  if (L.contains(n) || L.exists(l => n % l == 0)) println("YES")
  else println("NO")
}

import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
    val s = readLine.toInt
  println(if(List(4,7,47,74,447,477,744,747).exists(s%_ == 0)) "YES" else "NO")
  }
}

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

        import scala.io.StdIn

        var number: Int = Integer.parseInt(StdIn.readLine())
        var string: String = ""
        var out: String = "NO"

        string = String.valueOf(number)
        string = string.replace("4","")
        string = string.replace("7","")
        if (string.equals("")){
            out = "YES"
        }

        for (i <- 4 to number){

            string = String.valueOf(i)
            string = string.replace("4","")
            string = string.replace("7","")
            if (string.equals("") && number%i == 0){
              out = "YES"
            }
        }

        println(out)

  }
}

import scala.io.StdIn._

object HelloWorldMain {

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

    val luckOrNot = readInt()

    val allLuckies = for( i <- 1 to 1000 if i.toString.matches("(4|7)*") )  yield i

    var result = "NO"
    allLuckies.foreach(i => if(luckOrNot % i == 0 ) result = "YES" )

    println(result)

  }
}

import scala.io.StdIn.readInt

object LuckyNumbers {

   def main(args: Array[String]) {
     val n = readInt
     if (Range(1,n).inclusive.
        filter { p => p.toString().toSet subsetOf Set('4','7') }.
        exists(n%_ == 0))
       println("YES")
     else
       println("NO")
   }

}

object Main extends App{
  val in= readLine
  val n =in.toInt
  if(List(4,7,44,47,74,77,444,447,474,477,744,747,774,777).exists(t => n % t ==0))
    println("YES")else println("NO")
}

import scala.io.StdIn._

object cf extends App
{
    val v = readInt
    print(if(List(4,7,44,47,74,77,444,447,474,477,744,747,774,777).exists(kuy => v%kuy==0)) "YES" else "NO")
}

import scala.io.StdIn._

object Task extends App{
	val N = readLine.split(" ").map{_.toInt}.head

	def isLucky(n:Int):Boolean = {
    def aux(n:Int, div:String):Boolean = {
      val d = div.toInt

      if(n < d)
        false
      else if(n % d == 0)
        true
      else {
        aux(n, div + "4") || aux(n, div + "7")
      }
    }

    aux(n, "4") || aux(n, "7")
	}

	if(isLucky(N))
	  println("YES")
	else
	  println("NO")
}

import scala.io.StdIn._

object Solution {

	var n = readInt

	def isLucky(n:Int):Boolean = {
		var nst = n.toString
		var ret = true
		for(i <- 0 until nst.size) {
			if(nst(i) != '4' && nst(i) != '7') ret = false
		}
		ret
	}

	def main(args:Array[String]):Unit = {
		var almostLucky = false
		for(i <- 1 to n) {
			if(isLucky(i) && !almostLucky && n%i == 0) {
				println("YES")
				almostLucky = true
			}
		}
		if(!almostLucky) println("NO")
	}

}

object Divider{

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

    val list = List(4,7,47,74,444,447,474,477,744,774,747,777)

    if(list.contains(n) || list.exists(x => n % x == 0) ) println("YES") else print("NO")
  }
}

object One22A extends App {

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

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

	val n = in.nextInt

	lucky(n) match {
		case true => yes
		case false =>
			(4 to n - 1).exists(lucky) match {
				case true => yes
				case false => no
			}
	}

	in.close()
	out.close()

	def yes = out.println("YES")
	def no = out.println("NO")
	def lucky(str: Int) = n % str == 0 && str.toString.forall(x => x == '4' || x == '7')

}

object CF0122A extends App {

  val l = List(4, 7, 47, 74, 444, 447, 474, 744, 774, 747, 777)

  def del(v: Int): Boolean = {

    var t = false

    l.foreach(n => {
      if (v%n == 0) {
        t = true
      }
    })

    t
  }

  val str = readLine()
  val value = str.toInt
  if (value % 4 == 0 || value % 7 == 0 || del(value)) {
    println("YES")
  } else {
    val status = str.getBytes.forall(b => {
      b == '4' || b == '7'
    })

    if (status) {
      println("YES")
    } else {
      println("NO")
    }
  }

}

import scala.io.StdIn

object Task {

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

    val x: Int = StdIn.readInt()
    if (solve(x)) {
      println("YES")
    }
    else {
      println("NO")
    }

  }

  private def solve(x: Int): Boolean = {

    val lucky: Array[Int] = Array(4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777)
    for (l <- lucky) {
      if (x % l == 0) {
        return true
      }
    }
    return false

  }

}

import scala.collection.immutable

object Hello extends App {

  import scala.io.StdIn._

  val k = readInt()

  def countNums(n: Int): Int = n.toString.length

  def permutationsWithRepetitions[T](input : List[T], n : Int) : List[List[T]] = {
    require(input.nonEmpty && n > 0)
    n match {
      case 1 => for (el <- input) yield List(el)
      case _ => for (el <- input; perm <- permutationsWithRepetitions(input, n - 1)) yield el :: perm
    }
  }

  def allPermutationsWithRepetitions[T](input : List[T], n : Int, result: List[List[List[T]]]): List[List[List[T]]] =
    if (n == 0) result
    else allPermutationsWithRepetitions(input, n - 1, result :+ permutationsWithRepetitions(input, n))

  val nums: immutable.Seq[Int] = allPermutationsWithRepetitions(List(4, 7), countNums(k), List()).flatten.map(_.mkString("")).map(Integer.parseInt)

  if (nums.exists(k % _ == 0) || nums.contains(k)) println("YES") else println("NO")
}

import scala.io.StdIn._

object HappyNum extends App {
  val num = readInt
  var ok = false

  val list = List(4, 7, 44, 47, 74, 77, 444, 447, 477, 474, 744, 747, 774, 777)

  if (list.contains(num)) {
    ok = true
  }else {
    for(i <- list){
      if (num % i == 0) ok = true
    }
  }

  if (ok) print("YES")
  else print("NO")

}

object HappyNum extends App {
  val num = readLine()
  val numnum = num.toInt
  val listNum = num.toList
  var ok = true

  for(i <- listNum){
    if (i != '4' && i != '7'){
      ok = false
    }
  }
  if (!ok && numnum % 7 == 0 || numnum % 4 == 0){
    ok = true
  }
  if (ok) print("YES")
  else print("NO")
}

import scala.io.StdIn._

object HappyNum extends App {
  val num = readInt
  var ok = false

  val list = List(4, 7, 44, 47, 74, 77, 444, 447, 474, 744, 747, 774, 777)

  if (list.contains(num)) {
    ok = true
  }else {
    for(i <- list){
      if (num % i == 0) ok = true
    }
  }

  if (ok) print("YES")
  else print("NO")

}

object LuckyDivision {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val input = scanner.nextInt();
		if (isLucky(input)) {
			println("YES")
			System.exit(0)
		}
		val sqrtInput = Math.round (Math.sqrt(input))
				for (i <- 1 to sqrtInput.toInt) {
					if (isLucky(i) && input % i == 0) {
						println("YES")
						System.exit(0)
					}
				}
		println("NO")
	}

	def isLucky(in: Int) : Boolean = {
			var lucky = true
					var tmp = in
					while (lucky && tmp > 0) {
						val rem = tmp % 10
								if (rem != 4 && rem != 7) {
									lucky = false
								}
						tmp = tmp / 10
					}
			lucky
	}
}

object LuckyDivision {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val input = scanner.nextInt();
		if (isLucky(input)) {
			println("YES")
			System.exit(0)
		}
		val sqrtInput = Math.round (Math.sqrt(input))
				for (i <- 1 to sqrtInput.toInt + 1) {
					if (isLucky(i) && input % i == 0) {
						println("YES")
						System.exit(0)
					}
				}
		println("NO")
	}

	def isLucky(in: Int) : Boolean = {
			var lucky = true
					var tmp = in
					while (lucky && tmp > 0) {
						val rem = tmp % 10
								if (rem != 4 && rem != 7) {
									lucky = false
								}
						tmp = tmp / 10
					}
			lucky
	}
}

object CF0122A extends App {

  val str = readLine()
  val value = str.toInt
  if (value % 4 == 0 || value % 7 == 0) {
    println("YES")
  } else {
    val status = str.getBytes.forall(b => {
      b == '4' || b == '7'
    })

    if (status) {
      println("YES")
    } else {
      println("NO")
    }
  }

}


Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.

The input contains the only integer n (1 ≤ n ≤ 106).

NoteThe pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1)  →  (1,2)  →  (3,2)  →  (5,2).

object Main {

    val inf = 1000000000

    def gcdCount(a: Int, b: Int, sum: Int):Int =
        if (b != 0) gcdCount(b, a % b, sum + a / b)
        else if (a == 1) (sum - 1)
        else inf

    def main(args: Array[String]) {
        val n = nextInt
        val ans = (1 to n).map(gcdCount(n, _, 0))
        println(ans.min)
    }

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

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

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


Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colours.Arkady has already painted some (possibly none or all) segments and passes the paintbrush to you. You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour. Two ways are considered different if and only if a segment is painted in different colours in them.

The first line contains a single positive integer n (1 ≤ n ≤ 100) — the length of the canvas. The second line contains a string s of n characters, the i-th of which is either 'C' (denoting a segment painted in cyan), 'M' (denoting one painted in magenta), 'Y' (one painted in yellow), or '?' (an unpainted one).

If there are at least two different ways of painting, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower).

NoteFor the first example, there are exactly two different ways of colouring: CYCMY and CYMCY.For the second example, there are also exactly two different ways of colouring: CMCMY and CYCMY.For the third example, there are four ways of colouring: MCYCM, MCYCY, YCYCM, and YCYCY.For the fourth example, no matter how the unpainted segments are coloured, the existing magenta segments will prevent the painting from satisfying the requirements. The similar is true for the fifth example.

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 s = readLine

  val ok = (!(s.contains("CC") || s.contains("YY") || s.contains("MM"))) &&
    (s.startsWith("?") || s.endsWith("?") || s.contains("??") ||
      s.contains("C?C") || s.contains("Y?Y") || s.contains("M?M"))

  println(if (ok) "Yes" else "No")
}

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val n = read.toInt
        val s = readString

        for (i <- 0 until n - 1)
            if (s(i) != '?' && s(i) == s(i + 1)){
                print("NO")
                return
            }

        if (s(0) == '?' || s(n - 1) == '?') {
            print("YES")
            return
        }

        for (i <- 1 until n - 2)
            if (s(i) == '?') {
                if (s(i + 1) == '?') {
                    print("YES")
                    return
                } else if (s(i - 1) == s(i + 1)) {
                                print("YES")
                                return
                            }
            }
        print("NO")
    }
}

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val n = read.toInt
        val s = readString

        for (i <- 0 until n - 1)
            if (s(i) == '?') {
                if (s(i + 1) == '?') {
                    print("YES")
                    return
                } else if (i > 0 && s(i - 1) == s(i + 1)) {
                    print("YES")
                    return
                }
            } else if (s(i) == s(i + 1)){
                print("NO")
                return
            }
        print("NO")
    }
}

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val n = read.toInt
        val s = readString

        for (i <- 0 until n - 1)
            if (s(i) != '?' && s(i) == s(i + 1)){
                print("NO")
                return
            }
        for (i <- 0 until n - 1)
            if (s(i) == '?') {
                if (s(i + 1) == '?') {
                    print("YES")
                    return
                } else if (i ==0) {
                            print("YES")
                            return
                        } else if (s(i - 1) == s(i + 1)) {
                                print("YES")
                                return
                            }
            }
        print("NO")
    }
}

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val n = read.toInt
        val s = readString

        if (n == 1)
            if (s(0) == '?') {
                print("YES")
                return
            } else {
                print("NO")
                return
            }

        for (i <- 0 until n - 1)
            if (s(i) != '?' && s(i) == s(i + 1)){
                print("NO")
                return
            }
        for (i <- 0 until n - 1)
            if (s(i) == '?') {
                if (s(i + 1) == '?') {
                    print("YES")
                    return
                } else if (i ==0) {
                            print("YES")
                            return
                        } else if (s(i - 1) == s(i + 1)) {
                                print("YES")
                                return
                            }
            }
        print("NO")
    }
}

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val n = read.toInt
        val s = readString

        for (i <- 0 until n - 1)
            if (s(i) == s(i + 1)){
                print("NO")
                return
            }
        for (i <- 0 until n - 1)
            if (s(i) == '?') {
                if (s(i + 1) == '?') {
                    print("YES")
                    return
                } else if (i ==0) {
                            print("YES")
                            return
                        } else if (s(i - 1) == s(i + 1)) {
                                print("YES")
                                return
                            }
            }
        print("NO")
    }
}

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val n = read.toInt
        val s = readString

        for (i <- 0 until n - 1)
            if (s(i + 1) != '?' && s(i) == s(i + 1)) {
                print("NO")
                return
            }
        print("YES")
    }
}

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val n = read.toInt
        val s = readString

        for (i <- 0 until n - 1)
            if (s(i) == '?') {
                if (s(i + 1) == '?') {
                    print("YES")
                    return
                } else if (i ==0) {
                            print("YES")
                            return
                        } else if (s(i - 1) == s(i + 1)) {
                                print("YES")
                                return
                            }
            } else if (s(i) == s(i + 1)){
                print("NO")
                return
            }
        print("NO")
    }
}


Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an a1 × b1 rectangle, the paintings have shape of a a2 × b2 and a3 × b3 rectangles.Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?

The first line contains two space-separated numbers a1 and b1 — the sides of the board. Next two lines contain numbers a2, b2, a3 and b3 — the sides of the paintings. All numbers ai, bi in the input are integers and fit into the range from 1 to 1000.

If the paintings can be placed on the wall, print "YES" (without the quotes), and if they cannot, print "NO" (without the quotes).

NoteThat's how we can place the pictures in the first test:And that's how we can do it in the third one.

import io.StdIn._

object Solution {
  def main(args: Array[String]) {
    val p = readLine().split(" ").map(_.toInt).sortBy(-_)
    val a = readLine().split(" ").map(_.toInt).sortBy(-_)
    val b = readLine().split(" ").map(_.toInt).sortBy(-_)

    var found = false
    if (p(0)-a(0)>=0 && p(1)-a(1)>=0) {
      val r1 = Array(p(0)-a(0), p(1)).sortBy(-_)
      if (r1(0)>=b(0) && r1(1)>=b(1)) found = true
      else {
        val r2 = Array(p(0), p(1)-a(1)).sortBy(-_)
        if (r2(0)>=b(0) && r2(1)>=b(1)) found = true
      }
    }
    if (p(0)-a(1)>=0 && p(1)-a(0)>=0) {
      val r1 = Array(p(0)-a(1), p(1)).sortBy(-_)
      if (r1(0)>=b(0) && r1(1)>=b(1)) found = true
      else {
        val r2 = Array(p(0), p(1)-a(0)).sortBy(-_)
        if (r2(0)>=b(0) && r2(1)>=b(1)) found = true
      }
    }

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

import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _560B extends CodeForcesApp[Boolean]({scanner => import scanner._
  val List(a1, b1, a2, b2, a3, b3) = List.fill(6)(nextInt)
  def fit(r: R) = {
    val (x, y) = r
    //debug(x, y, a1, b1)
    (x <= a1 && y <= b1) || (x <= b1 && y <= a1)
  }
  type R = (Int, Int)
  def join(r1: R, r2: R): R = (r1._1 + r2._1, r1._2 max r2._2)
  def allSwapJoin(r1: R, r2: R): List[R] = join(r1, r2) :: join(r1, r2.swap) :: join(r1.swap, r2) :: join(r1.swap, r2.swap) :: Nil
  def allJoin(r1: R, r2: R): List[R] = allSwapJoin(r1, r2) ::: allSwapJoin(r2, r1)
  allJoin((a2, b2), (a3, b3)) exists fit
}) {
  override def format(result: Boolean) = if (result) "YES" else "NO"
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final def isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None
  final def counter[A] = collection.mutable.Map.empty[A, Int] withDefaultValue 0
}

import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _560B extends CodeForcesApp[Boolean]({scanner => import scanner._
  val List(a1, b1, a2, b2, a3, b3) = List.fill(6)(nextInt)
  def fit(r: R) = {
    val (x, y) = r
    //debug(x, y, a1, b1)
    (x <= a1 && y <= b1) || (x <= b1 && y <= a1)
  }
  type R = (Int, Int)
  def join(r1: R, r2: R): R = (r1._1 + r2._1, r1._2 min r2._2)
  def allSwapJoin(r1: R, r2: R): List[R] = join(r1, r2) :: join(r1, r2.swap) :: join(r1.swap, r2) :: join(r1.swap, r2.swap) :: Nil
  def allJoin(r1: R, r2: R): List[R] = allSwapJoin(r1, r2) ::: allSwapJoin(r2, r1)
  allJoin((a2, b2), (a3, b3)) exists fit
}) {
  override def format(result: Boolean) = if (result) "YES" else "NO"
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final def isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None
  final def counter[A] = collection.mutable.Map.empty[A, Int] withDefaultValue 0
}


The year 2015 is almost over.Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 201510 = 111110111112. Note that he doesn't care about the number of zeros in the decimal representation.Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?Assume that all positive integers are always written without leading zeros.

The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 1018) — the first year and the last year in Limak's interval respectively.

Print one integer – the number of years Limak will count in his chosen interval.

NoteIn the first sample Limak's interval contains numbers 510 = 1012, 610 = 1102, 710 = 1112, 810 = 10002, 910 = 10012 and 1010 = 10102. Two of them (1012 and 1102) have the described property.

import scala.io.Source

object Solution extends App {

  def ceil(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) "10" + "1" * (str.length - 1)
    else {
      val ones = str.takeWhile(_ == '1').length
      "1" * ones + "0" + "1" * (str.length - ones - 1)
    }
  }

  def floor(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) str.dropRight(1) + '0'
    else {
      val ones = str.takeWhile(_ == '1').length
      if (ones == 1)
        "1" * (str.length - 2) + "0"
      else
        "1" * (ones - 1) + "0" + "1" * (str.length - ones)
    }
  }

  def count(aSize: Int, aZeroPosition: Int, bSize: Int, bZeroPosition: Int): Int = {
    if (aSize > bSize || (aZeroPosition > bZeroPosition && aSize == bSize)) 0
    else if (aSize == bSize && aZeroPosition == bZeroPosition) 1
    else if (aZeroPosition == aSize) count(aSize + 1, 1, bSize, bZeroPosition)
    else 1 + count(aSize, aZeroPosition + 1, bSize, bZeroPosition)
  }

  val in = Source.stdin.getLines()
  val Array(a, b) = in.next().split(' ').map(_.toLong)
  val c = ceil(a)
  val f = floor(b)
//  println(a.toBinaryString)
//  println(c)
//  println(b.toBinaryString)
//  println(f)
  println(count(c.length, c.indexOf('0'), f.length, f.indexOf('0')))
}

import scala.collection._

object B 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(a, b) = readLongs(2)
  var res = 0L

  for (l <- 1 to 62) {
    val x = (1L << l) - 1
    for (j <- 0 until l - 1) {
      val y = x ^ (1L << j)
      if (a <= y && y <= b) {
        res += 1
      }
    }
  }
  println(res)
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toLong)

    var num = 0

    for (i <- 2 to 63) {
      for (j <- 0 to i-2) {
        val y = ((1.toLong<<i) - 1) ^ (1.toLong<<j)

        if (y >= n && y <= m) {
          num += 1
//          println(i+".."+j+".."+y)
        }
      }
    }

    println(num)

  }
}

import java.util.Scanner
import java.lang.Long.parseLong

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val a = sc.nextLong()
    val b = sc.nextLong()

    //
    val a_2 = a.toBinaryString
    val b_2 = b.toBinaryString

    val a_2l = a_2.length
    var shaku = "10"
    var flag = true
    var ans = 0L
    var digi_cnt = 1
    while(flag){
      val tn = parseLong(shaku, 2)

      if(a <= tn){
        if(b >= tn)
          ans += 1
        else
          flag = false
      }

      digi_cnt += 1
      val sl = shaku.length
      if(sl == digi_cnt){
        shaku = shaku.updated(digi_cnt - 1, '1')
        shaku = shaku ++ "1"
        shaku = shaku.updated(1, '0')
        digi_cnt = 1
      }
      else{
        shaku = shaku.updated(digi_cnt - 1, '1')
        shaku = shaku.updated(digi_cnt, '0')
      }
    }

    println(ans)
  }
}

import scala.io.Source

object Solution extends App {

  def ceil(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) str + '0'
    else {
      val ones = str.takeWhile(_ == '1').length
      "1" * ones + "0" + "1" * (str.length - ones - 1)
    }
  }

  def floor(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) str.dropRight(1) + '0'
    else {
      val ones = str.takeWhile(_ == '1').length
      if (ones == 1)
        "1" * (str.length - 2) + "0"
      else
        "1" * (ones - 1) + "0" + "1" * (str.length - ones)
    }
  }

  def count(aSize: Int, aZeroPosition: Int, bSize: Int, bZeroPosition: Int): Int = {
    if (aSize > bSize || (aZeroPosition > bZeroPosition && aSize == bSize)) 0
    else if (aSize == bSize && aZeroPosition == bZeroPosition) 1
    else if (aZeroPosition == aSize) count(aSize + 1, 0, bSize, bZeroPosition)
    else 1 + count(aSize, aZeroPosition + 1, bSize, bZeroPosition)
  }

  val in = Source.stdin.getLines()
  val Array(a, b) = in.next().split(' ').map(_.toLong)
  val c = ceil(a)
  val f = floor(b)
  println(count(c.length, c.indexOf('0'), f.length, f.indexOf('0')))
}

import scala.io.Source

object Solution extends App {

  def ceil(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) str + '0'
    else {
      val ones = str.takeWhile(_ == '1').length
      "1" * ones + "0" + "1" * (str.length - ones - 1)
    }
  }

  def floor(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) str.dropRight(1) + '0'
    else {
      val ones = str.takeWhile(_ == '1').length
      if (ones == 1)
        "1" * (str.length - 2) + "0"
      else
        "1" * (ones - 1) + "0" + "1" * (str.length - ones)
    }
  }

  def count(aSize: Int, aZeroPosition: Int, bSize: Int, bZeroPosition: Int): Int = {
    if (aSize > bSize) 0
    else if (aSize == bSize && aZeroPosition == bZeroPosition) 1
    else if (aZeroPosition == aSize) count(aSize + 1, 1, bSize, bZeroPosition)
    else 1 + count(aSize, aZeroPosition + 1, bSize, bZeroPosition)
  }

  val in = Source.stdin.getLines()
  val Array(a, b) = in.next().split(' ').map(_.toLong)
  val c = ceil(a)
  val f = floor(b)
  println(count(c.length, c.indexOf('0'), f.length, f.indexOf('0')))
}

import scala.io.Source

object Solution extends App {

  def ceil(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) str + '0'
    else {
      val ones = str.takeWhile(_ == '1').length
      "1" * ones + "0" + "1" * (str.length - ones - 1)
    }
  }

  def floor(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) str.dropRight(1) + '0'
    else {
      val ones = str.takeWhile(_ == '1').length
      if (ones == 1)
        "1" * (str.length - 2) + "0"
      else
        "1" * (ones - 1) + "0" + "1" * (str.length - ones)
    }
  }

  def count(aSize: Int, aZeroPosition: Int, bSize: Int, bZeroPosition: Int): Int = {
    if (aSize > bSize || (aZeroPosition > bZeroPosition && aSize == bSize)) 0
    else if (aSize == bSize && aZeroPosition == bZeroPosition) 1
    else if (aZeroPosition == aSize) count(aSize + 1, 1, bSize, bZeroPosition)
    else 1 + count(aSize, aZeroPosition + 1, bSize, bZeroPosition)
  }

  val in = Source.stdin.getLines()
  val Array(a, b) = in.next().split(' ').map(_.toLong)
  val c = ceil(a)
  val f = floor(b)
  println(count(c.length, c.indexOf('0'), f.length, f.indexOf('0')))
}

import scala.io.Source

object Solution extends App {

  def ceil(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) str + '0'
    else {
      val ones = str.takeWhile(_ == '1').length
      "1" * ones + "0" + "1" * (str.length - ones - 1)
    }
  }

  def floor(a: Long): String = {
    val str = a.toBinaryString
    val zeroCount = str.count(_ == '0')
    if (zeroCount == 1) str
    else if (zeroCount == 0) str.dropRight(1) + '0'
    else {
      val ones = str.takeWhile(_ == '1').length
      if (ones == 1)
        "1" * (str.length - 2) + "0"
      else
        "1" * (ones - 1) + "0" + "1" * (str.length - ones)
    }
  }

  def count(aSize: Int, aZeroPosition: Int, bSize: Int, bZeroPosition: Int): Int = {
    if (aSize > bSize || (aZeroPosition < bZeroPosition && aSize == bSize)) 0
    else if (aSize == bSize && aZeroPosition == bZeroPosition) 1
    else if (aZeroPosition == aSize) count(aSize + 1, 1, bSize, bZeroPosition)
    else 1 + count(aSize, aZeroPosition + 1, bSize, bZeroPosition)
  }

  val in = Source.stdin.getLines()
  val Array(a, b) = in.next().split(' ').map(_.toLong)
  val c = ceil(a)
  val f = floor(b)
  println(count(c.length, c.indexOf('0'), f.length, f.indexOf('0')))
}


In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.After practice competition, participant number i got a score of ai. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.

The single line contains six integers a1, ..., a6 (0 ≤ ai ≤ 1000) — scores of the participants

Print "YES" (quotes for clarity), if it is possible to build teams with equal score, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").

NoteIn the first sample, first team can be composed of 1st, 2nd and 6th participant, second — of 3rd, 4th and 5th: team scores are 1 + 3 + 1 = 2 + 1 + 2 = 5.In the second sample, score of participant number 6 is too high: his team score will be definitely greater.

import java.io._
import java.util.Scanner
import scala.language.implicitConversions

object AcmICPC {

  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }

  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }

  import Lazy._

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

    val A = sc.nextLine().split(" ").map(str => str.toInt)
    val sum = A.sum
    val answer = A.combinations(3).exists(combination => combination.sum * 2 == sum)

    println(if(answer) "YES" else "NO")

  }
}

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 as = readInts(6)

  var can = false
  for (bs <- as.permutations) {
    if (bs.take(3).sum == bs.drop(3).sum) can = true
  }

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

  Console.flush
}

/**
  * @see http://codeforces.com/contest/890/problem/A
  */

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

  val vs = for {
    i <- 0 to 5
    j <- i to 5
    k <- j to 5
    if i != j && j != k && i != k && s - a(i) - a(j) - a(k) == a(i) + a(j) + a(k)
  } yield (i, j, k)

  if (vs.isEmpty) println("NO")
  else println("YES")
}

import scala.annotation.tailrec

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

  @tailrec
  def check(i: Int = 0, j: Int = 0, k: Int = 0): Boolean =
    if (i == n || j == n || k == n) false
    else if (s - a(i) - a(j) - a(k) == a(i) + a(j) + a(k)) true
    else check(i + (j + (k + 1) / n) / n, (j + (k + 1) / n) % n, (k + 1) % n)

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