Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \dots, i$$$ by $$$1$$$.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \dots, n$$$ by $$$1$$$.  Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$)  — the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the initial levels of trees moisture.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.

For each test case output a single integer — the minimum number of actions. It can be shown that the answer exists.

NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$.

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max}
  import scala.List
  import scala.collection.mutable.ListBuffer
  val n = readInt()
  for (i <- 1 to n){
    val k = readInt()
    val l = readLine.split(" ").map(_.toInt)
    val buf = scala.collection.mutable.ListBuffer.empty[Int]
    for (j <- 0 until l.length-1) {
      buf += (l(j) - l(j+1))
    }
    val b = buf.toList
    var t: Long  = 0
    var m: Long = 0
    val q = l(l.length-1)
    for (a <- b) {
      t+=abs(a)
      if (a < 0) {
        m +=a
      }

    }
    println(t+abs(q+m))
  }

}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.{abs,max}
  import scala.List
  import scala.collection.mutable.ListBuffer
  val n = readInt()
  for (i <- 1 to n){
    val k = readInt()
    val l = readLine.split(" ").map(_.toInt)
    val buf = scala.collection.mutable.ListBuffer.empty[Int]
    for (j <- 0 until l.length-1) {
      buf += (l(j) - l(j+1))
    }
    val b = buf.toList
    var t = 0
    var m = 0
    val q = l(l.length-1)
    for (a <- b) {
      t+=abs(a)
      if (a < 0) {
        m +=a
      }

    }
    println(t+abs(q+m))
  }

}


Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\,010\,111$$$ is a binary decimal, while $$$10\,201$$$ and $$$787\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$), denoting the number to be represented.

For each test case, output the smallest number of binary decimals required to represent $$$n$$$ as a sum.

NoteIn the first test case, $$$121$$$ can be represented as $$$121 = 110 + 11$$$ or $$$121 = 111 + 10$$$.In the second test case, $$$5$$$ can be represented as $$$5 = 1 + 1 + 1 + 1 + 1$$$.In the third test case, $$$1\,000\,000\,000$$$ is a binary decimal itself, thus the answer is $$$1$$$.

object Main extends Solution {
  override def solve(): Any = {
    (1 to nextInt).foreach(_ => println(nextInt.toString.max))
  }
}

trait Solution extends FastIO {
  val cases = 1
  lazy val isLocal: Boolean = sys.props.get("CLown1331").exists(_.toBoolean)
  override val isFileInput: Boolean = isLocal
  override val isFileOutput: Boolean = false

  def debug(x: => Any): Unit = if (isLocal) println(x)

  def solve(): Any

  def main(args: Array[String]): Unit = {
    if (isLocal)
      (1 to cases).foreach(_ => solve())
    else
      solve()
    flush()
  }
}

trait FastIO {

  import java.io._

  val isFileInput = false
  val isFileOutput = false
  val input = "res/in.txt"
  val output = "res/out.txt"

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

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

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

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

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

  def readLine: String = bf.readLine()

  def println(o: Any): Unit = out.println(o)

  def print(o: Any): Unit = out.print(o)

  def printf(s: String, o: Any*): PrintWriter = out.printf(s, o)

  def flush(): Unit = out.flush()
}

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

  val t = readInt()

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

    val ans = n.max

    println(ans)
  }
}


The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.Find any longest k-good segment.As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·105) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 106) — the elements of the array a.

Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.

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

object Solution extends App {
  val nks = readLine().split(" ")
  val nk = nks.map(_.toInt)

  val n = nk(0)
  val k = nk(1)

  val arr = readLine().split(" ")
  val inp = arr.map(_.toInt)

  val a = new Array[Int](1000001)

  var l = 0
  var r = 0
  var maxans = 0
  var maxR = 0
  var maxL = 0
  var curent = 0

  for ( r <- 0 to (n-1) ) {
      a ( inp(r) ) = a ( inp ( r ) ) + 1

      if ( a ( inp ( r ) ) == 1 ) {
        curent = curent + 1
      }

      if ( curent <= k ) {
        if ( r - l + 1 > maxans ) {
          maxR = r
          maxL = l
          maxans = r - l + 1
        }
      }

      while ( curent > k ) {
        a ( inp ( l ) ) = a ( inp ( l ) ) - 1

        if ( a ( inp ( l ) ) == 0 ) {
          curent = curent - 1
        }

        l = l + 1
      }

  }

  println ( (maxL+1) + " " + (maxR+1) )

}


A rectangle with its opposite corners in $$$(0, 0)$$$ and $$$(w, h)$$$ and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that:   exactly two of them belong to the same side of a rectangle;  the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$w$$$ and $$$h$$$ ($$$3 \le w, h \le 10^6$$$) — the coordinates of the corner of a rectangle. The next two lines contain the description of the points on two horizontal sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$x_1 < x_2 < \dots < x_k$$$ ($$$0 < x_i < w$$$) — the $$$x$$$ coordinates of the points in the ascending order. The $$$y$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$h$$$. The next two lines contain the description of the points on two vertical sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$y_1 < y_2 < \dots < y_k$$$ ($$$0 < y_i < h$$$) — the $$$y$$$ coordinates of the points in the ascending order. The $$$x$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$w$$$. The total number of points on all sides in all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.

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(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * a.compareTo(that.a)
        }
    }

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

    val t = readInt()

    for (tt <- 1 to t) {
        val w = readLong()
        val h = readLong()
        var x = 0L
        var y = 0L
        for (i <- 1 to 4){
            val k = readInt()
            val mn = readInt()
            var mx = 0
            for (j <- 2 to k) {
                mx = readInt()
            }
            if (i < 3)
                x = max(x, (mx - mn).toLong)
            else
                y = max(y, (mx - mn).toLong)
        }
        writer.println(max(x * h, y * w))

        def check(kk: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(st))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(st, mid)
            else
                return bs(mid, en)
        }
    }
    writer.flush()
}


Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.

Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.

import scala.io.StdIn.readLine

object Main extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val a = 1 :: readLine().split(" ").map(_.toInt).toList
  val intervals = a.zip(a.tail)
  val ans = intervals.map(cost).sum
  println(ans)

  def cost(interval: (Int, Int)): Long = {
    val (s, e) = interval
    if (s > e) (n - s + 1) + (e - 1)
    else e - s
  }
}

object cf extends App {
  import java.util.Scanner
  val in = new Scanner(System.in)

