    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, K, X = ni()
        val A = na(N)

        val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))
        dp(0).add(0, 0)
        rep(N, 1) { i =>
          val a = A(i - 1)
          rep_r(X) { x =>
            if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)
          }
        }

        val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1
        out.println(ans)
      }

      // todo test
      /**
        * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う
        * DP上で１個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意
        */
      class SlideMax(k: Int) {
        case class Entry(i: Int, v: Long)

        val queue = new java.util.ArrayDeque[Entry]()

        def nonEmpty(i: Int): Boolean = {
          maintenance(i)
          !queue.isEmpty
        }

        def max(i: Int): Long = {
          maintenance(i)
          queue.peek().v
        }

        def add(i: Int, x: Long): Unit = {
          maintenance(i)

          // 条件逆さまにすると最小になる
          while(!queue.isEmpty && queue.peekLast().v <= x) queue.removeLast()
          queue.addLast(Entry(i, x))
        }

        def maintenance(i: Int): Unit = {
          while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()
        }
      }

      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[Int](as.length + 1)
        rep(as.length) { i =>
          cum(i + 1) = cum(i) + as(i)
        }
        cum
      }
    }

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

object F extends App {
	val n = InputReader.nextInt
	val k = InputReader.nextInt
	val x = InputReader.nextInt
	var arr = Array.fill(n + 1)(0)

	for(i <- 1 to n) arr(i) = InputReader.nextInt

	val prv = Array.fill(n + 1)(-1L)
	val cur = Array.fill(n + 1)(-1L)

	prv(0) = 0L

	for (j <- 1 to x) {
		val q: Deque[Int] = new LinkedList[Int]()

		for (i <- 0 to n) {
			while (!q.isEmpty && i - q.getFirst > k)
				q.pollFirst

			cur(i) = if (q.isEmpty || prv(q.getFirst) == -1) -1 else prv(q.getFirst) + arr(i)

			while (!q.isEmpty && prv(i) >= prv(q.getLast))
				q.pollLast

			q.addLast(i)
		}

		for (i <- 0 to n) {
			prv(i) = cur(i)
			cur(i) = -1L
		}
	}

	println(prv.takeRight(k).max)
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	var tk = new StringTokenizer("")

	def read() = {
		while (!tk.hasMoreTokens)
			tk = new StringTokenizer(readLine)

		tk.nextToken
	}

