You are given a sequence $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ pairwise distinct positive integers.Find $$$\left\lfloor \frac n 2 \right\rfloor$$$ different pairs of integers $$$x$$$ and $$$y$$$ such that:   $$$x \neq y$$$;  $$$x$$$ and $$$y$$$ appear in $$$a$$$;  $$$x~mod~y$$$ doesn't appear in $$$a$$$. Note that some $$$x$$$ or $$$y$$$ can belong to multiple pairs.$$$\lfloor x \rfloor$$$ denotes the floor function — the largest integer less than or equal to $$$x$$$. $$$x~mod~y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.If there are multiple solutions, print any of them. It can be shown that at least one solution always exists.

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 a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the sequence. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$). All numbers in the sequence are pairwise distinct. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

The answer for each testcase should contain $$$\left\lfloor \frac n 2 \right\rfloor$$$ different pairs of integers $$$x$$$ and $$$y$$$ such that $$$x \neq y$$$, $$$x$$$ and $$$y$$$ appear in $$$a$$$ and $$$x~mod~y$$$ doesn't appear in $$$a$$$. Print the pairs one after another. You can print the pairs in any order. However, the order of numbers in the pair should be exactly such that the first number is $$$x$$$ and the second number is $$$y$$$. All pairs should be pairwise distinct. If there are multiple solutions, print any of them.

NoteIn the first testcase there are only two pairs: $$$(1, 4)$$$ and $$$(4, 1)$$$. $$$\left\lfloor \frac 2 2 \right\rfloor=1$$$, so we have to find one pair. $$$1~mod~4=1$$$, and $$$1$$$ appears in $$$a$$$, so that pair is invalid. Thus, the only possible answer is a pair $$$(4, 1)$$$.In the second testcase, we chose pairs $$$8~mod~2=0$$$ and $$$8~mod~4=0$$$. $$$0$$$ doesn't appear in $$$a$$$, so that answer is valid. There are multiple possible answers for that testcase.In the third testcase, the chosen pairs are $$$9~mod~5=4$$$ and $$$7~mod~5=2$$$. Neither $$$4$$$, nor $$$2$$$, appears in $$$a$$$, so that answer is valid.

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 n = readInt()
        val arr = new Array[Int](n+1)
        var mn = 1000001
        for (i <- 1 to n) {
            arr(i) = readInt()
            mn = min(mn, arr(i))
        }
        var cnt = (n/2).toInt
        for (i <- 1 to n) {
            if (arr(i) != mn) {
                if (cnt > 0) {
                    cnt -= 1
                    writer.println(arr(i) + " " + mn)
                }
            }
        }

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


Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied: The picture is connected, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side). Each gray cell has an even number of gray neighbours. There are exactly $$$n$$$ gray cells with all gray neighbours. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).Leo Jr. is now struggling to draw a beautiful picture with a particular choice of $$$n$$$. Help him, and provide any example of a beautiful picture.To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin $$$(0, 0)$$$, axes $$$0x$$$ and $$$0y$$$ are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.

The only line contains a single integer $$$n$$$ ($$$1 \leq n \leq 500$$$) — the number of gray cells with all gray neighbours in a beautiful picture.

In the first line, print a single integer $$$k$$$ — the number of gray cells in your picture. For technical reasons, $$$k$$$ should not exceed $$$5 \cdot 10^5$$$. Each of the following $$$k$$$ lines should contain two integers — coordinates of a gray cell in your picture. All listed cells should be distinct, and the picture should satisdfy all the properties listed above. All coordinates should not exceed $$$10^9$$$ by absolute value. One can show that there exists an answer satisfying all requirements with a small enough $$$k$$$.

NoteThe answer for the sample is pictured below:

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
//    val t = readLine().toInt
//    for (i <- 1 to t) {
     val n = readLine().toInt
   handle(n)
//    }
  }

  def handle(n: Int) = {
    def hat(left: Int, upper: Boolean) = {
      val yl = if (upper) 1 else -1
      val yh = if (upper) 2 else -2
      val mid = left + 1
      val right = left + 2
      println(f"$left $yl")
      println(f"$left $yh")
      println(f"$mid $yh")
      println(f"$right $yh")
      println(f"$right $yl")
    }

    println(2 * n + 3 + 5 * (n + 1))

    // main
    (-2 to 2 * n).foreach(i => println(f"$i 0"))

    (0 to n / 2).foreach(i => hat(-2 + 4 * i, upper = true))
    (0 to (n - 1) / 2).foreach(i => hat(4 * i, upper = false))
  }

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

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

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

}

import scala.collection.mutable.ArrayBuffer

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

    val k = nextInt
    val res = ArrayBuffer.empty[String]
    for (i <- 0 to k) {
      val ii = i
      res += s"${ii} ${ii}"
      res += s"${ii + 1} ${ii}"
      res += s"${ii} ${ii + 1}"
    }
    val ii = k
    res += s"${ii + 1} ${ii + 1}"

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

    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 scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
//    val t = readLine().toInt
//    for (i <- 1 to t) {
     val n = readLine().toInt
    println(15 * n)
    (0 until n).foreach(handle)
//    }
  }

  def handle(i: Int) = {
    //center
    println(f"${10*i} 0")
    //neighs
    println(f"${10*i + 1} 0")
    println(f"${10*i + 0} 1")
    println(f"${10*i - 1} 0")
    println(f"${10*i + 0} -1")
    // chains
    println(f"${10*i + 0} 2")
    println(f"${10*i + 1} 2")
    println(f"${10*i + 2} 2")
    println(f"${10*i + 2} 1")
    println(f"${10*i + 2} 0")

    println(f"${10*i + 0} -2")
    println(f"${10*i - 1} -2")
    println(f"${10*i - 2} -2")
    println(f"${10*i - 2} -1")
    println(f"${10*i - 2} 0")
  }

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

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

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
//    val t = readLine().toInt
//    for (i <- 1 to t) {
     val n = readLine().toInt
   handle(n)
//    }
  }

  def handle(n: Int) = {
    def hat(left: Int, upper: Boolean) = {
      val yl = if (upper) 1 else -1
      val yh = if (upper) 2 else -2
      val mid = left + 1
      val right = left + 2
      println(f"$left $yl")
      println(f"$left $yh")
      println(f"$mid $yh")
      println(f"$right $yh")
      println(f"$right $yl")
    }

    println(2 * n + 3 + 5 * (n + 1))

    // main
    (-2 to 2 * n).foreach(i => println(f"$i 0"))

    (0 to n / 2).foreach(i => hat(-2 + 4 * i, upper = true))
    (0 to (n - 1) / 2).foreach(i => hat(4 * i, upper = true))
  }

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

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

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
//    val t = readLine().toInt
//    for (i <- 1 to t) {
     val n = readLine().toInt
      handle(n)
//    }
  }

  def handle(n: Int) = {
    if (n == 1) {
      println(15)
      //center
      println("0 0")
      //neighs
      println("1 0")
      println("0 1")
      println("-1 0")
      println("0 -1")
      // chains
      println("0 2")
      println("1 2")
      println("2 2")
      println("2 1")
      println("2 0")

      println("0 -2")
      println("-1 -2")
      println("-2 -2")
      println("-2 -1")
      println("-2 0")
    }
    else {
      println(4 * n + 12)
      // core
      (0 until n).foreach(i => {
        println(f"$i 1")
        println(f"$i -1")
        println(f"$i 0")
      })
      //chain
      (-2 to n + 1).foreach(i => {
        println(f"$i 3")
      })
      println("-1 0")
      println("-2 0")
      println("-2 1")
      println("-2 2")
      println(f"$n 0")
      println(f"${n+1} 0")
      println(f"${n+1} 1")
      println(f"${n+1} 2")
    }
  }

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

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

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

}


The Department of economic development of IT City created a model of city development till year 2100.To prepare report about growth perspectives it is required to get growth estimates from the model.To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.

The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax2 + bx + c = 0 equation.

In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10 - 6.

import java.util.Scanner

object Main {

  def sqr(x: Long) = x * x

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

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

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

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

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

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

    val Array(a, b, c) = in.nextLine().split(' ').map(_.toDouble)

    val D = b * b - 4 * a * c

    var x1 = (-b + Math.sqrt(D)) / (2 * a)
    var x2 = (-b - Math.sqrt(D)) / (2 * a)