  val n, m = in.nextInt
  val a = for (i <- 1 to m) yield in.nextInt
  val res = (1 :: a.toList).sliding(2)
  .foldLeft(0L)((sum, pos) => {
    sum + ((pos(1) + n) - pos(0)) % n
  })
  println(res)
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def solve() {
		val (n,m) = (nextInt,nextInt)
		val a = for (i <- 1 to m) yield nextInt

		var cur = 1
		var ans = 0l
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	val in = new BufferedReader(new InputStreamReader(System.in))
	var st = new StringTokenizer("")

	def next : String = {
		while (!st.hasMoreTokens) {
			val line = in.readLine
			if (line == null) return null
			eat(line)
		}
		st.nextToken
	}

	def eat( s : String ) = st = new StringTokenizer(s)
	def nextInt = next.toInt
	def nextLong = next.toLong
	def nextDouble = next.toDouble

	def main(args: Array[String]) {
		eat("")
		solve
	}
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def solve() {
		val n = nextInt
		val m = nextInt
		val a = for (i <- 1 to m) yield nextInt

		var cur = 1
		var ans = 0l
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	val in = new BufferedReader(new InputStreamReader(System.in))
	var st = new StringTokenizer("")

	def next : String = {
		while (!st.hasMoreTokens) {
			val line = in.readLine
			if (line == null) return null
			eat(line)
		}
		st.nextToken
	}

	def eat( s : String ) = st = new StringTokenizer(s)
	def nextInt = next.toInt
	def nextLong = next.toLong
	def nextDouble = next.toDouble

	def main(args: Array[String]) {
		eat("")
		solve
	}
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def main(args: Array[String]) {
		val in = new FastReader
		//val n = in.nextInt
		//val m = in.nextInt
		val (n,m) = (in.nextInt,in.nextInt)
		val a = for (i <- 1 to m) yield in.nextInt

		var cur = 1
		var ans = 0l
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	class FastReader {
		val in = new BufferedReader(new InputStreamReader(System.in))
		var st = new StringTokenizer("")

		def FastReader {
			eat("")
		}

		def next : String = {
			while (!st.hasMoreTokens) {
				val line = in.readLine
				if (line == null) return null
				eat(line)
			}
			st.nextToken
		}

		def eat( s : String ) = st = new StringTokenizer(s)
		def nextInt = next.toInt
		def nextLong = next.toLong
		def nextDouble = next.toDouble
	}

}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def main(args: Array[String]) {
		val in = new FastReader
		val n = in.nextInt
		val m = in.nextInt
		val a = for (i <- 1 to m) yield in.nextInt

		var cur = 1
		var ans = 0l
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	class FastReader {
		val in = new BufferedReader(new InputStreamReader(System.in))
		var st = new StringTokenizer("")

		def FastReader {
			eat("")
		}

		def next : String = {
			while (!st.hasMoreTokens) {
				val line = in.readLine
				if (line == null) return null
				eat(line)
			}
			st.nextToken
		}

		def eat( s : String ) = st = new StringTokenizer(s)
		def nextInt = next.toInt
		def nextLong = next.toLong
		def nextDouble = next.toDouble
	}

}

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

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val house = readInts(m)
    var curr = 1
    var res = 0L
    for(i <- 0 until m) {
      if(house(i) < curr) {
        res += n - curr + house(i)
      } else if (house(i) > curr) {
        res += house(i) - curr
      }
      curr = house(i)
    }
    println(res)
  }
}

import scala.io.StdIn

object A extends App {

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toLong)
  val t = StdIn.readLine().split(" ").map(_.toLong)
  val result = t.iterator.sliding(2).withPartial(false).map { x =>
    if(x.head == x(1)) 0
    else if (x.head < x(1)) x(1) - x.head
    else n - (x.head - x(1))
  }.sum + (t(0) - 1)

  println(result)

}

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

object P339B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M = sc.nextInt

  type Tasks = List[Long]

  val A: Tasks = List.fill(M)(sc.nextLong)

  def solve(): Unit = {

    def cost(x: Long, y: Long): Long = if (y < x) y - x + N
                                    else y - x

    @tailrec
    def loop(acc: Long, pos: Long, tasks: Tasks): Long = tasks match {
        case Nil     => acc
        case x :: xs => loop(acc + cost(pos, x), x, xs)
      }

    out.println(loop(0, 1, A))
  }

  solve
  out.close
}

object XeniaAndRingroad {
	def main (args: Array[String]) {
		//Parsing the input
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextLong;
		val m = scanner.nextLong;
		var last : Long = 1;
		var moves : Long = 0;
		for (i <- 1 to m.asInstanceOf[Int]) {
		  val current = scanner.nextLong();
		  if (current >= last)
		    moves += (current - last)
		  else
		    moves += (n - last) + current
		  last = current;
		}
		println(moves)
	}
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  val Array(n, _) = readInts
  def ans = (1 +: readInts).sliding(2).map(x => (x.last.toLong - x.head + n) % n).sum

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

object Main {
  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val m = (Array(1) ++ a).sliding(2).map { x =>
      val x1 = x(0)
      val x2 = x(1)
      if (x2 < x1) (nm(0) - x1 + x2).toLong
      else (x2 - x1).toLong
    }
    println(m.sum)
  }
}

import java.util.Scanner

import scala.io.StdIn
import scala.io.StdIn.readLine
import Array._

object problem {

  def main(args: Array[String]) {
  val in = new Scanner(System.in)
    val (n, m) = (in.nextInt, in.nextInt)
    var x = 1
    var cnt = 0l
//    val a = ofDim[Int](m + 1)
    val a = for(i <- 1 to m) yield in.nextInt
    for(i <- a){

      if(i >= x){
//        println(cnt)
        cnt += i - x
//        println(cnt)
//        x = i
      }
      else{
//        println(cnt)
        cnt += n + i - x
//        println(cnt)
      }
      x = i

    }
  println(cnt)
  }
}

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

import Math.abs

object RingRoad {

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

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

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

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

   def main(args: Array[String]) {
     val (n,m) = readTuple
     val as = readLongs
     println(as.foldLeft( (1L, 0L)){ case ( (cur: Long, dist: Long), next: Long) =>
       (next,  dist + (if (next >= cur) next-cur else n-cur+next))
     }._2)

   }

}

object main extends App with fastIO {

  var (n, m) = (nextInt, nextInt)
  var a = Array.fill(m)(nextInt)