	def readLine() = rd.readLine
	def nextInt() = read.toInt
	def nextLong() = read.toLong
	def nextDouble() = read.toDouble
}

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, K, X = ni()
    val A = na(N)

    val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))
    dp(0).add(0, 0)
    rep(N, 1) { i =>
      val a = A(i - 1)
      rep_r(X) { x =>
        if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)
      }

      ""
    }

    val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1
    out.println(ans)
  }

  // todo test
  /**
    * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う
    * DP上で１個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意
    */
  class SlideMax(k: Int) {
    case class Entry(i: Int, v: Long)

    val queue = new java.util.ArrayDeque[Entry]()

    def nonEmpty(i: Int): Boolean = {
      maintenance(i)
      !queue.isEmpty
    }

    def max(i: Int): Long = {
      maintenance(i)
      queue.peek().v
    }

    def add(i: Int, x: Long): Unit = {
      maintenance(i)

      // 条件逆さまにすると最小になる
      while(!queue.isEmpty && queue.peekLast().v < x) queue.removeLast()
      queue.addLast(Entry(i, x))
    }

    def maintenance(i: Int): Unit = {
      while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()
    }
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

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

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

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

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

    val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))
    dp(0).add(0, 0)
    rep(N, 1) { i =>
      val a = A(i - 1)
      rep_r(X) { x =>
        if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)
      }
    }

    val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1
    out.println(ans)
  }

  // todo test
  /**
    * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う
    * DP上で１個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意
    */
  class SlideMax(k: Int) {
    case class Entry(i: Int, v: Long)

    val queue = new java.util.ArrayDeque[Entry]()

    def nonEmpty(i: Int): Boolean = {
      maintenance(i)
      !queue.isEmpty
    }

    def max(i: Int): Long = {
      maintenance(i)
      queue.peek().v
    }

    def add(i: Int, x: Long): Unit = {
      maintenance(i)

      // 条件逆さまにすると最小になる
      while(!queue.isEmpty && queue.peekLast().v < x) queue.removeLast()
      queue.addLast(Entry(i, x))
    }

    def maintenance(i: Int): Unit = {
      while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()
    }
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

object F extends App {
	val n = InputReader.nextInt
	val k = InputReader.nextInt
	val x = InputReader.nextInt
	var arr = Array.fill(n + 1)(0)

	for(i <- 1 to n) arr(i) = InputReader.nextInt

	val prv = Array.fill(n + 1)(-1L)
	val cur = Array.fill(n + 1)(-1L)

	prv(0) = 0L

	for (j <- 1 to x) {
		val q: Deque[Int] = new ArrayDeque[Int]()

		for (i <- 0 to n) {
			while (!q.isEmpty && i - q.getFirst > k)
				q.pollFirst

			cur(i) = if (q.isEmpty || prv(q.getFirst) == -1) -1 else prv(q.getFirst) + arr(i)

			while (!q.isEmpty && prv(i) >= prv(q.getLast))
				q.pollLast

			q.addLast(i)
		}

		for (i <- 0 to n) {
			prv(i) = cur(i)
			cur(i) = -1L
		}
	}

	println(prv.takeRight(k).max)
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	var tk = new StringTokenizer("")

	def read() = {
		while (!tk.hasMoreTokens)
			tk = new StringTokenizer(readLine)

		tk.nextToken
	}

	def readLine() = rd.readLine
	def nextInt() = read.toInt
	def nextLong() = read.toLong
	def nextDouble() = read.toDouble
}

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, K, X = ni()
    val A = na(N)

    val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))
    dp(0).add(0, 0)
    rep(N, 1) { i =>
      val a = A(i - 1)
      rep_r(X) { x =>
        if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)
      }
    }

    val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1
    out.println(ans)
  }

  // todo test
  /**
    * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う
    * DP上で１個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意
    */
  class SlideMax(k: Int) {
    case class Entry(i: Int, v: Long)

    val queue = new java.util.ArrayDeque[Entry]()

    def nonEmpty(i: Int): Boolean = {
      maintenance(i)
      !queue.isEmpty
    }

    def max(i: Int): Long = {
      maintenance(i)
      queue.peek().v
    }

    def add(i: Int, x: Long): Unit = {
      maintenance(i)

      // 条件逆さまにすると最小になる
      while(!queue.isEmpty && queue.peekLast().v < x) queue.removeLast()
      queue.addLast(Entry(i, x))
    }

    def maintenance(i: Int): Unit = {
      if (!queue.isEmpty && k < i - queue.peek().i + 1) queue.poll()
    }
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


import scala.annotation.tailrec
import scala.io.Source

object abcString extends App{
  val strings = for (str <- Source.stdin.getLines().drop(1)) yield str

  def yesNo(str: List[Char]): Boolean = {
    lazy val firstCount = str.count(_ == str.head)
    lazy val lastCount = str.count(_ == str.last)

    @tailrec
    def bracesMatch(openBraces: Int, first: Char, last: Char, remaining: List[Char]): Boolean = {
      if (openBraces >= 0)
        remaining match {
          case Nil => if (openBraces == 0) true else false
          case c :: cs => {
            val newOpenBraces = {
              if (c == first) openBraces + 1
              else if (c == last) openBraces - 1
              else if (firstCount > lastCount) openBraces - 1
              else openBraces + 1
            }
            bracesMatch(newOpenBraces, first, last, cs)
          }
        }
      else false
    }
    bracesMatch(0, str.head, str.last, str)
  }

  for (str <- strings) {
    val res =
      if (yesNo(str.toCharArray.toList)) "YES"
      else "NO"
    println(s"$res")
  }
}

import scala.annotation.tailrec
import scala.io.Source

object abcString extends App{
  val strings = for (str <- Source.stdin.getLines().drop(1)) yield str

  def yesNo(str: List[Char]): Boolean = {
    @tailrec
    def bracesMatch(openBraces: Int, first: Char, last: Char, remaining: List[Char]): Boolean = {
      if (openBraces >= 0)
        remaining match {
          case Nil => if (openBraces == 0) true else false
          case c :: cs =>
            if (c == first) bracesMatch(openBraces + 1, first, last, cs)
            else if (c == last) bracesMatch(openBraces - 1, first, last, cs)
            else if (str.count(_ == first) > str.count(_ == last)) bracesMatch(openBraces - 1, first, last, cs)
            else bracesMatch(openBraces + 1, first, last, cs)
        }
      else false
    }
    bracesMatch(0, str.head, str.last, str)
  }

  for (str <- strings) {
    val res =
      if (yesNo(str.toCharArray.toList)) "YES"
      else "NO"
    println(s"$res")
  }
}


/**
 * Created by IntelliJ IDEA.
 * User: ymatsux
 * Date: 12/05/06
 * Time: 2:16
 * To change this template use File | Settings | File Templates.
 */

import java.util.Scanner
import scala.collection.mutable

object CF105B {

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val userToMaxScoreBuilder = mutable.Map.empty[String, Int]
    for (i <- 0 until n) {
      val user = sc.next()
      val score = sc.nextInt()
      userToMaxScoreBuilder(user) = math.max(score, userToMaxScoreBuilder.getOrElse(user, 0))
    }
    val userToMaxScore = userToMaxScoreBuilder.toMap
    val numberOfUsers = userToMaxScore.keys.size
    println(numberOfUsers)

    val scores = userToMaxScore.values.toArray
    for (user <- userToMaxScore.keys) {
      val maxScore = userToMaxScore(user)
      val countAbove = scores.count(_ > maxScore)
      if (countAbove <= numberOfUsers * 1 / 100) {
        println(user + " " + "pro")
      } else if (countAbove <= numberOfUsers * 10 / 100) {
        println(user + " " + "hardcore")
      } else if (countAbove <= numberOfUsers * 20 / 100) {
        println(user + " " + "average")
      } else if (countAbove <= numberOfUsers * 50 / 100) {
        println(user + " " + "random")
      } else {
        println(user + " " + "noob")
      }
    }
  }
}

import java.util.Scanner
import scala.math.max
import scala.collection.mutable

object CF105B {

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val userToMaxScoreBuilder = mutable.Map.empty[String, Int]
    for (i <- 0 until n) {
      val user = sc.next()
      val score = sc.nextInt()
      userToMaxScoreBuilder(user) = max(score, userToMaxScoreBuilder.getOrElse(user, 0))
    }
    val userToMaxScore = userToMaxScoreBuilder.toMap
    val numberOfUsers = userToMaxScore.keys.size
    println(numberOfUsers)

    val scores = userToMaxScore.values
    for (user <- userToMaxScore.keys) {
      val maxScore = userToMaxScore(user)
      val countAbove = scores.count(_ > maxScore)
      if (countAbove <= numberOfUsers * 1 / 100) {
        println(user + " " + "pro")
      } else if (countAbove <= numberOfUsers * 10 / 100) {
        println(user + " " + "hardcore")
      } else if (countAbove <= numberOfUsers * 20 / 100) {
        println(user + " " + "average")
      } else if (countAbove <= numberOfUsers * 50 / 100) {
        println(user + " " + "random")
      } else {
        println(user + " " + "noob")
      }
    }
  }
}

import java.util.Scanner
import scala.math.max
import scala.collection.mutable

