On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.

The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.

If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.  Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.

object D41 {

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

  def main(args: Array[String]): Unit = {
    var tests = 1 // readInt
    while (tests > 0) {
      val Array(n, m, k) = readInts(3)
      val MOD = k + 1
      val g = Array.fill(n)(read.map(_ - '0').toArray)
      val dp = Array.fill(n, m, MOD)(-1)
      for (i <- n - 1 to 0 by -1; j <- 0 until m) {
        if (i == n - 1) {
          dp(i)(j)(g(i)(j) % MOD) = g(i)(j)
        } else {
          for (mod <- 0 until MOD) {
            if (j >= 1 && dp(i + 1)(j - 1)(mod) >= 0)
              dp(i)(j)((g(i)(j) + dp(i + 1)(j - 1)(mod)) % MOD) = math.max(
                dp(i)(j)((g(i)(j) + dp(i + 1)(j - 1)(mod)) % MOD),
                dp(i + 1)(j - 1)(mod) + g(i)(j)
              )
            if (j < m - 1 && dp(i + 1)(j + 1)(mod) >= 0)
              dp(i)(j)((g(i)(j) + dp(i + 1)(j + 1)(mod)) % MOD) = math.max(
                dp(i)(j)((g(i)(j) + dp(i + 1)(j + 1)(mod)) % MOD),
                dp(i + 1)(j + 1)(mod) + g(i)(j)
              )
          }
        }
      }

      var res = -1
      var idxJ = 0
      for (j <- 0 until m if (dp(0)(j)(0) > res)) {
        res = dp(0)(j)(0)
        idxJ = j
      }
      out.println(res)
      if (res != -1) {
        // tracePath
        var idxI = 0
        var mod = 0
        val path = ArrayBuffer.empty[Char]
        while (idxI < n - 1) {
          val next = dp(idxI)(idxJ)(mod) - g(idxI)(idxJ)
          var done = false
          if (idxJ - 1 >= 0 && dp(idxI + 1)(idxJ - 1)(next % MOD) == next) {
            mod = next % MOD
            idxJ -= 1
            path.append('R')
            done = true
          }
          if (!done && idxJ + 1 < m && dp(idxI + 1)(idxJ + 1)(next % MOD) == next) {
            mod = next % MOD
            idxJ += 1
            path.append('L')
            done = true
          }
          idxI += 1
        }
        out.println(idxJ + 1)
        out.println(path.reverseIterator.mkString(""))
      }
      tests -= 1
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.

First line contains one integer n (1 ≤ n ≤ 105) — number of voters in the city. Each of the next n lines describes one voter and contains two integers ai and bi (0 ≤ ai ≤ 105; 0 ≤ bi ≤ 104) — number of the candidate that voter is going to vote for and amount of money you need to pay him to change his mind. You are the candidate 0 (so if a voter wants to vote for you, ai is equal to zero, in which case bi will also be equal to zero).

Print one integer — smallest amount of money you need to spend to win the elections.

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)

  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
  }