    if (x1 < x2) {
      val c = x1
      x1 = x2
      x2 = c
    }

    println("%.10f\n%.10f".format(x1, x2))
  }
}

import scala.io.StdIn

object Forecast {

  def main(args: Array[String]) {
    val Array(a, b, c) = StdIn.readLine().split("\\s").map(_.toInt)
    val d = Math.sqrt(b * b - 4 * a * c)
    val x1 = -(b + d) / (2 * a)
    val x2 = -(b - d) / (2 * a)
    println(Math.max(x1, x2))
    println(Math.min(x1, x2))
  }

}


You are given $$$n$$$ chips on a number line. The $$$i$$$-th chip is placed at the integer coordinate $$$x_i$$$. Some chips can have equal coordinates.You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:  Move the chip $$$i$$$ by $$$2$$$ to the left or $$$2$$$ to the right for free (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 2$$$ or with $$$x_i + 2$$$);  move the chip $$$i$$$ by $$$1$$$ to the left or $$$1$$$ to the right and pay one coin for this move (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 1$$$ or with $$$x_i + 1$$$). Note that it's allowed to move chips to any integer coordinate, including negative and zero.Your task is to find the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate (i.e. all $$$x_i$$$ should be equal after some sequence of moves).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of chips. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), where $$$x_i$$$ is the coordinate of the $$$i$$$-th chip.

Print one integer — the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate.

NoteIn the first example you need to move the first chip by $$$2$$$ to the right and the second chip by $$$1$$$ to the right or move the third chip by $$$2$$$ to the left and the second chip by $$$1$$$ to the left so the answer is $$$1$$$.In the second example you need to move two chips with coordinate $$$3$$$ by $$$1$$$ to the left so the answer is $$$2$$$.

import scala.io.StdIn

object Main extends App {

  val n: Int = StdIn.readInt()
  val arr: Array[Int] = StdIn.readLine().split(" ").map(_.toInt)

  val odd = arr.filter(item => item%2 == 0).length
  val notOdd = arr.filter(item => item%2 != 0).length

  val res = Math.min(odd, notOdd)

  println(res)

}

//package codeforces.contest1213

object ChipsMoving {

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val (evens, odds) =
      io.StdIn.readLine.split(" ").map(_.toInt).foldLeft((0, 0)) {
        case ((e, o), i) =>
          if ((i & 1) == 1) (e, o + 1) else (e + 1, o)
      }
    println(evens min odds)
  }

}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]) = {
    val numberChips: Int = readInt()
    val chipsCoord = readLine().split(" ").map(_.toInt).toList
    var oddCoord: Int = 0
    var evenCoord: Int = 0
    for (i <- 0 until numberChips) {
      if (chipsCoord(i) % 2 == 0) {
        evenCoord += 1
      } else {
        oddCoord += 1
      }
    }
    println(s"${Math.min(evenCoord, oddCoord)}")
  }
}

import java.io._
import java.util.StringTokenizer
import scala.util.Try

object Sol extends App {
  val (in, out) = Try {(
    new Reader("input.txt"),
    new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))
  )} getOrElse {(
    new Reader(),
    new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
  )}

  val n = in.nextInt
  val a = in.nextLine.split(" ").map(_.toInt)
  def move(x: Int, y: Int) = if ((x - y).abs % 2 == 1) 1 else 0
  def cost(pos: Int): Int = a.foldLeft(0)((acc, cur) => acc + move(pos, cur))

  out.println(a.map(cost).min)
  out.flush()
  out.close()

  class Reader() {
    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 java.io._
import java.util.StringTokenizer
import scala.util.Try

object Sol extends App {
  val (in, out) = Try {(
    new Reader("input.txt"),
    new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))
  )} getOrElse {(
    new Reader(),
    new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
  )}

  val n = in.nextInt
  val a = in.nextLine.split(" ").map(_.toInt)
  val evens = a.count(_ % 2 == 0)

  out.println(evens min (n - evens))
  out.flush()
  out.close()

  class Reader() {
    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 java.io._
import java.util.StringTokenizer
import scala.util.Try

object Sol extends App {
  val (in, out) = Try {(
    new Reader("input.txt"),
    new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))
  )} getOrElse {(
    new Reader(),
    new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
  )}

  val n = in.nextInt
  val a = in.nextLine.split(" ").map(_.toInt)
  val parts = a.partition(_ % 2 == 0)

  out.println(Math.min(parts._1.length, parts._2.length))
  out.flush()
  out.close()

  class Reader() {
    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 java.io._
import java.util.StringTokenizer
import scala.util.Try

object Sol extends App {
  val (in, out) = Try {(
    new Reader("input.txt"),
    new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))
  )} getOrElse {(
    new Reader(),
    new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
  )}

  val n = in.nextInt
  val a = in.nextLine.split(" ").map(_.toInt)
  def move(x: Int, y: Int) = if ((x - y).abs == 1) 1 else 0
  def cost(pos: Int): Int = a.foldLeft(0)((acc, cur) => acc + move(pos, cur))
  implicit def ord: Ordering[Int] = (x: Int, y : Int) => cost(x).compareTo(cost(y))

  out.println(a.min)
  out.flush()
  out.close()

  class Reader() {
    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 java.io._
import java.util.StringTokenizer
import scala.util.Try

object Sol extends App {
  val in = Try(new Reader("input.txt")).getOrElse(new Reader())
  val out = Try(new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))))
    .getOrElse(new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))))

  val n = in.nextInt
  val a = in.nextLine.split(" ").map(_.toInt)
  def move(x: Int, y: Int) = if ((x - y).abs == 1) 1 else 0
  def cost(pos: Int): Int = a.foldLeft(0)((acc, cur) => acc + move(pos, cur))
  implicit def ord: Ordering[Int] = (x: Int, y : Int) => cost(x).compareTo(cost(y))

  out.println(a.min)
  out.flush()
  out.close()

  class Reader() {
    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 java.io._
import java.util.StringTokenizer
import scala.util.Try

object Sol extends App {
  val (in, out) = Try {(
    new Reader("input.txt"),
    new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))
  )} getOrElse {(
    new Reader(),
    new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
  )}

  val n = in.nextInt
  val a = in.nextLine.split(" ").map(_.toInt)
  def move(x: Int, y: Int) = if ((x - y).abs == 1) 1 else 0
  def cost(pos: Int): Int = a.foldLeft(0)((acc, cur) => acc + move(pos, cur))

  out.println(a.map(cost).min)
  out.flush()
  out.close()

  class Reader() {
    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
  }

}


This problem is an extension of the problem "Wonderful Coloring - 1". It has quite many differences, so you should read this statement completely.Recently, Paul and Mary have found a new favorite sequence of integers $$$a_1, a_2, \dots, a_n$$$. They want to paint it using pieces of chalk of $$$k$$$ colors. The coloring of a sequence is called wonderful if the following conditions are met:  each element of the sequence is either painted in one of $$$k$$$ colors or isn't painted;  each two elements which are painted in the same color are different (i. e. there's no two equal values painted in the same color);  let's calculate for each of $$$k$$$ colors the number of elements painted in the color — all calculated numbers must be equal;  the total number of painted elements of the sequence is the maximum among all colorings of the sequence which meet the first three conditions. E. g. consider a sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. One of the wonderful colorings of the sequence is shown in the figure.    The example of a wonderful coloring of the sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. Note that one of the elements isn't painted. Help Paul and Mary to find a wonderful coloring of a given sequence $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first one contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le n$$$) — the length of a given sequence and the number of colors, respectively. The second one contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, each of them must contain a description of a wonderful coloring for the corresponding test case. Each wonderful coloring must be printed as a sequence of $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$0 \le c_i \le k$$$) separated by spaces where   $$$c_i=0$$$, if $$$i$$$-th element isn't painted;  $$$c_i>0$$$, if $$$i$$$-th element is painted in the $$$c_i$$$-th color.  Remember that you need to maximize the total count of painted elements for the wonderful coloring. If there are multiple solutions, print any one.

NoteIn the first test case, the answer is shown in the figure in the statement. The red color has number $$$1$$$, the blue color — $$$2$$$, the green — $$$3$$$.

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

  val t = readInt()

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

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

    val in = {
      val ai2is = Array.fill(n + 1)(List.empty[Int])
      (0 until n).foreach { i => ai2is(an(i)) ::= i }
      ai2is.flatMap(_.take(k))
    }

    ((in.length % k) until in.length).foreach { j =>
      val (i, ci) = (in(j), (j % k) + 1)
      cn(i) = ci
    }

    println(cn.mkString(" "))
  }
}