object CF105B {

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val userToMaxScoreBuilder = mutable.Map.empty[String, Int]
    for (i <- 0 until n) {
      val user = sc.next()
      val score = sc.nextInt()
      userToMaxScoreBuilder(user) = max(score, userToMaxScoreBuilder.getOrElse(user, 0))
    }
    val userToMaxScore = userToMaxScoreBuilder.toMap
    val numberOfUsers = userToMaxScore.keys.size
    println(numberOfUsers)
    for (user <- userToMaxScore.keys) {
      val maxScore = userToMaxScore(user)
      val countAbove = userToMaxScore.values.count(_ > maxScore)
      if (countAbove <= numberOfUsers * 1 / 100) {
        println(user + " " + "pro")
      } else if (countAbove <= numberOfUsers * 10 / 100) {
        println(user + " " + "hardcore")
      } else if (countAbove <= numberOfUsers * 20 / 100) {
        println(user + " " + "average")
      } else if (countAbove <= numberOfUsers * 50 / 100) {
        println(user + " " + "random")
      } else {
        println(user + " " + "noob")
      }
    }
  }
}


object BTheNumberOnTheBoard extends App {
  val k: Int = scala.io.StdIn.readLine.toInt
  val n: String = scala.io.StdIn.readLine

  var cnt = Array.fill(10){0}
  var cur = n.foldLeft(0) { (cur, c) =>
    val digit = c - '0'
    cnt(digit) = cnt(digit) + 1
    cur + digit
  }

  var ans = 0
  for {
    i <- 0 until 10; j <- 0 until cnt(i)
    if cur < k
  } {
    ans = ans + 1
    cur = cur + 9 - i
  }

  print(ans)
}

import scala.io.StdIn

object Main extends App {

  val k = StdIn.readLine().toInt
  val n = StdIn.readLine().sortWith(_ < _)

  val sum = n.foldLeft(0)((z: Int,c: Char) => {
    z + c - 48
  })

  var diff = k - sum
  var count = 0
  while(diff > 0 && count < n.length) {
    diff = diff - (9 - (n.charAt(count) - 48))
    count = count + 1
  }
  println(count)

}

object B extends App {

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

  val Array(k) = readInts(1)
  val n = readLine.map(_ - '0').sorted

  var sum = n.sum

  var i = 0
  while (i < n.length && sum < k) {
    sum += 9 - n(i)
    i += 1
  }

  println(i)
}

import scala.io.StdIn

object Main extends App {

  val k = StdIn.readLine().toInt
  val n = StdIn.readLine().sortWith(_ < _)

  val sum = n.foldLeft(0)((z: Int,c: Char) => {
    z + c - 48
  })

  var diff = k - sum
  var count = 0

  while(diff > 0 && count < n.length) {
    diff = diff - (n.charAt(count) - 48)
    count = count + 1
  }
  println(count)

}


import scala.io._
import scala.collection.mutable._
import java.io.FileWriter
import java.io.PrintWriter

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var s1 = readLine;
    var s2 = readLine;
    for (i <- 0 until s2.length) {
      if (s2(i) != ' ' && s1.contains(s2(i))) {
        s1 = s1.replaceFirst(s2(i).toString, "");
      } else if (s2(i) != ' ') {
        println("NO");
        return;
      }
    }
    println("YES");
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val text = in.next.filter(_ != ' ').groupBy(identity).map(i => i._1 -> i._2.length)
  val message = in.next.filter(_ != ' ').groupBy(identity).map(i => i._1 -> i._2.length)
  if (message.keys.forall(i => text.getOrElse(i, 0) >= message(i)))
    println("YES")
  else
    println("NO")

}

import scala.io._
import scala.collection.mutable._
import java.io.FileWriter
import java.io.PrintWriter

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var s1 = readLine;
    var s2 = readLine;
    for (i <- 0 until s2.length) {
      if (s2(i) != ' ' && s1.contains(s2(i))) {
        s1.replace(s2(i).toString, "");
      } else if (s2(i) != ' ') {
        println("NO");
        return;
      }
    }
    println("YES");
  }
}

import scala.io._
import scala.collection.mutable._
import java.io.FileWriter
import java.io.PrintWriter

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var s1 = readLine;
    var s2 = readLine;
    for (i <- 0 until s2.length) {
      if (s2(i) != ' ' && s1.contains(s2(i))) {
        s1 = s1.replace(s2(i).toString, "");
      } else if (s2(i) != ' ') {
        println("NO");
        return;
      }
    }
    println("YES");
  }
}


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

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()

    val k = {
      val cs = Array.fill(26)(0)
      s.foreach(c => cs(c - 'a') += 1)

      val (c1, c2) = (cs.count(_ == 1), cs.count(_ > 1))

      c2 + c1 / 2
    }

    println(k)
  }
}

import scala.io.StdIn

object Main {
  implicit class Rep(n: Int) {
    def times[A](f: => A) { 1 to n foreach (_ => f) }
  }
  def main(args: Array[String]) = {
    StdIn.readInt.times {
      def f(string: String) = {
        val (gt2, rest) =
          (string.groupBy(identity) mapValues (_.length)).partition(kv =>
            kv._2 >= 2
          )
        println(gt2.size + (rest.size / 2))
      }
      f(StdIn.readLine)
    }
  }
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).sorted
  val first = data.take(n / 2 + n % 2)
  val second = data.drop(first.length)
  val result = Array.ofDim[Int](n)
  (0 until n by 2).foreach { i =>
    result(i) = first(i / 2)
  }
  (1 until n by 2).foreach { i =>
     result(i) = second(i / 2)
  }
  println(result.mkString(" "))
}

import java.util

import scala.collection.JavaConverters._

object ZSort {
  // https://codeforces.com/problemset/problem/652/B
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)

    if (n == 1) {
      println(arr.mkString)
    } else {
      val newArr = new util.ArrayList[Int](n)
      arr.zipWithIndex.foreach { case (curr, i) =>
        if (i == 0) {
          newArr.add(arr.head)
        } else {
          val prev = newArr.get(i - 1)
          if ((i + 1) % 2 == 0) {
            // even
            if (curr < prev) {
              newArr.add(prev)
              newArr.set(i - 1, curr)
            } else {
              newArr.add(curr)
            }
          } else {
            // odd
            if (curr > prev) {
              newArr.add(prev)
              newArr.set(i - 1, curr)
            } else {
              newArr.add(curr)
            }
          }
        }
      }

      println(newArr.asScala.mkString(" "))
    }
  }
}