  val allVoters = (0 until n).toArray.sortBy(voterCosts).reverse

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {

    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    val votes = Array.fill(voterCounts.length)(0)

    for (voter <- allVoters) {
      val candidate = voterFor(voter)
      if (candidate > 0) {
        if (votes(candidate) + 1 == votesToWin) {
          totalCost += voterCosts(voter)
          bribed += voter
          myVotes += 1
        } else votes(candidate) += 1
      }
    }

    var i = n - 1
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i -= 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)

  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
  }

  val allVoters = (0 until n).toArray.sortBy(voterCosts).reverse

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {

    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    val votes = Array.fill(voterCounts.length)(0)

    for {
      voter <- allVoters
      candidate = voterFor(voter)
      if candidate > 0
    } if (votes(candidate) + 1 == votesToWin) {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    } else votes(candidate) += 1

    var i = n - 1
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i -= 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.quickSort[Int](_)(Ordering.by(voterCosts))
  }

  val allVoters = (0 until n).toArray
  Sorting.quickSort[Int](allVoters)(Ordering.by(voterCosts))

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (pos < allVoters.size && bribed(allVoters(pos))) pos += 1
        if (pos == allVoters.size) {
          costToBribeCheapest = Long.MaxValue
          cnt = 0
        } else {
          costToBribeCheapest += voterCosts(allVoters(pos))
          //println(cnt, allVoters(pos))
          pos += 1
          cnt -= 1
        }
      }
      //println(numCandidatesWithMaxVoters, costToBribeFromBest, costToBribeCheapest)
      if (costToBribeFromBest <= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
        //while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        //bribe(allVoters(cheapestVoterPosition))
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))

  val allVoters = (0 until n).toArray.sortBy(voterCosts)
  //Sorting.stableSort(allVoters, voterCosts)
  if (n == 10) {
    println(allVoters.mkString(", "))
  }

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.stableSort(_, voterCosts)
  }

  val allVoters = (0 until n).toArray
  if (n == 10) {
    println(voterCosts.mkString(", "))
  }
  Sorting.stableSort(allVoters, voterCosts)

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.stableSort(_, voterCosts)
  }

  val allVoters = (0 until n).toArray
  Sorting.stableSort(allVoters, voterCosts)

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))

  val allVoters = (0 until n).toArray //.sortBy(voterCosts)
  Sorting.stableSort(allVoters, voterCosts)
  if (n == 10) {
    println(allVoters.mkString(", "))
  }

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest >= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        //        var cnt = numCandidatesWithMaxVoters + 1
        //
        //        while (cnt > 0) {
        //          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        //          bribe(allVoters(cheapestVoterPosition))
        //          cnt -= 1
        //        }
        while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        bribe(allVoters(cheapestVoterPosition))
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest >= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.quickSort[Int](_)(Ordering.by(voterCosts))
  }
  val allVoters = (0 until n).toArray.sortBy(voterCosts)

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._
import scala.util.Sorting

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterFor = Array.ofDim[Int](n)
  val voterCosts = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    voterFor(i) = a
    voterCosts(i) = b
    if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
    voterBuilders(a) += i
  }

  val votersByCandidate = voterBuilders.mapValues(_.result)
  votersByCandidate.values.foreach {
    Sorting.stableSort(_, voterCosts)
  }

  val allVoters = (0 until n).toArray
  Sorting.stableSort(allVoters, voterCosts)
  if (n == 10) {
    println(allVoters.mkString(", "))
  }

  val myInitialVotes = voterCounts(0)

  def getCost(votesToWin: Int): Long = {
    var totalCost = 0L
    var myVotes = myInitialVotes
    val bribed = new mutable.BitSet(n)
    for {
      candidate <- voterCounts.indices
      if voterCounts(candidate) >= votesToWin
      voter <- votersByCandidate(candidate).view(0, voterCounts(candidate) - votesToWin + 1)
    } {
      totalCost += voterCosts(voter)
      bribed += voter
      myVotes += 1
    }
    var i = 0
    while (myVotes < votesToWin) {
      val voter = allVoters(i)
      if (!bribed(voter) && voterFor(voter) > 0) {
        totalCost += voterCosts(voter)
        myVotes += 1
      }
      i += 1
    }
    totalCost
  }

  var left = 1 max myInitialVotes
  var right = n min (voterCounts.max + 1)

  while (left + 2 < right) {
    val m = (right - left) / 3
    val ml = left + m
    val mr = right - m
    val costL = getCost(ml)
    val costR = getCost(mr)
    if (costL < costR) right = mr else left = ml
  }

  var res = getCost(left)
  while (left < right) {
    left += 1
    res = res min getCost(left)
  }

  println(res)
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest < costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
        //while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        //bribe(allVoters(cheapestVoterPosition))
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(votersByCandidate(c)(voterPosition(c)))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest <= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
        //while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
        //bribe(allVoters(cheapestVoterPosition))
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}