object B2 extends App {
  import scala.reflect._
  import scala.io.StdIn._

  val t = readInt()

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

    val cn = {
      val cn = Array.fill(n)(0)

      val in = {
        val ai2is = Array.fill(n + 1)(List.empty[Int])
        (0 until n).foreach(i => ai2is(an(i)) ::= i)
        ai2is.flatMap(_.take(k))
      }

      ((in.length % k) until in.length).foreach { j =>
        val (i, ci) = (in(j), (j % k) + 1)
        cn(i) = ci
      }

      cn
    }

    println(cn.mkString(" "))
  }
}

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

object test {
    val writer =  new PrintWriter(System.out)
    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()

    def main(args: Array[String]): Unit = {
        val max_n = 200010
        var a = new Array[Int](max_n)
        val t = readInt()
        for (tt <- 1 to t) {
            var d = Map[Int, ArrayBuffer[Int]]()
            val n = readInt()
            val k = readInt()
            for (i <- 1 to n) {
                val x = readInt()
                if (! d.contains(x))
                    d(x) = new ArrayBuffer[Int]()
                if (d(x).length < k)
                    d(x).append(i)
            }
            var cnt = 0
            for ((key, value) <- d)
                cnt += value.length
            cnt -= cnt % k
            for ((key, value) <- d) {
                var i = 0
                while (cnt > 0 && i < value.length) {
                    a(value(i)) = if (cnt % k > 0) cnt % k else k
                    cnt -= 1
                    i += 1
                }
            }
            for (i <- 1 to n) {
                writer.print(a(i) + " ")
                a(i) = 0
            }
            writer.println()
            writer.flush()
        }
    }
}

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

  val t = readInt()

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

    val cn = {
      val counts = {
        val array = Array.fill(n + 1)(0)
        an.foreach { ai => array(ai) = k min (array(ai) + 1) }
        array.map { c => (c, c == k) }
      }

      var color  = k
      var ignore = counts.foldLeft(0) {
        case (sum, (count, false)) if count > 0 => (sum + count) % k
        case (sum, _)                           => sum
      }

      an.map { ai =>
        counts(ai) match {
          case (ci, true) =>
            counts(ai) = (0 max (ci - 1), true)
            ci
          case (_, false) =>
            if (ignore > 0) {
              ignore -= 1
              0
            } else {
              val ci = color
              color = if (color == 1) k else (color - 1)
              ci
            }
        }
      }
    }

    println(cn.mkString(" "))
  }
}

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

  val t = readInt()

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

    val cn = {
      val counts = {
        val array = Array.fill(n + 1)(0)
        an.foreach { ai => array(ai) = k min (array(ai) + 1) }

        array.map(c => (c, c == k))
      }

      var color    = k
      var composed = counts.foldLeft(0) {
        case (sum, (c, _)) if c < k => sum + c
        case (sum, _)               => sum
      } / k

      an.map { ai =>
        counts(ai) match {
          case (ci, true) if ci > 0                  =>
            counts(ai) = (ci - 1, true)
            ci
          case (ci, false) if ci > 0 && composed > 0 =>
            counts(ai) = (ci - 1, false)
            val cj = color
            if (color == 1) {
              color = k
              composed -= 1
            } else {
              color -= 1
            }
            cj
          case _                                     => 0
        }
      }

    }

    println(cn.mkString(" "))
  }
}


Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's".The restaurant "Alice's" serves $$$n$$$ kinds of food. The cost for the $$$i$$$-th kind is always $$$c_i$$$. Initially, the restaurant has enough ingredients for serving exactly $$$a_i$$$ dishes of the $$$i$$$-th kind. In the New Year's Eve, $$$m$$$ customers will visit Alice's one after another and the $$$j$$$-th customer will order $$$d_j$$$ dishes of the $$$t_j$$$-th kind of food. The $$$(i + 1)$$$-st customer will only come after the $$$i$$$-th customer is completely served.Suppose there are $$$r_i$$$ dishes of the $$$i$$$-th kind remaining (initially $$$r_i = a_i$$$). When a customer orders $$$1$$$ dish of the $$$i$$$-th kind, the following principles will be processed. If $$$r_i > 0$$$, the customer will be served exactly $$$1$$$ dish of the $$$i$$$-th kind. The cost for the dish is $$$c_i$$$. Meanwhile, $$$r_i$$$ will be reduced by $$$1$$$. Otherwise, the customer will be served $$$1$$$ dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $$$1$$$. If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $$$0$$$.If the customer doesn't leave after the $$$d_j$$$ dishes are served, the cost for the customer will be the sum of the cost for these $$$d_j$$$ dishes.Please determine the total cost for each of the $$$m$$$ customers.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), representing the number of different kinds of food and the number of customers, respectively. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$), where $$$a_i$$$ denotes the initial remain of the $$$i$$$-th kind of dishes. The third line contains $$$n$$$ positive integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 10^6$$$), where $$$c_i$$$ denotes the cost of one dish of the $$$i$$$-th kind. The following $$$m$$$ lines describe the orders of the $$$m$$$ customers respectively. The $$$j$$$-th line contains two positive integers $$$t_j$$$ and $$$d_j$$$ ($$$1 \leq t_j \leq n$$$, $$$1 \leq d_j \leq 10^7$$$), representing the kind of food and the number of dishes the $$$j$$$-th customer orders, respectively.

Print $$$m$$$ lines. In the $$$j$$$-th line print the cost for the $$$j$$$-th customer.

NoteIn the first sample, $$$5$$$ customers will be served as follows. Customer $$$1$$$ will be served $$$6$$$ dishes of the $$$2$$$-nd kind, $$$1$$$ dish of the $$$4$$$-th kind, and $$$1$$$ dish of the $$$6$$$-th kind. The cost is $$$6 \cdot 3 + 1 \cdot 2 + 1 \cdot 2 = 22$$$. The remain of the $$$8$$$ kinds of food will be $$$\{8, 0, 2, 0, 4, 4, 7, 5\}$$$. Customer $$$2$$$ will be served $$$4$$$ dishes of the $$$1$$$-st kind. The cost is $$$4 \cdot 6 = 24$$$. The remain will be $$$\{4, 0, 2, 0, 4, 4, 7, 5\}$$$. Customer $$$3$$$ will be served $$$4$$$ dishes of the $$$6$$$-th kind, $$$3$$$ dishes of the $$$8$$$-th kind. The cost is $$$4 \cdot 2 + 3 \cdot 2 = 14$$$. The remain will be $$$\{4, 0, 2, 0, 4, 0, 7, 2\}$$$. Customer $$$4$$$ will be served $$$2$$$ dishes of the $$$3$$$-rd kind, $$$2$$$ dishes of the $$$8$$$-th kind. The cost is $$$2 \cdot 3 + 2 \cdot 2 = 10$$$. The remain will be $$$\{4, 0, 0, 0, 4, 0, 7, 0\}$$$. Customer $$$5$$$ will be served $$$7$$$ dishes of the $$$7$$$-th kind, $$$3$$$ dishes of the $$$1$$$-st kind. The cost is $$$7 \cdot 3 + 3 \cdot 6 = 39$$$. The remain will be $$$\{1, 0, 0, 0, 4, 0, 0, 0\}$$$.In the second sample, each customer is served what they order except the last one, who leaves angrily without paying. For example, the second customer is served $$$6$$$ dishes of the second kind, so the cost is $$$66 \cdot 6 = 396$$$.In the third sample, some customers may not be served what they order. For example, the second customer is served $$$6$$$ dishes of the second kind, $$$6$$$ of the third and $$$1$$$ of the fourth, so the cost is $$$66 \cdot 6 + 666 \cdot 6 + 6666 \cdot 1 = 11058$$$.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

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

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N, M = ni()
    val A, C = na(N)
    val cheap = Array.ofDim[Integer](N)
    REP(N) { i =>
      cheap(i) = i
    }

    java.util.Arrays.sort(cheap, new Comparator[Integer] {
      override def compare(o1: Integer, o2: Integer): Int = {
        if (C(o1) == C(o2)) Integer.compare(o1, o2)
        else Integer.compare(C(o1), C(o2))
      }
    })
    var ptr = 0

    //    debug(cheap.mkString(" "))

    REP(M) { _ =>
      var cost = 0L
      val t = ni() - 1
      var d = ni()

      def eat(t: Int): Unit = {
        val num = min(d, A(t))
        //        debug(s"eat $t $num")
        cost += num.toLong * C(t)
        d -= num
        A(t) -= num
      }

      eat(t)

      while (d > 0 && ptr < N) {
        eat(cheap(ptr))
        if (A(cheap(ptr)) == 0) ptr += 1
      }

      //      debug(A)
      if (d > 0) out.println(0)
      else out.println(cost)
    }
  }

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

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

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

  def debug(num: Long): Unit = {
    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 = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.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 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]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

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

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N, M = ni()
    val A, C = na(N)
    val cheap = Array.ofDim[Integer](N)
    REP(N) { i =>
      cheap(i) = i
    }

    java.util.Arrays.sort(cheap, new Comparator[Integer] {
      override def compare(o1: Integer, o2: Integer): Int = {
        if (C(o1) == C(o2)) Integer.compare(o1, o2)
        else Integer.compare(C(o1), C(o2))
      }
    })
    var ptr = 0

