The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

The first line of input will contain an integer n (1 ≤ n ≤ 105), the number of events. The next line will contain n space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.

Print a single integer, the number of crimes which will go untreated.

NoteLets consider the second example:  Firstly one person is hired.  Then crime appears, the last hired person will investigate this crime.  One more person is hired.  One more crime appears, the last hired person will investigate this crime.  Crime appears. There is no free policeman at the time, so this crime will go untreated.  One more person is hired.  One more person is hired.  One more person is hired. The answer is one, as one crime (on step 5) will go untreated.

import java.util.Scanner

object practice {

  def main(args: Array[String]): Unit = {
    val scan = new Scanner(System.in)
    var str = scan.next
    var crimes = 0
    var polices = 0
    var in = 0
    for (i <- 1 to str.toInt) {
      in = scan.next.toInt
      if (in == -1) {
        if (polices <= 0) {
          crimes += 1
        } else {
          polices -= 1
        }
      } else {
        polices += in
      }

    }

    println(crimes)
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var n = in.next().toInt
  println(in.next().split(" ").map(_.toInt).foldLeft((0, 0)){
    case((count, pol), -1) if pol > 0 => (count, pol - 1)
    case((count, pol), -1) => (count + 1, 0)
    case((count, pol), el) => (count, pol + el)
  }._1)
}

object A {

  def main(args: Array[String]): Unit = {
    var n = readInt
//    var a = new Array[Int](n)
//    for (i <- 0 to n-1){
//      a(i) = readInt
//    }
    var a = readLine.split(" ").map(_.toInt)
    var cnt = 0
    var ans = 0
    for (i <- 0 to a.length-1){
         if (a(i) == -1) {
        	   if (cnt > 0){
        	     cnt = cnt -1
        	   }else
        		 ans = ans + 1
         }else cnt = cnt + a(i)
    }
    println(ans)
  }

}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    var officers = 0
    var res = 0
    for(i <- 0 until n) {
      if(input(i) == -1) {
        if(officers > 0)
          officers -= 1
        else
          res += 1
      } else {
        officers += input(i)
      }
    }
    println(res)
  }
}

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

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

  def solve(): Long = {
    val N = sc.nextInt

    @tailrec
    def loop(acc: Int, police: Int, i: Int): Int =  {
      if (i == N) acc
      else {
        val event = sc.nextInt
        if (event < 0) {
          if (police > 0) loop(acc, police - 1, i + 1)
          else loop(acc + 1, 0, i + 1)
        }
        else loop(acc, police + event, i + 1)
      }
    }

    loop(0, 0, 0)
  }

  out.println(solve)
  out.close
}

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

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

  def solve(): Int = {
    val N = sc.nextInt

    @tailrec
    def loop(acc: Int, police: Int, n: Int): Int = {
      if (n == N) acc
      else {
        val x = sc.nextInt
        if (x < 0) { // crime occured
          if (police > 0) { // at least one police officer
            loop(acc, police - 1, n + 1)
          }
          else {
            loop(acc + 1, 0, n + 1)
          }
        }
        else {
          loop(acc, police + x, n + 1)
        }
      }
    }
    loop(0, 0, 0)
  }

  out.println(solve)
  out.close
}

object recruits extends App {
	val (n, evts) = (readLine.toInt, readLine.split(' ').map(_.toInt))
	var (cnt, ans) = (0, 0)
	for (evt <- evts) {
		if (cnt == 0 && evt == -1) {
			ans += 1
		}
		else {
			cnt += evt
		}
	}
	print(ans)
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-17.
 */
object A427 extends App{
  val sc = new Scanner(System.in)
  var n = sc.nextInt()
  var policeNum = 0
  var untreated = 0

  while (n > 0) {
    var a = sc.nextInt()

    if (a == -1) {
      if (policeNum > 0) {
        policeNum -= 1
      } else {
        untreated += 1
      }
    } else {
      policeNum += a
    }

    n -= 1
  }

  println(untreated)
}

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

object PoliceRecruits {

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

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

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

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

   def main(args: Array[String]) {
     val n = readInt
     val events = readInts
     val sim = events.foldLeft( (0,0)){
       case ((crimes,pol),e) =>
         if (e > 0) (crimes,pol+e)
         else if (pol >= 1) (crimes,pol-1) else (crimes+1,pol)
     }
     println(sim._1)
   }

}

// http://codeforces.com/contest/427/problem/A
object A extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val ev = Array.fill(n)(sc.nextInt())
  var unrated, hired = 0;
  for (t <- ev) {
    if (t == -1) {
      if (hired == 0) unrated += 1
      else hired -= 1
    }
    else {
      hired += t
    }
  }
  println(unrated);
}

object main extends App with fastIO {

  val n = nextInt

  var (ans, cnt) = (0, 0)
  for (i <- 1 to n) {
    nextInt match {
      case -1 if cnt == 0 => ans += 1
      case n => cnt += n
    }
  }

  println(ans)
  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

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

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

import util.control.Breaks._
import scala.collection.mutable.ArrayBuffer

object main extends App with fastIO {

  val n = nextInt

  var (ans, cnt) = (0, 0)
  for (i <- 1 to n) {
    nextInt match {
      case -1 => { ans += -cnt + 1 max 0; cnt = cnt - 1 max 0 }
      case n => cnt += n
    }
  }

  println(ans)
  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

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

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

import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
//  val sc = new Scanner( new FileInputStream("src/input.txt") )
  val n = sc.nextInt

    var i = 0
    var res = 0
    def cup(up: Int) = {
      i += up
      if(i<0){
        res += 1
        i = 0
      }
      (i,res)
    }

  (0 until n).foreach( i=> {
    val t = sc.nextInt
    cup(t)
  })
  println(res)
}

import java.util.Scanner

object practice {

