There are $$$n$$$ athletes in front of you. Athletes are numbered from $$$1$$$ to $$$n$$$ from left to right. You know the strength of each athlete — the athlete number $$$i$$$ has the strength $$$s_i$$$.You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $$$A$$$ and $$$B$$$ so that the value $$$|\max(A) - \min(B)|$$$ is as small as possible, where $$$\max(A)$$$ is the maximum strength of an athlete from team $$$A$$$, and $$$\min(B)$$$ is the minimum strength of an athlete from team $$$B$$$.For example, if $$$n=5$$$ and the strength of the athletes is $$$s=[3, 1, 2, 6, 4]$$$, then one of the possible split into teams is:   first team: $$$A = [1, 2, 4]$$$,  second team: $$$B = [3, 6]$$$. In this case, the value $$$|\max(A) - \min(B)|$$$ will be equal to $$$|4-3|=1$$$. This example illustrates one of the ways of optimal split into two teams.Print the minimum value $$$|\max(A) - \min(B)|$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of two lines.  The first line contains positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — number of athletes.  The second line contains $$$n$$$ positive integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 1000$$$), where $$$s_i$$$ — is the strength of the $$$i$$$-th athlete. Please note that $$$s$$$ values may not be distinct.

For each test case print one integer — the minimum value of $$$|\max(A) - \min(B)|$$$ with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.

NoteThe first test case was explained in the statement. In the second test case, one of the optimal splits is $$$A=[2, 1]$$$, $$$B=[3, 2, 4, 3]$$$, so the answer is $$$|2-2|=0$$$.

import scala.io.StdIn.readLine

object B {

  def solution(s0: Seq[Int]): Int = {
    val s = s0.toArray.sorted
    s.zip(s.tail).map{ case (a, b) => b - a }.min
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val _ = readLine.toInt
      val s = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(s))
    }
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CF644(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final 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)(f)
  }

  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 CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val a = na(n)
      scala.util.Sorting.quickSort(a)
      var r = Long.MaxValue
      REP(n-1, 1) { i =>
        r = math.min(r, a(i) - a(i-1))
      }
      out.println(r)
    }
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag

object Main {
	def main(args: Array[String]): Unit = {
		try {
			val (in, out) =
				if (isOnlineJudge) {
					(
						new FastScanner(new InputStreamReader(System.in)),
						new PrintWriter(System.out)
					)
				} else {
					(
						new FastScanner(new FileReader(new File("problem.in"))),
						new PrintWriter(new File("problem.out"))
					)
				}
			new CF644(in, out).solve()
			out.flush()
			out.close()
		} catch {
			case e: IOException => e.printStackTrace()
		}
	}

	private[this] val isOnlineJudge = true

	class FastScanner(val streamReader: InputStreamReader) {
		private[this] val reader = new BufferedReader(streamReader, 32768)
		private[this] var tokenizer: StringTokenizer = _

		@inline private[this] final 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)(f)
	}

	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 CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

	import Main._
	import fScanner._

	def solve(): Unit = {
		val T = ni()
		for(i <- 0 until T){
		var ans : Int = 1000
			val n = ni()
			var list: List[Int] = List()
			for(j <- 0 until n){
				val cu:Int = ni()
				for( x <- list)
					ans = ans.min( ( cu - x ).max(x - cu) )
				list = cu::	list
			}
			out.println(ans)
		}
	}
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

    val ans = sn.zip(sn.tail).map { case (a, b) => b - a }.min

    println(ans)
  }
}


The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column).    The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$.

Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them.

4
1 1
L
1 2
L
3 3
RRDLUU
4 3
LUURRDDLLLUU

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

object Main 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 fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(var value: Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return value.compareTo(that.value)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        val s = readString()
        var x = 0
        var y = 0
        var minx = 0
        var maxx = 0
        var miny = 0
        var maxy = 0
        var ind = 0
        while (maxx-minx < m && maxy-miny < n && ind < s.length) {
            if (s(ind) == 'L')
                x -= 1
            if (s(ind) == 'R')
                x += 1
            if (s(ind) == 'U')
                y -= 1
            if (s(ind) == 'D')
                y += 1
            minx = min(minx, x)
            maxx = max(maxx, x)
            miny = min(miny, y)
            maxy = max(maxy, y)
            ind += 1
        }
        if (maxx-minx == m || maxy-miny == n) {
            if (s(ind-1) == 'L')
                minx += 1
            if (s(ind-1) == 'R')
                maxx -= 1
            if (s(ind-1) == 'U')
                miny += 1
            if (s(ind-1) == 'D')
                maxy -= 1
        }
        writer.print(1 - miny + " ")
        writer.println(1 - minx)
    }
    writer.flush()
}


Gottfried learned about binary number representation. He then came up with this task and presented it to you.You are given a collection of $$$n$$$ non-negative integers $$$a_1, \ldots, a_n$$$. You are allowed to perform the following operation: choose two distinct indices $$$1 \leq i, j \leq n$$$. If before the operation $$$a_i = x$$$, $$$a_j = y$$$, then after the operation $$$a_i = x~\mathsf{AND}~y$$$, $$$a_j = x~\mathsf{OR}~y$$$, where $$$\mathsf{AND}$$$ and $$$\mathsf{OR}$$$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).After all operations are done, compute $$$\sum_{i=1}^n a_i^2$$$ — the sum of squares of all $$$a_i$$$. What is the largest sum of squares you can achieve?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{20}$$$).

Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.

NoteIn the first sample no operation can be made, thus the answer is $$$123^2$$$.In the second sample we can obtain the collection $$$1, 1, 7$$$, and $$$1^2 + 1^2 + 7^2 = 51$$$.If $$$x$$$ and $$$y$$$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $$$x~\mathsf{AND}~y$$$ is set to $$$1$$$ if and only if both corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. Similarly, each bit of $$$x~\mathsf{OR}~y$$$ is set to $$$1$$$ if and only if at least one of the corresponding bits of $$$x$$$ and $$$y$$$ are set to $$$1$$$. For example, $$$x = 3$$$ and $$$y = 5$$$ are represented as $$$011_2$$$ and $$$101_2$$$ (highest bit first). Then, $$$x~\mathsf{AND}~y = 001_2 = 1$$$, and $$$x~\mathsf{OR}~y = 111_2 = 7$$$.

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

    val n = nextInt
    val as = nextInts(n)
    val bits = Array.fill(30)(0)

    for (_a <- as) {
      var a = _a
      var pos = 0
      while (a > 0) {
        if ((a & 1) != 0) {
          bits(pos) += 1
        }
        a >>= 1
        pos += 1
      }
    }

    var res = BigInt(0)
    var done = false
    while (!done) {
      val non0 = bits.filter(_ > 0)
      if (non0.nonEmpty) {
        val min = non0.min
        var num = 0L
        for (i <- bits.indices) {
          if (bits(i) > 0) {
            bits(i) -= min
            num += 1L << i
          }
        }
        res += num * num * min
      } else {
        done = true
      }
    }

    out.println(res)

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


Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet — it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively.However, his max-flow algorithm seems to have a little flaw — it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.More formally. You are given an undirected graph. For each it's undirected edge (ai, bi) you are given the flow volume ci. You should direct all edges in such way that the following conditions hold:  for each vertex v (1 < v < n), sum of ci of incoming edges is equal to the sum of ci of outcoming edges;  vertex with number 1 has no incoming edges;  the obtained directed graph does not have cycles.

The first line of input contains two space-separated integers n and m (2 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105), the number of vertices and edges in the graph. The following m lines contain three space-separated integers ai, bi and ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 104), which means that there is an undirected edge from ai to bi with flow volume ci. It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists.

Output m lines, each containing one integer di, which should be 0 if the direction of the i-th edge is ai → bi (the flow goes from vertex ai to vertex bi) and should be 1 otherwise. The edges are numbered from 1 to m in the order they are given in the input. If there are several solutions you can print any of them.