//    debug(cheap.mkString(" "))

    REP(M) { _ =>
      var cost = 0L
      val t = ni() - 1
      var d = ni()

      def eat(t: Int): Unit = {
        val num = min(d, A(t))
//        debug(s"eat $t $num")
        cost += num * C(t)
        d -= num
        A(t) -= num
      }

      eat(t)

      while (d > 0 && ptr < N) {
        eat(cheap(ptr))
        if (A(cheap(ptr)) == 0) ptr += 1
      }

//      debug(A)
      if (d > 0) out.println(0)
      else out.println(cost)
    }
  }

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

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

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

  def debug(num: Long): Unit = {
    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 = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.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 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]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.You are given an integer array $$$a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$$$.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[3, 4, 4]$$$ currently in the deque, adding an element $$$1$$$ to the beginning will produce the sequence $$$[\color{red}{1}, 3, 4, 4]$$$, and adding the same element to the end will produce $$$[3, 4, 4, \color{red}{1}]$$$.The elements of the array are sequentially added to the initially empty deque, starting with $$$a_1$$$ and finishing with $$$a_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or to the end.For example, if we consider an array $$$a = [3, 7, 5, 5]$$$, one of the possible sequences of actions looks like this: $$$\quad$$$ 1.add $$$3$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{3}]$$$ in it;$$$\quad$$$ 2.add $$$7$$$ to the end of the deque:deque has a sequence $$$[3, \color{red}{7}]$$$ in it;$$$\quad$$$ 3.add $$$5$$$ to the end of the deque:deque has a sequence $$$[3, 7, \color{red}{5}]$$$ in it;$$$\quad$$$ 4.add $$$5$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{5}, 3, 7, 5]$$$ in it;Find the minimal possible number of inversions in the deque after the whole array is processed. An inversion in sequence $$$d$$$ is a pair of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$d_i > d_j$$$. For example, the array $$$d = [5, 3, 7, 5]$$$ has exactly two inversions — $$$(1, 2)$$$ and $$$(3, 4)$$$, since $$$d_1 = 5 > 3 = d_2$$$ and $$$d_3 = 7 > 5 = d_4$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases.  The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — array size. The second line of the description contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the minimal possible number of inversions in the deque after executing the described algorithm.

NoteOne of the ways to get the sequence $$$[5, 3, 7, 5]$$$ in the deque, containing only two inversions, from the initial array $$$[3, 7, 5, 5]$$$ (the first sample test case) is described in the problem statement. Also, in this example, you could get the answer of two inversions by simply putting each element of the original array at the end of the deque. In this case, the original sequence $$$[3, 7, 5, 5]$$$, also containing exactly two inversions, will be in the deque as-is.

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

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

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

    case class pair(var value: Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return value.compareTo(that.value)
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val pa = new Array[pair](n)
        val arr = new Array[Int](n)
        for (i <- 0 until n) {
            arr(i) = readInt()
            pa(i) = pair(value = arr(i), ind = i)
        }
        quickSort(pa)
        val ind = new Array[Int](n)
        var cnt = 1
        for (i <- 0 until n) {
            if (i > 0 && pa(i).value != pa(i-1).value)
                cnt += 1
            ind(pa(i).ind) = cnt
        }
        val sum = fenwick(n)
        var ans = 0L
        for (i <- 0 until n) {
            val l = sum.query(ind(i)-1)
            val r = i - sum.query(ind(i))
            ans += min(l, r)
            sum.update(ind(i), 1L)
        }
        writer.println(ans)
    }
    writer.flush()
}


You are given two arrays $$$a$$$ and $$$b$$$ of positive integers, with length $$$n$$$ and $$$m$$$ respectively. Let $$$c$$$ be an $$$n \times m$$$ matrix, where $$$c_{i,j} = a_i \cdot b_j$$$. You need to find a subrectangle of the matrix $$$c$$$ such that the sum of its elements is at most $$$x$$$, and its area (the total number of elements) is the largest possible.Formally, you need to find the largest number $$$s$$$ such that it is possible to choose integers $$$x_1, x_2, y_1, y_2$$$ subject to $$$1 \leq x_1 \leq x_2 \leq n$$$, $$$1 \leq y_1 \leq y_2 \leq m$$$, $$$(x_2 - x_1 + 1) \times (y_2 - y_1 + 1) = s$$$, and $$$$$$\sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x.$$$$$$

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 2000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2000$$$). The third line contains $$$m$$$ integers $$$b_1, b_2, \ldots, b_m$$$ ($$$1 \leq b_i \leq 2000$$$). The fourth line contains a single integer $$$x$$$ ($$$1 \leq x \leq 2 \cdot 10^{9}$$$).

If it is possible to choose four integers $$$x_1, x_2, y_1, y_2$$$ such that $$$1 \leq x_1 \leq x_2 \leq n$$$, $$$1 \leq y_1 \leq y_2 \leq m$$$, and $$$\sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x$$$, output the largest value of $$$(x_2 - x_1 + 1) \times (y_2 - y_1 + 1)$$$ among all such quadruplets, otherwise output $$$0$$$.

NoteMatrix from the first sample and the chosen subrectangle (of blue color):  Matrix from the second sample and the chosen subrectangle (of blue color):

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)
    val B = na(M)
    val X = ni()

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

    def calcMinLen(n: Int, cum: Array[Int]) = {
      val len = Array.fill[Int](2001)(Integer.MAX_VALUE)
      rep(n) { l =>
        l until n foreach { r =>
          val i = r - l + 1
          len(i) = min(len(i), cum(r + 1) - cum(l))
        }
      }
      len
    }

    val cumA = cum(A)
    val cumB = cum(B)

    val minALen = calcMinLen(N, cumA)
    val minBLen = calcMinLen(M, cumB)

    var ans = 0
    rep(2000, 1) { aLen =>
      rep(2000, 1) { bLen =>
        val v = minALen(aLen).toLong * minBLen(bLen)
        if (v <= X) ans = max(ans, aLen * bLen)
      }
    }

    out.println(ans)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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 map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

object C1060 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val temp = stdin.readLine.split(" ")
    val (n, m) = (temp(0).toInt, temp(1).toInt)
    val a = stdin.readLine.trim.split(" ").map(_.toLong)
    val b = stdin.readLine.trim.split(" ").map(_.toLong)
    val x = stdin.readInt()

    def sum(array: Array[Long]): Array[Long] = {
      val res = Array.fill[Long](array.length)(Long.MaxValue)
      for (i <- array.indices) {
        var temp = 0L
        for (j <- array.indices if i + j < array.length) {
          temp = temp + array(i + j)
          res(j) = math.min(res(j), temp)
        }
      }
      res
    }

    val (sa, sb) = (sum(a), sum(b))
    var ans = 0
    for (i <- sa.indices) {
      for (j <- sb.indices if sa(i) * sb(j) <= x) {
        ans = math.max(ans, (i + 1) * (j + 1))
      }
    }

    println(ans)
  }
}