object Main332B {
  def readInts = readLine.split(" ")map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, k) = readInts
    val arr = readInts
    val sums = Array.ofDim[BigInt](n)
    var currentSum = BigInt(0)
    for (i <- (n-1) to 0 by -1) {
      currentSum += arr(i)
      if (i < n-k) currentSum -= arr(i+k)
      sums(i) = currentSum
    }
    var maxB = n-k
    var resA = n-k*2
    var resB = n-k
    for(a <- n-2*k to 0 by -1) {
      if(sums(a+k) >= sums(maxB)) maxB = a+k
      if(sums(a) + sums(maxB) >= sums(resA) + sums(resB)) {
        resA = a
        resB = maxB
      }
    }
    println((resA+1) + " " + (resB+1))
  }

}

import java.util._
import java.lang._
import java.io._

/**
 * @author kperikov
 */
object B_332 {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def partialSum(ints: Array[Int]): Array[Long] = {
    val sums = new Array[Long](ints.length)
    sums(0) = ints(0)
    for (i <- 1 until ints.length) {
      sums(i) = sums(i - 1) + ints(i)
    }
    sums
  }

  def sum(ints: Array[Long], x: Int, y: Int): Long = {
    x match {
      case 0 => ints(y)
      case _ => ints(y) - ints(x - 1)
    }
  }

  def solve = {
    val n = nextInt
    val k = nextInt
    val arr = new Array[Int](n)
    for (i <- 0 until n) {
      arr(i) = nextInt
    }
    val partialSums = partialSum(arr)
    var ans = (n - 2 * k, n - k)
    var max = sum(partialSums, n - 2 * k, n - k - 1) + sum(partialSums, n - k, n - 1)
    var suff = (n - k, sum(partialSums, n - k, n - 1))
    for (i <- n - 2 * k - 1 to 0 by -1) {
      var current = sum(partialSums, i + k, i + 2 * k - 1)
      if (current >= suff._2)
        suff = (i + k, current)
      current = sum(partialSums, i, i + k - 1) + suff._2
      if (current >= max) {
        max = current
        ans = (i, suff._1)
      }
    }
    println((ans._1 + 1) + " " + (ans._2 + 1))
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Long](n)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Long](n)
    val father = new Array[Int](n)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 until (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) = best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, father(k))
    var absurdity = sums(0) + best(k)

    for(i <- 1 to (n - 2 * k))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toLong)
  val sliding = Array.ofDim[Long](n - k + 1)
  sliding(0) = line.take(k).sum

  (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }
  val partSum = sliding.reverse.scanLeft(0l){ case(a, b) => Math.max(a, b) }.tail.reverse
  val max = (0 until sliding.length - k).foldLeft(0l) {
    case(max, i) =>
      Math.max(max, sliding(i) + partSum(i + k))
  }

  val index = (0 until sliding.length - k).find {
    i => sliding(i) + partSum(i + k) == max
  }.get

//  println(sliding.toList)
//  println(partSum.toList)
//  println(index)
//  println(partSum(index + k))

  val j = ((index + k) until sliding.length).find(i => sliding(i) == partSum(index + k)).get

  println(s"${index + 1} ${j + 1}")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val sliding = Array.ofDim[Int](n - k + 1)
  sliding(0) = line.take(k).sum

  (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }
  val partSum = sliding.reverse.scanLeft(0){ case(a, b) => Math.max(a, b) }.tail.reverse
  val max = (0 until sliding.length - k).foldLeft(0) {
    case(max, i) =>
      Math.max(max, sliding(i) + partSum(i + k - 1))
  }

  val index = (0 until sliding.length - k).find {
    i => sliding(i) + partSum(i + k - 1) == max
  }.get

  val j = ((index + k - 1) until sliding.length).find(i => sliding(i) == partSum(index + k - 1)).get

  println(max)
  println(line.toList)
  println(sliding.toList)
  println(partSum.toList)
  println(s"$index $j")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val sliding = Array.ofDim[Int](n - k + 1)
  sliding(0) = line.take(k).sum

  (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }
  val partSum = sliding.reverse.scanLeft(0){ case(a, b) => Math.max(a, b) }.tail.reverse
  val max = (0 until sliding.length - k).foldLeft(0) {
    case(max, i) =>
      Math.max(max, sliding(i) + partSum(i + k - 1))
  }

  val index = (0 until sliding.length - k).find {
    i => sliding(i) + partSum(i + k - 1) == max
  }.get

  val j = ((index + k - 1) until sliding.length).find(i => sliding(i) == partSum(index + k - 1)).get

  println(s"$index $j")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val sliding = Array.ofDim[Int](n - k + 1)
  sliding(0) = line.take(k).sum

  (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }
  val partSum = sliding.reverse.scanLeft(0){ case(a, b) => Math.max(a, b) }.tail.reverse
  val max = (0 until sliding.length - k).foldLeft(0) {
    case(max, i) =>
      Math.max(max, sliding(i) + partSum(i + k))
  }

  val index = (0 until sliding.length - k).find {
    i => sliding(i) + partSum(i + k) == max
  }.get