  println((1 :: a.toList).sliding(2)
    .foldLeft(0L)((sum, pos) => sum + ((pos(1) - pos(0) + n) % n) ))

  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

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

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

object main extends App with fastIO {

  var (n, m) = (nextInt, nextInt)

  var (ans, last) = (0l, 1)
  for (_ <- 1 to m) {
    var ind = nextInt
    ans += (if (last <= ind) ind - last else n - (last - ind))
    last = ind
  }

  println(ans)
  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

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

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

object main extends App with fastIO {

  var (n, m) = (nextInt, nextInt)

  var (ans, last) = (0l, 1)
  var a = for (_ <- 1 to m) yield {
    var ind = nextInt
    ans += (ind + n - last) % n
    last = ind
    ind
  }

  val res = (1 :: a.toList).sliding(2)
  .foldLeft(0L)((sum, pos) => {
    sum + ((pos(1) + n) - pos(0)) % n
  })
  //res.foreach { x => Console.err.println(x) }

  println(ans)
  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

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

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

object Solution extends App {
  val Array(n, m) = readLine.split(" ").map(_.toLong)
  val as = readLine.split(" ").map(_.toLong)

  val ups = as.foldLeft((0l, 1l)){ case(p, c) =>
    if(p._1 > c) {
      (c, p._2 + 1)
    } else {
      (c, p._2)
    }
  }

  println((ups._2-1)*n + (as.last - 1))
}

object cf extends App {
  import java.util.Scanner
  val in = new Scanner(System.in)

  val n, m = in.nextInt
  val a = for (i <- 1 to m) yield in.nextInt
  val res = (1 :: a.toList).sliding(2)
  .foldLeft(0)((sum, pos) => {
    sum + ((pos(1) + n) - pos(0)) % n
  })
  println(res)
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Solution {

	def solve() {
		val n = nextInt
		val m = nextInt
		val a = for (i <- 1 to m) yield nextInt

		var cur = 1
		var ans = 0
		for (ai <- a) {
			if (ai >= cur) ans += ai-cur
			else ans += n-(cur-ai)
			cur = ai
		}

		println(ans)
	}

	val in = new BufferedReader(new InputStreamReader(System.in))
	var st = new StringTokenizer("")

	def next : String = {
		while (!st.hasMoreTokens) {
			val line = in.readLine
			if (line == null) return null
			eat(line)
		}
		st.nextToken
	}

	def eat( s : String ) = st = new StringTokenizer(s)
	def nextInt = next.toInt
	def nextLong = next.toLong
	def nextDouble = next.toDouble

	def main(args: Array[String]) {
		eat("")
		solve
	}
}

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

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

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

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

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

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

import scala.io.StdIn

object A extends App {

  val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
  val t = StdIn.readLine().split(" ").map(_.toInt)
  val result = t.sliding(2).map { x =>
    if(x(0) == x(1)) 0
    else if (x(0) < x(1)) x(1) - x(0)
    else n - (x(0) - x(1))
  }.sum + (t(0) - 1)

  println(result)

}

import scala.io.StdIn

object A extends App {

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

  val result = t.sliding(2).map { x =>
    if(x(0) == x(1)) 0
    else if (x(0) < x(1)) x(1) - x(0)
    else x(0) - x(1) + n - 2
  }.sum + (t(0) - 1)

  println(result)

}

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

object P339B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M = sc.nextInt

  type Tasks = List[Int]

  val A: Tasks = List.fill(M)(sc.nextInt)

  def solve(): Unit = {

    @tailrec
    def loop(acc: Int, pos: Int, tasks: Tasks): Int = tasks match {
        case Nil     => acc
        case x :: xs => {
          val cost = x - pos
          if (cost < 0) loop(acc + cost + N, x, xs)
          else loop(acc + cost, x, xs)
        }
      }

    out.println(loop(0, 1, A))
  }

  solve
  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  val Array(n, _) = readInts
  def ans = (1 +: readInts).sliding(2).map(x => (x.last - x.head + n) % n).sum

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

object Main {
  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val m = (Array(1) ++ a).sliding(2).map { x =>
      val x1 = x(0)
      val x2 = x(1)
      if (x2 < x1) nm(0) - x1 + x2
      else x2 - x1
    }
    println(m.sum)
  }
}

import scala.io.StdIn
import scala.io.StdIn.readLine
import Array._

object problem {

  def main(args: Array[String]) {
  val Array(n, m) = readLine.split(" ").map(_.toInt)
    var x = 1
    var cnt = 0
    for(i <- 1 to m){
      if(x < i & x != i){
        cnt += x - i
        x = i
        println(cnt)
      }
      if(x > i & x != i){
        cnt += n - i + x
        x = i
      }
    }
  println(Math.abs(cnt))
  }
}

 import java.util.Scanner

import scala.io.StdIn
import scala.io.StdIn.readLine
import Array._

object problem {

  def main(args: Array[String]) {
  val in = new Scanner(System.in)
    val (n, m) = (in.nextInt, in.nextInt)
    var x = 1
    var cnt = 0
//    val a = ofDim[Int](m + 1)
    val a = for(i <- 1 to m) yield in.nextInt
    for(i <- a){

      if(i >= x){
//        println(cnt)
        cnt += i - x
//        println(cnt)
//        x = i
      }
      else{
//        println(cnt)
        cnt += n + i - x
//        println(cnt)
      }
      x = i

    }
  println(cnt)
  }
}

object main extends App with fastIO {

  var (n, m) = (nextInt, nextInt)
  var a = Array.fill(n)(nextInt)

  println((1 :: a.toList).sliding(2)
    .foldLeft(0L)((sum, pos) => sum + ((pos(1) + n) - pos(0)) % n ))
  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

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

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

object Solution extends App {
  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val as = readLine.split(" ").map(_.toInt)

  val ups = as.foldLeft((0, 1)){ case(p, c) =>
    if(p._1 > c) {
      (c, p._2 + 1)
    } else {
      (c, p._2)
    }
  }

