import scala.io.StdIn.readLine

object B {

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

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

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

class CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

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

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

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

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

	private[this] val isOnlineJudge = true

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

		@inline private[this] final def next(): String = {
			while (tokenizer == null || !tokenizer.hasMoreTokens)
				tokenizer = new StringTokenizer(reader.readLine)
			tokenizer.nextToken
		}

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

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

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

		def ni(): Int = nextInt()

		def nl(): Long = nextLong()

		def nc(): Char = nextChar()

		def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

class CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

	import Main._
	import fScanner._

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

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

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

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

    println(ans)
  }
}


object B1187 {

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

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

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

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn._

object B_1187 extends App {

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

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

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

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

    println(max + 1)
  }

}


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

object Solution_D extends App {

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

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

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

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

import scala.io.StdIn

object Solution_D extends App {

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

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

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

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

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

object Solution_D extends App {

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

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

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

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

import java.io._

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

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

object Solution_D extends App {

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

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

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

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


object Main extends App {

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

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

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

}

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

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

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

object Main extends App {

  val n = readInt
  val s = readLine

  def makeList(s: String) = {

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

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

    makeList(Nil, s)
  }

  def minByShifting(initialS: String): String = {

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

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

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

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

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

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

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

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

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

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

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

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

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

object Main extends App {

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

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

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

}


object B extends App {

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

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

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

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

    val f = fn.max

    println(f)
  }
}

object ProblemB extends App {

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

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()

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

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

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

}

object ProblemB extends App {

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

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()

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

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

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

}

object ProblemB extends App {

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

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()

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

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

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

}


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

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

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

import scala.io.StdIn._

object B_1200 extends App {
  val t = readInt()

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

    var B = m.toLong

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

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

      true
    }

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

}

object B extends App {

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

  val Array(t) = readInts(1)

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

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

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

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

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

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

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

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

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

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

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

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

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

      true
    }

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

}

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

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

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

      true
    }

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

}

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

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

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

      true
    }

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

}

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

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

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

      true
    }

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

}

import scala.io.StdIn._

object B_1200 extends App {
  val n = readInt()

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

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

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

      true
    }

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

}


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

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

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

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

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

  out.println(counts.max)

  out.flush()
  }

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

import scala.io.StdIn.readLine

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

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

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

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

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

    max
  }

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

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

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

}

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

  import scala.collection.mutable
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val shiftCount = scala.collection.mutable.HashMap[Int, Int]()
  val position = scala.collection.mutable.HashMap[Int, Int]()

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

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

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

}

object C extends App {
  import scala.collection.mutable

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

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

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

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

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

  println(ans)
}

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

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

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

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

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

  out.println(max)

  out.flush()

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

import scala.io.StdIn.readLine

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

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

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

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

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

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

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

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

}

import scala.io.StdIn.readLine

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

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

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

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

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

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

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

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

}

import scala.io.StdIn.readLine

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

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

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

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

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

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

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

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

}

import scala.io.StdIn.readLine

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

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

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

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

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

    max
  }

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

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

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

}


import scala.collection._

object A extends App {

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

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

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

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

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

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

    val ans = binSearch(0, 1000000)

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

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

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

  Console.flush
}

object C535 extends App {
  import java.util.Scanner

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

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

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

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

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

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

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

object C535 extends App {
  import java.util.Scanner

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

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

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

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

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

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

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

object C535 extends App {
  import java.util.Scanner

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

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

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

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

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

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

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


object E {
  import InOut._

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

  val n = nextInt
  val as = nextLongs(n)

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

  out.println(max)

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

object E extends App {
  val n  = scala.io.StdIn.readInt()
  val an = scala.io.StdIn.readLine().split(" ").map(_.toLong)

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

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

      t
    }

  println(ans)
}

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

  val n = nextInt
  val as = nextLongs(n)

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

  out.println(max)

  out.flush()

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

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

  val n = nextInt
  val as = nextLongs(n)

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

  out.println(max)