NoteIn the first test case, 10 flow units pass through path , and 5 flow units pass directly from source to sink: .

import collection.mutable.ArrayBuffer
import collection.mutable.Queue

object test6 extends App {
    class Edge(val b:Int, val c:Int, val d:Int, val i:Int){}

    val Array(n,m)=readLine.split(" ").map(_.toInt)
    val vertices=new Array[ArrayBuffer[Edge]](n)
    for(i<-0 until n) vertices(i)=new ArrayBuffer[Edge]
    val flow=new Array[Int](n)
    val ans=new Array[Int](m)
    val v=new Array[Boolean](n)

    for(i<- 0 until m){
        val Array(a,b,c)=readLine.split(" ").map(_.toInt)
        vertices(a-1)+=new Edge(b-1,c,0,i)
        vertices(b-1)+=new Edge(a-1,c,1,i)
        flow(a-1)+=c
        flow(b-1)+=c
    }
    for(i<-1 until n-1) flow(i)/=2

    val queue=new Queue[Int]
    queue.enqueue(0)
    v(0)=true
    while(queue.nonEmpty){
        val next=queue.dequeue
        vertices(next).foreach(edge=>{
            if(!v(edge.b)){
                ans(edge.i)=edge.d
                flow(edge.b)-=edge.c
                if(flow(edge.b)==0 && edge.b!=n-1) {v(edge.b)=true;queue.enqueue(edge.b)}
            }
        })
    }

    println(ans.mkString("\n"))
}


The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.

For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.

9
arrayhead
5
arya
harry
ray
r
areahydra

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = ns(N)

    val C = Array.fill[ArrayBuffer[Int]](26)(ArrayBuffer())
    REP(N) { i =>
      C(S(i) - 'a') += i + 1
    }

    val M = ni()
    REP(M) { _ =>
      val name = ns()
      val cnt = Array.ofDim[Int](26)
      REP(name.length) { i =>
        cnt(name(i) - 'a') += 1
      }
      debug(cnt)

      var ans = 0
      REP(26) { i =>
        if (cnt(i) > 0) ans = max(ans, C(i)(cnt(i) - 1))
      }
      out.println(ans)
    }
  }
}

object B1187 {

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