  def main(args: Array[String]): Unit = {
    val scan = new Scanner(System.in)
    var str = scan.next
    var crimes = 0
    var polices = 0
    var in = 0
    for (i <- 1 to str.toInt) {
      in = scan.next.toInt
      if (in == -1) {
        if (polices <= 0) {
          crimes += 1
        } else {
          polices -= 1
        }
      } else {
        polices += in
      }
      if (polices > 10) {
        polices = 10
      }

    }

    println(crimes)
  }

}


You are given a sequence a consisting of n integers. Find the maximum possible value of  (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj.

The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105).  The second line contains n space-separated integers ai (1 ≤ ai ≤ 106).

import scala.collection._
import scala.util.Random
import java.util.Arrays

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) = readInts(1)
  val as = readInts(n).sorted.distinct
  //val as = Array.fill(n)(Random.nextInt(1000000)).sorted
  val max = as.last

  var res = 0

  for (i <- as.indices) {
    val a = as(i)
    var x = a
    var prevJ = i
    while (x <= max) {
      x += a
      val j0 = Arrays.binarySearch(as, prevJ + 1, as.length, x)
      val j = if (j0 < 0) -j0 - 2 else j0 - 1
      if (j >= 0 && as(j) > a) res = res max (as(j) - x + a)
      prevJ = j
    }
  }

  println(res)
}

import java.util.Arrays

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

  val Array(n) = readInts(1)
  val as = readInts(n).sorted.distinct
  val max = as.last

  var res = 0

  for (i <- as.indices) {
    val a = as(i)
    var x = a
    var prevJ = i
    while (x <= max) {
      x += a
      val j0 = Arrays.binarySearch(as, prevJ + 1, as.length, x)
      val j = if (j0 < 0) -j0 - 2 else j0 - 1
      if (j >= 0 && as(j) > a) res = res max (as(j) - x + a)
      prevJ = j
    }
  }

  println(res)
}


Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $$$80\%$$$ of applicants are girls and majority of them are going to live in the university dormitory for the next $$$4$$$ (hopefully) years.The dormitory consists of $$$n$$$ rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number $$$i$$$ costs $$$c_i$$$ burles. Rooms are numbered from $$$1$$$ to $$$n$$$.Mouse doesn't sit in place all the time, it constantly runs. If it is in room $$$i$$$ in second $$$t$$$ then it will run to room $$$a_i$$$ in second $$$t + 1$$$ without visiting any other rooms inbetween ($$$i = a_i$$$ means that mouse won't leave room $$$i$$$). It's second $$$0$$$ in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from $$$1$$$ to $$$n$$$ at second $$$0$$$.What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?

The first line contains as single integers $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of rooms in the dormitory. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^4$$$) — $$$c_i$$$ is the cost of setting the trap in room number $$$i$$$. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — $$$a_i$$$ is the room the mouse will run to the next second after being in room $$$i$$$.

Print a single integer — the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.

NoteIn the first example it is enough to set mouse trap in rooms $$$1$$$ and $$$4$$$. If mouse starts in room $$$1$$$ then it gets caught immideately. If mouse starts in any other room then it eventually comes to room $$$4$$$.In the second example it is enough to set mouse trap in room $$$2$$$. If mouse starts in room $$$2$$$ then it gets caught immideately. If mouse starts in any other room then it runs to room $$$2$$$ in second $$$1$$$.Here are the paths of the mouse from different starts from the third example:  $$$1 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$;  $$$2 \rightarrow 2 \rightarrow \dots$$$;  $$$3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$;  $$$4 \rightarrow 3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$$$;  $$$5 \rightarrow 6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$$$;  $$$6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$$$;  $$$7 \rightarrow 6 \rightarrow 7 \rightarrow \dots$$$; So it's enough to set traps in rooms $$$2$$$ and $$$6$$$.

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val C = map(N)(_ => sc.nextInt())
    val E = map(N)(_ => sc.nextInt() - 1)
    val visited, computed = Array.ofDim[Boolean](N)

    def findMin(from: Int, to: Int) = {
      var ms = C(from)
      var v = from
      while(v != to) {
        v = E(v)
        ms = min(ms, C(v))
      }
      ms
    }

    val stack = ArrayBuffer[Int]()
    var ans = 0
    rep(N) { i =>
      var v = i
      while (!visited(v)) {
        stack += v
        visited(v) = true
        v = E(v)
      }
      if (!computed(v)) {
        ans += findMin(E(v), v)
      }
      stack foreach (v => computed(v) = true)
      stack.clear()
    }

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object D 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 cs = readInts(n)
  val as = readInts(n).map(_ - 1)

  val visited = Array.fill(n){ false }
  val isCycle = Array.fill(n){ false }
  var num = 0
  val nums = Array.fill(n){ 0 }

  def dfs1(u: Int): Int = {
    if (visited(u)) {
      if (nums(u) > 0) nums(u)
      else {
        isCycle(u) = true
        num += 1
        nums(u) = num
        num
      }
    } else {
      visited(u) = true
      nums(u) = dfs1(as(u))
      nums(u)
    }
  }

  var i = 0
  while (i < n) {
    dfs1(i)
    i += 1
  }

  def dfs2(u: Int, start: Int, min: Int): Int = {
    val v = as(u)
    if (v == start) min
    else dfs2(v, start, min min cs(v))
  }

  i = 0
  var res = 0L
  while (i < n) {
    if (isCycle(i)) res += dfs2(i, i, cs(i))
    i += 1
  }

  println(res)
}


There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.

Print the minimum number of operations required to change balance in each bank to zero.

NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer:   transfer 1 from the first bank to the second bank;  transfer 3 from the second bank to the third;  transfer 6 from the third bank to the fourth.

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

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toLong)
    var ct = mutable.HashMap[Long, Int]();
    var s = 0L
    for (i <- 0 until n) {
      s += a(i)
      ct(s) = ct.getOrElse(s, 0) + 1
    }
    var ans = n
    for (i <- 0 until n) {
      ans = Math.min(n - ct(s), ans)
      s += a(i)
    }
    println(ans)
  }
}

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

object C {
  def main(args: Array[String]) {
    val sc = new MyScanner
    val n = sc.nextLine.toInt
    val a = sc.nextLine.split(" ").map(_.toInt)
    val freq = Map[Long, Int]()

    // Calculate the prefix sums
    var sum: Long = 0
    for (x <- a) {
      sum += x
      if (freq contains sum) {
        freq(sum) += 1
      } else {
        freq(sum) = 1
      }
    }

    // Get the most frequently appearing prefix sum
    var best = 0
    for ((k, v) <- freq) {
      best = Math.max(v, best)
    }
    println(n - best)
  }
}