  println((ups._2-1)*n + (as.last - 1))
}


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$:  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$.  $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain.

For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$.

import scala.collection.mutable.ArrayBuffer

object B extends App {

  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  @inline def operations(n: Int): List[List[Int]] = {
    val current = ArrayBuffer((1 to n) :_*)

    var result = List[List[Int]](current.toList)
    for (i <- 2 to n) {
      val j = n - i
      val a = current(j)
      val b = current(j + 1)

      current(j) = b
      current(j + 1) = a

      result = result :+ current.toList
    }

    result
  }

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val n = nextInt
      val seq = operations(n)
      println(seq.size)
      seq.foreach(a => println(a.mkString(" ")))
    }
  }

}

import scala.collection.mutable.ArrayBuffer

object B extends App {

  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  @inline def operations(n: Int): List[List[Int]] = {
    val current = ArrayBuffer((1 to n) :_*)

    var result = List[List[Int]](current.toList)
    for (i <- 2 to n) {
      val j = n - i
      val a = current(j)
      val b = current(j + 1)

      current(j) = b
      current(j + 1) = a

      result = result :+ current.toList
    }

    result
  }

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val n = nextInt
      val seq = operations(n)
      seq.foreach(a => println(a.mkString(" ")))
    }
  }

}


We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.

The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$  — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$

object Main1 extends App {

  val scanner = new java.util.Scanner(System.in)
  val t       = scanner.nextInt()
  val array   = new Array[Array[Long]](t)
  (0 until t).foreach { i =>
    val n  = scanner.nextInt()
    val ar = new Array[Long](n)
    (0 until n).foreach { j =>
      ar(j) = scanner.nextInt()
    }
    array(i) = ar
  }

  def check(ar: Array[Long]): Boolean = {
    val sumArr = ar.scan(0L)(_ + _).tail
    val indexSumZero = sumArr.indexWhere(_ == 0)
    val lastNonZero = ar.lastIndexWhere(_ != 0)
    indexSumZero match {
      case -1 => false
      case _ if lastNonZero > indexSumZero => false
      case _ if sumArr.exists(_ < 0) => false
      case _ => true
    }
  }

  (0 until t).foreach { i =>
    println(if (check(array(i))) "Yes" else "No")
  }
}

object Main extends App {

  val scanner = new java.util.Scanner(System.in)
  val t       = scanner.nextInt()
  val array   = new Array[Array[Int]](t)
  (0 until t).foreach { i =>
    val n  = scanner.nextInt()
    val ar = new Array[Int](n)
    (0 until n).foreach { j =>
      ar(j) = scanner.nextInt()
    }
    array(i) = ar
  }

  def check(ar: Array[Int]): Boolean = {
    val sumArr = ar.scan(0)(_ + _).tail
    val indexZero = sumArr.indexWhere(_ == 0)
    val lastNonZero = ar.lastIndexWhere(_ != 0)
    indexZero match {
      case -1 => false
      case _ if lastNonZero > indexZero => false
      case _ if sumArr.exists(_ < 0) => false
      case _ => true
    }
  }

  (0 until t).foreach { i =>
    println(if (check(array(i))) "Yes" else "No")
  }

}

object Main extends App {

  val scanner = new java.util.Scanner(System.in)
  val t       = scanner.nextInt()
  val array   = new Array[Array[Int]](t)
  (0 until t).foreach { i =>
    val n  = scanner.nextInt()
    val ar = new Array[Int](n)
    (0 until n).foreach { j =>
      ar(j) = scanner.nextInt()
    }
    array(i) = ar
  }

  def check(ar: Array[Int]): Boolean = {
    val sumArr = ar.scan(0)(_ + _).tail
    val indexZero = sumArr.indexWhere(_ == 0)
    val lastNonZero = sumArr.lastIndexWhere(_ != 0)
    indexZero match {
      case -1 => false
      case _ if lastNonZero > indexZero => false
      case _ if sumArr.exists(_ < 0) => false
      case _ => true
    }
  }

  (0 until t).foreach { i =>
    println(if (check(array(i))) "Yes" else "No")
  }

}

object Main extends App {

  val scanner = new java.util.Scanner(System.in)
  val t       = scanner.nextInt()
  val array   = new Array[Array[Int]](t)
  (0 until t).foreach { i =>
    val n  = scanner.nextInt()
    val ar = new Array[Int](n)
    (0 until n).foreach { j =>
      ar(j) = scanner.nextInt()
    }
    array(i) = ar
  }

  def check(ar: Array[Int]): Boolean = {
    val sumArr = ar.scan(0)(_ + _).tail
    val indexZero = sumArr.indexWhere(_ == 0)
    val lastNonZero = sumArr.lastIndexWhere(_ != 0)
    indexZero match {
      case -1 => false
      case _ if lastNonZero > indexZero => false
      case _ => true
    }
  }

  (0 until t).foreach { i =>
    println(if (check(array(i))) "Yes" else "No")
  }

}

object Main extends App {

  val scanner = new java.util.Scanner(System.in)
  val t       = scanner.nextInt()
  val array   = new Array[Array[Int]](t)
  (0 until t).foreach { i =>
    val n  = scanner.nextInt()
    val ar = new Array[Int](n)
    (0 until n).foreach { j =>
      ar(j) = scanner.nextInt()
    }
    array(i) = ar
  }

  def check(ar: Array[Int]): Boolean = {
    val sumArr = ar.scan(0)(_ + _)
    val indexZero = sumArr.indexWhere(_ == 0)
    val lastNonZero = sumArr.lastIndexWhere(_ != 0)
    indexZero match {
      case -1 => false
      case _ if lastNonZero > indexZero => false
      case _ => true
    }
  }

  (0 until t).foreach { i =>
    println(if (check(array(i))) "Yes" else "No")
  }

}

object Main extends App {

  val scanner = new java.util.Scanner(System.in)
  val t       = scanner.nextInt()
  val array   = new Array[Array[Int]](t)
  (0 until t).foreach { i =>
    val n  = scanner.nextInt()
    val ar = new Array[Int](n)
    (0 until n).foreach { j =>
      ar(j) = scanner.nextInt()
    }
    array(i) = ar
  }

  def check(ar: Array[Int]): Boolean = {
    val last = ar.lastIndexWhere(_ != 0)
    val ar2  = ar.take(last + 1)
    (1 to last).foldLeft(true) { (b, i) =>
      val left  = ar2.take(i).sum
      val right = ar2.takeRight(ar2.length - i).sum
      b && left == -right && (left > right)
    }
  }

  (0 until t).foreach { i =>
    println(if (check(array(i))) "Yes" else "No")
  }

}