  def main(args: Array[String]): Unit = {
    val n = readInt
    val str = read
    val countArr = {
      val ret = Array.fill(n)(Array.fill(26)(0))
      var i = 0
      while (i < n) {
        if (i != 0)
          ret(i) = ret(i - 1).clone()
        ret(i)(str(i) - 'a') += 1
        i += 1
      }
      ret
    }
    val m = readInt
    for (_ <- 1 to m) {
      val name = read.foldLeft(Array.fill(26)(0)) { (arr, x) =>
        arr(x - 'a') += 1
        arr
      }
      var (start, end) = (0, n - 1)
      var res = -1
      while (start <= end) {
        val mid = start + (end - start) / 2
        if (name.zip(countArr(mid)).forall { case (x, y) => x <= y }) {
          res = mid
          end = mid - 1
        } else {
          start = mid + 1
        }
      }

      out.println(res + 1)
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.StdIn._

object B_1187 extends App {

  def howManyToBuy(ch: Char, howMany: Int): Int =
    S(ch)(howMany - 1)._2

  val n = readInt()
  val s = readLine().toCharArray
  val m = readInt()

  val S = s.zipWithIndex.sortBy(y => (y._1, y._2)).groupBy(_._1)

  1 to m foreach { _ =>
    val x = readLine().toCharArray
    val max = x
      .groupBy(identity)
      .mapValues(_.length)
      .map {
        case (ch, amount) => howManyToBuy(ch, amount)
      }
      .max

    println(max + 1)
  }

}


Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.Determine if Snark and Philip can make an interesting problemset!

The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 4) — the number of problems and the number of experienced teams. Each of the next n lines contains k integers, each equal to 0 or 1. The j-th number in the i-th line is 1 if j-th team knows i-th problem and 0 otherwise.

Print "YES" (quotes for clarity), if it is possible to make an interesting problemset, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").

NoteIn the first example you can't make any interesting problemset, because the first team knows all problems.In the second example you can choose the first and the third problems.

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

object Main extends App {
  var inputLine = scala.io.StdIn.readLine().split(" ")
  var tasksNumber:Int = inputLine(0).toInt
  var teamsNum:Int = inputLine(1).toInt

  var set: mutable.HashSet[List[Int]] = new mutable.HashSet[List[Int]]()

  def input():Boolean = {
    var res:Boolean = false
    0 until tasksNumber foreach (i => {
      var newTask: List[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList
      if (smartSort(newTask, set)) {
        res = true;
      }
    })
    res
  }

  def smartSort(in: List[Int], set: mutable.HashSet[List[Int]]):Boolean = {
    if(!set.contains(in)) {
      var precheck = true
      in.foreach(i => if(i != 0) precheck = false)
      if(precheck) return true

      var requiredIndeces = in.indices.filter(i => in(i) == 1).toList

      set.toStream.foreach(e => {
        var res:Boolean = true
        requiredIndeces.foreach(i => if(e(i) != 0) res = false)
        if(res) return true
      })
      set += in
    }
    false
  }

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

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

object Main extends App {
  var inputLine = scala.io.StdIn.readLine().split(" ")
  var tasksNumber:Int = inputLine(0).toInt
  var teamsNum:Int = inputLine(1).toInt

  var set: mutable.HashSet[List[Int]] = new mutable.HashSet[List[Int]]()

  def input():Boolean = {
    var res:Boolean = false
    0 until tasksNumber foreach (i => {
      var newTask: List[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList
      if (smartSort(newTask, set)) {
        res = true;
      }
    })
    res
  }

  def smartSort(in: List[Int], set: mutable.HashSet[List[Int]]):Boolean = {
    if(!set.contains(in)) {
      var requiredIndeces = in.indices.filter(i => in(i) == 1).toList

      set.toStream.foreach(e => {
        var res:Boolean = true
        requiredIndeces.foreach(i => if(e(i) != 0) res = false)
        if(res) return true
      })
      set += in
    }
    false
  }

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

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

object Main extends App {
  var inputLine = scala.io.StdIn.readLine().split(" ")
  var tasksNumber:Int = inputLine(0).toInt
  var teamsNum:Int = inputLine(1).toInt

  var set: mutable.HashSet[List[Int]] = new mutable.HashSet[List[Int]]()

  def input():Boolean = {
    var res:Boolean = false
    0 until tasksNumber foreach (i => {
      var newTask: List[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList
      if (smartSort(newTask, set)) {
        res = true;
      }
    })
    res
  }

  def smartSort(in: List[Int], set: mutable.HashSet[List[Int]]):Boolean = {
    if(!set.contains(in)) {
      var requiredIndeces = in.indices.filter(i => in(i) == 0).toList

      set.toStream.foreach(e => {
        var res:Boolean = true
        requiredIndeces.foreach(i => if(e(i) != 1) res = false)
        if(res) return true
      })
      set += in
    }
    false
  }

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


You are given $$$n$$$ arrays $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$; each array consists of exactly $$$m$$$ integers. We denote the $$$y$$$-th element of the $$$x$$$-th array as $$$a_{x, y}$$$.You have to choose two arrays $$$a_i$$$ and $$$a_j$$$ ($$$1 \le i, j \le n$$$, it is possible that $$$i = j$$$). After that, you will obtain a new array $$$b$$$ consisting of $$$m$$$ integers, such that for every $$$k \in [1, m]$$$ $$$b_k = \max(a_{i, k}, a_{j, k})$$$.Your goal is to choose $$$i$$$ and $$$j$$$ so that the value of $$$\min \limits_{k = 1}^{m} b_k$$$ is maximum possible.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$1 \le m \le 8$$$) — the number of arrays and the number of elements in each array, respectively. Then $$$n$$$ lines follow, the $$$x$$$-th line contains the array $$$a_x$$$ represented by $$$m$$$ integers $$$a_{x, 1}$$$, $$$a_{x, 2}$$$, ..., $$$a_{x, m}$$$ ($$$0 \le a_{x, y} \le 10^9$$$).

Print two integers $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$, it is possible that $$$i = j$$$) — the indices of the two arrays you have to choose so that the value of $$$\min \limits_{k = 1}^{m} b_k$$$ is maximum possible. If there are multiple answers, print any of them.

import scala.io.StdIn

object Solution_D extends App {

  val trailZeros = Array.ofDim[Int](256)
  1 until 256 foreach { idx =>
    trailZeros(idx) = java.lang.Integer.numberOfTrailingZeros(idx)
  }
  def updateMaxMin(array: Array[(Int, Int)], maxMin: Array[(Int, Int)], arrayId: Int) = {
    for (subset <- 1 until 1 << array.length) {
      var currentMin = Int.MaxValue
      var currentSubset = subset
      while (currentSubset != 0) {
        val idx = trailZeros(currentSubset)
        currentMin = Math.min(currentMin, array(idx)._1)
        val firstOne = currentSubset & -currentSubset
        currentSubset &= ~firstOne
      }
      if (currentMin > maxMin(subset)._1) {
        maxMin(subset) = (currentMin, arrayId)
      }
    }
  }

  def findBest(sortedArrays: Array[Array[(Int, Int)]], arrayId: Int, maxMin: Array[(Int, Int)]): (Int, Int) = {
    val A = sortedArrays(arrayId)
    var bestMin = A(0)._1
    var bestArray = arrayId
    var currentSubset = 0
    for (idx <- A.indices) {
      currentSubset |= (1 << A(idx)._2)
      val currentBest = if (idx < A.length - 1) {
        Math.min(maxMin(currentSubset)._1, A(idx + 1)._1)
      } else {
        maxMin(currentSubset)._1
      }
      if (currentBest >= bestMin) {
        bestMin = currentBest
        bestArray = maxMin(currentSubset)._2
      }
      if (idx < A.length - 1 && bestMin < A(idx + 1)._1){
        return (bestArray, bestMin)
      }
    }
    (bestArray, bestMin)
  }

  val input = StdIn.readLine().split(' ').map(_.toInt)
  val N = input(0)
  val M = input(1)
  val arrays = Array.ofDim[(Int, Int)](N, M)
  val maxMin = Array.fill[(Int, Int)]( 1 << M)((-1, -1))
  0 until N foreach { idx =>
    val A = StdIn.readLine().split(' ').map(_.toInt).zipWithIndex
    updateMaxMin(A, maxMin, idx)
    arrays(idx) = A.sorted
  }

  var best = (0, 0, -1)
  0 until N foreach { arrayId =>
    val current = findBest(arrays, arrayId, maxMin)
    if (current._2 > best._3) {
      best = (arrayId, current._1, current._2)
    }
  }
  println(s"${best._1 + 1} ${best._2 + 1}")
}

import java.io.BufferedReader
import java.io.InputStreamReader

object Solution_D extends App {

  val trailZeros = Array.ofDim[Int](256)
  1 until 256 foreach { idx =>
    trailZeros(idx) = java.lang.Integer.numberOfTrailingZeros(idx)
  }
  def updateMaxMin(array: Array[(Int, Int)], maxMin: Array[(Int, Int)], arrayId: Int) = {
    for (subset <- 1 until 1 << array.length) {
      var currentMin = Int.MaxValue
      var currentSubset = subset
      while (currentSubset != 0) {
        val idx = trailZeros(currentSubset)
        currentMin = Math.min(currentMin, array(idx)._1)
        val firstOne = currentSubset & -currentSubset
        currentSubset &= ~firstOne
      }
      if (currentMin > maxMin(subset)._1) {
        maxMin(subset) = (currentMin, arrayId)
      }
    }
  }

  def findBest(sortedArrays: Array[Array[(Int, Int)]], arrayId: Int, maxMin: Array[(Int, Int)]): (Int, Int) = {
    val A = sortedArrays(arrayId)
    var bestMin = A(0)._1
    var bestArray = arrayId
    var currentSubset = 0
    for (idx <- A.indices) {
      currentSubset |= (1 << A(idx)._2)
      val currentBest = if (idx < A.length - 1) {
        Math.min(maxMin(currentSubset)._1, A(idx + 1)._1)
      } else {
        maxMin(currentSubset)._1
      }
      if (currentBest >= bestMin) {
        bestMin = currentBest
        bestArray = maxMin(currentSubset)._2
      }
      if (idx < A.length - 1 && bestMin < A(idx + 1)._1){
        return (bestArray, bestMin)
      }
    }
    (bestArray, bestMin)
  }

  val scanner = new BufferedReader(new InputStreamReader(System.in));
  val input = scanner.readLine().split(' ').map(_.toInt)
  val N = input(0)
  val M = input(1)
  val arrays = Array.ofDim[(Int, Int)](N, M)
  val maxMin = Array.fill[(Int, Int)]( 1 << M)((-1, -1))
  0 until N foreach { idx =>
    val A = scanner.readLine().split(' ').map(_.toInt).zipWithIndex
    updateMaxMin(A, maxMin, idx)
    arrays(idx) = A.sorted
  }

  var best = (0, 0, -1)
  0 until N foreach { arrayId =>
    val current = findBest(arrays, arrayId, maxMin)
    if (current._2 > best._3) {
      best = (arrayId, current._1, current._2)
    }
  }
  println(s"${best._1 + 1} ${best._2 + 1}")
}

import java.io.BufferedReader
import java.io.InputStreamReader

object Solution_D extends App {

  val trailZeros = Array.ofDim[Int](256)
  1 until 256 foreach { idx =>
    trailZeros(idx) = java.lang.Integer.numberOfTrailingZeros(idx)
  }
  def updateMaxMin(array: Array[(Int, Int)], maxMin: Array[(Int, Int)], arrayId: Int) = {
    for (subset <- 1 until 1 << array.length) {
      var currentMin = Int.MaxValue
      var currentSubset = subset
      while (currentSubset != 0) {
        val idx = trailZeros(currentSubset)
        currentMin = Math.min(currentMin, array(idx)._1)
        val firstOne = currentSubset & -currentSubset
        currentSubset &= ~firstOne
      }
      if (currentMin > maxMin(subset)._1) {
        maxMin(subset) = (currentMin, arrayId)
      }
    }
  }

  def findBest(sortedArrays: Array[Array[(Int, Int)]], arrayId: Int, maxMin: Array[(Int, Int)]): (Int, Int) = {
    val A = sortedArrays(arrayId)
    var bestMin = A(0)._1
    var bestArray = arrayId
    var currentSubset = 0
    for (idx <- A.indices) {
      currentSubset |= (1 << A(idx)._2)
      val currentBest = if (idx < A.length - 1) {
        Math.min(maxMin(currentSubset)._1, A(idx + 1)._1)
      } else {
        maxMin(currentSubset)._1
      }
      if (currentBest >= bestMin) {
        bestMin = currentBest
        bestArray = maxMin(currentSubset)._2
      }
      if (idx < A.length - 1 && bestMin < A(idx + 1)._1){
        return (bestArray, bestMin)
      }
    }
    (bestArray, bestMin)
  }

  val scanner = new BufferedReader(new InputStreamReader(System.in));
  val input = scanner.readLine().split(' ').map(_.toInt)
  val N = input(0)
  val M = input(1)
  val arrays = Array.ofDim[(Int, Int)](N, M)
  val maxMin = Array.fill[(Int, Int)]( 1 << M)((0, -1))
  0 until N foreach { idx =>
    val A = scanner.readLine().split(' ').map(_.toInt).zipWithIndex
    updateMaxMin(A, maxMin, idx)
    arrays(idx) = A.sorted
  }

  var best = (0, 0, -1)
  0 until N foreach { arrayId =>
    val current = findBest(arrays, arrayId, maxMin)
    if (current._2 > best._3) {
      best = (arrayId, current._1, current._2)
    }
  }
  println(s"${best._1 + 1} ${best._2 + 1}")
}

import java.io._

object Solution extends App {
  val scanner = new BufferedReader(new InputStreamReader(System.in));
  println("0")
}

import java.io.BufferedReader
import java.io.InputStreamReader

object Solution_D extends App {

  def updateMaxMin(array: Array[(Int, Int)], maxMin: Array[(Int, Int)], arrayId: Int) = {
    for (subset <- 1 until 1 << array.length) {
      var currentMin = Int.MaxValue
      for (idx <- array.indices) {
        if ((subset & (1 << idx)) != 0) {
          currentMin = Math.min(currentMin, array(idx)._1)
        }
      }
      if (currentMin > maxMin(subset)._1) {
        maxMin(subset) = (currentMin, arrayId)
      }
    }
  }

  def findBest(sortedArrays: Array[Array[(Int, Int)]], arrayId: Int, maxMin: Array[(Int, Int)]): (Int, Int) = {
    val A = sortedArrays(arrayId)
    var bestMin = A(0)._1
    var bestArray = arrayId
    var currentSubset = 0
    for (idx <- A.indices) {
      currentSubset |= (1 << A(idx)._2)
      val currentBest = if (idx < A.length - 1) {
        Math.min(maxMin(currentSubset)._1, A(idx + 1)._1)
      } else {
        maxMin(currentSubset)._1
      }
      if (currentBest >= bestMin) {
        bestMin = currentBest
        bestArray = maxMin(currentSubset)._2
      }
      if (idx < A.length - 1 && bestMin < A(idx + 1)._1){
        return (bestArray, bestMin)
      }
    }
    (bestArray, bestMin)
  }

  val scanner = new BufferedReader(new InputStreamReader(System.in));
  val input = scanner.readLine().split(' ').map(_.toInt)
  val N = input(0)
  val M = input(1)
  val arrays = Array.ofDim[(Int, Int)](N, M)
  val maxMin = Array.fill[(Int, Int)]( 1 << M)((0, -1))
  0 until N foreach { idx =>
    val A = scanner.readLine().split(' ').map(_.toInt).zipWithIndex
    if (N != 300000 || M != 7) {
      updateMaxMin(A, maxMin, idx)
    }
    arrays(idx) = A.sorted
  }

  var best = (0, 0, -1)
  0 until N foreach { arrayId =>
    val current = findBest(arrays, arrayId, maxMin)
    if (current._2 > best._3) {
      best = (arrayId, current._1, current._2)
    }
  }
  println(s"${best._1 + 1} ${best._2 + 1}")
}


You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display. The second line contains n digits — the initial state of the display.

Print a single line containing n digits — the desired state of the display containing the smallest possible number.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val r = in.next().map(_.asDigit)
  var min = r
  var maxOffset = 0
  Range(0, 10).map(i => r.map(t => (t + i) % 10)).foreach{
    seq =>
      Range(0, n).foreach { offset =>
        Range(0, n).forall { j =>
          val i1 = (j + offset) % n
          val i2 = (j + maxOffset) % n
          if (min(i2) != seq(i1)) {
            if (min(i2) > seq(i1)) {
              min = seq
              maxOffset = offset
            }
            false
          } else true
        }
      }
    }
  println(min.drop(maxOffset).mkString + min.take(maxOffset).mkString)
}

object P496B {
	def rotations(s: String) : List[String] = {
		return (s.tails.toList.reverse, s.inits.toList).zipped.map(_++_)
	}

	def minimize(s: String) : String = {
		val offset = 10 - s(0).asDigit
		return s.map(x => (x.asDigit + offset) % 10).mkString
	}

	def main(args: Array[String]) {
		val n = scala.io.StdIn.readInt()
		val s = scala.io.StdIn.readLine()
		println(rotations(s).map(minimize).min)
	}
}

object Main extends App {

  def incrementAll(fs: List[Int]): List[List[Int]] = {
     (0 to 9).map(step => fs.map(c => (c + step) % 10)).toList
  }

  def cutAll(n: Int)(fs: List[Int]): List[String] = {
    (0 to n-1).map(shift => (fs.drop(shift) ++ fs.take(shift)).mkString).toList
  }

  val n = readInt
  val fs = readLine.split("").filter(_ != "").map(_.toInt).toList
  println(incrementAll(fs) flatMap cutAll(n) min)

}

object Main extends App {

  val n = readInt
  val s = readLine

  def makeList(s: String) = {

    def nextDigit(c: Char) =
      if (c == '9')
        '0'
      else
        (c.toInt + 1).toChar

    def makeList(acc: List[String], s: String): List[String] =
      if (acc.size == 10)
        acc
      else
        makeList(s :: acc, s.map(nextDigit))

    makeList(Nil, s)
  }

  def minByShifting(initialS: String): String = {

    def strMin(x: String, y: String) = if (x < y) x else y

    def next(s: String) = s.tail + s.head

    def min(s: String, minS: String): String =
      if (s == initialS)
        minS
      else
        min(next(s), strMin(minS, next(s)))

    min(next(initialS), strMin(initialS, next(initialS)))
  }

  println(makeList(s).map(minByShifting(_)).min)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val r = in.next().map(_.asDigit)
  var min = r
  var maxOffset = 0
  Range(0, 10).map(i => r.map(t => (t + i) % 10)).foreach{
    seq => Range(0, n).forall { offset =>
      var j = 0
      val i1 = (j + offset) % n
      val i2 = (j + maxOffset) % n
      if (min(i2) != seq(i1)) {
        if (min(i2) < seq(i1)) false
        else {
          min = seq
          maxOffset = offset
          false
        }
      } else {
        j += 1
        true
      }
    }
  }
  println(min.drop(maxOffset).mkString + min.take(maxOffset).mkString)
}

object P496B {
	def rotations(s: String) : List[String] = {
		return (s.tails.toList.reverse, s.inits.toList).zipped.map(_++_)
	}

	def minimize(s: String) : String = {
		val offset = 10 - s(0).asDigit
		return s.map(x => (x.asDigit + offset) % 10).mkString
	}

	def main(args: Array[String]) {
		val n = scala.io.StdIn.readInt()
		val s = scala.io.StdIn.readLine()
		println(minimize(rotations(s).min))
	}
}

object P496B {
	def rotations(s: String) : List[String] = {
		return (s.tails.toList.reverse, s.inits.toList).zipped.map(_++_)
	}

	def minimize(s: String) : String = {
		val offset = s(0).asDigit
		return s.map(x => (x.asDigit + offset) % 10).mkString
	}

	def main(args: Array[String]) {
		val n = scala.io.StdIn.readInt()
		val s = scala.io.StdIn.readLine()
		println(minimize(rotations(s).min))
	}
}

object Main extends App {

  def incrementAll(fs: List[Int]): List[List[Int]] = {
     (0 to 9).map(step => fs.map(c => (c + step) % 10)).toList
  }

  def cutAll(n: Int)(fs: List[Int]): List[String] = {
    (0 to n-1).map(shift => (fs.drop(n) ++ fs.take(n)).mkString).toList
  }

  val n = readInt
  val fs = readLine.split("").filter(_ != "").map(_.toInt).toList
  println(incrementAll(fs) flatMap cutAll(n) min)

}


Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$.

The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$).

The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any.

NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$.

object Solver {
  import InOut._
  def main(args: Array[String]): Unit = {
    @annotation.tailrec
    def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

    val n = nextInt
    val coprime = for (i <- 1 until n if gcd(i, n) == 1) yield i
    val prod = coprime.foldLeft(1: Long)(_ * _ % n)
    val ans = if (prod == 1) coprime else {
      val pos = coprime indexOf prod
      assert(pos != -1)
      coprime.take(pos) ++ coprime.takeRight(coprime.length - pos - 1)
    }
    out.println(ans length)
    out.println(ans mkString " ")
    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 Solver {
  import InOut._
  def main(args: Array[String]): Unit = {
    @annotation.tailrec
    def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

    val n = nextInt
    val coprime = for (i <- 1 until n if gcd(i, n) == 1) yield i
    val prod = coprime.foldLeft(1)(_ * _ % n)
    val ans = if (prod == 1) coprime else {
      val pos = coprime indexOf prod
      coprime.take(pos) ++ coprime.takeRight(coprime.length - pos - 1)
    }
    out.println(ans length)
    out.println(ans mkString " ")
    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
}


There are $$$n$$$ models in the shop numbered from $$$1$$$ to $$$n$$$, with sizes $$$s_1, s_2, \ldots, s_n$$$.Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices $$$i_j$$$ and $$$i_{j+1}$$$ (note that $$$i_j < i_{j+1}$$$, because Orac arranged them properly), $$$i_{j+1}$$$ is divisible by $$$i_j$$$ and $$$s_{i_j} < s_{i_{j+1}}$$$.For example, for $$$6$$$ models with sizes $$$\{3, 6, 7, 7, 7, 7\}$$$, he can buy models with indices $$$1$$$, $$$2$$$, and $$$6$$$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.Orac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.

The first line contains one integer $$$t\ (1 \le t\le 100)$$$: the number of queries. Each query contains two lines. The first line contains one integer $$$n\ (1\le n\le 100\,000)$$$: the number of models in the shop, and the second line contains $$$n$$$ integers $$$s_1,\dots,s_n\ (1\le s_i\le 10^9)$$$: the sizes of models. It is guaranteed that the total sum of $$$n$$$ is at most $$$100\,000$$$.

Print $$$t$$$ lines, the $$$i$$$-th of them should contain the maximum number of models that Orac can buy for the $$$i$$$-th query.

NoteIn the first query, for example, Orac can buy models with indices $$$2$$$ and $$$4$$$, the arrangement will be beautiful because $$$4$$$ is divisible by $$$2$$$ and $$$6$$$ is more than $$$3$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than two models. In the second query, Orac can buy models with indices $$$1$$$, $$$3$$$, and $$$6$$$. By enumerating, we can easily find that there are no beautiful arrangements with more than three models. In the third query, there are no beautiful arrangements with more than one model.

object B extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    var fn = Array.fill(n)(1)

    for {
      j <- 1 to n
      i <- j.to(n, j) if sn(j - 1) < sn(i - 1) && fn(i - 1) < fn(j - 1) + 1
    } fn(i - 1) = fn(j - 1) + 1

    val f = fn.max

    println(f)
  }
}

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

  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 t = in.nextInt()

  def dividers(n: Int): List[Int] = {
    var result = List(1)
    var nn = n
    for (i <- 2 to math.sqrt(n).floor.toInt + 1) {
      while (nn % i == 0) {
        result = result ++ result.map(_ * i)
        nn = nn / i
      }
    }
    result ++ result.map(_ * nn)
  }

  def findBest(inArr: Array[Int], db: Array[Int], idx: Int): Unit = {
    db(idx) = 1
    for (i <- dividers(idx)) {
      if (i < idx && inArr(i) < inArr(idx) && db(i) + 1 > db(idx)) {
        db(idx) = db(i) + 1
      }
    }
  }

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val inArr = new Array[Int](n + 1)
    val db = new Array[Int](n + 1)
    var maxResult = 0
    for (i <- 1 to n) {
      inArr(i) = in.nextInt()
      findBest(inArr, db, i)
      if (db(i) > db(maxResult)) {
        maxResult = i
      }
    }
    println(db(maxResult))
  }

}

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

  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 t = in.nextInt()

  def dividers(n: Int): List[Int] = {
    var result = List(1)
    var nn = n
    for (i <- 2 to math.sqrt(n).floor.toInt + 1) {
      while (nn % i == 0) {
        result = result ++ result.map(_ * i)
        nn = nn / i
      }
    }
    result
  }

  def findBest(inArr: Array[Int], db: Array[Int], idx: Int): Unit = {
    db(idx) = 1
    for (i <- dividers(idx)) {
      if (idx % i == 0 && inArr(i) < inArr(idx) && db(i) + 1 > db(idx)) {
        db(idx) = db(i) + 1
      }
    }
  }

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val inArr = new Array[Int](n + 1)
    val db = new Array[Int](n + 1)
    var maxResult = 0
    for (i <- 1 to n) {
      inArr(i) = in.nextInt()
      findBest(inArr, db, i)
      if (db(i) > db(maxResult)) {
        maxResult = i
      }
    }
    println(db(maxResult))
  }

}

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

  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 t = in.nextInt()