import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)

  val voterBuilders = mutable.Map.empty[Int, mutable.ArrayBuilder.ofInt]
  val voterCounts = Array.fill(100001) { 0 }
  val voterPosition = Array.fill(100001) { 0 }
  val voterCostsBuilder = new mutable.ArrayBuilder.ofInt
  val candidatesByVoters = Array.ofDim[Int](n)

  var voterId = 0
  for (i <- 0 until n) {
    val tl = tokenizeLine
    val a, b = tl.nextToken.toInt
    voterCounts(a) += 1
    if (a > 0) {
      candidatesByVoters(voterId) = a
      voterCostsBuilder += b
      if (!voterBuilders.contains(a)) voterBuilders += (a -> new mutable.ArrayBuilder.ofInt)
      voterBuilders(a) += voterId
      voterId += 1
    }
  }

  val candidatesByVoterCounts = Array.fill(100000) { mutable.Set.empty[Int] }
  for (c <- voterCounts.indices) if (c > 0 && voterCounts(c) > 0) candidatesByVoterCounts(voterCounts(c)) += c

  var maxVoterCount = voterCounts.max

  val voterCosts = voterCostsBuilder.result
  val votersByCandidate = voterBuilders.mapValues(_.result.sortBy(voterCosts))
  val allVoters = (0 until voterId).sortBy(voterCosts)
  val bribed = new mutable.BitSet(voterId)

  var myVotes = voterCounts(0)
  var cheapestVoterPosition = 0
  var totalCost = 0L

  def bribe(voterId: Int): Unit = {
    //require(!bribed(voterId))
    totalCost += voterCosts(voterId)
    myVotes += 1
    bribed += voterId
    val candidate = candidatesByVoters(voterId)
    candidatesByVoterCounts(voterCounts(candidate)) -= candidate
    voterCounts(candidate) -= 1
    candidatesByVoterCounts(voterCounts(candidate)) += candidate
  }

  while (myVotes <= maxVoterCount) {

    val numCandidatesWithMaxVoters = candidatesByVoterCounts(maxVoterCount).size

    if (myVotes + numCandidatesWithMaxVoters <= maxVoterCount) {

      var costToBribeFromBest = 0L

      for (c <- candidatesByVoterCounts(maxVoterCount)) {
        while (bribed(voterPosition(c))) voterPosition(c) += 1
        costToBribeFromBest += voterCosts(votersByCandidate(c)(voterPosition(c)))
      }

      var costToBribeCheapest = 0L
      var cnt = numCandidatesWithMaxVoters + 1
      var pos = cheapestVoterPosition

      while (cnt > 0) {
        while (bribed(allVoters(pos))) pos += 1
        costToBribeCheapest += voterCosts(allVoters(pos))
        cnt -= 1
      }

      if (costToBribeFromBest >= costToBribeCheapest) {
        for (c <- candidatesByVoterCounts(maxVoterCount)) {
          bribe(votersByCandidate(c)(voterPosition(c)))
        }
      } else {

        var cnt = numCandidatesWithMaxVoters + 1

        while (cnt > 0) {
          while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
          bribe(allVoters(cheapestVoterPosition))
          cnt -= 1
        }
      }

    } else {
      while (bribed(allVoters(cheapestVoterPosition))) cheapestVoterPosition += 1
      bribe(allVoters(cheapestVoterPosition))
    }

    while (candidatesByVoterCounts(maxVoterCount).isEmpty && maxVoterCount > 0) maxVoterCount -= 1
  }

  println(totalCost)
}


Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition Ai ≥ Bj holds. Help Leha rearrange the numbers in the array A so that the sum  is maximally possible, where A' is already rearranged array.

First line of input data contains single integer m (1 ≤ m ≤ 2·105) — length of arrays A and B. Next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 109) — array A. Next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109) — array B.

Output m integers a'1, a'2, ..., a'm — array A' which is permutation of the array A.

object A extends App {

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

  val Array(m) = readInts(1)
  val as = readInts(m).sorted
  val bs = readInts(m).zipWithIndex.sortBy(_._1)

  val res = Array.ofDim[Int](m)

  for (i <- as.indices) res(bs(i)._2) = as(m - i - 1)

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

  println(res.mkString(" "))

  Console.flush
}