  out.flush()

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


//package codeforces.contest1213

import scala.collection.immutable.TreeSet

object BadPrices {

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

      println {
        val indexedSeq = io.StdIn.readLine.split(" ").map(_.toInt)

        (0 to n - 2)
          .foldRight((0, collection.mutable.TreeSet(indexedSeq.last))) {
            case (i, (res, set)) =>
              val v = indexedSeq(i)
              val minFound = set.until(v).nonEmpty

              (if (minFound) res + 1 else res, set += v)
          }
          ._1
      }
    }
  }

}

object Main extends App {
  val t = readInt()
  for (i <- 0 to t-1) {
      var i = readInt() - 2
      val a = readLine().split(" ").map(_.toInt)
      var rs = 0
      var temp = a(i+1)
      while(i>=0){
          if(a(i) > temp)
            rs += 1
          else
            temp = a(i)
          i-=1
      }
      println(rs)
  }
}

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

object Main extends App {

  val n = StdIn.readInt()

  for (i <- 0 to n-1) {
    val k = StdIn.readInt()
    val st: Array[String] = StdIn.readLine().split(" ")
    val arr: Array[Int] = st.map(_.toInt)

    var res: Int = 0

    //O(n^2) - TL
//    for (i <- 0 to k-1) {
//      var good: Boolean = true
//      Breaks.breakable {
//        for (j <- i + 1 to k - 1) {
//          if (arr(j) < arr(i)) {
//            good = false
//            if (!good) Breaks.break
//          }
//        }
//      }
//      if (!good) {
//        res += 1
//      }
//    }

    //O(n)
    var min = arr(arr.size-1)
    for (i <- k-1 to 0 by -1) {
      if (arr(i) > min) {
        res += 1
      }
      min = Math.min(arr(i), min)
    }

    println(res)
  }

}

//package codeforces.contest1213

import scala.collection.immutable.TreeSet

object BadPrices {

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

      println {
        val indexedSeq = io.StdIn.readLine.split(" ").map(_.toInt)

        (0 to n - 2)
          .foldRight((0, TreeSet(indexedSeq.last))) {
            case (i, (res, set)) =>
              val v = indexedSeq(i)
              val minFound = set.until(v).nonEmpty

              (if (minFound) res + 1 else res, set + v)
          }
          ._1
      }
    }
  }

}

object Main extends App {
  val t = readInt()
  for (i <- 0 to t-1) {
      val n = readInt()
      val a = readLine().split(" ").map(_.toInt)
      var rs = 0
      var temp = a(0)
      for(i <- 1 to n-1) {
          if(a(i) > temp) rs += 1
          temp = a(i)
      }
      println(rs)
  }
}


import scala.util.control.Breaks._
import scala.util.control.Breaks

//Julian_Miranda

object LittleElephantAndBits {
  def main(args: Array[String]): Unit = {
    var a = readLine
    var pos = -1

    val loop = new Breaks
    loop.breakable {
      for (i <- 0 to a.length() - 1) {
        breakable {
          if (a.charAt(i) == '0') {
            pos = i
            loop.break
          }
        }
      }
    }

    if (pos == -1) {
      for (i <- 1 to a.length()) {
        if (i < a.length()) {
          print(a.charAt(i))
        }
      }
    } else {
      for (i <- 0 to a.length() - 1) {
        breakable {
          if (i == pos) break;
          else {
            print(a.charAt(i))
          }
        }
      }
    }
    println()
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-29.
 */
object A258 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val a = sc.next()

    if (a.indexOf("1") != -1) {
      val startWith1 = a.substring(a.indexOf("1"))

      if (startWith1.indexOf("0") != -1) {
        val pre = startWith1.substring(0, startWith1.indexOf("0"))
        val post = startWith1.substring(startWith1.indexOf("0") + 1)
        println(pre + post)
      } else {
        println(startWith1.substring(1))
      }
    } else {
      println(a.substring(1))
    }
  }
}