object C1060 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val temp = stdin.readLine.split(" ")
    val (n, m) = (temp(0).toInt, temp(1).toInt)
    val a = stdin.readLine.trim.split(" ").map(_.toLong)
    val b = stdin.readLine.trim.split(" ").map(_.toLong)
    val x = stdin.readInt()

    import scala.util.control.Breaks._
    def sum(array: Array[Long]):Array[Long] ={
      val res = Array.fill[Long](array.length)(Long.MaxValue)
      for (i <- array.indices){
        var temp = 0L
        for (j <- array.indices if i+j < array.length){
          temp = temp + array(i+j)
          res(j) = math.min(res(j), temp)
        }
      }
      res
    }

    val (sa, sb) = (sum(a), sum(b))
    var ans = 0
    for (i <- sa.indices){
      breakable{
        for (j <- sb.indices){
          if (sa(i) * sb(j) <= x){
            ans = math.max(ans, (i+1)*(j+1))
          } else break
        }
      }

    }

    println(ans)
  }
}


Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$="abac", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: "ab", "ba", "ac". Therefore, the string $$$b$$$="abbaac".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.

The first line contains a single positive integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case consists of one line in which the string $$$b$$$ is written, consisting of lowercase English letters ($$$2 \le |b| \le 100$$$) — the string Bob came up with, where $$$|b|$$$ is the length of the string $$$b$$$. It is guaranteed that $$$b$$$ was built according to the algorithm given above.

Output $$$t$$$ answers to test cases. Each answer is the secret string $$$a$$$, consisting of lowercase English letters, that Bob came up with.

NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string $$$a$$$="ac", the string $$$a$$$ has a length $$$2$$$, so the string $$$b$$$ is equal to the string $$$a$$$.In the third test case, Bob came up with the string $$$a$$$="bcdaf", substrings of length $$$2$$$ of string $$$a$$$ are: "bc", "cd", "da", "af", so the string $$$b$$$="bccddaaf".

//package codeforces.contests._1367

object _1 {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val s = io.StdIn.readLine
      println(s.indices.by(2).map(s).mkString + s.last)
    }
  }

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val b = readLine().toCharArray.toList
      handle(b)
    }
  }

  def handle(list: List[Char]): Unit = {
    print(list.head)
    list.tail.zipWithIndex.foreach(tup => if (tup._2 % 2 == 0) print(tup._1))
    println()
  }

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

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

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

}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val n = StdIn.readLine().toInt
    for (_ <- 1 to n) {
      val str = StdIn.readLine()
      var res = "" + str.head
      for (i <- 1 until str.length by 2) {
        res += str(i)
      }
      println(res)
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val b = readLine()
    val a = b.init.zipWithIndex.collect { case (c, i) if i % 2 == 0 => c }.mkString + b.last

    println(a)
  }
}

object Main extends App {
  val r = new FastScanner(java.lang.System.in)
  val o = new java.io.PrintWriter(java.lang.System.out)
  for(_ <- 1 to r.nextInt()) {
    val s = r.nextToken()
    o.print(s(0))
    for(k <- 1 until s.length by 2) {
      o.print(s(k))
    }
    o.println()
  }
  o.close()
}

import scala.annotation.tailrec
import scala.collection.mutable.StringBuilder

object FastScanner {
  val zero = 0.toByte
  val cr = '\r'.toByte
  val nl = '\n'.toByte
  val BUFFER_SIZE = 0x10000
}

class FastScanner(private val input: java.io.InputStream) {
  private val b = new Array[Byte](FastScanner.BUFFER_SIZE)
  private var n = 0
  private var pos = 0
  private var eof = false
  private def read ():Boolean = {
    if (eof) {
      return false
    }
    pos = 0
    n = input.read(b)
    if (n < 0) {
      eof = true
    }
    n > 0
  }
  private def nextByte(): Byte = {
    if (pos >= n && !read ()) {
      0
    } else {
      val r = b(pos)
      pos += 1
      r
    }
  }
  def nextToken(k: Int = -1): String = {
    val sb = if(k >= 0) new StringBuilder(k) else new StringBuilder()
    var b = skipBlanks()
    assert(b > 0)
    while(b > 32) {
      sb.append(b.toChar)
      b = nextByte()
    }
    sb.toString
  }
  @tailrec
  private def skipBlanks(): Byte = {
    val b = nextByte()
    if(b > 32 || b < 1) b else skipBlanks()
  }
  def nextInt():Int = {
    val b = skipBlanks()
    @tailrec
    def f(t: Int): Int = {
      val b = nextByte ()
      if (b <= 32) t else f(10 * t + (b - 48))
    }
    require(b > 0)
    if (b < 48) -f(0) else f(b - 48)
  }
}

import scala.io.StdIn._

object A extends App {

  val t = readInt()
  1 to t foreach { _ =>
    val A = readLine().toCharArray
    val a = A(0)
    val b = A(1)

    val rest = 3 until A.length by 2 map { i =>
      A(i)
    }

    println("" + a + b + rest.mkString)
  }

}

object A extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

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

  def solve = {
    var n = nextInt

    1.to(n).foreach(_ => {
      val b = nextString
      val max = b.length
      for (a <- 0 until max by 2){
        print(b(a))
      }
      println(b(max - 1))
    })

//    out.println(a.reduceLeft[Int](_+_))
  }

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


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Each of $$$a_i$$$ has between $$$3$$$ and $$$5$$$ divisors. Consider $$$a = \prod a_i$$$ — the product of all input integers. Find the number of divisors of $$$a$$$. As this number may be very large, print it modulo prime number $$$998244353$$$.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 500$$$) — the number of numbers. Each of the next $$$n$$$ lines contains an integer $$$a_i$$$ ($$$1 \leq a_i \leq 2\cdot 10^{18}$$$). It is guaranteed that the number of divisors of each $$$a_i$$$ is between $$$3$$$ and $$$5$$$.

Print a single integer $$$d$$$ — the number of divisors of the product $$$a_1 \cdot a_2 \cdot \dots \cdot a_n$$$ modulo $$$998244353$$$. Hacks input For hacks, the input needs to be provided in a special format. The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 500$$$) — the number of numbers. Each of the next $$$n$$$ lines contains a prime factorization of $$$a_i$$$. The line contains an integer $$$k_i$$$ ($$$2 \leq k_i \leq 4$$$) — the number of prime factors of $$$a_i$$$ and $$$k_i$$$ integers $$$p_{i,j}$$$ ($$$2 \leq p_{i,j} \leq 2 \cdot 10^{18}$$$) where $$$p_{i,j}$$$ is the $$$j$$$-th prime factor of $$$a_i$$$.  Before supplying the input to the contestant, $$$a_i = \prod p_{i,j}$$$ are calculated. Note that each $$$p_{i,j}$$$ must be prime, each computed $$$a_i$$$ must satisfy $$$a_i \leq 2\cdot10^{18}$$$ and must have between $$$3$$$ and $$$5$$$ divisors. The contestant will be given only $$$a_i$$$, and not its prime factorization.  For example, you need to use this test to get the first sample: 32 3 32 3 52 11 13

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = nal(N)
    val f = mutable.Map[Long, Int]() withDefaultValue 0
    val ab = mutable.Map[Long, Int]() withDefaultValue 0

    rep(N) { i =>
      val sqrt = math.sqrt(A(i)).toLong
      val cbrb = math.cbrt(A(i)).toLong
      val quort = math.sqrt(sqrt).toLong
      if (quort * quort * quort * quort == A(i)) {
        f(quort) = f(quort) + 4
      } else if (sqrt * sqrt == A(i)) {
        f(sqrt) = f(sqrt) + 2
      } else if (cbrb * cbrb * cbrb == A(i)) {
        f(cbrb) = f(cbrb) + 3
      } else {
        ab(A(i)) = ab(A(i)) + 1
      }
    }

    val ab_seq = ab.keys.toSeq
    val ab_f = mutable.Set[Long]()
    rep(ab_seq.length) { i =>
      i + 1 until ab_seq.length foreach { j =>
        val g = gcd(ab_seq(i), ab_seq(j))
        if (g > 1) {
          ab_f += g
          ab_f += ab_seq(i) / g
          ab_f += ab_seq(j) / g
        }
      }
    }

    def findFactor(a: Long): Option[Long] = {
      f.keys.find(a % _ == 0) orElse ab_f.find(a % _ == 0)
    }

    var ans = 1L
    ab_seq.zipWithIndex foreach { case (x, i) =>
      val cnt = ab(x)
      findFactor(x) match {
        case Some(a) =>
          val b = x / a
          f(a) = f(a) + cnt
          f(b) = f(b) + cnt

        case None => ans = ans * (cnt + 1) * (cnt + 1) % MOD
      }
    }

    f.foreach { case (_, cnt) =>
      ans = ans * (cnt + 1) % MOD
    }

    out.println(ans)
  }

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

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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 map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