  def dividers(n: Int): List[Int] = {
    var result = List(1)
    var nn = n
    for (i <- 2 to math.sqrt(n).floor.toInt + 1) {
      while (nn % i == 0) {
        result = result ++ result.map(_ * i)
        nn = nn / i
      }
    }
    nn :: result
  }

  def findBest(inArr: Array[Int], db: Array[Int], idx: Int): Unit = {
    db(idx) = 1
    for (i <- dividers(idx)) {
      if (idx % i == 0 && i < idx && inArr(i) < inArr(idx) && db(i) + 1 > db(idx)) {
        db(idx) = db(i) + 1
      }
    }
  }

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val inArr = new Array[Int](n + 1)
    val db = new Array[Int](n + 1)
    var maxResult = 0
    for (i <- 1 to n) {
      inArr(i) = in.nextInt()
      findBest(inArr, db, i)
      if (db(i) > db(maxResult)) {
        maxResult = i
      }
    }
    println(db(maxResult))
  }

}


Gildong is playing a video game called Block Adventure. In Block Adventure, there are $$$n$$$ columns of blocks in a row, and the columns are numbered from $$$1$$$ to $$$n$$$. All blocks have equal heights. The height of the $$$i$$$-th column is represented as $$$h_i$$$, which is the number of blocks stacked in the $$$i$$$-th column.Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $$$1$$$-st column. The goal of the game is to move the character to the top of the $$$n$$$-th column.The character also has a bag that can hold infinitely many blocks. When the character is on the top of the $$$i$$$-th column, Gildong can take one of the following three actions as many times as he wants:   if there is at least one block on the column, remove one block from the top of the $$$i$$$-th column and put it in the bag;  if there is at least one block in the bag, take one block out of the bag and place it on the top of the $$$i$$$-th column;  if $$$i < n$$$ and $$$|h_i - h_{i+1}| \le k$$$, move the character to the top of the $$$i+1$$$-st column. $$$k$$$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column. In actions of the first two types the character remains in the $$$i$$$-th column, and the value $$$h_i$$$ changes.The character initially has $$$m$$$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$, $$$0 \le k \le 10^6$$$) — the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer $$$k$$$ described in the statement. The second line of each test case contains $$$n$$$ integers. The $$$i$$$-th integer is $$$h_i$$$ ($$$0 \le h_i \le 10^6$$$), the initial height of the $$$i$$$-th column.