object Contest extends App {
  val s = readLine()
  val p = s.indexOf('0')
  val ans = if (p == -1) s.substring(1) else s.substring(0, p) + s.substring(p+1)
  println(ans)
}

import java.util.StringTokenizer

object _258A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val s = next
  val pos = s.indexWhere(ch => ch == '0')
  if (pos != -1) println(s.take(pos) + s.drop(pos + 1))
  else println(s.drop(1))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val nStr = str.replaceFirst("0", "")
  if (str.length == nStr.length)
    println(str.tail)
  else
    println(nStr)
}

object Main {

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

    def fixNumber(n: String): String = {
      val index = n.indexOf("0")
      if (index >= 0)
        n.substring(0, index) + n.substring(index+1)
      else
        n.substring(1)
    }

    print(fixNumber(readLine))
  }

}

import scala.util.control.Breaks._

//Julian_Miranda

object LittleElephantAndBits {
  def main(args: Array[String]): Unit = {
    var a = readLine
    var pos = -1

    for (i <- 0 to a.length()-1) {
      breakable {
        if (a.charAt(i) == '0') {
          pos = i
          break;
        }
      }
    }

    if (pos == -1) {
      for (i <- 1 to a.length()) {
        if(i < a.length()){
          print(a.charAt(i))
        }
      }
    } else {
      for (i <- 0 to a.length()-1) {
        breakable {
          if (i == pos)break;
          else{
            print(a.charAt(i))
          }
        }
      }
    }
    println()
  }
}


object F extends App {

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

  val deltas = Array.fill(n){ 0 }

  for (i <- 1 until n) {
    var k = 1
    while (k < n) {
      val parent = (i - 1) / k
      val nextK = if (parent == 0) n else (i - 1) / parent + 1
      if (as(i) < as(parent)) {
        deltas(k) += 1
        if (nextK < n) deltas(nextK) -= 1
      }
      k = nextK
    }
  }

  val res = deltas.scan(0){ _ + _ }.drop(2)

  println(res.mkString(" "))
}

import java.util.StringTokenizer

import scala.io.Source

object F extends App {
  object In {
    private val lines = Source.stdin.getLines()
    private var tokenizer: StringTokenizer = new StringTokenizer(lines.next())

    def next(): String = {
      if (tokenizer.hasMoreTokens) {
        tokenizer.nextToken()
      } else {
        tokenizer = new StringTokenizer(lines.next())
        next()
      }
    }

    def nextInt() = next().toInt
    def nextDouble() = next().toDouble
  }

  val emptyIntArray = Array.empty[Int]

  class MinTree(d0: Array[Int]) {
    val offset = 1 << (32 - Integer.numberOfLeadingZeros(d0.length))
    val data = Array.fill(2 * offset)(emptyIntArray)
    for (i <- 0 until d0.length) {
      data(i + offset) = Array.ofDim[Int](1)
      data(i + offset)(0) = d0(i)
    }
    for (i <- offset - 1 to 1 by -1) {
      data(i) = merge(data(2 * i), data(2 * i + 1))
    }

    def merge(a: Array[Int], b: Array[Int]): Array[Int] = {
      val rv = Array.ofDim[Int](a.length + b.length)
      var ai, bi, ci = 0
      while (ai < a.length && bi < b.length) {
        if (a(ai) < b(bi)) {
          rv(ci) = a(ai)
          ai += 1
        } else {
          rv(ci) = b(bi)
          bi += 1
        }
        ci += 1
      }
      while (ai < a.length) {
        rv(ci) = a(ai)
        ci += 1
        ai += 1
      }
      while (bi < b.length) {
        rv(ci) = b(bi)
        ci += 1
        bi += 1
      }
      rv
    }

    def countLess(a: Array[Int], v: Int): Int = {
      if (a.length == 0 || a(0) >= v) {
        0
      } else if (a(a.length - 1) < v) {
        a.length
      } else {
        def bs(l: Int, r: Int): Int = {
          if (r - l == 1) r else {
            val m = (l + r) >>> 1
            if (a(m) < v) {
              bs(m, r)
            } else {
              bs(l, m)
            }
          }
        }
        bs(0, a.length)
      }
    }