class MyScanner {
  var br = new BufferedReader(new InputStreamReader(System.in))
  var st: StringTokenizer = null
  def next(): String = {
    while (st == null || !st.hasMoreElements()) {
      try {
        st = new StringTokenizer(br.readLine())
      } catch {
        case e: IOException =>
           e.printStackTrace()
      }
    }
    return st.nextToken()
  }
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextLine(): String = {
    var str = ""
    try {
       str = br.readLine()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
    return str
  }
  def close() = {
    try {
      br.close()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
  }
}

import java.io._
import java.math._
import java.util._
import scala.collection.JavaConversions._

object C {
  def main(args: Array[String]) {
    val sc = new MyScanner
    val n = sc.nextLine.toInt
    val a = sc.nextLine.split(" ").map(_.toInt)
    val freq = new HashMap[Long, Int]

    var sum: Long = 0
    for (x <- a) {
      sum += x
      if (freq containsKey sum) {
        freq put (sum, freq.get(sum) + 1)
      } else {
        freq put (sum, 1)
      }
    }

    var best = 0
    for ((k, v) <- freq) {
      best = Math.max(v, best)
    }
    println(n - best)
  }
}

class MyScanner {
  var br = new BufferedReader(new InputStreamReader(System.in))
  var st: StringTokenizer = null
  def next(): String = {
    while (st == null || !st.hasMoreElements()) {
      try {
        st = new StringTokenizer(br.readLine())
      } catch {
        case e: IOException =>
           e.printStackTrace()
      }
    }
    return st.nextToken()
  }
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextLine(): String = {
    var str = ""
    try {
       str = br.readLine()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
    return str
  }
  def close() = {
    try {
      br.close()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
  }
}

import java.io._
import java.math._
import java.util._
import scala.collection.mutable.Map

object C {
  def main(args: Array[String]) {
    val sc = new MyScanner()
    val n = sc.nextInt
    var freq = Map[Long, Int]()

    // Calculate the prefix sums
    var sum: Long = 0
    for (i <- 0 until n) {
      sum += sc.nextInt
      if (freq contains sum) {
        freq(sum) += 1
      } else {
        freq(sum) = 1
      }
    }

    // Get the most frequently appearing prefix sum
    var best = 0
    for ((k, v) <- freq) {
      best = Math.max(v, best)
    }
    println(n - best)
  }
}

class MyScanner {
  var br = new BufferedReader(new InputStreamReader(System.in))
  var st: StringTokenizer = null
  def next(): String = {
    while (st == null || !st.hasMoreElements()) {
      try {
        st = new StringTokenizer(br.readLine())
      } catch {
        case e: IOException =>
           e.printStackTrace()
      }
    }
    return st.nextToken()
  }
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextLine(): String = {
    var str = ""
    try {
       str = br.readLine()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
    return str
  }
  def close() = {
    try {
      br.close()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toInt)
    var p = n - 1
    while (p > 0 && a(p) == 0) {
      p -= 1
    }
    var ans = p
    for (i <- 0 until n) {
      var s = -a(i)
      while (s != 0) {
        p += 1
        s += a(p % n)
      }
      ans = Math.min(ans, p - 1 - i)
    }
    println(ans)
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toLong)
    if (n == 1) {
      println(0)
      return
    }
    var p = n - 1
    while (p > 0 && a(p) == 0) {
      p -= 1
    }
    var ans = p
    for (i <- 0 until n) {
      var s = -a(i)
      while (s != 0) {
        p += 1
        s += a(p % n)
      }
      ans = Math.min(ans, p - 1 - i)
    }
    println(ans)
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toLong)
    if (n == 1) {
      println(0)
      return
    }
    var p = n - 1
    while (p > 0 && a(p) == 0) {
      p -= 1
    }
    var ans = p
    for (i <- 0 until n) {
      if (a(i) != 0) {
        p = i + n
      }
      ans = Math.min(ans, p - 1 - i)
    }
    println(ans)
  }
}

import java.io._
import java.math._
import java.util._
import scala.collection.mutable.Map

object C {
  def main(args: Array[String]) {
    val sc = new MyScanner()
    val n = sc.nextInt
    val a = new Array[Int](n)
    var freq = Map[Int, Int]()

    // Calculate the prefix sums
    var sum = 0
    for (i <- 0 until n) {
      sum += sc.nextInt
      a(i) = sum
      if (freq contains sum) {
        freq(sum) += 1
      } else {
        freq(sum) = 1
      }
    }

    // Get the most frequently appearing prefix sum
    var best = 0
    for ((k, v) <- freq) {
      best = Math.max(v, best)
    }
    println(n - best)
  }
}

class MyScanner {
  var br = new BufferedReader(new InputStreamReader(System.in))
  var st: StringTokenizer = null
  def next(): String = {
    while (st == null || !st.hasMoreElements()) {
      try {
        st = new StringTokenizer(br.readLine())
      } catch {
        case e: IOException =>
           e.printStackTrace()
      }
    }
    return st.nextToken()
  }
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextLine(): String = {
    var str = ""
    try {
       str = br.readLine()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
    return str
  }
  def close() = {
    try {
      br.close()
    } catch {
      case e: IOException =>
         e.printStackTrace()
    }
  }
}


There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) — the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) — the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.

Print a single integer – the largest number of enemy spaceships that can be destroyed.

NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.

import scala.collection.mutable

object C extends App {

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

  val Array(n, m) = readInts(2)
  val ays = readInts(n)
  val bys = readInts(m)

  val hitBy = mutable.Map.empty[Double, mutable.Set[Int]]

  for {
    i <- ays.indices
    j <- bys.indices
  } {
    val mid = (ays(i) + bys(j)) / 2d
    if (hitBy.contains(mid)) {
      hitBy(mid) += -i - 1
      hitBy(mid) += j
    } else {
      hitBy(mid) = mutable.Set(-i - 1, j)
    }
  }

  var max = 0

  for {
    inC1 <- hitBy.valuesIterator
    inC2 <- hitBy.valuesIterator
    if inC1.size + inC2.size > max
  } {
    var total = inC1.size
    for (x <- inC2) if (!inC1(x)) total += 1
    if (total > max) max = total
  }

  println(max)
}


There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.

Only one line containing two positive integers a and b (1 ≤ a, b ≤ 109).

Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output  - 1 as the answer.

NoteYou can see following graphs for sample 1 and sample 3.

import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
  val a = sc.nextInt
  val b = sc.nextInt

  val t1 = (a + b) / 2.0
  val t2 = (a - b) / 2.0

  def a(t: Double) = {
    val dv = (t / b).toInt
    if (dv == 0)
      -1
    else
      t / dv
  }

  val a1 = a(t1)
  val a2 = a(t2)

  if (a1 == -1) {
      println(a2)
  } else if (a2 == -1) {
    println(a1)
  } else {
    println(math.min(a1, a2))
  }
}

import scala.io.StdIn._

object C extends App {
  def solve(x: Long, y: Long) = {
    if (y > x) -1.toDouble
    else if (x == y) {
      x.toDouble
    } else {
      val k = (x - y) / (2*y)
      if (k == 0) {
        val c = (x.toDouble + y) / (2 * k + 2)
        if (c < y) -1.toDouble
        else c
      } else {
        val A = (x.toDouble - y) / (2 * k)
//        println(A)
        val B = (x.toDouble + y) / (2 * k + 2)
//        println(B)

        if (A < y && B < y) -1.toDouble
        else if (A < y) B
        else if (B < y) A
        else Math.min(A, B)
      }
    }
  }