import scala.collection.mutable

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 gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  def pow(n: Long, p: Int): Long = {
    var res = 1L
    var i = 0
    while (i < p) {
      res *= n
      i += 1
    }
    res
  }

  def root(number: Long, p: Int): Long = {
    var n = Math.pow(number, 1d / p).toLong
    while (pow(n + 1, p) <= number) n += 1
    n
  }

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLine.toLong }
  val as0 = as.clone()

  val divisors = mutable.LongMap.empty[Int].withDefaultValue(0)

  def add(p: Long, cnt: Int): Unit = {
    divisors(p) += cnt
  }

  for (i <- as.indices) if (as(i) > 1) {
    val r4 = root(as(i), 4)
    if (as(i) == pow(r4, 4)) {
      add(r4, 4)
      as(i) = 1
    } else {
      val r3 = root(as(i), 3)
      if (as(i) == pow(r3, 3)) {
        add(r3, 3)
        as(i) = 1
      } else {
        val r2 = root(as(i), 2)
        if (as(i) == pow(r2, 2)) {
          add(r2, 2)
          as(i) = 1
        }
      }
    }
  }

  val gcds = mutable.Set.empty[Long]
  gcds ++= divisors.keys

  var i = 0
  while (i < n) {
    if (as(i) > 1) {
      var j = i + 1
      while (j < n) {
        if (as(j) > 1) {}
        val d = gcd(as(i), as(j))
        if (d > 1) gcds += d
        j += 1
      }
    }
    i += 1
  }

  for (g <- gcds) {
    var i = 0
    while (i < n) {
      if (as(i) != g && as(i) % g == 0) {
        add(g, 1)
        as(i) /= g
        if (as(i) > 1) {
          add(as(i), 1)
          as(i) = 1
        }
      }
      i += 1
    }
  }

  val composites = mutable.LongMap.empty[Int].withDefaultValue(0)
  i = 0
  while (i < n) {
    if (as(i) == as0(i)) composites(as(i)) += 1
    i += 1
  }

  val MOD = 998244353L
  var res = 1L
  for ((_, v) <- divisors) {
    res = res * (v + 1) % MOD
  }
  for ((_, v) <- composites) {
    res = res * (v + 1) * (v + 1) % MOD
  }

  println(res)
}

import scala.collection.mutable

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 gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  def pow(n: Long, p: Int): Long = {
    var res = 1L
    var i = 0
    while (i < p) {
      res *= n
      i += 1
    }
    res
  }

  def root(number: Long, p: Int): Long = {
    var n = Math.pow(number, 1d / p).toLong
    while (pow(n + 1, p) <= number) n += 1
    n
  }

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLine.toLong }

  val divisors = mutable.LongMap.empty[Int].withDefaultValue(0)

  def add(p: Long, cnt: Int): Unit = {
    divisors(p) += cnt
  }

  for (i <- as.indices) if (as(i) > 1) {
    val r4 = root(as(i), 4)
    if (as(i) == pow(r4, 4)) {
      add(r4, 4)
      as(i) = 1
    } else {
      val r3 = root(as(i), 3)
      if (as(i) == pow(r3, 3)) {
        add(r3, 3)
        as(i) = 1
      } else {
        val r2 = root(as(i), 2)
        if (as(i) == pow(r2, 2)) {
          add(r2, 2)
          as(i) = 1
        }
      }
    }
  }

  val gcds = mutable.Set.empty[Long]
  gcds ++= divisors.keys

  for {
    i <- 0 until n
    if as(i) > 1
    j <- i + 1 until n
    if as(j) > 1
    d = gcd(as(i), as(j))
    if d > 1
  } gcds += d

  for {
    g <- gcds.toSeq.sorted
    i <- 0 until n
    if as(i) != g && as(i) % g == 0
  } {
    add(g, 1)
    as(i) /= g
    if (as(i) > 1) {
      add(as(i), 1)
      as(i) = 1
    }
  }

  val composites = mutable.LongMap.empty[Int].withDefaultValue(0)
  for (a <- as) if (a > 1) composites(a) += 1

  val MOD = 998244353L
  var res = 1L
  for ((_, v) <- divisors) {
    res = res * (v + 1) % MOD
  }
  for ((_, v) <- composites) {
    res = res * (v + 1) * (v + 1) % MOD
  }

  println(res)
}

import scala.collection.mutable

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

  def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  def sqrt(number: Long): Long = {
    def next(n: Long, i: Long): Long = (n + i / n) >> 1

    val one = 1L

    var n = one
    var n1 = next(n, number)

    while ((n1 - n).abs > one) {
      n = n1
      n1 = next(n, number)
    }

    while (n1 * n1 > number) {
      n1 -= one
    }

    n1
  }

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLine.toLong }

  val LIMIT = 1259929
  val LIMIT_SQRT = Math.sqrt(LIMIT).toInt + 1
  val isPrime = Array.fill(LIMIT)(true)
  val primesBuilder = new mutable.ArrayBuilder.ofInt
  primesBuilder += 2
  isPrime(0) = false
  isPrime(1) = false

  var i = 4
  while (i < LIMIT) {
    isPrime(i) = false
    i += 2
  }
  i = 3
  while (i <= LIMIT_SQRT) {
    if (isPrime(i)) {
      primesBuilder += i
      var j = i * i
      val ii = i + i
      while (j < LIMIT) {
        isPrime(j) = false
        j += ii
      }
    }
    i += 2
  }

  val primes = primesBuilder.result()

  val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)

  def add(p: Long, cnt: Int): Unit = {
    divisors(p) += cnt
  }

  for (j <- as.indices) {
    var aa = as(j)
    var i = 0
    while (i < primes.length && aa >= primes(i)) {
      val p = primes(i)
      if (aa % p == 0) {
        aa /= p
        add(p, 1)
      } else i += 1
    }
    as(j) = aa
  }

  val gcdsBuilder = new mutable.ArrayBuilder.ofLong
  val haveGcd = mutable.Set.empty[Long]

  i = 0
  while (i < n) {
    if (as(i) > 1) {
      var j = i + 1
      while (j < n) {
        if (as(j) > 1) {
          val d = gcd(as(i), as(j))
          if (d > 1 && !haveGcd(d)) {
            gcdsBuilder += d
            haveGcd += d
          }
        }
        j += 1
      }
    }
    i += 1
  }

  val gcds = gcdsBuilder.result()
  var j = 0
  while (j < gcds.length) {
    val g = gcds(j)
    var i = 0
    while (i < as.length) {
      if (as(i) % g == 0) {
        as(i) /= g
        add(g, 1)
      }
      i += 1
    }
    j += 1
  }

  var unknownDivisors = 0
  for (i <- as.indices) if (as(i) > 1) {
    val r = sqrt(as(i))
    if (as(i) == r * r) add(r, 2)
    else {
      if ((as(i) < isPrime.length && isPrime(as(i).toInt))
        || BigInt(as(i)).isProbablePrime(20)) add(as(i), 1)
      else unknownDivisors += 2
    }
  }

  val MOD = 998244353L
  var res = 1L
  for ((_, v) <- divisors) {
    res = res * (v + 1) % MOD
  }
  for (_ <- 1 to unknownDivisors) res = res * 2 % MOD

  println(res)
}