The store sells $$$n$$$ beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them.A necklace is a set of beads connected in a circle.For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options):  And the following necklaces cannot be assembled from beads sold in the store:  The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store. We call a necklace $$$k$$$-beautiful if, when it is turned clockwise by $$$k$$$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace.    As you can see, this necklace is, for example, $$$3$$$-beautiful, $$$6$$$-beautiful, $$$9$$$-beautiful, and so on, but it is not $$$1$$$-beautiful or $$$2$$$-beautiful.In particular, a necklace of length $$$1$$$ is $$$k$$$-beautiful for any integer $$$k$$$. A necklace that consists of beads of the same color is also beautiful for any $$$k$$$.You are given the integers $$$n$$$ and $$$k$$$, and also the string $$$s$$$ containing $$$n$$$ lowercase letters of the English alphabet — each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $$$k$$$-beautiful necklace you can assemble.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 2000$$$). The second line of each test case contains the string $$$s$$$ containing $$$n$$$ lowercase English letters — the beads in the store. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2000$$$.

Output $$$t$$$ answers to the test cases. Each answer is a positive integer — the maximum length of the $$$k$$$-beautiful necklace you can assemble.

6
6 3
abcbac
3 6
aaa
7 1000
abczgyo
5 4
ababa
20 10
aaebdbabdbbddaadaadc
20 5
ecbedececacbcbccbdec

NoteThe first test case is explained in the statement.In the second test case, a $$$6$$$-beautiful necklace can be assembled from all the letters.In the third test case, a $$$1000$$$-beautiful necklace can be assembled, for example, from beads "abzyo".

//package codeforces.contests._1367

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

      val Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)
      val s = io.StdIn.readLine

      val freq = new Array[Int](26)
      s.foreach(c => freq(c - 'a') += 1)

      val kPairs = new Array[Int](n + 1)
      freq.foreach { f =>
        for (i <- 1 to f) kPairs(i) += f / i
      }
      /*
      n = 7, k = 1000
      abczgyo

      2 pairs are 3 and k = 4, e.g. "aabbcc", abab

      a -7
      b - 6
      c - 5

      abc abc abc a bc abc
      aabbc aabbc aabbc

      k = 10, 5 repetition thrice
       */

      println {
        (1 to n).foldLeft(0) { (acc, i) =>
          acc max {
            val x = (if (kPairs(i) > 0) {
              i * (kPairs(i) to 1 by -1).find(k % _ == 0).get
            } else 0) max (if (kPairs(i) >= k) i * k else 0) max (if (k % i == 0) i else 0) max (if (kPairs(i) >= 1) i else 0)
            x
          }
        }
      }
    }
  }
}

import scala.io.StdIn.readLine

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

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

  def handle(k: Int, list: Array[Char]): Int = {
    val gr = list.groupBy(i => i).map(tup => tup._2.length).toList.sortBy(t => t).reverse

    for (l <- (1 to list.length).reverse) {
      if (canSatisfy(l, gr, k)) return l
    }

    1
  }

  def canSatisfy(length: Int, bonds: List[Int], rawK: Int): Boolean = {
    def helper(groupSize: Int,  numGroups: Int, bs: List[Int]): Boolean = bs match {
      case Nil => numGroups <= 0
      case b :: bs => numGroups <= 0 || {
        if (groupSize > b) false else helper(groupSize, numGroups - b / groupSize, bs)
      }
    }

    val k = (rawK - 1) % length + 1
    val gcd = BigInt(length).gcd(BigInt(k)).toInt
    if (gcd == 1) bonds.head >= length else {
      val numOfGroups = length / gcd
      helper(numOfGroups, gcd, bonds)
    }
  }

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

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

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

}

object Main extends App {
  val r = new FastScanner(java.lang.System.in)
  val o = new java.io.PrintWriter(java.lang.System.out)
  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)
  for(_ <- 1 to r.nextInt()) {
    val n = r.nextInt()
    val k = r.nextInt()
    val s = r.nextToken(n)
    val c = Array.ofDim[Int](26)
    for(i <- s) c(i.toInt - 97) += 1
    val d = c.sorted.filter(_ > 0).reverse
    var res = 0
    for(l <- 1 to n) {
      //0, k, 2k, 3k, ... (mod l)
      //kx == y (mod l)
      val g = gcd(l, k)
      val gs = l / g
      //g groups, group size gs
      val t = d.foldLeft(0) { (acc, x) => acc + (x / gs) }
      if(t >= g) res = l
    }
    o.println(res)
  }
  o.close()
}

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

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

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