    def count(l: Int, r: Int, v: Int): Int = {
      var ll = l + offset
      var rr = r + offset
      var rv = 0
      while (ll <= rr) {
        if ((ll & 1) == 1) {
          rv += countLess(data(ll), v)
        }
        if ((rr & 1) == 0) {
          rv += countLess(data(rr), v)
        }
        ll = (ll + 1) >>> 1
        rr = (rr - 1) >>> 1
      }
      rv
    }
  }

  val n = In.nextInt()
  val d = Array.fill(n)(In.nextInt())

  val t = new MinTree(d)
  for (k <- 1 until n) {
    var count = 0
    var i = 0
    while (k * i + 1 < n) {
      count += t.count(k * i + 1, math.min(n - 1, k * (i + 1)), d(i))
      i += 1
    }
    print(count + " ")
  }
  println()
}

object F extends App {

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

  val deltas = Array.fill(n){ 0 }

  for (i <- 1 until n) {
    var k = 1
    var violating = false
    val a = as(i)
    while (k < n) {
      val parent = (i - 1) / k
      if (a < as(parent)) {
        if (!violating) {
          deltas(k) += 1
          violating = true
        }
      } else {
        if (violating) {
          deltas(k) -= 1
          violating = false
        }
      }
      k = if (parent == 0) n else (i - 1) / parent + 1
    }
  }

  val res = deltas.scan(0){ _ + _ }.drop(2)

  println(res.mkString(" "))
}

object F extends App {

  object BIT {

    def query(t: Array[Int], r: Int, acc: Int = 0): Int =
      if (r < 0) acc else query(t, (r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)

    def update(t: Array[Int], i: Int, delta: Int): Unit =
      if (i < t.length) {
        t(i) += delta
        update(t, i | (i + 1), delta)
      }

    def apply(n: Int): Array[Int] = {
      Array.fill(n) { 0 }
    }

  }

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

  val bit = BIT(n)

  for (i <- 1 until n) {
    var nextK = 1
    var violating = false
    while (nextK < n) {
      val k = nextK
      val parent = (i - 1) / k
      if (as(i) < as(parent)) {
        if (!violating) {
          BIT.update(bit, k, 1)
          violating = true
        }
      } else {
        if (violating) {
          BIT.update(bit, k, -1)
          violating = false
        }
      }
      nextK = if (parent == 0) n else (i - 1) / parent + 1
          println(i, k, nextK)
    }
  }

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

  val res = Array.tabulate(n - 1){ i => BIT.query(bit, i + 1) }

  println(res.mkString(" "))

  Console.flush
}

import scala.collection._

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val tMin = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    val tMax = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) tMin(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        tMin(v) = Math.min(tMin(v2), tMin(v2 + 1))
        tMax(v) = Math.max(tMax(v2), tMax(v2 + 1))
      }
    }

    def query(l: Int, r: Int, p: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      val res = if (l > r) 0
      else if (l == tl && r == tr) {
        if (tMin(v) >= p) 0
        else if (tMax(v) < p) r - l + 1
        else -1
      } else -1

      if (res >= 0) res
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        query(l, Math.min(r, tm), p, v2, tl, tm) +
          query(Math.max(l, tm + 1), r, p, v2 + 1, tm + 1, tr)
      }
    }

  }
  val Array(n) = readInts(1)
  val as = readInts(n)

  val segTree = SegTree(as)

  val res = Array.ofDim[Int](n - 1)

  for (k <- 0 until n - 1) {
    var cnt = 0
    var v = 0
    var r = 0
    while (r <= n && v < n) {
      val l = r + 1 // k * v + 1
      r = (l + k) min (n - 1)
      //println(l, r)
      cnt += segTree.query(l, r, as(v))
      v += 1
    }
    res(k) = cnt
  }

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

  println(res.mkString(" "))

  Console.flush
}