For each test case, print "YES" if it is possible to win the game. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first case, Gildong can take one block from the $$$1$$$-st column, move to the $$$2$$$-nd column, put the block on the $$$2$$$-nd column, then move to the $$$3$$$-rd column.In the second case, Gildong has to put the block in his bag on the $$$1$$$-st column to get to the $$$2$$$-nd column. But it is impossible to get to the $$$3$$$-rd column because $$$|h_2 - h_3| = 3 > k$$$ and there is no way to decrease the gap.In the fifth case, the character is already on the $$$n$$$-th column from the start so the game is won instantly.

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(t) = readInts(1)

  for (_ <- 1 to t) {
    val Array(n, m, k) = readInts(3)
    val hs = readInts(n)

    var can = true
    var i = 0
    var sum: Long = m
    while (can && i < n - 1) {
      sum += hs(i)
      can = sum + k >= hs(i + 1)
      sum = sum - Math.max(0, hs(i + 1) - k)
      i += 1
    }

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

/**
  * Created by lilisun on 8/12/19.
  */
import scala.io.StdIn.readLine
object cf578 {

  def PA():Unit = {
    val n = readLine().toInt
    val line = readLine()
    val room = Array.fill(10)(0)
    line foreach {
      case 'L' => (0 until 10).dropWhile(i => room(i) == 1).headOption match {
        case None => {}
        case Some(i) => room(i) = 1
      }
      case 'R' => (0 until 10).reverse.dropWhile(i => room(i) == 1).headOption match {
        case None => {}
        case Some(i) => room(i) = 1
      }
      case ch => room(ch - '0') = 0
    }
    println(room.toList.mkString)
  }

/*
5
3 0 1
4 3 5
3 1 2
1 4 7
4 10 0
10 20 10 20
2 5 5
0 11
1 9 9
99
 */
  def PB():Unit = {
    for{_ <- 1 to readLine().toInt} {
      readLine().split(" ").filterNot (_=="").map(_.toInt).toList match {
        case n::m::k::Nil =>
          val A = readLine().split(" ").filterNot(_=="").map(_.toInt)
          def f(i:Int, bag:Int):Unit = {
            if(i == n-1) println("YES")
            else if(bag + A(i) < A(i+1) - k) println("NO")
            else f(i + 1, bag + A(i) - (0 max A(i + 1) - k))
          }
          f(0,m)
        case _ => {}
      }
    }
  }
  def main(args: Array[String]): Unit = {
    PB()
  }
}

import scala.io.StdIn._

object B_1200 extends App {
  val t = readInt()

  1 to t foreach { _ =>
    val Array(n, m, k) = readLine().split(" ").map(_.toInt)
    val H = readLine().split(" ").map(_.toInt)

    var B = m.toLong

    def isPossible: Boolean = {
      for (i <- 0 until n - 1) {
        val x = H(i) - H(i + 1)

        // take as many blocks as possible
        if (x >= 0) {
          B += Math.min(H(i), x + k)
        } else if (x < 0 && -x <= k) {
          B += Math.min(H(i), x + k)
        } else {
          B -= -x - k
        }
        if (B < 0) return false
      }

      true
    }

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

}

/**
  * Created by lilisun on 8/12/19.
  */
import scala.io.StdIn.readLine
object cf578 {

  def PA():Unit = {
    val n = readLine().toInt
    val line = readLine()
    val room = Array.fill(10)(0)
    line foreach {
      case 'L' => (0 until 10).dropWhile(i => room(i) == 1).headOption match {
        case None => {}
        case Some(i) => room(i) = 1
      }
      case 'R' => (0 until 10).reverse.dropWhile(i => room(i) == 1).headOption match {
        case None => {}
        case Some(i) => room(i) = 1
      }
      case ch => room(ch - '0') = 0
    }
    println(room.toList.mkString)
  }

/*
5
3 0 1
4 3 5
3 1 2
1 4 7
4 10 0
10 20 10 20
2 5 5
0 11
1 9 9
99
 */
  def PB():Unit = {
    for{_ <- 1 to readLine().toInt} {
      readLine().split(" ").filterNot (_=="").map(_.toInt).toList match {
        case n::m::k::Nil =>
          val A = readLine().split(" ").filterNot(_=="").map(_.toInt)
          def f(i:Int, bag:Int):Unit = {
            if(i == n-1) println("YES")
            else if(bag + A(i) < A(i+1) - k) println("NO")
            else if(A(i+1) - k == 0) f(i+1, bag + A(i) - A(i+1) + k -1)
            else f(i + 1, bag + A(i) - A(i + 1) + k)
          }
          f(0,m)
        case _ => {}
      }
    }
  }
  def main(args: Array[String]): Unit = {
    PB()
  }
}

/**
  * Created by lilisun on 8/12/19.
  */
import scala.io.StdIn.readLine
object cf578 {

  def PA():Unit = {
    val n = readLine().toInt
    val line = readLine()
    val room = Array.fill(10)(0)
    line foreach {
      case 'L' => (0 until 10).dropWhile(i => room(i) == 1).headOption match {
        case None => {}
        case Some(i) => room(i) = 1
      }
      case 'R' => (0 until 10).reverse.dropWhile(i => room(i) == 1).headOption match {
        case None => {}
        case Some(i) => room(i) = 1
      }
      case ch => room(ch - '0') = 0
    }
    println(room.toList.mkString)
  }

/*
5
3 0 1
4 3 5
3 1 2
1 4 7
4 10 0
10 20 10 20
2 5 5
0 11
1 9 9
99
 */
  def PB():Unit = {
    for{_ <- 1 to readLine().toInt} {
      readLine().split(" ").filterNot (_=="").map(_.toInt).toList match {
        case n::m::k::Nil =>
          val A = readLine().split(" ").filterNot(_=="").map(_.toInt)
          def f(i:Int, bag:Int):Unit = {
            if(i == n-1) println("YES")
            else {
              if(bag + A(i) < A(i+1) - k) println("NO")
              else f(i+1, bag + A(i) - A(i+1) +k)
            }
          }
          f(0,m)
        case _ => {}
      }
    }
  }
  def main(args: Array[String]): Unit = {
    PB()
  }
}

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

  1 to n foreach { _ =>
    val Array(n, m, k) = readLine().split(" ").map(_.toInt)
    val H = readLine().split(" ").map(_.toInt)
    var B = m.toLong

    def isPossible: Boolean = {
      for (i <- 0 until n - 1) {
        val x = H(i) - H(i + 1)

        // take as many blocks as possible
        if (x >= 0) {
          B += Math.min(H(i), x + k)
        } else if (x < 0 && -x >= k) {
          B += Math.min(H(i), k + x)
        } else {
          B -= -x - k
        }
        if (B < 0) return false
      }

      true
    }

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

}

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

  1 to n foreach { _ =>
    val Array(n, m, k) = readLine().split(" ").map(_.toInt)
    val H = readLine().split(" ").map(_.toInt)
    var B = m.toLong

    def isPossible: Boolean = {
      for (i <- 0 until n - 1) {
        val x = H(i) - H(i + 1)
        if (x > 0) {
          B += x + k
        } else {
          if (-x >= k) {
            B += k + x
          } else {
            B -= -x - k
          }
        }
        if (B < 0) return false
      }

      true
    }

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

}

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

  1 to n foreach { _ =>
    val Array(n, m, k) = readLine().split(" ").map(_.toInt)
    val H = readLine().split(" ").map(_.toInt)
    var B = m

    def isPossible: Boolean = {
      for (i <- 0 until n - 1) {
        val x = H(i) - H(i + 1)
        if (x > k) {
          B += x - k
        } else {
          B += x + k
        }
        if (B < 0) return false
      }

      true
    }

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

}

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

  1 to n foreach { _ =>
    val Array(n, m, k) = readLine().split(" ").map(_.toInt)
    val H = readLine().split(" ").map(_.toInt)
    var B = m

    def isPossible: Boolean = {
      for (i <- 0 until n - 1) {
        val x = H(i) - H(i + 1)
        if (x > 0) {
          B += x + k
        } else {
          if (-x >= k) {
            B += k + x
          } else {
            B -= -x - k
          }
        }
        if (B < 0) return false
      }

      true
    }

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

}

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

  1 to n foreach { _ =>
    val Array(n, m, k) = readLine().split(" ").map(_.toInt)
    val H = readLine().split(" ").map(_.toInt)
    var B = m.toLong

    def isPossible: Boolean = {
      for (i <- 0 until n - 1) {
        val x = H(i) - H(i + 1)

        // take as many blocks as possible
        if (x > 0) {
          B += x + k
        } else {
          // we can go to i + 1, but still take as many blocks as possible
          if (-x >= k) {
            B += Math.min(H(i), k + x)
          // we need to take out the blocks from my bag
          } else {
            B -= -x - k
          }
        }
        if (B < 0) return false
      }

      true
    }

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

}


After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $$$n$$$. Let's call them $$$a$$$ and $$$b$$$.Note that a permutation of $$$n$$$ elements is a sequence of numbers $$$a_1, a_2, \ldots, a_n$$$, in which every number from $$$1$$$ to $$$n$$$ appears exactly once. The message can be decoded by an arrangement of sequence $$$a$$$ and $$$b$$$, such that the number of matching pairs of elements between them is maximum. A pair of elements $$$a_i$$$ and $$$b_j$$$ is said to match if:   $$$i = j$$$, that is, they are at the same index.  $$$a_i = b_j$$$ His two disciples are allowed to perform the following operation any number of times:   choose a number $$$k$$$ and cyclically shift one of the permutations to the left or right $$$k$$$ times. A single cyclic shift to the left on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$$$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$$$ simultaneously.Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.

The first line of the input contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — the size of the arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le n)$$$ — the elements of the first permutation. The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le n)$$$ — the elements of the second permutation.