object Main extends App {
  val scanner = new java.util.Scanner(System.in)
  val t       = scanner.nextInt()
  val array   = new Array[Array[Int]](t)
  (0 until t).foreach { i =>
    val n  = scanner.nextInt()
    val ar = new Array[Int](n)
    (0 until n).foreach { j =>
      ar(j) = scanner.nextInt()
    }
    array(i) = ar
  }

  def check(ar: Array[Int]): String = {
    val result = (1 until ar.length).foldLeft(true) { (b, i) =>
      val left  = ar.take(i).sum
      val right = ar.takeRight(ar.length - i).sum
      left == -right && ((left > right) || (left == 0 && right == 0)) && b
    }
    if (result) "Yes" else "No"
  }

  (0 until t).foreach { i =>
    println(check(array(i)))
  }
}

object Main extends App {
    val scanner = new java.util.Scanner(System.in)
    val t     = scanner.nextInt()
    val array = new Array[Array[Int]](t)
    (0 until t).foreach { i =>
      val n  = scanner.nextInt()
      val ar = new Array[Int](n)
      (0 until n).foreach { j =>
        ar(j) = scanner.nextInt()
      }
      array(i) = ar
    }

    def check(ar: Array[Int]): String = {
      val result = (1 until ar.length).foldLeft(true) { (b, i) =>
        val left = ar.take(i).sum
        val right = ar.takeRight(ar.length - i).sum
        left == -right && left > right && b
      }
      if (result) "Yes" else "No"
    }

    (0 until t).foreach { i =>
      println(check(array(i)))
    }
}

object Main extends App {
    val scanner = new java.util.Scanner(System.in)
    val t     = scanner.nextInt()
    val array = new Array[Array[Int]](t)
    (0 until t).foreach { i =>
      val n  = scanner.nextInt()
      val ar = new Array[Int](n)
      (0 until n).foreach { j =>
        ar(j) = scanner.nextInt()
      }
      array(i) = ar
    }

    def check(ar: Array[Int]): String = {
      val result = (1 until ar.length).foldLeft(true) { (b, i) =>
        val left = ar.take(i).sum
        val right = ar.takeRight(ar.length - i).sum
        left == -right && left >= right && b
      }
      if (result) "Yes" else "No"
    }

    (0 until t).foreach { i =>
      println(check(array(i)))
    }
}

  object Main extends App {
    val scanner = new java.util.Scanner(System.in)
    val t     = scanner.nextInt()
    val array = new Array[Array[Int]](t)
    (0 until t).foreach { i =>
      val n  = scanner.nextInt()
      val ar = new Array[Int](n)
      (0 until n).foreach { j =>
        ar(j) = scanner.nextInt()
      }
      array(i) = ar
    }

    def check(ar: Array[Int]): String = {
      val b = (1 until ar.length).foldLeft(true) { (b, i) =>
        val left = ar.take(i).sum
        val right = ar.takeRight(ar.length - 1).sum
        left == -right && left >= right && b
      }
      if (b) "Yes" else "No"
    }

    (0 until t).foreach { i =>
      println(check(array(i)))
    }
  }

object Main extends App {
  val scanner = new java.util.Scanner(System.in)
  val t     = scanner.nextInt()
  val array = new Array[Array[Int]](t)
  (0 until t).foreach { i =>
    val n  = scanner.nextInt()
    val ar = new Array[Int](n)
    (0 until n).foreach { j =>
      ar(j) = scanner.nextInt()
    }
    array(i) = ar
  }

  def check(ar: Array[Int]): String = {
    val b = ar.head == -1 * ar.tail.sum && ar.last == -1 * ar.init.sum
    if (b) "Yes" else "No"
  }

  (0 until t).foreach { i =>
    println(check(array(i)))
  }
}


There are $$$n$$$ heaps of stone. The $$$i$$$-th heap has $$$h_i$$$ stones. You want to change the number of stones in the heap by performing the following process once:   You go through the heaps from the $$$3$$$-rd heap to the $$$n$$$-th heap, in this order.  Let $$$i$$$ be the number of the current heap.  You can choose a number $$$d$$$ ($$$0 \le 3 \cdot d \le h_i$$$), move $$$d$$$ stones from the $$$i$$$-th heap to the $$$(i - 1)$$$-th heap, and $$$2 \cdot d$$$ stones from the $$$i$$$-th heap to the $$$(i - 2)$$$-th heap.  So after that $$$h_i$$$ is decreased by $$$3 \cdot d$$$, $$$h_{i - 1}$$$ is increased by $$$d$$$, and $$$h_{i - 2}$$$ is increased by $$$2 \cdot d$$$.  You can choose different or same $$$d$$$ for different operations. Some heaps may become empty, but they still count as heaps. What is the maximum number of stones in the smallest heap after the process?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$). The second lines of each test case contains $$$n$$$ integers $$$h_1, h_2, h_3, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the maximum number of stones that the smallest heap can contain.

NoteIn the first test case, the initial heap sizes are $$$[1, 2, 10, 100]$$$. We can move the stones as follows.   move $$$3$$$ stones and $$$6$$$ from the $$$3$$$-rd heap to the $$$2$$$-nd and $$$1$$$ heap respectively. The heap sizes will be $$$[7, 5, 1, 100]$$$;  move $$$6$$$ stones and $$$12$$$ stones from the last heap to the $$$3$$$-rd and $$$2$$$-nd heap respectively. The heap sizes will be $$$[7, 17, 7, 82]$$$. In the second test case, the last heap is $$$1$$$, and we can not increase its size.In the third test case, it is better not to move any stones.In the last test case, the final achievable configuration of the heaps can be $$$[3, 5, 3, 4, 3, 3]$$$.

import java.util

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val hs = nextLongs(n)
      val add = Array.fill(n)(0L)

      def can(lim: Long): Boolean = {
        util.Arrays.fill(add, 0)
        var i = n - 1
        var ok = true
        while (i > 1) {
          val avail = Math.min(hs(i), hs(i) + add(i) - lim)
          val d = avail / 3
          if (d > 0) {
            add(i - 1) += d
            add(i - 2) += d * 2
            add(i) -= d * 3
          }
          i -= 1
        }
        i = 0
        while (i < n) {
          if (hs(i) + add(i) < lim) {
            ok = false
            i = n
          }
          i += 1
        }
//        val tot = hs.indices.map(i => hs(i) + add(i))
//        println(lim, tot.mkString(" "))
        ok
      }

      @annotation.tailrec
      def binSearch(low: Long, hi: Long): Long = {
        if (hi < low) low
        else {
          val mid = (low + hi) / 2
          if (can(mid)) binSearch(mid + 1, hi)
          else binSearch(low, mid - 1)
        }
      }