import scala.collection._

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val tMin = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    val tMax = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) tMin(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        tMin(v) = Math.min(tMin(v2), tMin(v2 + 1))
        tMax(v) = Math.max(tMax(v2), tMax(v2 + 1))
      }
    }

    def query(l: Int, r: Int, p: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      val res = if (l > r) 0
      else if (l == tl && r == tr) {
        if (tMin(v) >= p) 0
        else if (tMax(v) < p) r - l + 1
        else -1
      } else -1

      if (res >= 0) res
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        query(l, Math.min(r, tm), p, v2, tl, tm) +
          query(Math.max(l, tm + 1), r, p, v2 + 1, tm + 1, tr)
      }
    }

  }
  val Array(n) = readInts(1)
  val as = readInts(n)

  val segTree = SegTree(as)

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

  for (k <- 0 until n - 1) {
    var cnt = 0L
    var v = 0
    var r = 0
    while (r < n - 1) {
      val l = r + 1 // k * v + 1
      r = (l + k) min (n - 1)
      //println(l, r)
      cnt += segTree.query(l, r, as(v))
      v += 1
    }
    res(k) = cnt
  }

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

  println(res.mkString(" "))

  Console.flush
}


import scala.collection.mutable
//package codeforces

object MilitaryProblem {

  //  private def computeSizes(n: Int, childrenMap: Map[Int, Array[Int]], parentArray: Array[Int]): Array[Int] = {
  //    val result = Array.fill(n + 1)(1)
  //
  //    def compute(set: Set[Int]): Unit = {
  //      set.foreach(node => result(parentArray(node)) += result(node))
  //      if (!(set.size == 1 && set.contains(0))) compute(set map parentArray)
  //    }
  //
  //    compute((1 to n).filter(node => !childrenMap.contains(node)).toSet) // starting with the leaves
  //    result
  //  }

  def main(args: Array[String]): Unit = {
    val Array(n, q) = io.StdIn.readLine.split(" ").map(_.toInt)

    //    val parentArray: Array[Int] = Array(0, 0) ++ io.StdIn.readLine.split(" ").map(_.toInt)
    //    var childrenMap: Map[Int, Array[Int]] = parentArray.zipWithIndex.groupBy(_._1).map { case (p, elems) => (p, elems.unzip._2) }

    val parentArray: Array[Int] = io.StdIn.readLine.split(" ").map(_.toInt)
    val children: Array[mutable.Queue[Int]] = Array.fill(n + 1)(mutable.Queue[Int]())

    var i: Int = 0
    while (i < parentArray.length) {
      children(parentArray(i)).enqueue(i + 2)
      i += 1
    }

    //val subtreeCount: Array[Int] = computeSizes(n, childrenMap, parentArray)

    //val childrenMapWithPrefixSum = childrenMap.map { case (node, children) => (node, children.scanLeft(1) { case (res, elem) => res + subtreeCount(elem) }) }

    val sortedSeq, startingPositionInSortedSeq, endingPositionInSortedSeq = new Array[Int](n + 1)
    i = 0
    dfs(1)

    def dfs(node: Int): Unit = {
      sortedSeq(i) = node
      startingPositionInSortedSeq(node) = i
      i += 1
      children(node).foreach(dfs)
      endingPositionInSortedSeq(node) = i - 1
    }

    i = 0
    while (i < q) {
      val Array(u, k) = io.StdIn.readLine.split(" ").map(_.toInt)

      val startingPos = startingPositionInSortedSeq(u)
      val endingPos = endingPositionInSortedSeq(u)

      if (endingPos - startingPos + 1 < k) println(-1)
      else println(sortedSeq(startingPos + k - 1))

      i += 1
      //println(computeQueryResult(u, k))
    }

    //    def computeQueryResult(u: Int, k: Int): Int = {
    //      if (k > subtreeCount(u)) -1
    //      else if (k == 1) u
    //      else {
    //        val childPrefixSum: Array[Int] = childrenMapWithPrefixSum(u)
    //        val i = childPrefixSum.search(k).insertionPoint // optimized  binary search
    //
    //        val newU = childrenMap(u)(i - 1)
    //        val newK = k - childPrefixSum(i - 1)
    //        computeQueryResult(newU, newK)
    //      }
    //    }
  }
}