//  println(sliding.toList)
//  println(partSum.toList)
//  println(index)
//  println(partSum(index + k))

  val j = ((index + k) until sliding.length).find(i => sliding(i) == partSum(index + k)).get

  println(s"${index + 1} ${j + 1}")
}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Long](n)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Long](n)
    val father = new Array[Int](n)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 until (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) =best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, 0)
    var absurdity = 0 : Long

    for(i <- 0 until (n - 2 * k + 1))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Int](n + 1)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Int](n)
    val father = new Array[Int](n)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 until (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) =best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, 0)
    var absurdity = 0

    for(i <- 0 until (n - 2 * k + 1))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Int](n + 1)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Int](n + 1)
    val father = new Array[Int](n + 1)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 to (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) =best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, 0)
    var absurdity = 0

    for(i <- 0 until (n - 2 * k))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Long](n)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Long](n)
    val father = new Array[Int](n)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 until (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) = best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, k)
    var absurdity = sums(0) + best(k)

    for(i <- 1 to (n - 2 * k))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object Main332B {
  def readInts = readLine.split(" ")map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, k) = readInts
    val arr = readInts
    val sums = Array.ofDim[Int](n)
    var currentSum = 0
    for (i <- (n-1) to 0 by -1) {
      currentSum += arr(i)
      if (i < n-k) currentSum -= arr(i+k)
      sums(i) = currentSum
    }
    var maxB = n-k
    var resA = n-k*2
    var resB = n-k
    for(a <- n-2*k to 0 by -1) {
      if(sums(a+k) >= sums(maxB)) maxB = a+k
      if(sums(a) + sums(maxB) >= sums(resA) + sums(resB)) {
        resA = a
        resB = maxB
      }
    }
    println((resA+1) + " " + (resB+1))
  }

}

object Main332B {
  def readInts = readLine.split(" ")map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, k) = readInts
    val arr = readInts
    val sums = Array.ofDim[Long](n)
    var currentSum = 0
    for (i <- (n-1) to 0 by -1) {
      currentSum += arr(i)
      if (i < n-k) currentSum -= arr(i+k)
      sums(i) = currentSum
    }
    var maxB = n-k
    var resA = n-k*2
    var resB = n-k
    for(a <- n-2*k to 0 by -1) {
      if(sums(a+k) >= sums(maxB)) maxB = a+k
      if(sums(a) + sums(maxB) >= sums(resA) + sums(resB)) {
        resA = a
        resB = maxB
      }
    }
    println((resA+1) + " " + (resB+1))
  }

}


import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine.toInt
    val a = StdIn.readLine.split(" ").map(_.toInt).sorted
    println(a((a.length - 1) / 2))
  }
}

object A extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _)

  println(a(n / 2))
}

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

  override def apply(io: IO): io.type = {
    val as = io.read[Vector[Int]].sorted
    val ans = as((as.length - 1)/2)
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import scala.io.StdIn

object A extends App {

  val numbers = {
    StdIn.readLine()
    StdIn.readLine().split(" ").map(_.toInt)
  }.sorted

  val numbersCount = numbers.length

  val numberIndex = if (numbersCount % 2 == 0) {
    (numbersCount / 2) - 1
  } else {
    numbersCount / 2
  }
  println(numbers(numberIndex))
}

import scala.io.StdIn

object Game extends App {

  val n = StdIn.readInt()
  val arr = StdIn.readLine().split(" ").map(_.toInt)

  print(impl(n, arr))

  def impl(n: Int, arr: Array[Int]): Int = {
    val sorted: Array[Int] = arr.sorted.reverse
    sorted(n / 2)
  }
}

import scala.io.StdIn

object A extends App {

  val numbers = {
    StdIn.readLine()
    StdIn.readLine().split(" ").map(_.toInt)
  }.sorted

  val numbersCount = numbers.length

  val numberIndex = numbersCount / 2

  println(numbers(numberIndex))
}

object A extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

  println(a(n / 2))
}


import scala.io.StdIn._

object Main {
  def getMS(b: Int): Int = {
    var k = 0;
    var a = b;
    while(a > 0) {
      a = (a >> 1);
      k = k + 1;
    }
    k
  }
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach { _ =>
      val n = readInt
      val a = readLine.split(" ").map(_.toInt)
      val result: Long = a.groupBy(getMS(_)).map { case (a, b) => (b.size.toLong * (b.size.toLong - 1)) / 2 }.sum
      println(result)
    }
  }
}

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

  def higher(a: Int): Int = {
    @annotation.tailrec
    def go(h: Int): Int = if (1 << h > a) h else go(h + 1)
    go(1)
  }

  val t = readInt()

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

    val bits = Array.fill(32)(0)

    val ans = an.foldLeft(0L) {
      case (count, h) =>
        bits(h) += 1
        count + bits(h) - 1
    }

    println(ans)
  }
}


import java.io._

object _1726B extends App {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)

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

  val in: InputReader = if (isOnlineJudge) new InputReader(System.in) else new InputReader(new File("src/test/resources/1726/B/input_0.txt"))
  val out = if (isOnlineJudge) new PrintWriter(System.out) else new PrintWriter(new File("1726_output.txt"))
  import in._

  /********* Solution *********/
  repeat {
    val n, m = nextInt()

    val ans: Iterator[Int] =
      if (m < n) Iterator.empty
      else if (m%n == 0) Iterator.tabulate(n)(_ => m/n)
      else if (n%2 == 1) Iterator.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))
      else if (m%2 == 0) Iterator.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)
      else Iterator.empty

      if (ans.isEmpty) {
        out.println("No")
      } else {
        out.println("Yes")
        ans.foreach({i =>
          out.print(i)
          out.print(" ")
        })
        out.println()
      }
  }
  out.close()

  /***********************/

  def repeat(f: => Unit): Unit = (1 to nextInt()).foreach(_ => f)

  class InputReader(reader: BufferedReader) {
    def this(file: File) = this(new BufferedReader(new FileReader(file)))
    def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

    val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

    def nextLine(): String = reader.readLine()
    def next(): String = tokens.next()
    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextDouble(): Double = next().toDouble
  }
}