//      println(can(8))
//      println(can(7))
//      println(can(6))

      val res = binSearch(0, hs.max + 1)

      out.println(res - 1)
    }

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

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(val l: Int, val r: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (r-l).compareTo(that.r-that.l)
        }
    }

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

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n+1)
        for (i <- 1 to n) {
            arr(i) = readInt()
        }
        writer.println(bs(1, 1000000000))
        def check(kk: Long): Boolean = {
            val b = new Array[Int](n+1)
            for (i <- (3 to n).reverse) {
                if (arr(i) + b(i) < kk)
                    return false
                val d = (min(arr(i) + b(i) - kk, arr(i)) / 3).toInt
                b(i-1) += d
                b(i-2) += 2*d
            }
            if (arr(2) + b(2) < kk)
                return false
            if (arr(1) + b(1) < kk)
                return false
            return true
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}


Ashishgup and FastestFinger play a game. They start with a number $$$n$$$ and play in turns. In each turn, a player can make any one of the following moves:  Divide $$$n$$$ by any of its odd divisors greater than $$$1$$$.  Subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer  — $$$n$$$ ($$$1 \leq n \leq 10^9$$$).

For each test case, print "Ashishgup" if he wins, and "FastestFinger" otherwise (without quotes).

FastestFinger
Ashishgup
Ashishgup
FastestFinger
Ashishgup
FastestFinger
Ashishgup

NoteIn the first test case, $$$n = 1$$$, Ashishgup cannot make a move. He loses.In the second test case, $$$n = 2$$$, Ashishgup subtracts $$$1$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the third test case, $$$n = 3$$$, Ashishgup divides by $$$3$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the last test case, $$$n = 12$$$, Ashishgup divides it by $$$3$$$. Now $$$n = 4$$$, FastestFinger is forced to subtract $$$1$$$, and Ashishgup gets $$$3$$$, so he wins by dividing it by $$$3$$$.

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

    val LIMIT = 100000
    val isPrime = Array.fill(LIMIT)(true)
    isPrime(0) = false
    isPrime(1) = false

    var i = 2
    while (i * i < LIMIT) {
      var j = i * i
      if (isPrime(j)) {
        while (j < LIMIT) {
          isPrime(j) = false
          j += i
        }
      }
      //println(i)
      i += 1
    }
    val primes = isPrime.indices.toArray.filter(isPrime(_))
//println(primes.length)
    for (_ <- 1 to nextInt) {
      var n = nextInt
      var step = 0
      while (n > 1) {
        step += 1
        val b = 1 << Integer.numberOfTrailingZeros(n)
        if (n % 2 == 1) {
          n = 1
        } else if (n == 2) {
          n = 1
        } else if (n > b) {
          var i = 1
          while (i < primes.length && n % primes(i) != 0) {
            i += 1
          }
          if (i < primes.length && b == 2) {
            if (n == primes(i) * b) {
              n = b
            } else {
              n = primes(i) * b
            }
          } else {
            n = b
          }
        } else {
          n -= 1
        }
        //println(step, n, b)
      }
      val win = step % 2 == 1 //n > 1 && (n % 2 == 1 || ((Integer.bitCount(n) > 1 || n == 2) && (n / 2 % 2 == 0)))
      out.println(if (win) "Ashishgup" else "FastestFinger")

      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 = {

    for (_ <- 1 to nextInt) {
      var n = nextInt

      var step = 0
      while (n > 1) {
        step += 1
        val b = 1 << Integer.numberOfTrailingZeros(n)
        if (n % 2 == 1) {
          n = 1
        } else if (n == 2) {
          n = 1
        } else if (n > b) {
          n = b
        } else {
          n -= 1
        }
        //println(step, n, b)
      }
      val win = step % 2 == 1 //n > 1 && (n % 2 == 1 || ((Integer.bitCount(n) > 1 || n == 2) && (n / 2 % 2 == 0)))
      out.println(if (win) "Ashishgup" else "FastestFinger")

      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 LIMIT = 100000
    val isPrime = Array.fill(LIMIT)(true)
    isPrime(0) = false
    isPrime(1) = false

    var i = 2
    while (i * i < LIMIT) {
      var j = i * i
      if (isPrime(j)) {
        while (j < LIMIT) {
          isPrime(j) = false
          j += i
        }
      }
      //println(i)
      i += 1
    }
    val primes = isPrime.indices.toArray.filter(isPrime(_))
//println(primes.length)
    for (_ <- 1 to nextInt) {
      var n = nextInt
      var step = 0
      while (n > 1) {
        step += 1
        val b = 1 << Integer.numberOfTrailingZeros(n)
        if (n % 2 == 1) {
          n = 1
        } else if (n == 2) {
          n = 1
        } else if (n > b) {
          var i = 1
          while (n % primes(i) != 0 && i < primes.length) {
            i += 1
          }
          if (i < primes.length && (n / b) / primes(i) > 0) {
            if (n == primes(i) * b) {
              n = b
            } else {
              n = primes(i) * b
            }
          } else {
            n = b
          }
        } else {
          n -= 1
        }
//        println(step, n, b)
      }
      val win = step % 2 == 1 //n > 1 && (n % 2 == 1 || ((Integer.bitCount(n) > 1 || n == 2) && (n / 2 % 2 == 0)))
      out.println(if (win) "Ashishgup" else "FastestFinger")

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


We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7.The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.

The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.

Print the minimum number of steps modulo 109 + 7.

NoteThe first example: "ab"  →  "bba".The second example: "aab"  →  "abba"  →  "bbaba"  →  "bbbbaa".

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

  var res = 0L
  val MOD = 1000000007L

  var aCnt = 0L
  var pow = 1L
  for (c <- s) {
    if (c == 'a') {
      aCnt = (aCnt + pow) % MOD
      pow = 2 * pow % MOD
    } else res = (res + aCnt) % MOD
  }

  println(res)
}


Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence $$$a$$$ of length $$$n$$$. In each operation, she can select an arbitrary interval $$$[l, r]$$$ and for all values $$$i$$$ ($$$0\leq i \leq r-l$$$), replace $$$a_{l+i}$$$ with $$$a_{l+i} \,\&\, a_{r-i}$$$ at the same time, where $$$\&$$$ denotes the bitwise AND operation. This operation can be performed any number of times.For example, if $$$n=5$$$, the array is $$$[a_1,a_2,a_3,a_4,a_5]$$$, and Mocha selects the interval $$$[2,5]$$$, then the new array is $$$[a_1,a_2\,\&\, a_5, a_3\,\&\, a_4, a_4\,\&\, a_3, a_5\,\&\, a_2]$$$.Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).

For each test case, print one integer — the minimal value of the maximum value in the sequence.

NoteIn the first test case, Mocha can choose the interval $$$[1,2]$$$, then the sequence becomes $$$[ 0, 0]$$$, where the first element is $$$1\,\&\,2$$$, and the second element is $$$2\,\&\,1$$$.In the second test case, Mocha can choose the interval $$$[1,3]$$$, then the sequence becomes $$$[ 1,1,1]$$$, where the first element is $$$1\,\&\,3$$$, the second element is $$$1\,\&\,1$$$, and the third element is $$$3\,\&\,1$$$.

import java.io._
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new BufferedReader(new java.io.InputStreamReader(System.in))
    val writer =  new PrintWriter(System.out)
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val a = readArrayInt()
        var rs = a(0)
        for (i <- 1 until n)
            rs &= a(i)

        writer.println(rs)
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}

import scala.io.StdIn

object Problem extends App {
  def start() = {
    println(parseInput().map(testCase => minMaxValue(testCase)).mkString("\n"))
  }

  def arrayOp(array: Array[Int], l: Int, r: Int): Array[Int] = {
    for( i <- 0.to(r-l)) {
      array(l+i) = array(l+i) & array(r-i)
    }
    array
  }

  def minMaxValue(given: Array[Int]): Int = {
    given.foldLeft(Int.MaxValue)(_ & _)
  }

  def parseInput(): Array[Array[Int]] = {
    val testCases: Int = StdIn.readLine().stripLineEnd.trim.toInt
    var input = Array[Array[Int]]()
    for (_ <- 0L.until(testCases)) {
      val n = StdIn.readLine().stripLineEnd.trim.toInt
      val testCase = StdIn.readLine().split(" ").map(_.stripLineEnd.trim.toInt)
      input = input ++ Array(testCase)
    }
    input
  }

  start()
}

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

// values always get less after operation, so just and all of numbers
object Solution {
  def solve(input: Array[Int]): Int =
    input.fold(input(0)) { (v1, v2) => v1 & v2 }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    val n = input.nextInt()
    val nums = (1 to n).map(_ => input.nextInt()).toArray
    output.println(solve(nums))
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val ans = an.tail.foldLeft(an.head)(_ & _)

    println(ans)
  }
}