//package codeforces

import scala.collection.Searching._
import scala.collection.mutable

/*

link- http://codeforces.com/contest/1006/problem/E

Pre-order traversal sequence, find the kth element starting from node u

 */
object MilitaryProblem {

  def main(args: Array[String]): Unit = {
    val Array(n, q) = io.StdIn.readLine.split(" ").map(_.toInt)
    val parentArray: Array[Int] = io.StdIn.readLine.split(" ").map(_.toInt)

    val children: Array[mutable.Queue[Int]] = Array.fill(n + 1)(mutable.Queue[Int]())

    //    var i: Int = 0
    //    while (i < parentArray.length) {
    //      children(parentArray(i)).enqueue(i + 2)
    //      i += 1
    //    }

    computeChildrenMapping(0)

    def computeChildrenMapping(idx: Int): Unit = {
      if (idx < parentArray.length) {
        children(parentArray(idx)).enqueue(idx + 2)
        computeChildrenMapping(idx + 1)
      }
    }

    val sortedSeq, startingPositionInSortedSeq, endingPositionInSortedSeq = new Array[Int](n + 1)
    var i = 0
    dfs(1)

    def dfs(node: Int): Unit = {
      sortedSeq(i) = node
      startingPositionInSortedSeq(node) = i
      i += 1
      children(node).foreach(dfs)
      endingPositionInSortedSeq(node) = i - 1
    }

    //    i = 0
    //    while (i < q) {
    //      val Array(u, k) = io.StdIn.readLine.split(" ").map(_.toInt)
    //
    //      val startingPos = startingPositionInSortedSeq(u)
    //      val endingPos = endingPositionInSortedSeq(u)
    //
    //      if (endingPos - startingPos + 1 < k) println(-1)
    //      else println(sortedSeq(startingPos + k - 1))
    //
    //      i += 1
    //    }

    solveQueries(0)

    def solveQueries(idx: Int): Unit = {
      if (idx < q) {
        val Array(u, k) = io.StdIn.readLine.split(" ").map(_.toInt)

        val startingPos = startingPositionInSortedSeq(u)
        val endingPos = endingPositionInSortedSeq(u)

        if (endingPos - startingPos + 1 < k) println(-1)
        else println(sortedSeq(startingPos + k - 1))

        solveQueries(idx + 1)
      }
    }

  }

  // Another Solution although inefficient