  val Array(a, b) = readLine().split(" ").map(_.toLong)
  val answer = solve(a, b)

  println(if (answer > 0) "%.12f".format(answer) else "-1")
}

import java.text.DecimalFormat

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

object C extends App {
  def solve(x: Int, y: Int) = {
    if (y > x) -1.toDouble
    else if (x == y) {
      x.toDouble
    } else {
      val k = (x - y) / (2*y)
      if (k == 0) {
        val c = (x.toDouble + y) / (2 * k + 2)
        if (c > y) -1.toDouble
        else c
      } else {
        val A = (x.toDouble - y) / (2 * k)
//        println(A)
        val B = (x.toDouble + y) / (2 * k + 2)
//        println(B)

        if (A < y && B < y) -1.toDouble
        else if (A < y) B
        else if (B < y) A
        else Math.min(A, B)
      }
    }
  }

  val answer = solve(1, 3)

  println(if (answer > 0) "%.12f".format(answer) else "-1")
}

import scala.io.StdIn._

object C extends App {
  def solve(x: Long, y: Long) = {
    if (y > x) -1.toDouble
    else if (x == y) {
      x.toDouble
    } else {
      val k = (x - y) / (2*y)
      if (k == 0) {
        val c = (x.toDouble + y) / (2 * k + 2)
        if (c > y) -1.toDouble
        else c
      } else {
        val A = (x.toDouble - y) / (2 * k)
//        println(A)
        val B = (x.toDouble + y) / (2 * k + 2)
//        println(B)

        if (A < y && B < y) -1.toDouble
        else if (A < y) B
        else if (B < y) A
        else Math.min(A, B)
      }
    }
  }

  val Array(a, b) = readLine().split(" ").map(_.toLong)
  val answer = solve(a, b)

  println(if (answer > 0) "%.12f".format(answer) else "-1")
}


Nauuo is a girl who loves drawing circles.One day she has drawn a circle and wanted to draw a tree on it.The tree is a connected undirected graph consisting of $$$n$$$ nodes and $$$n-1$$$ edges. The nodes are numbered from $$$1$$$ to $$$n$$$.Nauuo wants to draw a tree on the circle, the nodes of the tree should be in $$$n$$$ distinct points on the circle, and the edges should be straight without crossing each other."Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.Nauuo wants to draw the tree using a permutation of $$$n$$$ elements. A permutation of $$$n$$$ elements is a sequence of integers $$$p_1,p_2,\ldots,p_n$$$ in which every integer from $$$1$$$ to $$$n$$$ appears exactly once.After a permutation is chosen Nauuo draws the $$$i$$$-th node in the $$$p_i$$$-th point on the circle, then draws the edges connecting the nodes.The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $$$998244353$$$, can you help her?It is obvious that whether a permutation is valid or not does not depend on which $$$n$$$ points on the circle are chosen.

The first line contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$), denoting there is an edge between $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree.

The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo $$$998244353$$$.

NoteExample 1All valid permutations and their spanning trees are as follows.Here is an example of invalid permutation: the edges $$$(1,3)$$$ and $$$(2,4)$$$ are crossed.Example 2Every permutation leads to a valid tree, so the answer is $$$4! = 24$$$.

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

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

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

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

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

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

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

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

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

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

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

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

  val NN = 200000

  def powMod(x: Int, n: Int, m: Int): Int = {
    def step(x: Long, n: Int, stack: Long): Long = {
      n match {
        case 0 => stack
        case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
      }
    }
    step(x, n, 1).toInt
  }

  val F = Array.ofDim[Long](NN + 1)
  F(0) = 1
  REP(NN) { i =>
    F(i + 1) = F(i) * (i + 1) % MOD
  }
  val I = Array.ofDim[Long](F.length)
  I(NN) = powMod(F(NN).toInt, MOD - 2, MOD)

  // x! = x(x-1)!
  // x!I(x!) ≡ (x-1)!I((x-1)!)
  // I((x-1)!) ≡ I(x!) * x   MODがでかいので(x-1)!はMODと素
  REP_r(NN) { i =>
    I(i) = I(i + 1) * (i + 1) % MOD
  }

  def comb(n: Int, k: Int): Long = {
    if (n < k) 0
    else F(n) * I(n - k) % MOD * I(k) % MOD
  }

  def rev(x: Int) = {
    I(x) * F(x - 1) % MOD
  }

  def solve(): Unit = {
    val N = ni()
    val (from, to) = na2(N - 1, -1)
    val g = packUGraph(N, from, to)
    val (_, parent, queue) = traceBfs(g)

    val dp = Array.ofDim[Long](N)
    REP_r(N) { i =>
      val v = queue(i)
      var mul = 1L
      var cnt = 1 // v自身
      REP(g(v).length) { j =>
        val u = g(v)(j)
        if (u != parent(v)) {
          cnt += 1
          mul = mul * dp(u) % MOD
        }
      }
      if (v == 0) {
        // 回転して同じものを考慮する
        dp(v) = F(cnt - 1) * mul % MOD * N % MOD
      } else {
        dp(v) = F(cnt) * mul % MOD
      }
    }

    debug(dp)

    out.println(dp(0))
  }

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }
}


Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = $$$2$$$, b = $$$3$$$ changes the value of a to $$$5$$$ (the value of b does not change).In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations "a += b" or "b += a". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value $$$n$$$. What is the smallest number of operations he has to perform?