//package codeforces.contests._1367

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

      val Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)
      val s = io.StdIn.readLine

      val freq = new Array[Int](26)
      s.foreach(c => freq(c - 'a') += 1)

      val kPairs = new Array[Int](n + 1)
      freq.foreach { f =>
        for (i <- 1 to f) kPairs(i) += f / i
      }
      /*
      n = 7, k = 1000
      abczgyo

      2 pairs are 3 and k = 4, e.g. "aabbcc", abab

      a -7
      b - 6
      c - 5

      abc abc abc a bc abc
      aabbc aabbc aabbc

      k = 10, 5 repetition thrice
       */

      println {
        (1 to n).foldLeft(0) { (acc, i) =>
          acc max {
            (if (kPairs(i) > 0 && k % kPairs(i) == 0) i * kPairs(i) else 0) max (if (kPairs(i) >= k) i * k else 0) max (if (k % i == 0) i else 0) max (if (kPairs(i) >= 1) i else 0)
          }
        }
      }
    }
  }
}


— Do you have a wish?  — I want people to stop gifting each other arrays.O_o and Another Young BoyAn array of $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$ fell down on you from the skies, along with a positive integer $$$k \le n$$$.You can apply the following operation at most $$$k$$$ times:   Choose an index $$$1 \le i \le n$$$ and an integer $$$1 \le x \le 10^9$$$. Then do $$$a_i := x$$$ (assign $$$x$$$ to $$$a_i$$$). Then build a complete undirected weighted graph with $$$n$$$ vertices numbered with integers from $$$1$$$ to $$$n$$$, where edge $$$(l, r)$$$ ($$$1 \le l < r \le n$$$) has weight $$$\min(a_{l},a_{l+1},\ldots,a_{r})$$$.You have to find the maximum possible diameter of the resulting graph after performing at most $$$k$$$ operations.The diameter of a graph is equal to $$$\max\limits_{1 \le u < v \le n}{\operatorname{d}(u, v)}$$$, where $$$\operatorname{d}(u, v)$$$ is the length of the shortest path between vertex $$$u$$$ and vertex $$$v$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le k \le n$$$). The second line of each test case contains $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the maximum possible diameter of the graph after performing at most $$$k$$$ operations.

NoteIn the first test case, one of the optimal arrays is $$$[2,4,5]$$$.The graph built on this array:   $$$\operatorname{d}(1, 2) = \operatorname{d}(1, 3) = 2$$$ and $$$\operatorname{d}(2, 3) = 4$$$, so the diameter is equal to $$$\max(2,2,4) = 4$$$.

object Main {
  private val in = scala.io.StdIn

  val inf = 1000000000

  def checkAns(x: Int, k1: Int, b: Array[Int]): Boolean = {
    var k = k1
    val a = new Array[Int](b.length)
    val n = a.length
    for (i <- 0 until n)
      a(i) = b(i)

    var mn = 2

    if (2 * a(0) < x) {
      a(0) = inf;
      k = k - 1;
    }
    for (i <- 1 until n) {
      if (2 * a(i) < x) {
        k = k - 1;
        a(i) = inf;
      }

      if (Math.min(a(i - 1), a(i)) >= x) mn = 0
      else if (Math.max(a(i - 1), a(i)) >= x) mn = Math.min(mn, 1);
    }
    mn <= k
  }

  def main(args: Array[String]): Unit = {
    val t = in.readInt()
    for (_ <- 1 to t) {
      val Array(n, k) = in.readLine().split(" ").map(_.toInt)
      val a = in.readLine().split(" ").map(_.toInt)

      var l = 0
      var r = inf + 1
      while (l < r - 1) {
        val m = (l + r) / 2
        if (checkAns(m, k, a)) l = m
        else r = m;
      }
      println(l)
    }
  }
}