object _1726B extends CodeForcesApp {
  override def solve() = repeat() {
    val n, m = nextInt()

    val ans: Seq[Int] =
      if (m < n) Seq.empty
      else if (m%n == 0) Seq.tabulate(n)(_ => m/n)
      else if (n%2 == 1) Seq.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))
      else if (m%2 == 0) Seq.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)
      else Seq.empty

    if (ans.isEmpty) {
      out.println("No")
    } else {
      out.println("Yes")
      out.println(ans.mkString(" "))
    }
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  import java.io._
  var in = new BufferedReader(new InputStreamReader(System.in))
  var out = new PrintWriter(System.out)

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextN[C[_], A](r: => A)(implicit b: collection.generic.CanBuild[A, C[A]]): C[A] = Iterator.fill(nextInt())(r).to[C]

  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(x)

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

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

  override def solve() = repeat {
    val n, m = in.nextInt()

    val ans: Iterator[Int] =
      if (m < n) Iterator.empty
      else if (m%n == 0) Iterator.tabulate(n)(_ => m/n)
      else if (n%2 == 1) Iterator.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))
      else if (m%2 == 0) Iterator.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)
      else Iterator.empty

    if (ans.isEmpty) {
      out.println("No")
    } else {
      out.println("Yes")
      out.println(ans.mkString(" "))
      out.println()
    }
  }
}
/****************************[Ignore Template Below]****************************************/
import java.io._

trait CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  var in: InputReader = new InputReader(System.in)
  var out: PrintWriter = new PrintWriter(System.out)

  def repeat(f: => Unit): Unit = (1 to in.nextInt()).foreach(_ => f)

  def solve(): Any

  def main(args: Array[String]): Unit = {
    if (!isOnlineJudge) {
      in = new InputReader(new File(args(0)))
      out = new PrintWriter(new File(args(1)))
    }
    try solve() finally out.flush()
  }
}

class InputReader(in: BufferedReader) {
  def this(file: File) = this(new BufferedReader(new FileReader(file)))
  def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble

  //def nextCollection[C[_], A](n: Int = nextInt())(r: _ => A)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(r).to[C]
}

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

  override def solve() = repeat {
    val n, m = in.nextInt()

    val ans: Iterator[Int] =
      if (m < n) Iterator.empty
      else if (m%n == 0) Iterator.tabulate(n)(_ => m/n)
      else if (n%2 == 1) Iterator.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))
      else if (m%2 == 0) Iterator.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)
      else Iterator.empty

    if (ans.isEmpty) {
      out.println("No")
    } else {
      out.println("Yes")
      ans.foreach({i =>
        out.print(i)
        out.print(" ")
      })
      out.println()
    }
  }
}
/****************************[Ignore Template Below]****************************************/
import java.io._

trait CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  var in: InputReader = new InputReader(System.in)
  var out: PrintWriter = new PrintWriter(System.out)

  def repeat(f: => Unit): Unit = (1 to in.nextInt()).foreach(_ => f)

  def solve(): Any

  def main(args: Array[String]): Unit = {
    if (!isOnlineJudge) {
      in = new InputReader(new File(args(0)))
      out = new PrintWriter(new File(args(1)))
    }
    try solve() finally out.flush()
  }
}

class InputReader(in: BufferedReader) {
  def this(file: File) = this(new BufferedReader(new FileReader(file)))
  def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble

  //def nextCollection[C[_], A](n: Int = nextInt())(r: _ => A)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(r).to[C]
}


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

import scala.collection.immutable
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 C339A(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 C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val l = nl()
    val r = nl()

    val k = nl()

    val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(p => Long.MaxValue >= p && Long.MaxValue / p >= k)
    val y = (if(Long.MaxValue / x.last >= k) x ++ Seq(x.last * k) else x).filter(p => p >= l && p <=r)
    if(y.nonEmpty) {
      out.print(y.mkString(" "))
    } else out.println(-1)
  }
}

// object Main
import java.io.{IOException, InputStream, PrintWriter}
import java.util.InputMismatchException

import scala.collection.mutable.ArrayBuffer

object Main {

    def solveCase(caseNo: Int, in: InputReader, out: PrintWriter): Unit = {
        val l, r, k = in.nextLong()
        var c = BigInt(1)
        val answer = new ArrayBuffer[String]
        while (c <= r) {
            if (c >= l) {
                answer.append(c.toString)
            }
            c *= k

        }
        if (answer.isEmpty) {
            println(-1)
        } else {
            println(answer.mkString(" "))
        }

    }

    def solve(in: InputReader, out: PrintWriter): Unit = {
        solveCase(1, in, out)
//        val caseCount = in.nextInt()
//        for (caseNo <- 1 to caseCount) {
//            solveCase(caseNo, in, out)
//        }
    }

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

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

    def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def nextLong(): Long = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0l
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while (!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

    def nextDouble(): Double = {
        next().toDouble
    }

    def close(): Unit = {
        inputStream.close()
    }
}

/**
  * Created by octavian on 16/01/2016.
  */
object LinkTree {

  def main (args: Array[String]) {
    //System.setIn(new FileInputStream("src/link.in"))
    //System.setOut(new PrintStream(new FileOutputStream("src/link.out")))
    val Array(l, r, k): Array[BigInt] = readLine().split(" ").map(x => BigInt(x)).toArray
    var acc: BigInt = 1
    var found = false
    while(acc <= r) {
      if(l <= acc) {
        print(acc + " ")
        found = true
      }
      acc *= k
    }

    if(found == false) {
      println("-1")
    }
  }

}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._, control._
import scala.math.Ordering.Implicits._

object _614A extends CodeForcesApp {
  override type Result = Stream[BigInt]

  override def solve(read: InputReader) = {
    val l, r, k = read[BigInt]
    Stream.iterate(BigInt(1))(_ * k).dropWhile(_ < l).takeWhile(_ <= r)
  }