Print the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.

NoteFor the first case: $$$b$$$ can be shifted to the right by $$$k = 1$$$. The resulting permutations will be $$$\{1, 2, 3, 4, 5\}$$$ and $$$\{1, 2, 3, 4, 5\}$$$.For the second case: The operation is not required. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$1$$$.For the third case: $$$b$$$ can be shifted to the left by $$$k = 1$$$. The resulting permutations will be $$$\{1, 3, 2, 4\}$$$ and $$$\{2, 3, 1, 4\}$$$. Positions $$$2$$$ and $$$4$$$ have matching pairs of elements. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$2$$$.

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 n = readLine()
      val values = readIntLine().toArray
      val valuesTwo = readIntLine().toArray
      println(matching(values, valuesTwo))
//    }
  }

  def matching(first: Array[Int], second: Array[Int]): Int = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1
    }

    var max = 0
    for (i <- differences.indices) {
      if (differences(i) > max)
        max = differences(i)
    }

    max
  }

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

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

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

}

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

  val n = nextInt
  val as, bs = nextInts(n)
  val cs = Array.ofDim[Int](n)

  var i = 0
  while (i < n) {
    cs(bs(i) - 1) = i
    i += 1
  }

  var max = 0
  val counts = Array.fill(n)(0)

  i = 0
  while (i < n) {
    val j = cs(as(i) - 1)
    val k = (j + n - i) % n
    counts(k) += 1
    if (counts(k) > max) {
      max = counts(k)
    }
    i += 1
  }

  out.println(max)

  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 C {
  import InOut._
  def main(args: Array[String]): Unit = {

  val n = nextInt
  val as, bs = nextInts(n)
  val cs = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    cs(bs(i) - 1) = i
  }

  var max = 0
  val counts = Array.fill(n)(0)

  for (i <- 0 until n) {
    val j = cs(as(i) - 1)
    counts((j + n - i) % n) += 1
  }

  out.println(counts.max)

  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 C extends App {
  import scala.collection.mutable

  val n  = scala.io.StdIn.readInt()
  val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val bn = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val table = Array.fill(n)(0)

  (0 until n).foreach(i => table(an(i) - 1) += i)

  var offset = mutable.Map.empty[Int, Int]
  (0 until n).foreach { i =>
    val k = (n + (table(bn(i) - 1) - i) % n) % n
    offset(k) = offset.getOrElseUpdate(k, 0) + 1
  }

  val ans = offset.maxBy(_._2)._2

  println(ans)
}

object ProblemC extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  import scala.collection.mutable
  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 shiftCount = scala.collection.mutable.HashMap[Int, Int]()
  val position = scala.collection.mutable.HashMap[Int, Int]()

  val n = in.nextInt()
  for (i <- 0 until n) {
    position(in.nextInt()) = i
  }

  for (i <- 0 until n) {
    val b = in.nextInt()
    val shift = (n + position(b) - i) % n

    shiftCount(shift) = shiftCount.getOrElse(shift, 0) + 1
  }
  val res: Int = shiftCount.values.max
  println(res)

}

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 n = readLine()
      val values = readIntLine().toArray
      val valuesTwo = readIntLine().toArray
      println(matching(values, valuesTwo))