A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Let $$$p$$$ be any permutation of length $$$n$$$. We define the fingerprint $$$F(p)$$$ of $$$p$$$ as the sorted array of sums of adjacent elements in $$$p$$$. More formally,$$$$$$F(p)=\mathrm{sort}([p_1+p_2,p_2+p_3,\ldots,p_{n-1}+p_n]).$$$$$$For example, if $$$n=4$$$ and $$$p=[1,4,2,3],$$$ then the fingerprint is given by $$$F(p)=\mathrm{sort}([1+4,4+2,2+3])=\mathrm{sort}([5,6,5])=[5,5,6]$$$.You are given a permutation $$$p$$$ of length $$$n$$$. Your task is to find a different permutation $$$p'$$$ with the same fingerprint. Two permutations $$$p$$$ and $$$p'$$$ are considered different if there is some index $$$i$$$ such that $$$p_i \ne p'_i$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 668$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2\le n\le 100$$$)  — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1,\ldots,p_n$$$ ($$$1\le p_i\le n$$$). It is guaranteed that $$$p$$$ is a permutation.

For each test case, output $$$n$$$ integers $$$p'_1,\ldots, p'_n$$$ — a permutation such that $$$p'\ne p$$$ and $$$F(p')=F(p)$$$. We can prove that for every permutation satisfying the input constraints, a solution exists. If there are multiple solutions, you may output any.

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

  val t = readInt()

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

    val ans = pn.reverse

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

import scala.collection.mutable.ArrayBuffer

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m = in.nextInt()
      val data = in.nextLineInt(m)
      println(data.reverse.mkString(" "))
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

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

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

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

  val t = readInt()

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

    val mod = pn.indexOf(1) % 2

    val ans = pn.zipWithIndex.map { case (p, i) => if (i % 2 == mod) p + 1 else p - 1 }

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


Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.

NoteIn the first test case, you can add roads   from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$,  from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$,  from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$,  from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$,  from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$.  The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val ds = nextLongs(n).sorted

      var res = 0L
      var prev = 0L
      var mul = 0L
      var back = 0L
      for (d <- ds) {
        val x = (d - prev)
        res += x
        back += mul * x
        res -= back
        prev = d
        mul += 1
      }

      out.println(res)
    }

    out.flush()
  }

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


Alex decided to go on a touristic trip over the country.For simplicity let's assume that the country has $$$n$$$ cities and $$$m$$$ bidirectional roads connecting them. Alex lives in city $$$s$$$ and initially located in it. To compare different cities Alex assigned each city a score $$$w_i$$$ which is as high as interesting city seems to Alex.Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city $$$v$$$ from city $$$u$$$, he may choose as the next city in the trip any city connected with $$$v$$$ by the road, except for the city $$$u$$$.Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.

First line of input contains two integers $$$n$$$ and $$$m$$$, ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$) which are numbers of cities and roads in the country. Second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^9$$$) which are scores of all cities. The following $$$m$$$ lines contain description of the roads. Each of these $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$) which are cities connected by this road. It is guaranteed that there is at most one direct road between any two cities, no city is connected to itself by the road and, finally, it is possible to go from any city to any other one using only roads. The last line contains single integer $$$s$$$ ($$$1 \le s \le n$$$), which is the number of the initial city.