  def usingReverseLevelOrderTraversal(args: Array[String]): Unit = {
    val Array(n, q) = io.StdIn.readLine.split(" ").map(_.toInt)

    val parentArray: Array[Int] = Array(0, 0) ++ io.StdIn.readLine.split(" ").map(_.toInt)
    var childrenMap: Map[Int, Array[Int]] = parentArray.zipWithIndex.groupBy(_._1).map { case (p, elems) => (p, elems.unzip._2) }

    val subtreeSizeCount: Array[Int] = { // reverse level order traversal to compute sizes of each subtree
      val result = Array.fill(n + 1)(1)

      def compute(set: Set[Int]): Unit = {
        set.foreach(node => result(parentArray(node)) += result(node))
        if (!(set.size == 1 && set.contains(0))) compute(set map parentArray)
      }

      compute((1 to n).filter(node => !childrenMap.contains(node)).toSet) // starting with the leaves
      result
    }

    val childrenMapWithPrefixSum = childrenMap.map { case (node, children) => (node, children.scanLeft(1) { case (res, elem) => res + subtreeSizeCount(elem) }) }

    var i = 0
    while (i < q) {
      val Array(u, k) = io.StdIn.readLine.split(" ").map(_.toInt)
      println(computeQueryResult(u, k))
      i += 1
    }

    def computeQueryResult(u: Int, k: Int): Int = {
      if (k > subtreeSizeCount(u)) -1
      else if (k == 1) u
      else {
        val childPrefixSum: Array[Int] = childrenMapWithPrefixSum(u)
        val i = childPrefixSum.search(k).insertionPoint // optimized with binary search

        val newU = childrenMap(u)(i - 1)
        val newK = k - childPrefixSum(i - 1)
        computeQueryResult(newU, newK)
      }
    }
  }
}

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, Q = ni()
    val from, to = Array.ofDim[Int](N - 1)
    REP(N -1) { i =>
      from(i) = ni() - 1
      to(i) = i + 1
    }

    val g = packDGraph(N, from, to)
    val (tour, _) = traceDfs(g)
    val pos = Array.ofDim[Int](N)
    REP(N) { i =>
      pos(tour(i)) = i
    }
    val childCnt = Array.ofDim[Int](N)
    REP_r(N) { v =>
      REP(g(v).length) { j =>
        val u = g(v)(j)
        childCnt(v) += childCnt(u) + 1
      }
    }

    REP(Q) { _ =>
      val u, k = ni() - 1
      if (k > childCnt(u)) out.println(-1)
      else {
        out.println(tour(pos(u) + k) + 1)
      }
    }
  }

  def traceDfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int]) = {
    val n = g.length
    val stack = mutable.Stack[Int]()
    val ix = Array.ofDim[Int](n)
    val tour = Array.ofDim[Int](n)
    val parent = Array.ofDim[Int](n)
    parent(rt) = -1
    var p = 0

    tour(p) = rt
    p += 1
    stack.push(rt)

    while(stack.nonEmpty) {
      val v = stack.top
      val es = g(v)
      if (ix(v) == es.length) stack.pop()
      else {
        val u = es(ix(v))
        if (u != parent(v)) {
          parent(u) = v
          stack.push(u)
          tour(p) = u
          p += 1
        }
        ix(v) += 1
      }
    }

    (tour, parent)
  }

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

  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 D{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,m)=(nextInt,nextInt)
    val edges=for(i<-0 until m) yield(i,nextInt,nextInt)
    val edgesSorted=scala.util.Sorting.stableSort(edges, (e1: Tuple3[Int, Int,Int], e2: Tuple3[Int, Int,Int]) => if(e1._2 < e2._2){
                                                    true
                                                  }
                                                  else if(e1._2>e2._2){
                                                    false
                                                  }else{
                                                    e1._3 > e2._3
                                                  })

    val nextNode=Array.ofDim[Int](n)
    var lastNode=0
    val ans=Array.ofDim[(Int,Int)](m)
    nextNode(0)=2
    for(i<-0 until m){
      val (idx,_,isTree)=edgesSorted(i)
      if(isTree==1){
        ans(idx)=(lastNode+1,lastNode+2)
        nextNode(lastNode)=lastNode+2
        lastNode+=1
      }else{
        var has=false
        breakable{
          for(j<-0 until lastNode){
            if(nextNode(j)<=lastNode){
              ans(idx)=(j+1,nextNode(j)+1)
              nextNode(j)+=1
              has=true
              break
            }
          }
        }
        if(has==false){
          out.println(-1)
          out.flush()
          out.close()
          return
        }
      }
    }
    ans.foreach(a=>println(a._1+" "+a._2))
    //code ends here
    out.flush
    out.close
  }
}

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

/**
 * Created by antonkov on 9/17/15.
 */