import java.io._
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new BufferedReader(new java.io.InputStreamReader(System.in))
    val writer =  new PrintWriter(System.out)
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val a = readArrayInt()
        writer.println(a.min)

    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}


This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $$$a_1, a_2, \dots, a_n$$$.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$$$, where $$$a_1 \dots a_p$$$ and $$$b_1 \dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally,  if $$$p \ge q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$;  if $$$p < q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$, your task is to help students to calculate $$$\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\,244\,353$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array.

Print the answer modulo $$$998\,244\,353$$$.

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

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

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

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

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

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

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

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

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

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

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

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

  /*
    * 10^18までのpowを配列で用意しておく
    */
  val pow10 = Array.ofDim[Long](30)
  pow10(0) = 1
  REP(pow10.length - 1)(i => pow10(i + 1) = pow10(i) * 10 % MOD)

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val MAX = 10
    val D = Array.ofDim[Int](MAX)
    REP(N) { i =>
      D(log10(A(i))) += 1
    }
    debug(D)

    var ans = 0L
    def contributeX(x: Int): Unit = {
      var a = x
      REP(MAX) { i =>
        val d = a % 10
        REP(MAX) { j =>
          val k = i + (min(i, j) + 1)
          ans += pow10(k) * d % MOD * D(j) % MOD
          debug(s"contributeX i:$i j:$j k:$k d:$d Dj:${D(j)} ans:$ans")
        }
        a /= 10
      }
      ans %= MOD
    }

    def contributeY(y: Int): Unit = {
      var a = y
      REP(MAX) { i =>
        val d = a % 10
        REP(MAX) { j =>
          val k = i + min(i - 1, j) + 1
          ans += pow10(k) * d % MOD * D(j) % MOD
          debug(s"contributeY i:$i j:$j k:$k d:$d Dj:${D(j)} ans:$ans")
        }
        a /= 10
      }
      ans %= MOD
    }

    REP(N) { i =>
      contributeX(A(i))
      contributeY(A(i))
    }

    out.println(ans)
  }

  /**
    * @return log10の整数値
    */
  def log10(x: Long): Int = {
    var a = x
    var i = 0
    while(a >= 10) {
      a /= 10
      i += 1
    }
    i
  }
}


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times:  if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  ...  remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.

The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.

Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).

object CF_490_3_C {

  type In  = (Int, Int, String)
  type Out = String
  type SC = Seq[Char]