The first line contains a single integer $$$T$$$ ($$$1 \leq T \leq 100$$$) — the number of test cases. Each of the following $$$T$$$ lines describes a single test case, and contains three integers $$$a, b, n$$$ ($$$1 \leq a, b \leq n \leq 10^9$$$) — initial values of a and b, and the value one of the variables has to exceed, respectively.

For each test case print a single integer — the smallest number of operations needed. Separate answers with line breaks.

NoteIn the first case we cannot make a variable exceed $$$3$$$ in one operation. One way of achieving this in two operations is to perform "b += a" twice.

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val abn = readIntLine()
      println(handle(Math.min(abn.head, abn(1)), Math.max(abn.head, abn(1)), abn.last, 0))
    }
  }

  def handle(a: Int, b: Int, n: Int, acc: Int): Int = if (b > n) acc else handle(b, a + b, n, acc + 1)

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

}

object A {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      var a, b, n = nextLong
      var i = 0
      while (a <= n && b <= n) {
        if (a < b) {
          a += b
        } else {
          b += a
        }
        i += 1
      }

      out.println(i)

      out.flush()
    }
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object A extends App {
  import scala.io.StdIn._
  import scala.annotation.tailrec

  val t = readInt()

  def mult(a: List[List[Int]], b: List[List[Int]]): List[List[Int]] =
    for {
      row <- a
    } yield for {
      col <- b.transpose
    } yield row.zip(col).foldLeft(0) { case (sum, (r, c)) => sum + r * c }

  def binpow(a: List[List[Int]], n: Int): List[List[Int]] =
    (0 to (math.log(n) / math.log(2)).toInt)
      .foldLeft((List(List(1, 0), List(0, 1)), a)) {
        case ((r, a), i) =>
          (if ((1 & (n >> i)) == 1) mult(a, r) else r, mult(a, a))
      }
      ._1

  def fib(n: Int): (Int, Int) = {
    val List(fibn, fibn1) = mult(List(List(0, 1)), binpow(List(List(0, 1), List(1, 1)), n)).head
    (fibn, fibn1)
  }

  (0 until t).foreach { _ =>
    val Array(a, b, n) = readLine().split(" ").map(_.toInt)

    val ans = (0 to n).collectFirst { case i if { val (c1, c2) = fib(i); c2 * a.max(b) + c1 * a.min(b) > n } => i }.get

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, n) = readLine().split(" ").map(_.toInt)

    lazy val fibs: Stream[(Int, Int)] = (0, 0) #:: (1, 1) #:: (fibs zip fibs.tail).map {
      case ((a, _), (b, i)) => (a + b, i + 1)
    }

    val ans = fibs.zip(fibs.tail).collectFirst { case ((f0, i), (f1, _)) if f1 * a.max(b) + f0 * a.min(b) > n => i }.get

    println(ans)
  }
}


Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of $$$2$$$ rows and $$$n$$$ columns. Monocarp controls a character, which starts in cell $$$(1, 1)$$$ — at the intersection of the $$$1$$$-st row and the $$$1$$$-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ in one step if $$$|x_1 - x_2| \le 1$$$ and $$$|y_1 - y_2| \le 1$$$. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell $$$(2, n)$$$ — at the intersection of row $$$2$$$ and column $$$n$$$.Help Monocarp determine if it is possible to complete the level.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of columns. The next two lines describe the level. The $$$i$$$-th of these lines describes the $$$i$$$-th line of the level — the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell. Additional constraint on the input: cells $$$(1, 1)$$$ and $$$(2, n)$$$ are safe.

For each test case, output YES if it is possible to complete the level, and NO otherwise.

NoteConsider the example from the statement.In the first test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (2, 3)$$$.In the second test case, one of the possible paths is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 3) \rightarrow (2, 4)$$$.In the fourth test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (1, 3) \rightarrow (2, 4) \rightarrow (1, 5) \rightarrow (2, 6)$$$.

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

object ComputerGame extends App {
  def solve():Unit = {
    val t = readLine().trim.toInt
    for(_ <- 1 to t) {
      val n = readLine().trim.toInt
      val grid: Array[String] = new Array[String](2)
      grid(0) = readLine().trim
      grid(1) = readLine().trim
      var isPossible:Boolean = true
      breakable {
        for (i <- 0 until n) {
          isPossible = grid(0)(i) == '0' || grid(1)(i) == '0'
          if (!isPossible) break
        }
      }
      val ans = if(isPossible) "YES" else "NO"
      println(ans)
    }
  }
  solve()
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val s1 = readString()
        val s2 = readString()
        var reach = true
        for (i <- 0 until n) {
            if (s1(i) == '1' && s2(i) == '1')
                reach = false
        }
        if (reach)
            writer.println("YES")
        else
            writer.println("NO")
    }
    writer.flush()
}


Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.Optimal sequence of actions in the second sample case:   In the first day Anastasia collects 8 pebbles of the third type.  In the second day she collects 8 pebbles of the fourth type.  In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.  In the fourth day she collects 7 pebbles of the fifth type.  In the fifth day she collects 1 pebble of the second type.

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n = read[Int]
    val k = read[Long]
    val pebbles = read[Seq, Long](n)
    val chunks = pebbles.sumWith(i => (i + k - 1)/k)
    val ans = (chunks + 1)/2
    write(ans)
  }

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

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

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

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

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

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

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