object B {
  class Edge(val w: Int, val inMst: Boolean, val num: Int) {
    override def toString = s"Edge($w, $inMst, $num)"
  }

  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n, m = in.nextInt()
    var edges = new Array[Edge](m)
    for (i <- 0 until m) {
      edges(i) = new Edge(in.nextInt(), in.nextInt() == 1, i)
    }
    edges = edges.sortWith((e1, e2) => if (e1.w != e2.w) e1.w < e2.w else e2.inMst < e1.inMst )
    val q = new ArrayDeque[(Int, Int)]()
    var v = 1
    val res = new Array[(Int, Int)](m)
    for (e <- edges) {
      if (e.inMst) {
        v += 1
        def addEdges {
          for (u <- 1 until v) {
            if (q.size() >= m)
              return
            q.add((u, v))
          }
        }
        addEdges
        res(e.num) = q.pollLast()
      } else {
        if (q.isEmpty) {
          out.println(-1)
          return
        }
        res(e.num) = q.pollFirst()
      }
    }
    for ((u, v) <- res) {
      out.println(u + " " + v)
    }
  }

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

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

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

/**
 * Created by antonkov on 9/17/15.
 */
object B {
  class Edge(val w: Int, val inMst: Boolean, val num: Int)

  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n, m = in.nextInt()
    val edges = new Array[Edge](m)
    for (i <- 0 until m) {
      edges(i) = new Edge(in.nextInt(), in.nextInt() == 1, i)
    }
    edges.sortWith((e1, e2) => e1.w < e2.w)
    val q = new ArrayDeque[(Int, Int)]()
    var v = 1
    val res = new Array[(Int, Int)](m)
    for (e <- edges) {
      if (e.inMst) {
        v += 1
        for (u <- 1 until v) {
          q.add((u, v))
        }
        res(e.num) = q.pollLast()
      } else {
        if (q.isEmpty) {
          out.println(-1)
          return
        }
        res(e.num) = q.pollFirst()
      }
    }
    for ((u, v) <- res) {
      out.println(u + " " + v)
    }
  }

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

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

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

/**
 * Created by antonkov on 9/17/15.
 */
object B {
  class Edge(val w: Int, val inMst: Boolean, val num: Int) {
    override def toString = s"Edge($w, $inMst, $num)"
  }

  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n, m = in.nextInt()
    var edges = new Array[Edge](m)
    for (i <- 0 until m) {
      edges(i) = new Edge(in.nextInt(), in.nextInt() == 1, i)
    }
    edges = edges.sortWith((e1, e2) => if (e1.w != e2.w) e1.w < e2.w else e2.inMst < e1.inMst )
    val q = new ArrayDeque[(Int, Int)]()
    var v = 1
    val res = new Array[(Int, Int)](m)
    for (e <- edges) {
      if (e.inMst) {
        v += 1
        def addEdges {
          for (u <- 1 until v) {
            if (q.size() >= n)
              return
            q.add((u, v))
          }
        }
        addEdges
        res(e.num) = q.pollLast()
      } else {
        if (q.isEmpty) {
          out.println(-1)
          return
        }
        res(e.num) = q.pollFirst()
      }
    }
    for ((u, v) <- res) {
      out.println(u + " " + v)
    }
  }

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

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

object D{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,m)=(nextInt,nextInt)
    val edges=for(i<-0 until m) yield(i,nextInt,nextInt)
    val edgesSorted=scala.util.Sorting.stableSort(edges, (e1: Tuple3[Int, Int,Int], e2: Tuple3[Int, Int,Int]) => e1._2 < e2._2)

    val nextNode=Array.ofDim[Int](n)
    var lastNode=0
    val ans=Array.ofDim[(Int,Int)](m)
    nextNode(0)=2
    for(i<-0 until m){
      val (idx,_,isTree)=edgesSorted(i)
      if(isTree==1){
        ans(idx)=(lastNode+1,lastNode+2)
        nextNode(lastNode)=lastNode+2
        lastNode+=1
      }else{
        var has=false
        breakable{
          for(j<-0 until lastNode){
            if(nextNode(j)<=lastNode){
              ans(idx)=(j+1,nextNode(j)+1)
              nextNode(j)+=1
              has=true
              break
            }
          }
        }
        if(has==false){
          out.println(-1)
          out.flush()
          out.close()
          return
        }
      }
    }
    ans.foreach(a=>println(a._1+" "+a._2))
    //code ends here
    out.flush
    out.close
  }
}