  def solve(in: In): Out = {
    val (n, k, s) = in
    val removals = s.toSeq.sorted.take(k)
    s.diff(removals)
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int, {i.nextLine; i.nextLine})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object C999A {

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

  def main(args: Array[String]): Unit = {
    var Array(n, k) = readInts(2)
    val str = read
    val marked = Array.fill(n)(0)
    var char = 'a'
    while(k > 0 && char <= 'z') {
      for(i <- 0 until n if k > 0) {
        if(str(i) == char && marked(i) == 0) {
          marked(i) = 1
          k -= 1
        }
      }
      char = (char.toInt + 1).toChar
    }
    for(i <- 0 until n) if(marked(i) == 0)
      out.print(str(i))
    out.println("")
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object Main2 extends App {

  import java.io._
  import java.util.{StringTokenizer}

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val n = in.nextInt
  var k = in.nextInt
  var s = in.next
  var cnt = s.groupBy(ch => ch).mapValues(_.length)
  for (ch <- 'a' to 'z') {
    val x = cnt.getOrElse(ch, 0)
    val c = x min k
    cnt += ch -> c
    k -= c
  }

  s foreach { ch =>
    val x = cnt getOrElse(ch, 0)
    if (x == 0) out.print(ch)
    else cnt += ch -> (x - 1)
  }

  out.flush()
  out.close()

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    def nextInt: Int = next.toInt

    def nextLong: Long = next.toLong

    def nextDouble: Double = next.toDouble

    def nextLine: String = br.readLine
  }

}

import scala.io.StdIn

object AlphabeticRemovals {
  def main(args: Array[String]): Unit = {
    val k = StdIn.readLine().split(" ")(1).toInt
    val input = StdIn.readLine()
    println(solve(input, k))
  }

  def solve(input: String, k: Int): String = {
    if (k >= input.length) return ""

    val charCount = input.groupBy(identity).mapValues(_.length)
    val alphabet = charCount.keys.toSeq.sorted

    val result = calculate(Seq.empty, alphabet, k, charCount)
    val kill = result._1
    val keep = result._2
    val decide = result._3
    var remove = result._4

    input.filterNot(c => kill.contains(c) || (c == decide
      && {remove -= 1; remove >= 0}))
  }

  private def calculate(kill: Seq[Char], keep: Seq[Char], k:Int, map: Map[Char, Int]) : (Seq[Char], Seq[Char], Char, Int) = {
    val next: Char = keep.head
    val occurs: Int = map(next)

    if (occurs > k) {
      (kill, keep.tail, next, k)
    } else {
      calculate(kill :+ next, keep.tail, k - occurs, map)
    }
  }
}


The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given an integer $$$n$$$. You have to find a sequence $$$s$$$ consisting of digits $$$\{1, 3, 7\}$$$ such that it has exactly $$$n$$$ subsequences equal to $$$1337$$$.For example, sequence $$$337133377$$$ has $$$6$$$ subsequences equal to $$$1337$$$:   $$$337\underline{1}3\underline{3}\underline{3}7\underline{7}$$$ (you can remove the second and fifth characters);  $$$337\underline{1}\underline{3}3\underline{3}7\underline{7}$$$ (you can remove the third and fifth characters);  $$$337\underline{1}\underline{3}\underline{3}37\underline{7}$$$ (you can remove the fourth and fifth characters);  $$$337\underline{1}3\underline{3}\underline{3}\underline{7}7$$$ (you can remove the second and sixth characters);  $$$337\underline{1}\underline{3}3\underline{3}\underline{7}7$$$ (you can remove the third and sixth characters);  $$$337\underline{1}\underline{3}\underline{3}3\underline{7}7$$$ (you can remove the fourth and sixth characters). Note that the length of the sequence $$$s$$$ must not exceed $$$10^5$$$.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of queries.  Next $$$t$$$ lines contains a description of queries: the $$$i$$$-th line contains one integer $$$n_i$$$ ($$$1 \le n_i \le 10^9$$$).

For the $$$i$$$-th query print one string $$$s_i$$$ ($$$1 \le |s_i| \le 10^5$$$) consisting of digits $$$\{1, 3, 7\}$$$. String $$$s_i$$$ must have exactly $$$n_i$$$ subsequences $$$1337$$$. If there are multiple such strings, print any of them.

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      var n = ni()
      val sevens = Array.ofDim[Int](10001)
      var i = 10000
      while(n > 0) {
        while(i * (i - 1) / 2 > n) i -=1
        n -= i * (i - 1) / 2
        sevens(i) += 1
      }
      out.print("1")
      REP(10000, 1) { i =>
        out.print("3")
        REP(sevens(i)) { _ =>
          out.print("7")
        }
      }
      out.println()
    }
  }
}


Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.

The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font:

Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).

/**
 * Created by infm on 4/24/14.
 */
object Main {
  val in = {
    val lines = {
      scala.io.Source.stdin.getLines().buffered
    }
    lines map (_ split ' ') filter (_.nonEmpty) flatten
  }

  def main(args: Array[String]){
    val mirrored = "AHIMOTUVWXY"
    val current = in.next
    if (current == current.reverse && current.forall(mirrored.contains(_)))
      println("YES")
    else
      println("NO")
  }
}

/**
 * Created by infm on 4/24/14.
 */
object A {
  val in = {
    val lines = {
      scala.io.Source.stdin.getLines().buffered
    }
    lines map (_ split ' ') filter (_.nonEmpty) flatten
  }

  def main(args: Array[String]){
    val mirrored = "AHIMOTUVWXY"
    val current = in.next
    if (current == current.reverse && current.forall(mirrored.contains(_)))
      println("YES")
    else
      println("NO")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val set = Set('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y')
  if (str == str.reverse && str.forall(set))
    println("YES")
  else
    println("NO")
}

object Main {

	val in = {
		val lines = {
			scala.io.Source.stdin.getLines.buffered
			//val bf = new BufferedReader(new InputStreamReader(System.in))
			//Iterator.continually(readLine)
			//Iterator.continually(bf.readLine)
		}
		lines map (_ split ' ') filter (_.nonEmpty) flatten
	}

	//val out = new PrintWriter(System.out)

	def nextInt = in.next().toInt
	def nextLong = in.next().toLong

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

		val mirror = "AHIMOTUVWXY"

		val name = in.next

		if (name == name.reverse && name.forall(mirror.contains(_)))
			println("YES")
		else
			println("NO")

	}

}

/**
 * Created by yangchaozhong on 3/12/15.
 */
object CF420A extends App {
  import scala.collection.immutable.HashSet
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

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

  def solve = {
    val name = nextString
    val chars = HashSet('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y')
    val len = name.length
    val half = len / 2
    val sum = (0 to (half - 1)).map(i => Math.abs(name(i) - name(len - 1 - i))).sum
    val count = name.count(!chars.contains(_))
    if (sum == 0 && count == 0)
      out.println("YES")
    else
      out.println("NO")
  }

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

object Main {
  def main(args: Array[String]) {
    val name = readLine()
    val goodChars = Set[Char]('A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y')
    for (i <- 0 to name.length / 2) {
      if (name(i) != name(name.length - 1 - i) || !goodChars.contains(name(i))) {
        println("NO")
        return
      }
    }
    println("YES")
  }
}

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

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

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

  def solve = {
    val name = nextString
    if (name.length <= 1)
      out.println("NO")
    else {
      val len = name.length
      val half = len / 2
      val sum = (0 to (half - 1)).map(i => Math.abs(name(i) - name(len - 1 - i))).sum
      if (sum == 0)
        out.println("YES")
      else
        out.println("NO")
    }
  }

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