/**
  * Created by ruslan on 3/29/17.
  */
object ProblemA extends App {
    import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}
import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

class  FastScanner(val in: BufferedReader) {
  var st: StringTokenizer = _;

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

  def nextInt(): Integer = {
    Integer.parseInt(nextToken());
  }

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

  def nextDouble(): Double = {
    nextToken().toDouble;
  }
}

  val n = in.nextInt();
  val k = in.nextInt();
  var res = 0;

  for (i <- 1 to n) {
    val w = in.nextInt();
    res += w / k;
    if (w % k > 0) res += 1;
  }

  res = res / 2 + (if (res % 2 == 1) 1 else 0)

  println(res)

}

object Anastasia extends App {

  val Array(n: Int, k: Int) = readLine.split(' ').map(_.toInt)
  val ww: Array[Int] = readLine.split(' ').map(_.toInt)

  val pocketCount = for (w <- ww) yield {
    val ratio = w / k
    val remainder = w % k
    if (remainder == 0) ratio else ratio + 1
  }

  val ratio = pocketCount.sum / 2
  val remainder = pocketCount.sum % 2
  val result = if (remainder == 0) ratio else ratio + 1

  println(result)
}


Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--:  First, a type is a string "int".  Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces.  No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform.

The first line contains a single integer n (1 ≤ n ≤ 105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int".

If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters.  It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values.

object Solution {
  var tokens: List[String] = null;

  def nextToken(): String = {
    if (tokens.isEmpty) {
      throw new Exception("nope")
    }
    val token = tokens.head
    tokens = tokens.tail
    token
  }

  def parse(buf: StringBuffer) {
    if (nextToken() == "int") {
      buf.append("int")
    } else {
      buf.append("pair<")
      parse(buf)
      buf.append(",")
      parse(buf)
      buf.append(">")
    }
  }

  def main(args: Array[String]) {
    val n = readInt()
    tokens = readLine().split(" ").toList
    try {
      val buf = new StringBuffer()
      parse(buf)
      if (!tokens.isEmpty) {
        throw new Exception("nope")
      }
      println(buf)
    } catch {
      case e => println("Error occurred")
    }
  }
}


Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are $$$n$$$ students living in a building, and for each of them the favorite drink $$$a_i$$$ is known. So you know $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le k$$$) is the type of the favorite drink of the $$$i$$$-th student. The drink types are numbered from $$$1$$$ to $$$k$$$.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $$$k$$$ types of drink sets, the $$$j$$$-th type contains two portions of the drink $$$j$$$. The available number of sets of each of the $$$k$$$ types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $$$\lceil \frac{n}{2} \rceil$$$, where $$$\lceil x \rceil$$$ is $$$x$$$ rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $$$n$$$ is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if $$$\lceil \frac{n}{2} \rceil$$$ sets will be chosen optimally and students will distribute portions between themselves optimally?

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 1\,000$$$) — the number of students in the building and the number of different drinks. The next $$$n$$$ lines contain student's favorite drinks. The $$$i$$$-th line contains a single integer from $$$1$$$ to $$$k$$$ — the type of the favorite drink of the $$$i$$$-th student.

Print exactly one integer — the maximum number of students that can get a favorite drink.

NoteIn the first example, students could choose three sets with drinks $$$1$$$, $$$1$$$ and $$$2$$$ (so they will have two sets with two drinks of the type $$$1$$$ each and one set with two drinks of the type $$$2$$$, so portions will be $$$1, 1, 1, 1, 2, 2$$$). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks $$$1$$$, $$$2$$$ and $$$3$$$. In this case the portions will be $$$1, 1, 2, 2, 3, 3$$$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $$$a_i = 1$$$ (i.e. the first, the third or the fourth).

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val C = Array.ofDim[Int](K)
    REP(N) { _ =>
      C(ni() - 1) += 1
    }
    val cntOdd = C.count(_ % 2 == 1)
    val ans = N - cntOdd / 2
    out.println(ans)
  }
}

object Main {

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