  override def format(result: Result) = if (result.isEmpty) "-1" else result mkString " "
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(l, r, k) = in.next().split(' ').map(_.toLong)
  var res = List.empty[Long]
  var i = BigInt(1)
  while (i <= r) {
    if (i >= l)
      res ::= i.toLong
    i *= k
  }
  if (res.isEmpty)
    println(-1)
  else
    println(res.reverse.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(l, r, k) = in.next().split(' ').map(_.toLong)
  var res = List.empty[Long]
  var i = 1l
  while (i <= r) {
    if (i >= l)
      res ::= i
    i *= k
  }
  if (res.isEmpty)
    println(-1)
  else
    println(res.reverse.mkString(" "))
}

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

import scala.collection.immutable
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 C339A(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 C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val l = nl()
    val r = nl()

    val k = nl()

    val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(p => r>=p && Long.MaxValue / p >= k).filter(p => p>=l)
    if(x.nonEmpty) {
      out.print(x.mkString(" "))
      if(Long.MaxValue / k >= x.last && x.last * k <= r) out.println(s" ${x.last * k}")
    } else out.println(-1)
  }
}

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

import scala.collection.immutable
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 C339A(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 C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val l = nl()
    val r = nl()

    val k = nl()

    val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(p => r>=p && Long.MaxValue / p >= k).filter(p => p>=l)
    if(x.nonEmpty) {
      out.println(x.mkString(" "))
    } else out.println(-1)
  }
}

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

import scala.collection.immutable
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 C339A(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 C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val l = nl()
    val r = nl()

    val k = nl()

    val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(r>=).filter(p => p>=l)
    if(x.nonEmpty) {
      out.println(x.mkString(" "))
    } else out.println(-1)
  }
}


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

/**
  * @author antipov.
  *         15.07.2016 14:47.
  */
object B extends App {

  def solve() = {
    val n = readInt
    val g = new Array[List[Int]](n)
    (0 until n) foreach (i => g(i) = Nil)

    (1 until n) map (i => {
      val parent = readInt - 1
      g(parent) = i :: g(parent)
    })

    val sizes = new Array[Int](n)
    val res = new Array[Double](n)
    calcSizes(0, sizes);
    calcRes(0, 1, res)

    res foreach (i => print(i + " "))

    def calcSizes(v: Int, res: Array[Int]): Int = {
      res(v) = (g(v) map (ch => calcSizes(ch, res)) sum)
      res(v) + 1
    }

    def calcRes(v: Int, mo: Double, res: Array[Double]): Unit = {
      res(v) = mo
      g(v) foreach (ch => calcRes(ch, mo + 1 + (sizes(v) - (sizes(ch) + 1)) / 2.0, res))
    }
  }

  def readInt(): Int = IO.nextInt

  def readLong(): Long = IO.nextLong

  def println(a: Any) = IO.println(a)

  def print(a: Any) = IO.print(a)

  def printf(locale: Locale, format: String, values: Any*) = IO.printf(locale, format, values)

  solve()
  IO.close
}

object IO {

  val in = new BufferedReader(new InputStreamReader(System.in))
  val out = new PrintWriter(System.out)
  var tok = new StringTokenizer("")

  def nextToken() = {
    while (!tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine())
    }
    tok.nextToken()
  }

  def nextInt = nextToken().toInt

  def nextLong = nextToken().toLong

  def println(a: Any) = out.println(a)

  def print(a: Any) = out.print(a)

  def printf(locale: Locale, format: String, values: Any*) = out.printf(locale, format, values)

  def close = {
    in.close()
    out.close()
  }
}

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

object Main extends App {
    def nextInt(): Int = IO.nextInt()

    val n = nextInt()
    val g: Array[ArrayBuffer[Int]] = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer[Int]())
    val p: Array[Int] = Array.fill[Int](n)(0)
    (1 until n).foreach{ i =>
        p(i) = nextInt - 1
        g(p(i)) += i
    }

    val size: Array[Int] = Array.fill[Int](n)(0)
    dfs(0)

    val exp: Array[Double] = Array.fill[Double](n)(1)
    dfs1(0)

    exp.map(i => print(i + " "))
    println("")

    IO.close

    def dfs(v: Int): Int = {
        var ret = 1
        for(i <- g(v)) {
            ret += dfs(i)
        }
        size(v) = ret
        ret
    }

    def dfs1(v: Int) {
        // val sum = g(v).map(i => size(i)).sum
        var sum = 0
        for(i <- g(v)) sum += size(i)
        for(i <- g(v)) {
            exp(i) = exp(p(i)) + 1 + (sum - size(i)).toDouble / 2
            dfs1(i)
        }
    }
}

object IO {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(System.out)
    var str = new StringTokenizer("")

    def next(): String = {
        while(!str.hasMoreElements()) {
            str = new StringTokenizer(in.readLine())
        }
        str.nextToken()
    }

    def nextInt() = next().toInt
    def println(a: AnyVal) = out.println(a)
    def print(a: AnyVal) = out.print(a)

    def close() = {
        in.close()
        out.close()
    }
}


object _1738A extends CodeForcesApp {
  override def solve(io: IO) = io.repeat() {
    val n = io.nextInt()
    val isFrost = Seq.fill(n)(io.nextBool())
    val damages = Seq.fill(n)(io.nextLong())

    val all = isFrost.zip(damages).toMultiMap.mapValues(_.sorted(desc[Long])).withDefaultValue(Nil)

    var ans = all(true).zipAll(all(false), 0L, 0L) sumWith {
      case (frost, fire) if frost > 0 && fire > 0 => 2*(frost + fire)
      case (frost, fire) => frost + fire
    }

    if (all(true).length == all(false).length)
      ans -= damages.min

    io.printLine(ans)
  }

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C]).withDefaultValue(b().result())
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B =
      t.foldLeft(n.zero)({ case (c, x) => n.plus(c, f(x)) })
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextBool(): Boolean = nextInt() == 1
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): this.type = { out.print(xs.mkString(" ")); this }
  def printLine(xs: Any*): this.type = { out.println(xs.mkString(" ")); this }
  def printLines(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }

  override def close() = out.close()
}

import scala.util.Sorting.quickSort
import scala.math.Ordered.orderingToOrdered

object Main {

    class Hero(var x: Int = 0, var y: Int = 0) extends Ordered[Hero] {

        def compare(that: Hero): Int = (that.y, this.x) compare (this.y, that.x)

        override def toString: String =
            s"($x, $y)"
    }