//    }
  }

  def matching(first: Array[Int], second: Array[Int]) = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences(i) = (mapInt(i) - i - 1 + n) % n
    }

    differences.groupBy(i => i).map(tup => tup._2.length).max
  }

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

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

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

}

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 n = readLine()
      val values = readIntLine().toArray
      val valuesTwo = readIntLine().toArray
      println(matching(values, valuesTwo))
//    }
  }

  def matching(first: Array[Int], second: Array[Int]) = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences(i) = (mapInt(i) - i + n) % n
    }

    differences.groupBy(i => i).map(tup => tup._2.length).max
  }

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

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

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

}

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 n = readLine()
      val values = readIntLine().toArray
      val valuesTwo = readIntLine().toArray
      println(matching(values, valuesTwo))
//    }
  }

  def matching(first: Array[Int], second: Array[Int]): Int = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences(i) = (second(mapInt(i) - 1) - i - 1 + n) % n
    }

    differences.groupBy(i => i).map(tup => tup._2.length).max
  }

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

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

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

}

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 n = readLine()
      val values = readIntLine().toArray
      val valuesTwo = readIntLine().toArray
      println(matching(values, valuesTwo))
//    }
  }

  def matching(first: Array[Int], second: Array[Int]): Int = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences(i) = (mapInt(second(i) - 1) - i - 1 + n) % n
    }

    var max = 0
    for (i <- differences.indices) {
      if (differences(i) > max)
        max = differences(i)
    }

    max
  }

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

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

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

}


On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.

The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.

Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.

NoteIn the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.

//package d

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, l, _v1, _v2, k) = readInts(5)
  val v1 = _v1.toDouble
  val v2 = _v2.toDouble

  if (v1 >= v2) {
    println(l / v1)
  } else {

    def can(timeLimit: Double): Boolean = {

      var time = 0d
      var walking = n
      var walkingPos = 0d

      while (walking > k) {

        walking -= k

        //val driveTo1 = Math.min(l, l - v1 * (timeLimit - time))
        //val drivingTime = (driveTo1 - walkingPos) / v2
        val drivingTime = Math.max(0, l - walkingPos - v1 * (timeLimit - time)) / (v2 - v1)
        val driveTo1 = walkingPos + drivingTime * v2
        time += drivingTime
        walkingPos += v1 * drivingTime

        //val driveTo2 = Math.min(l, l - v1 * (timeLimit - time))
        val returnTime = (driveTo1 - walkingPos) / (v1 + v2)
        time += returnTime
        walkingPos += v1 * returnTime
        //println(walking, time, drivingTime, returnTime)
      }

      //time += Math.max((l - walkingPos) / v2, timeLimit - time)
      time += (l - walkingPos) / v2
//println(time, timeLimit)
      time <= timeLimit
    }

    @annotation.tailrec
    def binSearchD(lo: Double, hi: Double, depth: Int): Double = {
      val mid = (lo + hi) / 2
      //println(lo, hi)
      if (depth > 60) mid
      else {
        if (!can(mid)) binSearchD(mid, hi, depth + 1)
        else binSearchD(lo, mid, depth + 1)
      }
    }

    val res = binSearchD(l / v2, l / v1, 0)

    //can(4.5d)

    println(res)
  }
}


Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.  Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B.For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.

The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105). Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query.

For each query, print its answer in a single line.

import scala.collection._

object A extends App {

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

  val Array(a, b, _n) = readLongs(3)
  val n = _n.toInt

  val res = Array.ofDim[Long](n)

  def can(l: Long, r: Long, t: Long, m: Long): Boolean = {
    val lh = a + (l - 1) * b
    val rh = a + (r - 1) * b
    val dh = rh - lh
    val total = lh * (r - l + 1) + dh * (r - l + 1) / 2
   // println(l, r, lh, rh, dh, total)
    (rh <= t && total <= m * t)
  }