  import scala.reflect.ClassTag

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

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj) {
      f
    }
  }

  def debug(as: Array[Boolean]): Unit = if (!oj) {
    debug(as.map(x => if (x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = if (!oj) {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = if (!oj) {
    debug(as.mkString(" "))
  }

  def debugDim(m: Array[Array[Int]]): Unit = if (!oj) {
    REP(m.length) { i =>
      debug(m(i))
    }
  }

  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj) {
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i)
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i)
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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

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

class Main(out: java.io.PrintWriter, in: Main.InputReader) {

  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val n = in.nextInt()
    val k = in.nextInt()
    val a = new Array[Int](k + 1)
    for (_ <- 0 until n) {
      a(in.nextInt()) += 1
    }
    a.sorted
    var count = 0
    var d = (n + 1) / 2
    for {
      i <- k to 0 by -1
      if a(i) > 0
    } yield {
      count += a(i) - (a(i) % 2)
      d -= a(i) / 2
      a(i) = a(i) % 2
    }
    a.sorted
    for {
      i <- a.indices
      if d > 0

    } yield {
      if (a(i) > 0) {
        count += 1
        d -= 1
      }

    }
    out.println(count)

  }
}


A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes).A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string.The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ.

The first line contains integer n (1 ≤ n ≤ 105) — the number of strings in the set. Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct. The total length of the strings doesn't exceed 105.

Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings.

NoteOne can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum.

import scala.collection.mutable.ArrayBuffer

object D extends App {

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

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

  val Array(n) = readInts(1)

  val basis = ArrayBuffer.empty[String]

  //val basisByLetter = mutable.Map.empty[Char, Int]

  def overlap(a: String, b: String): Int = {
    var i = 0
    var res = 0
    while (i < a.length && i < b.length) {
      i += 1
      if (a.takeRight(i) == b.take(i)) res = i
    }
    res
  }

  var can = true
  var i = 0
  while (can && i < n) {
    i += 1

    val s = readLine
    val sDist = s.distinct
    if (s.length > sDist.length) can = false
    else {

      val empty = basis.indexOf("")

      var updated = if (empty == -1) {
        basis += s
        basis.size - 1
      } else {
        basis(empty) = s
        empty
      }

      var canMerge = true
      var step = 0
      while (canMerge) {

        canMerge = false

        var basisIdx = 0

        while (basisIdx < basis.size && !canMerge) {
          //println(step, basis.mkString(" "), updated, basisIdx, can, canMerge)
          if (basis(basisIdx).nonEmpty && basisIdx != updated) {
            val basisS = basis(basisIdx)
            val otherS = basis(updated)

            //println("A", basisS, otherS, overlap(basisS, otherS))
            //println("B", otherS, basisS, overlap(otherS, basisS))

            if (basisS.indexOfSlice(otherS) >= 0) {
              basis(updated) = ""
            } else if (otherS.indexOfSlice(basisS) >= 0) {
              basis(basisIdx) = otherS
              basis(updated) = ""
              updated = basisIdx
              canMerge = true
            } else if (overlap(basisS, otherS) > 0) {
              val prefLen = overlap(basisS, otherS)
              val s2 = basisS + otherS.drop(prefLen)
              val s2Dist = s2.distinct
              if (s2.length > s2Dist.length) can = false
              else {
                basis(basisIdx) = s2
                basis(updated) = ""
                updated = basisIdx
                canMerge = true
              }
            } else if (overlap(otherS, basisS) > 0) {
              val prefLen = overlap(otherS, basisS)
              val s2 = otherS + basisS.drop(prefLen)
              val s2Dist = s2.distinct
              if (s2.length > s2Dist.length) can = false
              else {
                basis(basisIdx) = s2
                basis(updated) = ""
                updated = basisIdx
                canMerge = true
              }
            } else if (otherS.exists(c => basisS.contains(c))) can = false
          }

          basisIdx += 1
        }
        step += 1
      }

    }

  }

  if (can) {
    val res = basis.sorted.mkString
    if (res.length == res.distinct.length) println(res)
    else println("NO")
  } else println("NO")
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object D 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 basis = ArrayBuffer.empty[String]

  val basisByLetter = mutable.Map.empty[Char, Int]

  def overlap(a: String, b: String): Int = {
    var i = 0
    while (i < a.length && i < b.length && a.takeRight(i + 1) == b.take(i + 1)) i += 1
    i
  }

  var can = true
  var i = 0
  while (can && i < n) {
    i += 1

    val s = readLine
    val sDist = s.distinct
    if (s.length > sDist.length) can = false
    else {

      val cPos = s.indexWhere(basisByLetter.contains)

      if (cPos == -1) {
        s.foreach(c => basisByLetter(c) = basis.size)
        basis += s
      } else {
        val basisIdx = basisByLetter(s(cPos))
        val basisS = basis(basisIdx)
        if (basisS.indexOfSlice(s) >= 0) {
          // ok
        } else if (s.indexOfSlice(basisS) >= 0) {
          s.foreach(c => basisByLetter(c) = basisIdx)
          basis(basisIdx) = s
        } else if (overlap(basisS, s) > 0) {
          val prefLen = overlap(basisS, s)
          val s2 = basisS + s.drop(prefLen)
          val s2Dist = s2.distinct
          if (s2.length > s2Dist.length) can = false
          else {
            s2.foreach(c => basisByLetter(c) = basisIdx)
            basis(basisIdx) = s2
          }
        } else if (overlap(s, basisS) > 0) {
          val prefLen = overlap(s, basisS)
          val s2 = s + basisS.drop(prefLen)
          val s2Dist = s2.distinct
          if (s2.length > s2Dist.length) can = false
          else {
            s2.foreach(c => basisByLetter(c) = basisIdx)
            basis(basisIdx) = s2
          }
        } else can = false

      }

    }

  }

  if (can) println(basis.sorted.mkString)
  else println("NO")
}

import scala.collection.mutable.ArrayBuffer

object D extends App {

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

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

  val Array(n) = readInts(1)

  val basis = ArrayBuffer.empty[String]

  //val basisByLetter = mutable.Map.empty[Char, Int]

  def overlap(a: String, b: String): Int = {
    var i = 0
    while (i < a.length && i < b.length && a.takeRight(i + 1) == b.take(i + 1)) i += 1
    i
  }

  var can = true
  var i = 0
  while (can && i < n) {
    i += 1

    val s = readLine
    val sDist = s.distinct
    if (s.length > sDist.length) can = false
    else {

      val empty = basis.indexOf("")

      var updated = if (empty == -1) {
        basis += s
        basis.size - 1
      } else {
        basis(empty) = s
        empty
      }

      var canMerge = true
      var step = 0
      while (canMerge) {

        canMerge = false

        var basisIdx = 0

        while (basisIdx < basis.size && !canMerge) {
          //println(step, basis.mkString(" "), updated, basisIdx, can, canMerge)
          if (basis(basisIdx).nonEmpty && basisIdx != updated) {
            val basisS = basis(basisIdx)
            val otherS = basis(updated)

            if (basisS.indexOfSlice(otherS) >= 0) {
              basis(updated) = ""
            } else if (otherS.indexOfSlice(basisS) >= 0) {
              basis(basisIdx) = otherS
              basis(updated) = ""
              updated = basisIdx
              canMerge = true
            } else if (overlap(basisS, otherS) > 0) {
              val prefLen = overlap(basisS, otherS)
              val s2 = basisS + otherS.drop(prefLen)
              val s2Dist = s2.distinct
              if (s2.length > s2Dist.length) can = false
              else {
                basis(basisIdx) = s2
                basis(updated) = ""
                updated = basisIdx
                canMerge = true
              }
            } else if (overlap(otherS, basisS) > 0) {
              val prefLen = overlap(otherS, basisS)
              val s2 = otherS + basisS.drop(prefLen)
              val s2Dist = s2.distinct
              if (s2.length > s2Dist.length) can = false
              else {
                basis(basisIdx) = s2
                basis(updated) = ""
                updated = basisIdx
                canMerge = true
              }
            } else if (otherS.exists(c => basisS.contains(c))) can = false
          }

          basisIdx += 1
        }
        step += 1
      }

    }

  }

  if (can) {
    val res = basis.sorted.mkString
    if (res.length == res.distinct.length) println(res)
    else println("NO")
  } else println("NO")
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object D 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 basis = ArrayBuffer.empty[String]

  val basisByLetter = mutable.Map.empty[Char, Int]

  def overlap(a: String, b: String): Int = {
    var i = 0
    while (i < a.length && i < b.length && a.takeRight(i + 1) == b.take(i + 1)) i += 1
    i
  }

  var can = true
  var i = 0
  while (can && i < n) {
    i += 1

    val s = readLine
    val sDist = s.distinct
    if (s.length > sDist.length) can = false
    else {

      val cPos = s.indexWhere(basisByLetter.contains)

      if (cPos == -1) {
        s.foreach(c => basisByLetter(c) = basis.size)
        basis += s
      } else {
        val basisIdx = basisByLetter(s(cPos))
        val basisS = basis(basisIdx)
        if (basisS.indexOfSlice(s) >= 0) {
          // ok
        } else if (s.indexOfSlice(basisS) >= 0) {
          s.foreach(c => basisByLetter(c) = basisIdx)
          basis(basisIdx) = s
        } else if (overlap(basisS, s) > 0) {
          val prefLen = overlap(basisS, s)
          val s2 = basisS + s.drop(prefLen)
          val s2Dist = s2.distinct
          if (s2.length > s2Dist.length) can = false
          else {
            s2.foreach(c => basisByLetter(c) = basisIdx)
            basis(basisIdx) = s2
          }
        } else if (overlap(s, basisS) >= 0) {
          val prefLen = overlap(s, basisS)
          val s2 = s + basisS.drop(prefLen)
          val s2Dist = s2.distinct
          if (s2.length > s2Dist.length) can = false
          else {
            s2.foreach(c => basisByLetter(c) = basisIdx)
            basis(basisIdx) = s2
          }
        } else {
          s.foreach(c => basisByLetter(c) = basis.size)
          basis += s
        }

      }

    }

  }

  if (can) println(basis.sorted.mkString)
  else println("NO")
}


A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You are given a permutation of $$$1,2,\dots,n$$$, $$$[a_1,a_2,\dots,a_n]$$$. For integers $$$i$$$, $$$j$$$ such that $$$1\le i<j\le n$$$, define $$$\operatorname{mn}(i,j)$$$ as $$$\min\limits_{k=i}^j a_k$$$, and define $$$\operatorname{mx}(i,j)$$$ as $$$\max\limits_{k=i}^j a_k$$$.Let us build an undirected graph of $$$n$$$ vertices, numbered $$$1$$$ to $$$n$$$. For every pair of integers $$$1\le i<j\le n$$$, if $$$\operatorname{mn}(i,j)=a_i$$$ and $$$\operatorname{mx}(i,j)=a_j$$$ both holds, or $$$\operatorname{mn}(i,j)=a_j$$$ and $$$\operatorname{mx}(i,j)=a_i$$$ both holds, add an undirected edge of length $$$1$$$ between vertices $$$i$$$ and $$$j$$$.In this graph, find the length of the shortest path from vertex $$$1$$$ to vertex $$$n$$$. We can prove that $$$1$$$ and $$$n$$$ will always be connected via some path, so a shortest path always exists.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 5\cdot 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1\le n\le 2.5\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1\le a_i\le n$$$). It's guaranteed that $$$a$$$ is a permutation of $$$1$$$, $$$2$$$, $$$\dots$$$, $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5\cdot 10^5$$$.