import scala.collection.mutable

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 gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  def next(n: Long, i: Long): Long = (n + i / n) >> 1

  def pow(n: Long, p: Int): Long = {
    var res = 1L
    for (_ <- 1 to p) res *= n
    res
  }

  def root(number: Long, p: Int): Long = {

    var n = 1L
    var n1 = next(n, number)

    while ((n1 - n).abs > 1) {
      n = n1
      n1 = next(n, number)
    }

    while (pow(n1, p) > number) n1 -= 1

    n1
  }

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLine.toLong }
  val as0 = as.clone()

  val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)

  def add(p: Long, cnt: Int): Unit = {
    divisors(p) += cnt
  }

  for (i <- as.indices) if (as(i) > 1) {
    val r4 = root(as(i), 4)
    if (as(i) == pow(r4, 4)) {
      add(r4, 3)
      as(i) = r4
    } else {
      val r3 = root(as(i), 3)
      if (as(i) == pow(r3, 3)) {
        add(r3, 2)
        as(i) = r3
      } else {
        val r2 = root(as(i), 2)
        if (as(i) == pow(r2, 2)) {
          add(r2, 1)
          as(i) = r2
        }
      }
    }
  }

  val gcds = mutable.Set.empty[Long]
  for {
    i <- 0 until n
    if as(i) > 1
    j <- i + 1 until n
    if as(j) > 1
    d = gcd(as(i), as(j))
    if d > 1
  } gcds += d

  for {
    g <- gcds
    i <- 0 until n
    if as(i) % g == 0
  } {
    as(i) /= g
    add(g, 1)
  }

  val MOD = 998244353L
  var res = 1L
  for ((_, v) <- divisors) {
    res = res * (v + 1) % MOD
  }
  for (i <- 0 until n) {
    if (as(i) > 1) {
      res = if (as(i) == as0(i)) res * 4 % MOD else res * 2 % MOD
    }
  }

  println(res)
}

import scala.collection.mutable

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 gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  def next(n: Long, i: Long): Long = (n + i / n) >> 1

  def pow(n: Long, p: Int): Long = {
    var res = 1L
    for (_ <- 1 to p) res *= n
    res
  }

  def root(number: Long, p: Int): Long = {

    var n = 1L
    var n1 = next(n, number)

    while ((n1 - n).abs > 1) {
      n = n1
      n1 = next(n, number)
    }

    while (pow(n1, p) > number) n1 -= 1

    n1
  }

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLine.toLong }
  val as0 = as.clone()

  val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)

  def add(p: Long, cnt: Int): Unit = {
    divisors(p) += cnt
  }

  for (i <- as.indices) if (as(i) > 1) {
    val r4 = root(as(i), 4)
    if (as(i) == pow(r4, 4)) {
      add(r4, 3)
      as(i) = r4
    } else {
      val r3 = root(as(i), 3)
      if (as(i) == pow(r3, 3)) {
        add(r3, 2)
        as(i) = r3
      } else {
        val r2 = root(as(i), 2)
        if (as(i) == pow(r2, 2)) {
          add(r2, 1)
          as(i) = r2
        }
      }
    }
  }

  val gcds = mutable.Set.empty[Long]
  for {
    i <- 0 until n
    if as(i) > 1
    j <- i + 1 until n
    if as(j) > 1
    d = gcd(as(i), as(j))
    if d > 1
  } gcds += d

  for {
    g <- gcds
    i <- 0 until n
    if as(i) % g == 0
  } {
    as(i) /= g
    add(g, 1)
  }

  var unknownDivisors = 0
  for (i <- 0 until n) {
    if (as(i) > 1) {
      if (divisors.contains(as(i))) add(as(i), 1)
      else if (as(i) == as0(i)) unknownDivisors += 2
      else unknownDivisors += 1
    }
  }

  val MOD = 998244353L
  var res = 1L
  for ((_, v) <- divisors) {
    res = res * (v + 1) % MOD
  }
  for (_ <- 1 to unknownDivisors) res = res * 2 % MOD

  println(res)
}

import scala.collection.mutable

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

  def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  def sqrt(number: Long): Long = {
    def next(n: Long, i: Long): Long = (n + i / n) >> 1

    val one = 1L

    var n = one
    var n1 = next(n, number)

    while ((n1 - n).abs > one) {
      n = n1
      n1 = next(n, number)
    }

    while (n1 * n1 > number) {
      n1 -= one
    }

    n1
  }

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLine.toLong }

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

  var i = 2
  while (i * i < LIMIT) {
    if (isPrime(i)) {
      var j = i * i
      val ii = i + i
      while (j < LIMIT) {
        isPrime(j) = false
        j += ii
      }
    }
    i += 1
  }

  val primes = Array.ofDim[Int](97178)
  i = 0
  var j = 0
  while (i < LIMIT) {
    if (isPrime(i)) {
      primes(j) = i
      j += 1
    }
    i += 1
  }

  val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)

  def add(p: Long, cnt: Int): Unit = {
    divisors(p) += cnt
  }

  for (j <- as.indices) {
    var aa = as(j)
    var i = 0
    while (i < primes.length && aa >= primes(i)) {
      val p = primes(i)
      if (aa % p == 0) {
        aa /= p
        add(p, 1)
      } else i += 1
    }
    as(j) = aa
  }

  val gcdsBuilder = new mutable.ArrayBuilder.ofLong
  val haveGcd = mutable.Set.empty[Long]

  i = 0
  while (i < n) {
    if (as(i) > 1) {
      var j = i + 1
      while (j < n) {
        if (as(j) > 1) {
          val d = gcd(as(i), as(j))
          if (d > 1 && !haveGcd(d)) {
            gcdsBuilder += d
            haveGcd += d
          }
        }
        j += 1
      }
    }
    i += 1
  }

  val gcds = gcdsBuilder.result()
  j = 0
  while (j < gcds.length) {
    val g = gcds(j)
    var i = 0
    while (i < as.length) {
      if (as(i) % g == 0) {
        as(i) /= g
        add(g, 1)
      }
      i += 1
    }
    j += 1
  }

  var unknownDivisors = 0
  for (i <- as.indices) if (as(i) > 1) {
    val r = sqrt(as(i))
    if (as(i) == r * r) add(r, 2)
    else {
      if ((as(i) < isPrime.length && isPrime(as(i).toInt))
        || BigInt(as(i)).isProbablePrime(20)) add(as(i), 1)
      else unknownDivisors += 2
    }
  }

  val MOD = 998244353L
  var res = 1L
  for ((_, v) <- divisors) {
    res = res * (v + 1) % MOD
  }
  for (_ <- 1 to unknownDivisors) res = res * 2 % MOD

  println(res)
}

import scala.collection.mutable

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

  def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  def sqrt(number: Long): Long = {
    def next(n: Long, i: Long): Long = (n + i / n) >> 1

    val one = 1L

    var n = one
    var n1 = next(n, number)

    while ((n1 - n).abs > one) {
      n = n1
      n1 = next(n, number)
    }

    while (n1 * n1 > number) {
      n1 -= one
    }

    n1
  }

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLine.toLong }

  val LIMIT = 1259929
  val LIMIT_SQRT = Math.sqrt(LIMIT).toInt + 1
  val isPrime = Array.fill(LIMIT)(true)
  val primesBuilder = new mutable.ArrayBuilder.ofInt
  primesBuilder += 2
  isPrime(0) = false
  isPrime(1) = false

  var i = 4
  while (i < LIMIT) {
    isPrime(i) = false
    i += 2
  }
  i = 3
  while (i * i < LIMIT_SQRT) {
    if (isPrime(i)) {
      primesBuilder += i
      var j = i * i
      val ii = i + i
      while (j < LIMIT) {
        isPrime(j) = false
        j += ii
      }
    }
    i += 2
  }

  val primes = primesBuilder.result()

  val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)

  def add(p: Long, cnt: Int): Unit = {
    divisors(p) += cnt
  }

  for (j <- as.indices) {
    var aa = as(j)
    var i = 0
    while (i < primes.length && aa >= primes(i)) {
      val p = primes(i)
      if (aa % p == 0) {
        aa /= p
        add(p, 1)
      } else i += 1
    }
    as(j) = aa
  }

  val gcdsBuilder = new mutable.ArrayBuilder.ofLong
  val haveGcd = mutable.Set.empty[Long]

  i = 0
  while (i < n) {
    if (as(i) > 1) {
      var j = i + 1
      while (j < n) {
        if (as(j) > 1) {
          val d = gcd(as(i), as(j))
          if (d > 1 && !haveGcd(d)) {
            gcdsBuilder += d
            haveGcd += d
          }
        }
        j += 1
      }
    }
    i += 1
  }

  val gcds = gcdsBuilder.result()
  var j = 0
  while (j < gcds.length) {
    val g = gcds(j)
    var i = 0
    while (i < as.length) {
      if (as(i) % g == 0) {
        as(i) /= g
        add(g, 1)
      }
      i += 1
    }
    j += 1
  }

  var unknownDivisors = 0
  for (i <- as.indices) if (as(i) > 1) {
    val r = sqrt(as(i))
    if (as(i) == r * r) add(r, 2)
    else {
      if ((as(i) < isPrime.length && isPrime(as(i).toInt))
        || BigInt(as(i)).isProbablePrime(20)) add(as(i), 1)
      else unknownDivisors += 2
    }
  }

  val MOD = 998244353L
  var res = 1L
  for ((_, v) <- divisors) {
    res = res * (v + 1) % MOD
  }
  for (_ <- 1 to unknownDivisors) res = res * 2 % MOD

  println(res)
}