Output single integer which is the maximum possible sum of scores of visited cities.

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

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

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

  class InputReader(val stream: InputStream) {
    private[this] val reader = new BufferedReader(new InputStreamReader(stream), 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 = {
    var i = from
    while(i <= to) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val n, m = ni()
    val w = na(n)
    val (from, to) = na2(m, -1)
    val s = ni() - 1
    val g = packUGraph(n, from, to)
    val (_, p, q) = traceBfs(g, s)
    val dp = Array.ofDim[Boolean](n)
    dp(s) = true
    REP_r(n) { i =>
      val v = q(i)
      REP(g(v).length) { j =>
        val u = g(v)(j)
        if (p(u) == v) {
          dp(v) |= dp(u)
        } else if (u != p(v)) {
          dp(v) |= true
        }
      }
    }
    debug(dp)
    var ans = sumL(dp.zipWithIndex.filter(_._1).map(_._2).map(w))
    var add = 0L

    val calced = Array.ofDim[Long](n)
    REP(n) { i =>
      val v = q(i)
      if (!dp(v)) {
        calced(v) = w(v)
        if (p(v)>= 0 && !dp(p(v))) calced(v) += calced(p(v))
        add = max(add, calced(v))
      }
    }
    ans += add
    out.println(ans)
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }
}

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

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

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

  class InputReader(val stream: InputStream) {
    private[this] val reader = new BufferedReader(new InputStreamReader(stream), 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 = {
    var i = from
    while(i <= to) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val n, m = ni()
    val w = na(n)
    val (from, to) = na2(m, -1)
    val s = ni() - 1
    val g = packUGraph(n, from, to)
    val (_, p, q) = traceBfs(g, s)
    val dp = Array.ofDim[Boolean](n)
    dp(s) = true
    REP_r(n) { i =>
      val v = q(i)
      REP(g(v).length) { j =>
        val u = g(v)(j)
        if (p(u) == v) {
          dp(v) |= dp(u)
        } else if (u != p(v)) {
          dp(v) |= true
        }
      }
    }
    debug(dp)
    var ans = sumL(dp.zipWithIndex.filter(_._1).map(_._2).map(w))
    var add = 0L

    val calced = Array.ofDim[Boolean](n)
    def calc(v: Int): Long = {
      var node = v
      var cnt = 0L
      while(!dp(node)) {
        calced(node) = true
        cnt += w(node)
        node = p(node)
      }
      cnt
    }

    REP_r(n) { i =>
      val v = q(i)
      if (!calced(v)) {
        add = max(add, calc(v))
      }
    }
    ans += add
    out.println(ans)
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }
}


You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:   Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$;  Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$;  Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$).

Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it.

object CF565A extends App {

  import scala.io.StdIn

  val q = StdIn.readInt
  for (_ <- 0 until q) {
    var n = StdIn.readLong
    var count = 0
    while (n > 1 && (n % 2 == 0 || n % 3 == 0 || n % 5 == 0)) {
      if (n % 2 == 0) {
        n /= 2
      } else if (n % 3 == 0) {
        n = n / 3 * 2
      } else if (n % 5 == 0) {
        n = n / 5 * 4
      }

      count += 1
    }

    if (n == 1) println(count) else println(-1)
  }
}

object Main {

  val in = new java.util.Scanner(System.in)
  def nextInt = in.next().toInt

  def divide(n: Long): Int = {
    var count = 0
    var num = n
    while (num != 1) {
      if (num % 2 == 0) num = num / 2
      else if (num % 3 == 0) num = 2 * num / 3
      else if (num % 5 == 0) num = 4 * num / 5
      else return -1
      count += 1
    }
    count
  }

  def main(args: Array[String]): Unit = {
    val taskCount = nextInt
    val results = for (test <- 1 to taskCount) yield {
      val n = in.nextLong
      divide(n)
    }

    results foreach println
  }
}

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

  override def apply(io: IO): io.type = {
    val nums = io.read[Seq[Long]]
    val ans = nums.map(solve(_, 0))
    io.writeAll(ans, separator = "\n")
  }

  @tailrec
  def solve(x: Long, acc: Int): Int = {
    if (x == 1) {
      acc
    } else if(x%2 == 0) {
      solve(x/2, acc + 1)
    } else if(x%3 == 0) {
      solve(2*(x/3), acc + 1)
    } else if (x%5 == 0) {
      solve(4*(x/5), acc + 1)
    } else {
      -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 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 writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  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 java.util
import java.util.Scanner
import scala.util.control.Breaks._

import scala.io.StdIn

object Atask565 extends App {

  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()

  val q = new util.ArrayList[BigInt]()

  for (i <- 0 until n) {
    line = new Scanner(StdIn.readLine())
    q.add(line.nextBigInteger())
  }

  for (i <- 0 until n) {
    var temp: BigInt = q.get(i)
    var ops = 0
    breakable {
      while (true) {
        if (temp == 1) {
          println(ops)
          break()
        }
        if (((temp * 4) % 5) == BigInt(0)) {
          ops += 1
          temp = (temp * 4) / 5
        } else {
          if (((temp * 2) % 3) == BigInt(0)) {
            ops += 1
            temp = (temp * 2) / 3
          } else {
            if ((temp % 2) == BigInt(0)) {
              ops += 1
              temp = temp / 2
            } else {
              ops = -1
              println(ops)
              break()
            }
          }
        }
      }
    }
  }
}


There are two rival donut shops.The first shop sells donuts at retail: each donut costs $$$a$$$ dollars.The second shop sells donuts only in bulk: box of $$$b$$$ donuts costs $$$c$$$ dollars. So if you want to buy $$$x$$$ donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them is greater or equal to $$$x$$$.You want to determine two positive integer values:   how many donuts can you buy so that they are strictly cheaper in the first shop than in the second shop?  how many donuts can you buy so that they are strictly cheaper in the second shop than in the first shop? If any of these values doesn't exist then that value should be equal to $$$-1$$$. If there are multiple possible answers, then print any of them.The printed values should be less or equal to $$$10^9$$$. It can be shown that under the given constraints such values always exist if any values exist at all.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a \le 10^9$$$, $$$2 \le b \le 10^9$$$, $$$1 \le c \le 10^9$$$).

For each testcase print two positive integers. For both shops print such $$$x$$$ that buying $$$x$$$ donuts in this shop is strictly cheaper than buying $$$x$$$ donuts in the other shop. $$$x$$$ should be greater than $$$0$$$ and less or equal to $$$10^9$$$. If there is no such $$$x$$$, then print $$$-1$$$. If there are multiple answers, then print any of them.

NoteIn the first testcase buying any number of donuts will be cheaper in the second shop. For example, for $$$3$$$ or $$$5$$$ donuts you'll have to buy a box of $$$10$$$ donuts for $$$4$$$ dollars. $$$3$$$ or $$$5$$$ donuts in the first shop would cost you $$$15$$$ or $$$25$$$ dollars, respectively, however. For $$$20$$$ donuts you'll have to buy two boxes for $$$8$$$ dollars total. Note that $$$3$$$ and $$$5$$$ are also valid answers for the second shop, along with many other answers.In the second testcase buying any number of donuts will be either cheaper in the first shop or the same price. $$$8$$$ donuts cost $$$32$$$ dollars in the first shop and $$$40$$$ dollars in the second shop (because you have to buy two boxes). $$$10$$$ donuts will cost $$$40$$$ dollars in both shops, so $$$10$$$ is not a valid answer for any of the shops.In the third testcase $$$1$$$ donut costs $$$2$$$ and $$$3$$$ dollars, respectively. $$$2$$$ donuts cost $$$4$$$ and $$$3$$$ dollars. Thus, $$$1$$$ is a valid answer for the first shop and $$$2$$$ is a valid answer for the second shop.In the fourth testcase $$$10^9$$$ donuts cost $$$10^{18}$$$ dollars in the first shop and $$$10^9$$$ dollars in the second shop.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toLong)

    val (ans1, ans2) = (if (a < c) 1 else -1, if (a * b > c) b else -1)

    println(s"$ans1 $ans2")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toLong)

    val (ans1, ans2) = a * b - c match {
      case 0          => (if (b > 1) 1 else -1, -1)
      case d if d < 0 => (b, -1)
      case d if d > 0 => (if (a < c) 1 else -1, b)
    }

    println(s"$ans1 $ans2")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val (ans1, ans2) = a * b - c match {
      case 0          => (if (b > 1) 1 else -1, -1)
      case d if d < 0 => (b, -1)
      case d if d > 0 => (if (a <= c) 1 else -1, b)
    }

    println(s"$ans1 $ans2")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val (ans1, ans2) = a * b - c match {
      case 0          => (if (b > 1) 1 else -1, -1)
      case d if d < 0 => (b, -1)
      case d if d > 0 => (if (a < c) 1 else -1, b)
    }

    println(s"$ans1 $ans2")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val (ans1, ans2) = a * b - c match {
      case 0          => (if (b == 1) -1 else 1, -1)
      case d if d < 0 => (1, -1)
      case d if d > 0 => (if (a < c) 1 else -1, b)
    }

    println(s"$ans1 $ans2")
  }
}