For each test case, print a single line containing one integer — the length of the shortest path from $$$1$$$ to $$$n$$$.

NoteThe following are illustrations of constructed graphs in example test cases.    the constructed graph in test case 1     the constructed graph in test case 2     the constructed graph in test case 3     the constructed graph in test case 4     the constructed graph in test case 5

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      tokenizer = new StringTokenizer(input.readLine())
      val A = ListBuffer.empty[Int]
      for (j <- 1 to n) {
        A += tokenizer.nextToken.toInt
      }
      var B = A.toArray
      var now = 0
      var pos = 0
      var st = 0
      var con = 0
      var cou = 0
      var noc = 0
      if (n == 1) {
        println(0)
      }
      else {
        if (B(0) < B(1)) {
          pos = 0
        }
        else pos = 1
        while ((B(now) != n) && B(now) != 0) {
          if (st < n - 1) {
            st += 1
            if (B(st) > B(con)) {
              con = st
              if (pos == 1) {
                now = noc
                pos = 0
                cou += 1
              }
            }
            if (B(st) < B(noc)) {
              noc = st
              if (pos == 0) {
                now = con
                pos = 1
                cou += 1
              }
            }
          }
          else {
            if (pos == 0) {
              now = con
              pos = 1
              cou += 1
              noc = now
              st = now
            }
            else if (pos == 1) {
              now = noc
              pos = 0
              cou += 1
              con = now
              st = now
            }
          }
        }
        B = B.reverse
        now = 0
        pos = 0
        st = 0
        con = 0
        noc = 0
        if (B(0) < B(1)) {
          pos = 0
        }
        else pos = 1
        while ((B(now) != n) && B(now) != 0) {
          if (st < n - 1) {
            st += 1
            if (B(st) > B(con)) {
              con = st
              if (pos == 1) {
                now = noc
                pos = 0
                cou += 1
              }
            }
            if (B(st) < B(noc)) {
              noc = st
              if (pos == 0) {
                now = con
                pos = 1
                cou += 1
              }
            }
          }
          else {
            if (pos == 0) {
              now = con
              pos = 1
              cou += 1
              noc = now
              st = now
            }
            else if (pos == 1) {
              now = noc
              pos = 0
              cou += 1
              con = now
              st = now
            }
          }
        }
        output.println(cou)
      }
    }
  }
}