import scala.collection.mutable

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

  def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  def sqrt(number: Long): Long = {
    def next(n: Long, i: Long): Long = (n + i / n) >> 1

    val one = 1L

    var n = one
    var n1 = next(n, number)

    while ((n1 - n).abs > one) {
      n = n1
      n1 = next(n, number)
    }

    while (n1 * n1 > number) {
      n1 -= one
    }

    n1
  }

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLine.toLong }

  val LIMIT = 1259929
  val LIMIT_SQRT = Math.sqrt(LIMIT).toInt + 1
  val isPrime = Array.fill(LIMIT)(true)
  val primesBuilder = new mutable.ArrayBuilder.ofInt
  isPrime(0) = false
  isPrime(1) = false

  var i = 4
  while (i < LIMIT) {
    isPrime(i) = false
    i += 2
  }
  i = 3
  while (i * i < LIMIT_SQRT) {
    if (isPrime(i)) {
      primesBuilder += i
      var j = i * i
      val ii = i + i
      while (j < LIMIT) {
        isPrime(j) = false
        j += ii
      }
    }
    i += 2
  }

  val primes = primesBuilder.result()

  val divisors = mutable.Map.empty[Long, Int].withDefaultValue(0)

  def add(p: Long, cnt: Int): Unit = {
    divisors(p) += cnt
  }

  for (j <- as.indices) {
    var aa = as(j)
    var i = 0
    while (i < primes.length && aa >= primes(i)) {
      val p = primes(i)
      if (aa % p == 0) {
        aa /= p
        add(p, 1)
      } else i += 1
    }
    as(j) = aa
  }

  val gcdsBuilder = new mutable.ArrayBuilder.ofLong
  val haveGcd = mutable.Set.empty[Long]

  i = 0
  while (i < n) {
    if (as(i) > 1) {
      var j = i + 1
      while (j < n) {
        if (as(j) > 1) {
          val d = gcd(as(i), as(j))
          if (d > 1 && !haveGcd(d)) {
            gcdsBuilder += d
            haveGcd += d
          }
        }
        j += 1
      }
    }
    i += 1
  }

  val gcds = gcdsBuilder.result()
  var j = 0
  while (j < gcds.length) {
    val g = gcds(j)
    var i = 0
    while (i < as.length) {
      if (as(i) % g == 0) {
        as(i) /= g
        add(g, 1)
      }
      i += 1
    }
    j += 1
  }

  var unknownDivisors = 0
  for (i <- as.indices) if (as(i) > 1) {
    val r = sqrt(as(i))
    if (as(i) == r * r) add(r, 2)
    else {
      if ((as(i) < isPrime.length && isPrime(as(i).toInt))
        || BigInt(as(i)).isProbablePrime(20)) add(as(i), 1)
      else unknownDivisors += 2
    }
  }

  val MOD = 998244353L
  var res = 1L
  for ((_, v) <- divisors) {
    res = res * (v + 1) % MOD
  }
  for (_ <- 1 to unknownDivisors) res = res * 2 % MOD

  println(res)
}


You are given a chessboard of size $$$n \times n$$$. It is filled with numbers from $$$1$$$ to $$$n^2$$$ in the following way: the first $$$\lceil \frac{n^2}{2} \rceil$$$ numbers from $$$1$$$ to $$$\lceil \frac{n^2}{2} \rceil$$$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $$$n^2 - \lceil \frac{n^2}{2} \rceil$$$ numbers from $$$\lceil \frac{n^2}{2} \rceil + 1$$$ to $$$n^2$$$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $$$\lceil\frac{x}{y}\rceil$$$ means division $$$x$$$ by $$$y$$$ rounded up.For example, the left board on the following picture is the chessboard which is given for $$$n=4$$$ and the right board is the chessboard which is given for $$$n=5$$$.  You are given $$$q$$$ queries. The $$$i$$$-th query is described as a pair $$$x_i, y_i$$$. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le q \le 10^5$$$) — the size of the board and the number of queries. The next $$$q$$$ lines contain two integers each. The $$$i$$$-th line contains two integers $$$x_i, y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — description of the $$$i$$$-th query.

For each query from $$$1$$$ to $$$q$$$ print the answer to this query. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$. Queries are numbered from $$$1$$$ to $$$q$$$ in order of the input.

NoteAnswers to the queries from examples are on the board in the picture from the problem statement.

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextLong()
    val Q = sc.nextInt()
    rep(Q) { i =>
      var x, y = sc.nextInt() - 1
      if ((x + y) % 2 == 1) x += N.toInt
      val ans =
        x / 2 * N +
          (if(x % 2 == 1) (N - 1) / 2 + 1 else 0) +
          y / 2 +
          1
      out.println(ans)

    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val sb = StringBuilder.newBuilder
    val n = in.nextLong
    val q = in.nextInt

    for (_ <- 1 to q) {
      val y = in.nextLong
      val x = in.nextLong
      val r = if (x % 2 == 1 && y % 2 == 1)
        y / 2 * n + (x + 1) / 2
      else if (x % 2 == 0 && y % 2 == 1)
        (n * n + 1) / 2 + y / 2 * n + x / 2
      else if (x % 2 == 1 && y % 2 == 0)
        (n + 1) * n / 2 + (y - 1) / 2 * n + (x + 1) / 2
      else
        (y / 2 * n) - (n - x) / 2
      sb.append(r)
      sb.append('\n')
    }
    print(sb.toString())
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object B extends App {

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

  val Array(n, q) = readLongs(2)

  val res = Array.ofDim[Long](q.toInt)
  val half = n * n / 2

  for (i <- 0 until q.toInt) {
    val Array(x, y) = readLongs(2)
    val xy = (x - 1) * n + y - 1
    res(i) = if ((x + y) % 2 == 0) xy / 2 + 1 else half + xy / 2 + 1 + n % 2
  }

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

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

  Console.flush
}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val sb = StringBuilder.newBuilder
    val n = in.nextInt
    val q = in.nextInt

    for (i <- 1 to q) {
      val y = in.nextInt.toLong
      val x = in.nextInt.toLong
      val r = if (x % 2 == 1 && y % 2 == 1)
        y / 2 * n + (x + 1) / 2
      else if (x % 2 == 0 && y % 2 == 1)
        (n * n + 1) / 2 + y / 2 * n + x / 2
      else if (x % 2 == 1 && y % 2 == 0)
        (n + 1) * n / 2 + (y - 1) / 2 * n + (x + 1) / 2
      else
        (y / 2 * n) - (n - x) / 2
      sb.append(r)
      if (i != q)
        sb.append('\n')
    }
    println(sb.toString())
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val out = new PrintWriter(System.out)
    val n = in.nextInt
    val q = in.nextInt

    for (_ <- 1 to q) {
      val y = in.nextInt.toLong
      val x = in.nextInt.toLong
      val r = if (x % 2 == 1 && y % 2 == 1)
        y / 2 * n + (x + 1) / 2
      else if (x % 2 == 0 && y % 2 == 1)
        (n * n + 1) / 2 + y / 2 * n + x / 2
      else if (x % 2 == 1 && y % 2 == 0)
        (n + 1) * n / 2 + (y - 1) / 2 * n + (x + 1) / 2
      else
        (y / 2 * n) - (n - x) / 2
      out.println(r)
    }
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val out = new PrintWriter(System.out)
    val n = in.nextInt
    val q = in.nextInt

    for (_ <- 1 to q) {
      val x = in.nextInt.toLong
      val y = in.nextInt.toLong
      val r = if (x % 2 == 1 && y % 2 == 1)
        y / 2 * n + (x + 1) / 2
      else if (x % 2 == 0 && y % 2 == 1)
        (n * n + 1) / 2 + y / 2 * n + x / 2
      else if (x % 2 == 1 && y % 2 == 0)
        (n + 1) * n / 2 + (y - 1) / 2 * n + (x + 1) / 2
      else
        (y / 2 * n) - (n - x) / 2
      out.println(r)
    }
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}