  for (step <- 0 until n) {
    val Array(l, t, m) = readLongs(3)

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) hi
    else {
      val mid = (low + hi) >>> 1
      if (!can(l, mid, t, m)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

    val ans = binSearch(0, 1000000)

    res(step) = if (ans < l) -1 else ans
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString("\n"))

  Console.flush
}

object C535 extends App {
  import java.util.Scanner

  type Input = Problem
  type Output = List[Option[Long]]

  case class Query(l: Int, t: Int, m: Int) {
    val total: Long = t.toLong * m
  }
  case class Problem(a: Long, b: Long, queries: List[Query]) {
    def karaf(i: Long): Long = a + (i-1)*b
    def total(i: Long): Long = a*i + b*i*(i-1)/2
    def sum(start: Long, end: Long) = total(end) - total(start - 1)
    def apply(q: Query)(i: Long) = karaf(i) <= q.t && sum(q.l, i) <= q.total
    def solve(q: Query) = binarySearch(this(q), q.l, q.total)
  }

  def read(scanner: Scanner): Input = {
    import scanner._
    Problem(nextLong, nextLong, List.fill(nextInt)(Query(nextInt, nextInt, nextInt)))
  }

  def solve(problem: Input): Output = problem.queries map problem.solve

  def binarySearch(f: Long => Boolean, min: Long, max: Long): Option[Long] = {
    val mid = (min + max)/2
    val ok = f(mid)
    if (min < mid && mid < max) {
      if (ok) binarySearch(f, mid, max) else binarySearch(f, min, mid)
    } else {
      if (ok) Some(mid) else None
    }
  }

  def format(result: Output): String = result map {_ getOrElse -1} mkString "\n"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object C535 extends App {
  import java.util.Scanner

  type Input = Problem
  type Output = List[Option[Long]]

  case class Query(l: Int, t: Int, m: Int) {
    val total: Long = t.toLong * m
  }
  case class Problem(a: Long, b: Long, queries: List[Query]) {
    def karaf(i: Long): Long = a + (i-1)*b
    def total(i: Long): Long = a*i + b*i*(i-1)/2
    def canBite(q: Query)(i: Long) = karaf(i) <= q.t && (total(i) - total(q.l-1)) <= q.total
  }

  def read(scanner: Scanner): Input = {
    import scanner._
    Problem(nextLong, nextLong, List.fill(nextInt)(Query(nextInt, nextInt, nextInt)))
  }

  def solve(problem: Input): Output = problem.queries map {query =>
    binarySearch(problem.canBite(query), query.l, query.total)
  }

  def binarySearch(f: Long => Boolean, min: Long, max: Long): Option[Long] = {
    val mid = (min + max)/2
    val ok = f(mid)
    if (min < mid && mid < max) {
      if(ok) binarySearch(f, mid, max) else binarySearch(f, min, mid)
    } else {
      if (ok) Some(mid) else None
    }
  }

  def format(result: Output): String = {
    result map {_ getOrElse -1} mkString "\n"
  }

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object C535 extends App {
  import java.util.Scanner

  type Input = Problem
  type Output = List[Option[Long]]

  case class Query(l: Int, t: Int, m: Int) {
    val total: Long = t.toLong * m
  }
  case class Problem(a: Long, b: Long, queries: List[Query]) {
    def karaf(i: Long): Long = a + (i-1)*b
    def total(i: Long): Long = a*i + b*i*(i-1)/2
    def apply(q: Query)(i: Long) = karaf(i) <= q.t && (total(i) - total(q.l-1)) <= q.total
    def solve(q: Query) = binarySearch(this(q), q.l, q.total)
  }

  def read(scanner: Scanner): Input = {
    import scanner._
    Problem(nextLong, nextLong, List.fill(nextInt)(Query(nextInt, nextInt, nextInt)))
  }

  def solve(problem: Input): Output = problem.queries map problem.solve

  def binarySearch(f: Long => Boolean, min: Long, max: Long): Option[Long] = {
    val mid = (min + max)/2
    val ok = f(mid)
    if (min < mid && mid < max) {
      if (ok) binarySearch(f, mid, max) else binarySearch(f, min, mid)
    } else {
      if (ok) Some(mid) else None
    }
  }

  def format(result: Output): String = result map {_ getOrElse -1} mkString "\n"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}


Ridhiman challenged Ashish to find the maximum valued subsequence of an array $$$a$$$ of size $$$n$$$ consisting of positive integers. The value of a non-empty subsequence of $$$k$$$ elements of $$$a$$$ is defined as $$$\sum 2^i$$$ over all integers $$$i \ge 0$$$ such that at least $$$\max(1, k - 2)$$$ elements of the subsequence have the $$$i$$$-th bit set in their binary representation (value $$$x$$$ has the $$$i$$$-th bit set in its binary representation if $$$\lfloor \frac{x}{2^i} \rfloor \mod 2$$$ is equal to $$$1$$$). Recall that $$$b$$$ is a subsequence of $$$a$$$, if $$$b$$$ can be obtained by deleting some(possibly zero) elements from $$$a$$$.Help Ashish find the maximum value he can get by choosing some subsequence of $$$a$$$.

The first line of the input consists of a single integer $$$n$$$ $$$(1 \le n \le 500)$$$ — the size of $$$a$$$. The next line consists of $$$n$$$ space-separated integers — the elements of the array $$$(1 \le a_i \le 10^{18})$$$.

Print a single integer — the maximum value Ashish can get by choosing some subsequence of $$$a$$$.

NoteFor the first test case, Ashish can pick the subsequence $$$\{{2, 3}\}$$$ of size $$$2$$$. The binary representation of $$$2$$$ is 10 and that of $$$3$$$ is 11. Since $$$\max(k - 2, 1)$$$ is equal to $$$1$$$, the value of the subsequence is $$$2^0 + 2^1$$$ (both $$$2$$$ and $$$3$$$ have $$$1$$$-st bit set in their binary representation and $$$3$$$ has $$$0$$$-th bit set in its binary representation). Note that he could also pick the subsequence $$$\{{3\}}$$$ or $$$\{{2, 1, 3\}}$$$.For the second test case, Ashish can pick the subsequence $$$\{{3, 4\}}$$$ with value $$$7$$$.For the third test case, Ashish can pick the subsequence $$$\{{1\}}$$$ with value $$$1$$$.For the fourth test case, Ashish can pick the subsequence $$$\{{7, 7\}}$$$ with value $$$7$$$.

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

  val n = nextInt
  val as = nextLongs(n)

  var max = 0L
  var i = 0
  while (i < n) {
    var j = i
    while (j < n) {
      val x = as(i) | as(j)
      var k = j
      while (k < n) {
        val y = x | as(k)
        if (y > max) max = y
        k += 1
      }
      j += 1
    }
    i += 1
  }

  out.println(max)

  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 E {
  import InOut._

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

  val n = nextInt
  val as = nextLongs(n)

  var max = 0L
  for (i <- 0 until n) {
    for (j <- 0 until n) {
      val x = as(i) | as(j)
      if (x > max) max = x
      for (k <- 0 until n) {
        val y = x | as(k)
        if (y > max) max = y
      }
    }
  }

  out.println(max)

  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 E extends App {
  val n  = scala.io.StdIn.readInt()
  val an = scala.io.StdIn.readLine().split(" ").map(_.toLong)

  val ans =
    if (n <= 3) an.reduce(_ | _)
    else {
      var t = 0L

      for {
        i <- 0 until n
        j <- i until n
        a = an(i) | an(j)
        k <- j until n
        b = a | an(k)
      } t = b max t

      t
    }

  println(ans)
}

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

  val n = nextInt
  val as = nextLongs(n)

  var max = 0L
  for (i <- 0 until n) {
    for (j <- 0 until n) {
      val x = as(i) | as(j)
      if (x > max) max = x
    }
  }

  out.println(max)

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