    def main(args:Array[String]): Unit = {
        var t = io.StdIn.readInt()

        def loopts(ts: Int): Int = {
            if ( ts < t ){
                var n = io.StdIn.readInt()

                var arrt:Array[Hero] = new Array[Hero](n)
                var a:Array[Int] = io.StdIn.readLine().split(" ").map(_.toInt)
                var b:Array[Int] = io.StdIn.readLine().split(" ").map(_.toInt)

                for ( i <- 0 until n )
                    arrt(i) = new Hero(a(i), b(i))

                quickSort[Hero](arrt)(Ordering[Hero])

                var Array(cnt0, cnt1) = {
                    def count(i: Int, cnt0: Int, cnt1: Int): Array[Int] = {
                        if ( i < n ){
                            if ( arrt(i).x == 0 )
                                count(i+1, cnt0+1, cnt1)
                            else
                                count(i+1, cnt0, cnt1+1)
                        }
                        else
                            Array(cnt0, cnt1)
                    }
                    count(0, 0, 0)
                }

                def solve(i: Int, cnt0: Int, cnt1: Int, acc: Long): Long = {
                    if ( i < n ){
                        if ( arrt(i).x == 0 && cnt0+cnt1 > 1 ){
                            if ( cnt1 > 0 )
                                solve(i+1, cnt0, cnt1-1, acc+2*arrt(i).y)
                            else
                                solve(i+1, cnt0, cnt1, acc+arrt(i).y)
                        }
                        else {
                            if ( cnt0 > 0 && cnt0+cnt1 > 1 )
                                solve(i+1, cnt0-1, cnt1, acc+2*arrt(i).y)
                            else
                                solve(i+1, cnt0, cnt1, acc+arrt(i).y)
                        }
                    }
                    else
                        acc
                }
                println(solve(0, cnt0, cnt1, 0))

                loopts(ts+1)
            }
            else
                0
        }

        loopts(0)
    }

}

import scala.util.Sorting.quickSort
import scala.math.Ordered.orderingToOrdered

object Main {

    class Hero(var x: Int = 0, var y: Int = 0) extends Ordered[Hero] {

        def compare(that: Hero): Int = (that.x, this.y) compare (this.x, that.y)

        override def toString: String =
            s"($x, $y)"
    }

    def main(args:Array[String]): Unit = {
        var t = io.StdIn.readInt()

        def loopts(ts: Int): Int = {
            if ( ts < t ){
                var n = io.StdIn.readInt()

                var arrt:Array[Hero] = new Array[Hero](n)
                var a:Array[Int] = io.StdIn.readLine().split(" ").map(_.toInt)
                var b:Array[Int] = io.StdIn.readLine().split(" ").map(_.toInt)

                var min: Int = 10^9
                for ( i <- 0 until n ){
                    arrt(i) = new Hero(a(i), b(i))
                    if ( min > b(i) )
                        min = b(i)
                }

                quickSort[Hero](arrt)(Ordering[Hero].reverse)

                var Array(cnt0, cnt1) = {
                    def count(i: Int, cnt0: Int, cnt1: Int): Array[Int] = {
                        if ( i < n ){
                            if ( arrt(i).x == 0 )
                                count(i+1, cnt0+1, cnt1)
                            else
                                count(i+1, cnt0, cnt1+1)
                        }
                        else
                            Array(cnt0, cnt1)
                    }
                    count(0, 0, 0)
                }

                def solve(i: Int, acc: Long): Long = {
                    if ( i < n ){
                        if ( cnt0 < cnt1 ){
                            if ( arrt(i).x == 0 || i < 2*cnt0 )
                                solve(i+1, acc+2*arrt(i).y)
                            else
                                solve(i+1, acc+arrt(i).y)
                        }
                        else {
                            if ( arrt(i).x == 1 || i < cnt1 )
                                solve(i+1, acc+2*arrt(i).y)
                            else
                                solve(i+1, acc+arrt(i).y)
                        }
                    }
                    else
                        if ( cnt0 != cnt1 )
                            acc
                        else
                            acc - min
                }
                println(solve(0, 0))
                loopts(ts+1)
            }
            else
                0
        }

        loopts(0)
    }

}


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

  override def solve(io: IO) = io.repeat {
    val n, x = io.read[Int]
    val as = io.read[Set, Int](n)
    val ans = Iterator.from(1)
      .filterNot(as)
      .drop(x)
      .dropWhile(as)
      .next()
    io.write(ans - 1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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

object A extends App {
  class Rank private (val x: Int, val as: List[Int])

  object Rank {
    def apply(x: Int, as: List[Int]): Rank = new Rank(x, as.distinct.sorted)
    def unapply(rank: Rank): Option[(Int, List[Int])] = Some(rank.x, rank.as)
  }

  private def possible(r: Rank): Int = {
    val Rank(x, as) = r

    val t = as.foldLeft((0, x)) {
      case ((i, x), j) =>
        if (i + 1 + x >= j) (j, x - math.min(x, j - i - 1))
        else (i + x, 0)
    }

    t._1 + t._2
  }

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

  val input: List[Rank] = (0 until t)
    .foldLeft(List.empty[Rank]) {
      case (rs, _) =>
        val Array(_, x) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

        Rank(x, as) :: rs
    }
    .reverse

  val output = input.map(possible)

  output.foreach(println)
}

object A extends App {
  class Rank private (val x: Int, val as: List[Int])

  object Rank {
    def unapply(rank: Rank): Option[(Int, List[Int])] = Some(rank.x, rank.as)

    def apply(x: Int, as: List[Int]): Rank = new Rank(x, as.distinct.sorted)
  }

  private def possible(r: Rank): Int = {
    val Rank(x, as) = r

    val t = as.foldLeft((0, x)) { case ((i, x), j) =>
      if (x == 0) (i, x)
      else (if (i + x >= j - 1) j else i + x, x - math.min(x, j - i - 1))
    }

    t._1 + t._2
  }

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

  val input: List[Rank] = (0 until t).foldLeft(List.empty[Rank]) {
    case (rs, _) =>
      val Array(_, x) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

      Rank(x, as) :: rs
  }.reverse

  val output = input.map(possible)

  output.foreach(println)
}