Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?

The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day.  Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree.

Print a single integer — the maximum number of fruit that Valera can collect.

NoteIn the first sample, in order to obtain the optimal answer, you should act as follows.   On the first day collect 3 fruits from the 1-st tree.  On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree.  On the third day collect the remaining fruits from the 2-nd tree.  In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither.

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, v) = in.next().split(' ').map(_.toInt)
  val data = Array.ofDim[Int](3001)
  (0 until n).foreach { _ =>
    val Array(a, b) = in.next().split(' ').map(_.toInt)
    data(a - 1) += b
  }
  val res = data.foldLeft((0, 0)) {
    case((soFar, fromPrev), el) if (fromPrev + el) <= v => (soFar + fromPrev + el, 0)
    case((soFar, fromPrev), el) if fromPrev >= v => (soFar + v, el)
    case((soFar, fromPrev), el) => (soFar + v, el + fromPrev - v)
  }._1
  println(res)
}

//package codeblocks

import java.util.Scanner
import scala.math._
object cf441B {

	val sc = new Scanner(System.in)
	def main(args : Array[String]) : Unit = {
		val n,v = sc.nextInt
		var a = new Array[Long](3002)
		for(i <- 1 to n) a(sc.nextInt)+=sc.nextInt
		var counts:Long = 0
		for(i <-1 to 3001){
			val today =min(v, a(i)+a(i-1))
			counts+=today
			a(i) = if(today!=v) 0 else min(a(i),a(i)+a(i-1)-v)
		}
		println(counts)
	}

}

object Bnew {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var ans = new Array[Long](3002)

    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      ans(x) += y
      }
    var cnt = ans(0)
    for (i <- 1 to 3001){
        var minn = min(v, (ans(i)+ans(i-1)))
    	cnt += minn
    	ans(i) = max(0, ans(i) - max(0,
    	    minn -ans(i-1)))
    }

    println(cnt)
  }

}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object B extends App {

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

  val Array(n, v) = readInts(2)
  val day1 = Array.fill(3002)(0)
  val day2 = Array.fill(3002)(0)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    day1(a - 1) += b
    day2(a) += b
  }

  var sum = 0
  var prevDay1take = 0
  for (i <- 0 to 3001) {
	val day2take = (day2(i) - prevDay1take) min v max 0
	val day1take = day1(i) min (v - day2take)
	prevDay1take = day1take
	//println(day1take, day2take)
	sum += day1take + day2take
  }

  println(sum)
}

/**
 * Created by slie742 on 9/09/2015.
 */

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

import Math.abs
import Math.max
import Math.min

object ValeraFruits {

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

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

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

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

  def count(garden: Map[Int,Int], v: Int) : Int = {
    val maxDay = garden.keys.max + 1
    def go(day: Int, leftFromPrev: Int, total: Int) : Int = {
      if (day > maxDay) total
      else {
        val harvested = leftFromPrev + min(v-leftFromPrev, garden.getOrElse(day,0))
        go(day + 1,min(v,garden.getOrElse(day,0) - (harvested-leftFromPrev))
          , total + harvested)
      }
    }
    go(1, 0, 0)
  }

  def main(args: Array[String]) {
    val (n,v) = readTuple()
    val garden = for {
      i <- 1 to n
      (a,b) = readTuple()
    } yield (a,b)
    val gardenGrouped = garden.groupBy{ case (a,b) => a}.mapValues( l => l.map(_._2).sum)
    println(count(gardenGrouped,v))
  }

}

import java.util.Scanner

object cf441B {

	val sc = new Scanner(System.in)
	def main(args : Array[String]) : Unit = {
		val n,v = sc.nextInt
		var arr = ( for(i <- 1 to n) yield (sc.nextInt,sc.nextInt)).toArray
	//	arr sortBy (_._1) foreach(println )
		var yetCollect = 0
		var sumCollect = 0
		for(i <- 1 to n+1){
			i match {
				case 1 => {
					//第一天只能采第一天的水果,yetCollect保存的为前一天所摘的数量
					if(v>=arr(i-1)._2){sumCollect+=arr(i-1)._2;yetCollect=arr(i-1)._2}
					else {sumCollect+=v;yetCollect=v}
				}
				case x => {
					if(x<=n){
						if(yetCollect == arr(i-2)._2){
							if(v>=arr(i-1)._2){sumCollect+=arr(i-1)._2;yetCollect=arr(i-1)._2}
							else {sumCollect+=v;yetCollect=v}
						}
						else{
							if(v>=arr(i-2)._2-yetCollect){
								yetCollect=arr(i-2)._2-yetCollect
								sumCollect+=yetCollect
							}
							else{
								yetCollect=v
								sumCollect+=yetCollect
							}

							if(v-yetCollect >0){
								if(v-yetCollect >= arr(i-1)._2){
									yetCollect=arr(i-1)._2
									sumCollect+=yetCollect}
								else {sumCollect+=v-yetCollect;yetCollect=v-yetCollect}
							}
							else
								yetCollect = 0

						}

					}
					else{
						if(yetCollect != arr(i-2)._2){
								if(v>=arr(i-2)._2-yetCollect){
									yetCollect=arr(i-2)._2-yetCollect
									sumCollect+=yetCollect
								}
								else{
									yetCollect=v
									sumCollect+=yetCollect
								}

						}
					}
				}
			}
		}
		println(sumCollect)
	}

}

object Bnew {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](3002)
    var minn = 30000
    var maxx = 0
    var cnt = 0
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      ans(x) += y
      minn = min(minn,x)
      maxx = max(maxx,x)
    }
    var bl = false;
    for (i <- minn to maxx){
      if (ans(i)>0){
        if (ans(i+1)==0){
            if (!bl)
        	cnt += min(2*v,ans(i))
        	else cnt += min(v,ans(i))
        	bl = false
        }
        else {
          if (!bl){
        	cnt += min(2*v,ans(i))
        	if (ans(i)<2*v){
        	  var coef= min(2*v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
        	}
          }
          else {cnt += min(v,ans(i))
            if (ans(i)<v){
              var coef= min(v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
            }
          }
          bl = true
        }
      }
//      println(cnt)
    }
    println(cnt)
  }

}

object b {
  import scala.math._

  def sort(xs: Array[Int],ys: Array[Int]) {
		def swap(i: Int, j: Int) {
		val t = xs(i); xs(i) = xs(j); xs(j) = t
		}
		def swap2(i: Int, j: Int) {
		val t = ys(i); ys(i) = ys(j); ys(j) = t
		}
		def sort1(l: Int, r: Int) {
		val pivot = xs((l + r) / 2)
		var i = l; var j = r
		while (i <= j) {
		while (xs(i) < pivot) i += 1
		while (xs(j) > pivot) j -= 1
		if (i <= j) {
		swap(i, j)
		swap2(i, j)
		i += 1
		j -= 1
		}
		}
		if (l < j) sort1(l, j)
		if (j < r) sort1(i, r)
		}
		sort1(0, xs.length - 2)
		}

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](n+1)
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      a(i) = x
      b(i) = y
    }
//    for (i <- 0 until n-1)
//      for (j <- i+1 until n)
//        if (a(i)>a(j)){
//          var t = a(i)
//          a(i) = a(j)
//          a(j) = t
//          t = b(i)
//          b(i) = b(j)
//          b(j) = t
//        }
    sort(a,b)
   ans(0) = min(b(0),v)
   b(0) -= ans(0)
   for (i <- 1 to n){
     if (a(i)-a(i-1)>1){
       ans(i-1) += min(v,b(i-1))
       b(i-1) -= ans(i-1)
       ans(i) += min(v,b(i))
       b(i) -= ans(i)
     }
     else{
     ans(i) = min(v,b(i)+b(i-1))
     if (ans(i) > b(i-1)){
       b(i) -= ans(i) - b(i-1)
       b(i-1) = 0
     }else {b(i-1) -= ans(i)}
     }
     ans(i) += ans(i-1)
//     println(ans(i))
   }

   println(ans(n))
  }

}

object b {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](n+1)
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      a(i) = x
      b(i) = y
    }
    for (i <- 0 until n-1)
      for (j <- i+1 until n)
        if (a(i)>a(j)){
          var t = a(i)
          a(i) = a(j)
          a(j) = t
          t = b(i)
          b(i) = b(j)
          b(j) = t
        }
   ans(0) = min(b(0),v)
   b(0) -= ans(0)
   for (i <- 1 to n){
     ans(i) = min(v,b(i)+b(i-1))
     if (ans(i) > b(i-1)){
       b(i) -= ans(i) - b(i-1)
       b(i-1) = 0
     }else {b(i-1) -= ans(i)}
     ans(i) += ans(i-1)
//     println(ans(i))
   }

   println(ans(n))
  }

}

object b {
  import scala.math._

  def sort(xs: Array[Int],ys: Array[Int]) {
		def swap(i: Int, j: Int) {
		val t = xs(i); xs(i) = xs(j); xs(j) = t
		}
		def swap2(i: Int, j: Int) {
		val t = ys(i); ys(i) = ys(j); ys(j) = t
		}
		def sort1(l: Int, r: Int) {
		val pivot = xs((l + r) / 2)
		var i = l; var j = r
		while (i <= j) {
		while (xs(i) < pivot) i += 1
		while (xs(j) > pivot) j -= 1
		if (i <= j) {
		swap(i, j)
		swap2(i, j)
		i += 1
		j -= 1
		}
		}
		if (l < j) sort1(l, j)
		if (j < r) sort1(i, r)
		}
		sort1(0, xs.length - 2)
		}

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](n+1)
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      a(i) = x
      b(i) = y
    }
//    for (i <- 0 until n-1)
//      for (j <- i+1 until n)
//        if (a(i)>a(j)){
//          var t = a(i)
//          a(i) = a(j)
//          a(j) = t
//          t = b(i)
//          b(i) = b(j)
//          b(j) = t
//        }
    sort(a,b)
   ans(0) = min(b(0),v)
   b(0) -= ans(0)
   for (i <- 1 to n){
     if (a(i)-a(i-1)>1){
       ans(i-1) += v
       b(i-1) -= v
       ans(i) += v
       b(i) -= v
     }
     else{
     ans(i) = min(v,b(i)+b(i-1))
     if (ans(i) > b(i-1)){
       b(i) -= ans(i) - b(i-1)
       b(i-1) = 0
     }else {b(i-1) -= ans(i)}
     }
     ans(i) += ans(i-1)
//     println(ans(i))
   }

   println(ans(n))
  }

}

object Bnew {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](3002)
    var minn = 30000
    var maxx = 0
    var cnt = 0
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      ans(x) = y
      minn = min(minn,x)
      maxx = max(maxx,x)
    }
    var bl = false;
    for (i <- minn to maxx){
      if (ans(i)>0){
        if (ans(i+1)==0){
            if (!bl)
        	cnt += min(2*v,ans(i))
        	else cnt += min(v,ans(i))
        	bl = false
        }
        else {
          if (!bl){
        	cnt += min(2*v,ans(i))
        	if (ans(i)<2*v){
        	  var coef= min(2*v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
        	}
          }
          else {cnt += min(v,ans(i))
            if (ans(i)<v){
              var coef= min(v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
            }
          }
          bl = true
        }
      }
//      println(cnt)
    }
    println(cnt)
  }

}

object b {
  import scala.math._

  def sort(xs: Array[Int],ys: Array[Int]) {
		def swap(i: Int, j: Int) {
		val t = xs(i); xs(i) = xs(j); xs(j) = t
		}
		def swap2(i: Int, j: Int) {
		val t = ys(i); ys(i) = ys(j); ys(j) = t
		}
		def sort1(l: Int, r: Int) {
		val pivot = xs((l + r) / 2)
		var i = l; var j = r
		while (i <= j) {
		while (xs(i) < pivot) i += 1
		while (xs(j) > pivot) j -= 1
		if (i <= j) {
		swap(i, j)
		swap2(i, j)
		i += 1
		j -= 1
		}
		}
		if (l < j) sort1(l, j)
		if (j < r) sort1(i, r)
		}
		sort1(0, xs.length - 2)
		}

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var a = new Array[Int](n+1)
    var b = new Array[Int](n+1)
    var ans = new Array[Int](n+1)
    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      a(i) = x
      b(i) = y
    }
//    for (i <- 0 until n-1)
//      for (j <- i+1 until n)
//        if (a(i)>a(j)){
//          var t = a(i)
//          a(i) = a(j)
//          a(j) = t
//          t = b(i)
//          b(i) = b(j)
//          b(j) = t
//        }
    sort(a,b)
   ans(0) = min(b(0),v)
   b(0) -= ans(0)
   for (i <- 1 to n){
     ans(i) = min(v,b(i)+b(i-1))
     if (ans(i) > b(i-1)){
       b(i) -= ans(i) - b(i-1)
       b(i-1) = 0
     }else {b(i-1) -= ans(i)}
     ans(i) += ans(i-1)
//     println(ans(i))
   }

   println(ans(n))
  }

}

object Bnew {
  import scala.math._

  def main(args: Array[String]): Unit = {
    var Array(n,v) = readLine.split(" ").map(_.toInt)
    var ans = new Array[Long](3002)
    var minn = 30000
    var maxx = 0
    var cnt = ans(0)

    for (i <- 0 until n){
      var Array(x,y) = readLine.split(" ").map(_.toInt)
      ans(x) += y
      minn = min(minn,x)
      maxx = max(maxx,x)
    }
    var bl = false;
    for (i <- minn to maxx){
      if (ans(i)>0){
        if (ans(i+1)==0){
            if (!bl)
        	cnt += min(2*v,ans(i))
        	else cnt += min(v,ans(i))
        	bl = false
        }
        else {
          if (!bl){
        	cnt += min(2*v,ans(i))
        	if (ans(i)<2*v){
        	  var coef= min(2*v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
        	}
          }
          else {cnt += min(v,ans(i))
            if (ans(i)<v){
              var coef= min(v - ans(i),ans(i+1))
        	  ans(i+1) -= coef
        	  cnt += coef
            }
          }
          bl = true
        }
      }
//      println(cnt)
    }
    println(cnt)
  }

}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object B extends App {

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

  val Array(n, v) = readInts(2)
  val day1 = Array.fill(3002)(0)
  val day2 = Array.fill(3002)(0)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    day1(a - 1) += b
    day2(a) += b
  }

  var sum = 0
  var prevDay1take = 0
  for (i <- 0 to n) {
	val day2take = (day2(i) - prevDay1take) min v max 0
	val day1take = day1(i) min (v - day2take)
	prevDay1take = day1take
	//println(day1take, day2take)
	sum += day1take + day2take
  }

  println(sum)
}


Sho has an array $$$a$$$ consisting of $$$n$$$ integers. An operation consists of choosing two distinct indices $$$i$$$ and $$$j$$$ and removing $$$a_i$$$ and $$$a_j$$$ from the array.For example, for the array $$$[2, 3, 4, 2, 5]$$$, Sho can choose to remove indices $$$1$$$ and $$$3$$$. After this operation, the array becomes $$$[3, 2, 5]$$$. Note that after any operation, the length of the array is reduced by two.After he made some operations, Sho has an array that has only distinct elements. In addition, he made operations such that the resulting array is the longest possible. More formally, the array after Sho has made his operations respects these criteria:   No pairs such that ($$$i < j$$$) and $$$a_i = a_j$$$ exist.  The length of $$$a$$$ is maximized. Output the length of the final array.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^4$$$) — the elements of the array.

For each test case, output a single integer — the length of the final array. Remember that in the final array, all elements are different, and its length is maximum.

NoteFor the first test case Sho can perform operations as follows:   Choose indices $$$1$$$ and $$$5$$$ to remove. The array becomes $$$[2, 2, 2, 3, 3, 3] \rightarrow [2, 2, 3, 3]$$$.  Choose indices $$$1$$$ and $$$4$$$ to remove. The array becomes $$$[2, 2, 3, 3] \rightarrow [2, 3]$$$.  The final array has a length of $$$2$$$, so the answer is $$$2$$$. It can be proven that Sho cannot obtain an array with a longer length.For the second test case Sho can perform operations as follows:   Choose indices $$$3$$$ and $$$4$$$ to remove. The array becomes $$$[9, 1, 9, 9, 1] \rightarrow [9, 1, 1]$$$.  Choose indices $$$1$$$ and $$$3$$$ to remove. The array becomes $$$[9, 1, 1] \rightarrow [1]$$$.  The final array has a length of $$$1$$$, so the answer is $$$1$$$. It can be proven that Sho cannot obtain an array with a longer length.

import scala.io.StdIn
import scala.math.BigDecimal.double2bigDecimal

object Main {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()

    for(_ <- 0 until t) {
      val n = StdIn.readInt()
      val part = StdIn.readLine().split(" ").map(_.toInt)

      val setSize = part.toSet.size
      val diff = part.length - setSize

      if(diff %2 == 0) {
        println(setSize)
      } else {
        println(setSize - 1)
      }
    }
  }
}


Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice". So now Ilya wants to compare his robots' performance in a simple game called "1-2-3". This game is similar to the "Rock-Paper-Scissors" game: both robots secretly choose a number from the set {1, 2, 3} and say it at the same moment. If both robots choose the same number, then it's a draw and noone gets any points. But if chosen numbers are different, then one of the robots gets a point: 3 beats 2, 2 beats 1 and 1 beats 3. Both robots' programs make them choose their numbers in such a way that their choice in (i + 1)-th game depends only on the numbers chosen by them in i-th game. Ilya knows that the robots will play k games, Alice will choose number a in the first game, and Bob will choose b in the first game. He also knows both robots' programs and can tell what each robot will choose depending on their choices in previous game. Ilya doesn't want to wait until robots play all k games, so he asks you to predict the number of points they will have after the final game.

The first line contains three numbers k, a, b (1 ≤ k ≤ 1018, 1 ≤ a, b ≤ 3).  Then 3 lines follow, i-th of them containing 3 numbers Ai, 1, Ai, 2, Ai, 3, where Ai, j represents Alice's choice in the game if Alice chose i in previous game and Bob chose j (1 ≤ Ai, j ≤ 3).  Then 3 lines follow, i-th of them containing 3 numbers Bi, 1, Bi, 2, Bi, 3, where Bi, j represents Bob's choice in the game if Alice chose i in previous game and Bob chose j (1 ≤ Bi, j ≤ 3).

Print two numbers. First of them has to be equal to the number of points Alice will have, and second of them must be Bob's score after k games.

NoteIn the second example game goes like this:The fourth and the seventh game are won by Bob, the first game is draw and the rest are won by Alice.

//package edu29

import scala.io.StdIn

object C extends App {
  def readArray = StdIn.readLine().split(" ").map(_.toInt)

  val Array(k, a0, b0) = StdIn.readLine().split(" ").map(_.toLong)
  val alice, bob = Array.fill(3)(readArray)
  def result(i: Int, j: Int) =
    if (i == j) (0L, 0L)
    else if (i - 1 == (j % 3)) (1L, 0L)
    else (0L, 1L)

  def go(a: Int = a0.toInt, b: Int = b0.toInt, seen: Map[(Int, Int), Int] = Map.empty, i: Int = 0): (Seq[(Int, Int)], Int) =
    if (seen.contains((a, b))) (seen.toSeq.sortBy(_._2).map(_._1), seen((a, b)))
    else go(alice(a - 1)(b - 1), bob(a - 1)(b - 1), seen + ((a, b) -> i), i + 1)

  val (full, init) = go()
//  println(full, init)
  val (pref, cycle) = full.map((result _).tupled).splitAt(init)
//  println(pref, cycle)

  def sumPoints(seq: Seq[(Long, Long)]) =
    seq.foldLeft((0L, 0L)) { case ((ap, bp), (a, b)) => (ap + a, bp + b) }

  def mulPoints(a: Long, b: Long)(c: Long) = (a * c, b * c)
  val mulp = (mulPoints _).tupled

  val (ap, bp) =
    if (k <= pref.length) sumPoints(pref.take(k.toInt))
    else {
      val n = k - pref.length
      val prefp = sumPoints(pref)
      val cyclic = mulp(sumPoints(cycle))(n / cycle.length)
      val last = sumPoints(cycle.take((n % cycle.length).toInt))
//      println(pref, cyclic, last)
      sumPoints(Seq(prefp, cyclic, last))
    }

  println(s"$ap $bp")

}

object Game123t863C extends App {
  import scala.collection.mutable.ListBuffer
  import scala.collection.mutable

  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val k = in.nextLong()
    val a = in.nextInt()
    val b = in.nextInt()

    val g = new Graph()
    val A = Array.ofDim[Int](5,5)
    val B = Array.ofDim[Int](5,5)
    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      A(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      B(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      val from = Node(i,j)
      val to = Node(A(i)(j),B(i)(j))
      g.addEdge(Edge(from,to))
    }

    val sc = g.findFinalScoreBoard(Node(a,b),k)

    out.println(s"${sc.bob} ${sc.alice}")

  }
  case class Node(a: Int, b: Int)
  case class Edge(from: Node, to: Node)
  case class ScoreBoard(bob: Long, alice: Long, tie: Long){
    def addGame(node: Node): ScoreBoard = {
      node match {
        case Node(3,2) => copy(bob = bob+1)
        case Node(2,1) => copy(bob = bob+1)
        case Node(1,3) => copy(bob = bob+1)
        case Node(2,3) => copy(alice = alice+1)
        case Node(1,2) => copy(alice = alice+1)
        case Node(3,1) => copy(alice = alice+1)
        case _ => copy(tie = tie+1)
      }
    }
    val numGames = bob + alice + tie

    def + (that: ScoreBoard): ScoreBoard = ScoreBoard(bob+that.bob,alice+that.alice,tie+that.tie)
    def - (that: ScoreBoard): ScoreBoard = ScoreBoard(that.bob-bob,that.alice-alice,that.tie-tie)
    def * (times: Long): ScoreBoard = ScoreBoard(bob*times,alice*times,tie*times)
  }
  class Game(val currentScore: ScoreBoard,val nodeToEvaluate: Node, calcNextNode: Node => Node){
    def this(nodeToEvaluate: Node,calcNextNode: Node => Node) = this(ScoreBoard(0,0,0),nodeToEvaluate,calcNextNode)
    def step(): Game = {
     new Game(currentScore.addGame(nodeToEvaluate),calcNextNode(nodeToEvaluate),calcNextNode)
    }
  }

  class Graph(){
    val edges = ListBuffer.empty[Edge]
    def addEdge(edge: Edge): Unit = edges.append(edge)

    private def next(node: Node): Node = {
      edges.find(_.from == node).get.to
    }

    val mapCycle = mutable.Map.empty[Node,Option[ScoreBoard]]

    def simulateSmall(node: Node, gamesLeft: Int): ScoreBoard = {
      (1 to gamesLeft).foldLeft(new Game(node,next)){
        case (prevGame,_) => {
          prevGame.step()
        }
      }.currentScore
    }
    def findFinalScoreBoard(node: Node, gamesLeft: Long): ScoreBoard = {
      if(gamesLeft > 0){
        if(mapCycle.contains(node)){
          val optScoreBoard = mapCycle(node)
          optScoreBoard.map{ sc =>
            val cyclesRequired = gamesLeft/sc.numGames
            val extraGames: Int = (if(cyclesRequired == 0) gamesLeft else gamesLeft % sc.numGames).toInt

            sc*cyclesRequired + simulateSmall(node,extraGames)
          }.getOrElse{
            ScoreBoard(0,0,0).addGame(node) + findFinalScoreBoard(next(node),gamesLeft-1)
          }
        }else{
          (1 to 15).foldLeft(Option(new Game(node,next))){
            case (Some(prevGame), _) =>
              val currentGame = prevGame.step()
              if(currentGame.nodeToEvaluate == node){
                mapCycle += node -> Some(currentGame.currentScore)
                None
              }else{
                Some(currentGame)
              }
            case (None, _ ) => None
          }
          if(!mapCycle.contains(node)){ // no se encontro ciclo
            mapCycle += node -> None

          }
          findFinalScoreBoard(node,gamesLeft)
        }
      }
      else{
        ScoreBoard(0,0,0)
      }
    }

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Game123t863C   extends App {
  import scala.collection.mutable.ListBuffer
  import scala.collection.mutable

  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val k = in.nextLong()
    val a = in.nextInt()
    val b = in.nextInt()

    val g = new Graph()
    val A = Array.ofDim[Int](5,5)
    val B = Array.ofDim[Int](5,5)
    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      A(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      B(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      val from = Node(i,j)
      val to = Node(A(i)(j),B(i)(j))
      g.addEdge(Edge(from,to))
    }

    val sc = g.findFinalScoreBoard(Node(a,b),k)

    out.println(s"${sc.bob} ${sc.alice}")

  }
  case class Node(a: Int, b: Int)
  case class Edge(from: Node, to: Node)
  case class ScoreBoard(bob: Long, alice: Long, tie: Long){
    def addGame(node: Node): ScoreBoard = {
      node match {
        case Node(3,2) => copy(bob = bob+1)
        case Node(2,1) => copy(bob = bob+1)
        case Node(1,3) => copy(bob = bob+1)
        case Node(2,3) => copy(alice = alice+1)
        case Node(1,2) => copy(alice = alice+1)
        case Node(3,1) => copy(alice = alice+1)
        case _ => copy(tie = tie+1)
      }
    }
    val numGames = bob + alice + tie

    def + (that: ScoreBoard): ScoreBoard = ScoreBoard(bob+that.bob,alice+that.alice,tie+that.tie)
    def - (that: ScoreBoard): ScoreBoard = ScoreBoard(that.bob-bob,that.alice-alice,that.tie-tie)
    def * (times: Long): ScoreBoard = ScoreBoard(bob*times,alice*times,tie*times)
  }
  class Game(val currentScore: ScoreBoard,val nodeToEvaluate: Node, calcNextNode: Node => Node){
    def this(nodeToEvaluate: Node,calcNextNode: Node => Node) = this(ScoreBoard(0,0,0),nodeToEvaluate,calcNextNode)
    def step(): Game = {
     new Game(currentScore.addGame(nodeToEvaluate),calcNextNode(nodeToEvaluate),calcNextNode)
    }
  }

  class Graph(){
    val edges = ListBuffer.empty[Edge]
    def addEdge(edge: Edge): Unit = edges.append(edge)

    private def next(node: Node): Node = {
      edges.find(_.from == node).get.to
    }

    val mapCycle = mutable.Map.empty[Node,Option[ScoreBoard]]

    def simulateSmall(node: Node, gamesLeft: Int): ScoreBoard = {
      (1 to gamesLeft).foldLeft(new Game(node,next)){
        case (prevGame,_) => {
          prevGame.step()
        }
      }.currentScore
    }
    def findFinalScoreBoard(node: Node, gamesLeft: Long): ScoreBoard = {
      if(mapCycle.contains(node)){
        val optScoreBoard = mapCycle(node)
        optScoreBoard.map{ sc =>
          val cyclesRequired = gamesLeft/sc.numGames
          val extraGames: Int = (if(cyclesRequired == 0) gamesLeft else gamesLeft % sc.numGames).toInt

          sc*cyclesRequired + simulateSmall(node,extraGames)
        }.getOrElse{
          ScoreBoard(0,0,0).addGame(node) + findFinalScoreBoard(next(node),gamesLeft-1)
        }
      }else{
        (1 to 15).foldLeft(Option(new Game(node,next))){
          case (Some(prevGame), _) =>
            val currentGame = prevGame.step()
            if(currentGame.nodeToEvaluate == node){
              mapCycle += node -> Some(currentGame.currentScore)
              None
            }else{
              Some(currentGame)
            }
          case (None, _ ) => None
        }
        if(!mapCycle.contains(node)){ // no se encontro ciclo
          mapCycle += node -> None

        }
        findFinalScoreBoard(node,gamesLeft)
      }
    }

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Game123t863C extends App {
  import scala.collection.mutable.ListBuffer
  import scala.collection.mutable

  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val k = in.nextLong()
    val a = in.nextInt()
    val b = in.nextInt()

    val g = new Graph()
    val A = Array.ofDim[Int](5,5)
    val B = Array.ofDim[Int](5,5)
    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      A(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      B(i)(j) = in.nextInt()
    }

    for{
      i <- 1 to 3
      j <- 1 to 3
    }yield{
      val from = Node(i,j)
      val to = Node(A(i)(j),B(i)(j))
      g.addEdge(Edge(from,to))
    }

    val sc = g.findFinalScoreBoard(Node(a,b),k)

    out.println(s"${sc.bob} ${sc.alice}")

  }
  case class Node(a: Int, b: Int)
  case class Edge(from: Node, to: Node)
  case class ScoreBoard(bob: Long, alice: Long, tie: Long){
    def addGame(node: Node): ScoreBoard = {
      node match {
        case Node(3,2) => copy(bob = bob+1)
        case Node(2,1) => copy(bob = bob+1)
        case Node(1,3) => copy(bob = bob+1)
        case Node(2,3) => copy(alice = alice+1)
        case Node(1,2) => copy(alice = alice+1)
        case Node(3,1) => copy(alice = alice+1)
        case _ => copy(tie = tie+1)
      }
    }
    val numGames = bob + alice + tie

    def + (that: ScoreBoard): ScoreBoard = ScoreBoard(bob+that.bob,alice+that.alice,tie+that.tie)
    def - (that: ScoreBoard): ScoreBoard = ScoreBoard(that.bob-bob,that.alice-alice,that.tie-tie)
    def * (times: Long): ScoreBoard = ScoreBoard(bob*times,alice*times,tie*times)
  }
  class Game(val currentScore: ScoreBoard,val nodeToEvaluate: Node, calcNextNode: Node => Node){
    def this(nodeToEvaluate: Node,calcNextNode: Node => Node) = this(ScoreBoard(0,0,0),nodeToEvaluate,calcNextNode)
    def step(): Game = {
     new Game(currentScore.addGame(nodeToEvaluate),calcNextNode(nodeToEvaluate),calcNextNode)
    }
  }

  class Graph(){
    val edges = ListBuffer.empty[Edge]
    def addEdge(edge: Edge): Unit = edges.append(edge)

    private def next(node: Node): Node = {
      edges.find(_.from == node).get.to
    }

    val mapCycle = mutable.Map.empty[Node,Option[ScoreBoard]]

    def simulateSmall(node: Node, gamesLeft: Int): ScoreBoard = {
      (1 to gamesLeft).foldLeft(new Game(node,next)){
        case (prevGame,_) => {
          prevGame.step()
        }
      }.currentScore
    }
    def findFinalScoreBoard(node: Node, gamesLeft: Long): ScoreBoard = {
      if(mapCycle.contains(node)){
        val optScoreBoard = mapCycle(node)
        optScoreBoard.map{ sc =>
          val cyclesRequired = gamesLeft/sc.numGames
          val extraGames: Int = (if(cyclesRequired == 0) gamesLeft else gamesLeft % cyclesRequired).toInt
          sc*cyclesRequired + simulateSmall(node,extraGames)
        }.getOrElse{
          ScoreBoard(0,0,0).addGame(node) + findFinalScoreBoard(next(node),gamesLeft-1)
        }
      }else{
        (1 to 11).foldLeft(Option(new Game(node,next))){
          case (Some(prevGame), _) =>
            val currentGame = prevGame.step()
            if(currentGame.nodeToEvaluate == node){
              mapCycle += node -> Some(currentGame.currentScore)
              None
            }else{
              Some(prevGame.step())
            }
          case (None, _ ) => None
        }
        if(!mapCycle.contains(node)){ // no se encontro ciclo
          mapCycle += node -> None

        }
        findFinalScoreBoard(node,gamesLeft)
      }
    }

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?

The first line contains a positive integer n (1 ≤ n ≤ 100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1 ≤ ai ≤ 109), the number of answer variants to question i.

Print a single number — the minimal number of clicks needed to pass the test it the worst-case scenario.  Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

NoteNote to the second sample. In the worst-case scenario you will need five clicks:   the first click selects the first variant to the first question, this answer turns out to be wrong.  the second click selects the second variant to the first question, it proves correct and we move on to the second question;  the third click selects the first variant to the second question, it is wrong and we go back to question 1;  the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question;  the fifth click selects the second variant to the second question, it proves correct, the test is finished.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong).zipWithIndex.foldLeft(0l) {
    case (result, (i, index)) => result + index * (i - 1) + i}
  println(data)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).zipWithIndex.foldLeft(0l) {
    case (result, (i, index)) => result + index * (i - 1) + i}
  println(data)
}


$$$n$$$ students attended the first meeting of the Berland SU programming course ($$$n$$$ is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups must be different. Furthermore, both groups should contain the same number of students.Each student has filled a survey in which they told which days of the week are convenient for them to attend a lesson, and which are not. Your task is to determine if it is possible to choose two different week days to schedule the lessons for the group (the first group will attend the lesson on the first chosen day, the second group will attend the lesson on the second chosen day), and divide the students into two groups, so the groups have equal sizes, and for each student, the chosen lesson day for their group is convenient.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of students. The $$$i$$$-th of the next $$$n$$$ lines contains $$$5$$$ integers, each of them is $$$0$$$ or $$$1$$$. If the $$$j$$$-th integer is $$$1$$$, then the $$$i$$$-th student can attend the lessons on the $$$j$$$-th day of the week. If the $$$j$$$-th integer is $$$0$$$, then the $$$i$$$-th student cannot attend the lessons on the $$$j$$$-th day of the week.  Additional constraints on the input: for each student, at least one of the days of the week is convenient, the total number of students over all testcases doesn't exceed $$$10^5$$$.

For each testcase print an answer. If it's possible to divide the students into two groups of equal sizes and choose different days for the groups so each student can attend the lesson in the chosen day of their group, print "YES" (without quotes). Otherwise, print "NO" (without quotes).

NoteIn the first testcase, there is a way to meet all the constraints. For example, the first group can consist of the first and the third students, they will attend the lessons on Thursday (the fourth day); the second group can consist of the second and the fourth students, and they will attend the lessons on Tuesday (the second day).In the second testcase, it is impossible to divide the students into groups so they attend the lessons on different days.

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

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

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007
    var days = new Array[ArrayBuffer[Int]](5)

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        for (i <- 0 to 4)
            days(i) = new ArrayBuffer[Int]()
        for (i  <- 1 to n) {
            for (j <- 0 to 4) {
                if (readInt() == 1)
                    days(j).append(i)
            }
        }
        var found = false
        for (i <- 0 to 4){
            for (j <- i+1 to 4) {
                if (!found && days(i).length >= n/2 && days(j).length >= n/2) {
                    val mark = new Array[Boolean](n + 1)
                    var cnt = 0
                    for (k <- days(i)) {
                        mark(k) = true
                    }
                    for (k <- days(j)) {
                        if (mark(k))
                            cnt += 1
                    }
                    val sz1 = days(i).length - cnt
                    val sz2 = days(j).length - cnt
                    cnt -= max(0, n/2-sz1)
                    cnt -= max(0, n/2-sz2)
                    if (cnt >= 0)
                        found = true
                }
            }
        }
        if (found)
            writer.println("YES")
        else
            writer.println("NO")

    }
    writer.flush()
}

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

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

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007
    var days = new Array[ArrayBuffer[Int]](5)

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        for (i <- 0 to 4)
            days(i) = new ArrayBuffer[Int]()
        for (i  <- 1 to n) {
            for (j <- 0 to 4) {
                if (readInt() == 1)
                    days(j).append(i)
            }
        }
        var found = false
        for (i <- 0 to 4){
            for (j <- i+1 to 4) {
                if (!found && days(i).length >= n/2 && days(j).length >= n/2) {
                    var mark = new Array[Boolean](n + 1)
                    var cnt = 0
                    for (k <- days(i))
                        mark(k) = true
                    for (k <- days(j)) {
                        if (mark(k))
                            cnt += 1
                    }
                    val sz1 = days(i).length - cnt
                    val sz2 = days(j).length - cnt
                    cnt -= min(0, n/2-sz1)
                    cnt -= min(0, n/2-sz2)
                    if (cnt >= 0)
                        found = true
                }
            }
        }
        if (found)
            writer.println("YES")
        else
            writer.println("NO")

    }
    writer.flush()
}


You are given a number $$$k$$$ and a string $$$s$$$ of length $$$n$$$, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met:   The first character '*' in the original string should be replaced with 'x';  The last character '*' in the original string should be replaced with 'x';  The distance between two neighboring replaced characters 'x' must not exceed $$$k$$$ (more formally, if you replaced characters at positions $$$i$$$ and $$$j$$$ ($$$i < j$$$) and at positions $$$[i+1, j-1]$$$ there is no "x" symbol, then $$$j-i$$$ must be no more than $$$k$$$). For example, if $$$n=7$$$, $$$s=$$$.**.*** and $$$k=3$$$, then the following strings will satisfy the conditions above:   .xx.*xx;  .x*.x*x;  .xx.xxx.  But, for example, the following strings will not meet the conditions:   .**.*xx (the first character '*' should be replaced with 'x');  .x*.xx* (the last character '*' should be replaced with 'x');  .x*.*xx (the distance between characters at positions $$$2$$$ and $$$6$$$ is greater than $$$k=3$$$). Given $$$n$$$, $$$k$$$, and $$$s$$$, find the minimum number of '*' characters that must be replaced with 'x' in order to meet the above conditions.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 500$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$). The second line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of the characters '.' and '*'. It is guaranteed that there is at least one '*' in the string $$$s$$$. It is guaranteed that the distance between any two neighboring '*' characters does not exceed $$$k$$$.

For each test case output the minimum number of '*' characters that must be replaced with 'x' characters in order to satisfy the conditions above.

import scala.io.StdIn

object B {

  def solution(args: Seq[String]): Seq[Int] = {
    def solve(n: Int, k: Int, str: List[Char]): Int = {

      def loop(ik: Int, prevK: Int, str0: List[Char], in: Boolean, result: Int): Int = {
        str0 match {
          case h :: hs =>

            if (!in) {
              h match {
                case '*' =>
                  loop(1, 1, hs, !in, 1)
                case '.' =>
                  loop(0, 0, hs, in, 0)
              }
            } else {
              h match {
                case '*' =>
                  if (ik == k) loop(1, 1, hs, in, result + 1)
                  else loop(ik + 1, 1, hs, in, result)

                case '.' =>
                  if (ik < k) loop(ik + 1, prevK + 1, hs, in, result)
                  else if (ik == k && prevK == k) result
                  else if (ik == k) loop(prevK + 1, prevK + 1, hs, in, result + 1)
                  else result - 1
              }
            }

          case Nil =>
            if(ik != prevK) result + 1
            else result
        }
      }

      loop(0, 0, str, false,  0)
    }

    for(i <- 0 until args.length by 2) yield {
      val nk = args(i).split(" ").map(_.toInt)
      val (n, k) = (nk(0), nk(1))
      solve(n, k, args(i + 1).toCharArray.toList)
    }
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    def readInput(result: List[String]): List[String] = {
      if (result.length < t * 2) readInput(result ::: List(StdIn.readLine))
      else result
    }

    val input = readInput(List.empty)
    solution(input).foreach(println)
  }
}

import scala.io.StdIn

object B {

  def solution(args: Seq[String]): Seq[Int] = {
    def solve(n: Int, k: Int, str: List[Char]): Int = {

      def loop(ik: Int, prevK: Int, str0: List[Char], in: Boolean, result: Int): Int = {
        str0 match {
          case h :: hs =>

            if (!in) {
              h match {
                case '*' =>
                  loop(1, 1, hs, !in, 1)
                case '.' =>
                  loop(0, 0, hs, in, 0)
              }
            } else {
              h match {
                case '*' =>
                  if (ik == k) loop(1, 1, hs, in, result + 1)
                  else loop(ik + 1, 1, hs, in, result)

                case '.' =>
                  if (ik < k) loop(ik + 1, prevK + 1, hs, in, result)
                  else if (ik == k) loop(prevK + 1, prevK + 1, hs, in, result + 1)
                  else result - 1
              }
            }

          case Nil =>
            if(ik != prevK) result + 1
            else result
        }
      }

      loop(0, 0, str, false,  0)
    }

    for(i <- 0 until args.length by 2) yield {
      val nk = args(i).split(" ").map(_.toInt)
      val (n, k) = (nk(0), nk(1))
      solve(n, k, args(i + 1).toCharArray.toList)
    }
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    def readInput(result: List[String]): List[String] = {
      if (result.length < t * 2) readInput(result ::: List(StdIn.readLine))
      else result
    }

    val input = readInput(List.empty)
    solution(input).foreach(println)
  }
}

import scala.io.StdIn

object B {

  def solution(args: Seq[String]): Seq[Int] = {
    def solve(n: Int, k: Int, str: List[Char]): Int = {

      def loop(ik: Int, prevK: Int, str0: List[Char], in: Boolean, result: Int): Int = {
        str0 match {
          case h :: hs =>

            if (!in) {
              h match {
                case '*' =>
                  loop(1, 1, hs, !in, 1)
                case '.' =>
                  loop(0, 0, hs, in, 0)
              }
            } else {
              h match {
                case '*' =>
                  if (ik == k) loop(1, 1, hs, in, result + 1)
                  else loop(ik + 1, 1, hs, in, result)

                case '.' =>
                  if (ik < k) loop(ik + 1, prevK + 1, hs, in, result)
                  else if (ik == k) loop(prevK + 1, prevK + 1, hs, in, result + 1)
                  else result - 1
              }
            }

          case Nil =>
            if(ik != prevK && ik == k) result + 1
            else result
        }
      }

      loop(0, 0, str, false,  0)
    }

    for(i <- 0 until args.length by 2) yield {
      val nk = args(i).split(" ").map(_.toInt)
      val (n, k) = (nk(0), nk(1))
      solve(n, k, args(i + 1).toCharArray.toList)
    }
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    def readInput(result: List[String]): List[String] = {
      if (result.length < t * 2) readInput(result ::: List(StdIn.readLine))
      else result
    }

    val input = readInput(List.empty)
    solution(input).foreach(println)
  }
}


This problem is same as the previous one, but has larger constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.

Print a single integer — the number of pairs of wires that are intersecting.

NoteIn the first example:  In the second example:  Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example:

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

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

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

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

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

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

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

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

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

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

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

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

  case class Coord(x: Int, y: Int)
  case class Line(a: Int, b: Int, c: Int) {
    def slope: Slope = Slope(a, b)
  }
  case class Slope(a: Int, b: Int)

  def toLine(c1: Coord, c2: Coord): Line = {
    var a = c2.y - c1.y
    var b = c1.x - c2.x

    if (a < 0) {
      a *= -1
      b *= -1
    }

    if (a != 0 && b != 0) {
      val g = gcd(a, b)
      a /= g
      b /= g
    }

    if (a == 0) b = 1
    else if (b == 0) a = 1

    val c = -(c1.x * a + c1.y * b)
    Line(a, b, c)
  }

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

  def solve(): Unit = {
    val N = ni()
    val P = Array.ofDim[Coord](N)
    REP(N) { i =>
      val x, y = ni()
      P(i) = Coord(x, y)
    }

    val lines = mutable.Set[Line]()

    REP(N - 1) { i =>
      TO(i + 1, N - 1) { j =>
        lines += toLine(P(i), P(j))
      }
    }

    val slope = mutable.Map[Slope, Int]().withDefaultValue(0)
    lines.foreach { l =>
      val s = l.slope
      slope(s) = slope(s) + 1
    }

    val lineNum = lines.size
    var ans = 0L
    slope.foreach { case (_, num) =>
      ans += num.toLong * (lineNum - num)
    }
    out.println(ans / 2)
  }
}


Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.

The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 109) — the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even. The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the numbers on Eugeny's cards.

If there is no answer, print -1. Otherwise, in the first line print the minimum number of exchanges. In the second line print n integers — Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to. If there are multiple answers, it is allowed to print any of them.

import java.util.StringTokenizer

import scala.util.Try

import scala.collection.JavaConverters._

object E extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()
  if (n % 2 != 0) println(-1) else Try {

    read()
    val arr = Array.fill(n)(int())
    val set = arr.toSet
    var emobase = set.count(_ % 2 == 0) * 2 - set.size
    val mset = new java.util.HashSet[Int]
    var changed = 0

    val forced = Math.max(0, emobase.abs - (n - set.size)) / 2
    val unchanged = if (forced == 0) Array.empty[Int] else
      if (emobase > 0) set.filter(_%2==0).toArray
      else set.filter(_%2!=0).toArray
    java.util.Arrays.sort(unchanged)
    val forcedSet = new java.util.HashSet[Int]
    unchanged.take(forced).foreach(forcedSet.add)

    val (even, odd) = Iterator
      .from(1, 1)
      .take(m)
      .filterNot(set.contains)
      .partition(_ % 2 == 0)

    var v = 0
    (0 until n).foreach { i =>
      v = arr(i)
      if (mset.contains(v) || forcedSet.contains(v)) {
        if (emobase > 0) {
          arr(i) = odd.next
          emobase -= 1
          changed += 1
        } else {
          arr(i) = even.next
          emobase += 1
          changed += 1
        }
      } else {
        mset.add(v)
      }
    }
    println(changed)
    println(arr.mkString(" "))
  }.getOrElse(println(-1))
}

/*
if (forced == 0) {
} else {
  if (emobase > 0 && (v%2==0)) {
    arr(i) = odd.next()
    emobase -= 1
    forced -= 1
    changed += 1
  } else if (emobase < 0 && (v%2!=0)) {
    arr(i) = even.next()
    emobase += 1
    forced -= 1
    changed += 1
  }
}*/

import java.util.StringTokenizer

import scala.util.Try

object E extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()
  if (n % 2 != 0) println(-1) else Try {

    read()
    val arr = Array.fill(n)(int())
    val set = arr.toSet
    var emobase = set.count(_ % 2 == 0) * 2 - set.size
    var forced = Math.max(0, emobase.abs - (n - set.size)) / 2
    val mset = new java.util.HashSet[Int]
    var changed = 0

    val (even, odd) = Iterator
      .from(1, 1)
      .take(m)
      .filterNot(set.contains)
      .partition(_ % 2 == 0)

    var v = 0
    (0 until n).foreach { i =>
      v = arr(i)
      if (mset.contains(v)) {
        if (emobase > 0) {
          arr(i) = odd.next
          emobase -= 1
          changed += 1
        } else {
          arr(i) = even.next
          emobase += 1
          changed += 1
        }
      } else {
        if (forced == 0) {
          mset.add(v)
        } else {
          if (emobase > 0 && (v%2==0)) {
            arr(i) = odd.next()
            emobase -= 1
            forced -= 1
            changed += 1
          } else if (emobase < 0 && (v%2!=0)) {
            arr(i) = even.next()
            emobase += 1
            forced -= 1
            changed += 1
          }
        }
      }
    }
    println(changed)
    println(arr.mkString(" "))
  }.getOrElse(println(-1))
}

import java.util.StringTokenizer

import scala.util.Try

object E extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()
  if (n % 2 != 0) println(-1) else Try {

    read()
    val arr = Array.fill(n)(int())
    val set = arr.toSet
    var emobase = set.map { i => if (i % 2 == 0) 1 else -1 }.sum
    var forced = Math.max(0, emobase.abs - (n - set.size)) / 2
    val mset = new java.util.HashSet[Int]
    var changed = 0

    val (even, odd) = Iterator
      .from(1, 1)
      .take(m)
      .filterNot(set.contains)
      .partition(_ % 2 == 0)

    var v = 0
    (0 until n).foreach { i =>
      v = arr(i)
      if (mset.contains(v)) {
        if (emobase > 0) {
          arr(i) = odd.next
          emobase -= 1
          changed += 1
        } else {
          arr(i) = even.next
          emobase += 1
          changed += 1
        }
      } else {
        if (forced == 0) {
          mset.add(v)
        } else {
          if (emobase > 0 && (v%2==0)) {
            arr(i) = odd.next()
            emobase -= 1
            forced -= 1
            changed += 1
          } else if (emobase < 0 && (v%2!=0)) {
            arr(i) = even.next()
            emobase += 1
            forced -= 1
            changed += 1
          }
        }
      }
    }
    println(changed)
    println(arr.mkString(" "))
  }.getOrElse(println(-1))
}


You are given a huge integer $$$a$$$ consisting of $$$n$$$ digits ($$$n$$$ is between $$$1$$$ and $$$3 \cdot 10^5$$$, inclusive). It may contain leading zeros.You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by $$$2$$$). For example, if $$$a = 032867235$$$ you can get the following integers in a single operation:   $$$302867235$$$ if you swap the first and the second digits;  $$$023867235$$$ if you swap the second and the third digits;  $$$032876235$$$ if you swap the fifth and the sixth digits;  $$$032862735$$$ if you swap the sixth and the seventh digits;  $$$032867325$$$ if you swap the seventh and the eighth digits. Note, that you can't swap digits on positions $$$2$$$ and $$$4$$$ because the positions are not adjacent. Also, you can't swap digits on positions $$$3$$$ and $$$4$$$ because the digits have the same parity.You can perform any number (possibly, zero) of such operations.Find the minimum integer you can obtain.Note that the resulting integer also may contain leading zeros.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. The only line of each test case contains the integer $$$a$$$, its length $$$n$$$ is between $$$1$$$ and $$$3 \cdot 10^5$$$, inclusive. It is guaranteed that the sum of all values $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.

For each test case print line — the minimum integer you can obtain.

NoteIn the first test case, you can perform the following sequence of operations (the pair of swapped digits is highlighted): $$$0 \underline{\textbf{70}} 9 \rightarrow 0079$$$.In the second test case, the initial integer is optimal. In the third test case you can perform the following sequence of operations: $$$246 \underline{\textbf{43}} 2 \rightarrow 24 \underline{\textbf{63}}42 \rightarrow 2 \underline{\textbf{43}} 642 \rightarrow 234642$$$.

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 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[Int]]): 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 def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

  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 = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._

  class Queue(n: Int) {
  private val as = Array.ofDim[Int](n)
  var p = 0
  var cur = 0

  def +=(a: Int): Unit = {
    as(p) = a
    p += 1
  }

  def dequeue(): Int = {
    val a = as(cur)
    cur += 1
    a
  }

  def head: Int = as(cur)

  def apply(i: Int): Int = as(cur + i)

  def length: Int = p - cur
  def isEmpty: Boolean = length == 0
  def nonEmpty: Boolean = !isEmpty

  def mkString(delimiter: String = ""): String = as.slice(cur, cur + length).mkString(delimiter)
}
}

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
  import Workspace._

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val s = ns()
      val odds, evens = new Queue(s.length)
      REP(s.length) { i =>
        val a = s(i)-'0'
        if (a % 2 == 0) evens += a
        else odds += a
      }

      while(odds.nonEmpty || evens.nonEmpty) {
        val v = if (odds.isEmpty) evens.dequeue()
        else if (evens.isEmpty) odds.dequeue()
        else {
          if (odds.head < evens.head) odds.dequeue()
          else evens.dequeue()
        }
        out.print(v)
      }
      out.println()
    }
  }
}


By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses:   "Success" if the activation was successful.  "Already on", if the i-th collider was already activated before the request.  "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program:   "Success", if the deactivation was successful.  "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) — activate the i-th collider, or "- i" (without the quotes) — deactivate the i-th collider (1 ≤ i ≤ n).

Print m lines — the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.

Success
Conflict with 6
Success
Already off
Success
Success
Success
Success
Conflict with 10
Already on

NoteNote that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3".

object B154 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)

    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(n + 1)(false)
    var i = 2
    while (i <= n) {
      if (!isComposite(i)) primes.append(i)
      var j = 0
      var break = false
      while (j < primes.size && i * primes(j) <= n && !break) {
        isComposite(i * primes(j)) = true
        if (i % primes(j) == 0)
          break = true
        j += 1
      }
      i += 1
    }
    val factorIndices = Array.fill(n + 1)(Array.empty[Int])
    val poss = cu.Map.empty[Int, Int]
    i = 0
    while (i < primes.length) {
      poss.put(primes(i), i)
      i += 1
    }
    i = 0
    while (i <= n) {
      var x = i
      val idxs = ArrayBuffer.empty[Int]
      var j = 0
      while (j < primes.length && primes(j) * primes(j) <= x) {
        if (x % primes(j) == 0) {
          idxs.append(j)
          while (x % primes(j) == 0) x /= primes(j)
        }
        j += 1
      }
      if (x > 1)
        idxs.append(poss(x))
      factorIndices(i) = idxs.toArray.clone()
      i += 1
    }

    val arr = Array.fill(primes.length)(-1) // stores number with factor i
    val on = Array.fill(n + 1)(false)
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var break = factorIndices(num).find(i => arr(i) != -1)
          if (break.isDefined) {
            out.println(s"Conflict with ${arr(break.get)}")
          } else {
            var i = 0
            factorIndices(num).foreach(arr(_) = num)
            on(num) = true
            out.println("Success")
          }
        }
      } else {
        if (!on(num)) {
          out.println("Already off")
        } else {
          factorIndices(num).foreach(arr(_) = -1)
          on(num) = false
          out.println("Success")
        }
      }
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B154 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)

    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(n + 1)(false)
    var i = 2
    while (i <= n) {
      if (!isComposite(i)) primes.append(i)
      var j = 0
      var break = false
      while (j < primes.size && i * primes(j) <= n && !break) {
        isComposite(i * primes(j)) = true
        if (i % primes(j) == 0)
          break = true
        j += 1
      }
      i += 1
    }
    val factors = Array.fill(n + 1)(Array.empty[Int])
    i = 0
    while (i <= n) {
      var x = i
      val idxs = ArrayBuffer.empty[Int]
      var j = 0
      while (j < primes.length && primes(j) * primes(j) <= x) {
        if (x % primes(j) == 0) {
          idxs.append(primes(j))
          while (x % primes(j) == 0) x /= primes(j)
        }
        j += 1
      }
      if (x > 1)
        idxs.append(x)
      factors(i) = idxs.toArray
      i += 1
    }

    val arr = Array.fill(n + 1)(-1) // stores number with factor i
    val on = Array.fill(n + 1)(false)
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var break = factors(num).find(i => arr(i) != -1)
          if (break.isDefined) {
            out.println(s"Conflict with ${arr(break.get)}")
          } else {
            var i = 0
            factors(num).foreach(arr(_) = num)
            on(num) = true
            out.println("Success")
          }
        }
      } else {
        if (!on(num)) {
          out.println("Already off")
        } else {
          factors(num).foreach(arr(_) = -1)
          on(num) = false
          out.println("Success")
        }
      }
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B154 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)

    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(n + 1)(false)
    var i = 2
    while (i <= n) {
      if (!isComposite(i)) primes.append(i)
      var j = 0
      var break = false
      while (j < primes.size && i * primes(j) <= n && !break) {
        isComposite(i * primes(j)) = true
        if (i % primes(j) == 0)
          break = true
        j += 1
      }
      i += 1
    }
    val factors = ArrayBuffer.empty[ArrayBuffer[Int]]
    i = 0
    while (i <= n) {
      var x = i
      val idxs = ArrayBuffer.empty[Int]
      var j = 0
      while (j < primes.length && primes(j) * primes(j) <= x) {
        if (x % primes(j) == 0) {
          idxs.append(primes(j))
          while (x % primes(j) == 0) x /= primes(j)
        }
        j += 1
      }
      if (x > 1)
        idxs.append(x)
      factors.append(idxs)
      i += 1
    }

    val arr = Array.fill(n + 1)(-1) // stores number with factor i
    val on = Array.fill(n + 1)(false)
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var break = factors(num).find(i => arr(i) != -1)
          if (break.isDefined) {
            out.println(s"Conflict with ${arr(break.get)}")
          } else {
            var i = 0
            factors(num).foreach(arr(_) = num)
            on(num) = true
            out.println("Success")
          }
        }
      } else {
        if (!on(num)) {
          out.println("Already off")
        } else {
          factors(num).foreach(arr(_) = -1)
          on(num) = false
          out.println("Success")
        }
      }
    }
    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))
    }
  }

}

import collection.mutable
import java.io._

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 29.02.12
 * Time: 5:17
 * To change this template use File | Settings | File Templates.
 */
object D {
  def main(args: Array[String]) {
    val Array(colliderCount, requestCount) = readLine split ' ' map (str => str.toInt)
    val colliders: Array[Collider] = Array((0 to colliderCount) map (_ => new Collider): _*)
    val conflicts = new Array[Int](1 + colliderCount)
    val output = new BufferedWriter(new OutputStreamWriter(System.out))
    for (prime <- 2 to colliderCount filter (i => colliders(i).primes == Nil)) {
      for (num <- (prime to colliderCount by prime)) {
        colliders(num).primes ::= prime
      }
    }
    for (i <- (1 to requestCount)) {
      val line = readLine
      val sign = line(0)
      val num = line.split(" ")(1).toInt
      val collider = colliders(num)
      (sign, collider.state) match {
        case ('+', true) => output.write("Already on\n")
        case ('-', false) => output.write("Already off\n")
        case ('+', false) => {
          collider.primes.find(prime => conflicts(prime) > 0) match {
            case Some(prime) => output.write("Conflict with %d\n".format(conflicts(prime)))
            case None => {
              collider.primes.foreach(prime => conflicts(prime) = num)
              collider.state = true
              output.write("Success\n")
            }
          }
        }
        case ('-', true) => {
          collider.primes.foreach(prime => conflicts(prime) = 0)
          collider.state = false
          output.write("Success\n")
        }
      }
    }
    output.flush
  }

  class Collider {
    var primes: List[Int] = Nil
    var state = false
  }

}

import collection.mutable
import java.io._

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 29.02.12
 * Time: 5:17
 * To change this template use File | Settings | File Templates.
 */
object D {
  val output = new BufferedWriter(new OutputStreamWriter(System.out))
  val input = new BufferedReader(new InputStreamReader(System.in))

  def main(args: Array[String]) {
    val Array(colliderCount, requestCount) = input.readLine split ' ' map (str => str.toInt)
    val colliders: Array[Collider] = Array((0 to colliderCount) map (_ => new Collider): _*)
    val conflicts = new Array[Int](1 + colliderCount)

    for (prime <- 2 to colliderCount filter (i => colliders(i).primes == Nil)) {
      for (num <- (prime to colliderCount by prime)) {
        colliders(num).primes ::= prime
      }
    }
    for (i <- (1 to requestCount)) {
      val line = input.readLine
      val sign = line(0)
      val num = line.split(" ")(1).toInt
      val collider = colliders(num)
      (sign, collider.state) match {
        case ('+', true) => output.write("Already on\n")
        case ('-', false) => output.write("Already off\n")
        case ('+', false) => {
          collider.primes.find(prime => conflicts(prime) > 0) match {
            case Some(prime) => output.write("Conflict with %d\n".format(conflicts(prime)))
            case None => {
              collider.primes.foreach(prime => conflicts(prime) = num)
              collider.state = true
              output.write("Success\n")
            }
          }
        }
        case ('-', true) => {
          collider.primes.foreach(prime => conflicts(prime) = 0)
          collider.state = false
          output.write("Success\n")
        }
      }
    }
    output.flush
  }

  class Collider {
    var primes: List[Int] = Nil
    var state = false
  }

}

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import java.io.File
import java.io.BufferedOutputStream
import java.io.PrintWriter

object D {
  object Int {
    def unapply(s: String) : Some[Int] = Some(s.toInt)
  }
  val N = 100001

  val factors = new Array[ListBuffer[Int]](N)
  val active = new Array[Boolean](N)

  factors.indices.foreach(factors(_) = ListBuffer[Int]())

  (2 until N/2).foreach (fc => (fc until N by fc).foreach (factors(_) += fc))

  val usedBy = new Array[Int](N)

  def main(args: Array[String]): Unit = {
    val output = new PrintWriter(new BufferedOutputStream(System.out, 100000))

    val lines = scala.io.Source.stdin.getLines()
    lines.next()
    lines.foreach( cmd => {
      val s = cmd.split(" ")
      val n = s(1).toInt
      output.println( if (s(0).equals("+")) {
          if (active(n)) "Already on"
          else factors(n).find(usedBy(_) > 0) match { case Some(uf) => "Conflict with " + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; "Success" }
      } else {
          if (!active(n)) "Already off"
          else { factors(n).foreach(usedBy(_) = 0); active(n) = false; "Success" }
     })
    })

    output.close()
}
}

object B154 {

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

  case class Sieve(to: Int) {
    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(to + 1)(false)
    def sieve(): Unit = { // Works in linear time
      for (i <- 2 until to) {
        if (!isComposite(i)) primes.append(i)
        var j = 0
        var break = false
        while (j < primes.size && i * primes(j) < to && !break) {
          isComposite(i * primes(j)) = true
          if (i % primes(j) == 0)
            break = true
          j += 1
        }
      }
    }
  }
  val s = Sieve(100000 + 10)
  s.sieve()

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val arr = Array.fill(s.primes.length)(-1)
    val on = cu.Set.empty[Int]
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on.contains(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var bad = -1
          while (bad == -1 && i < arr.length && s.primes(i) <= num) {
            if (num % s.primes(i) == 0) {
              if (arr(i) == -1) {
                arr(i) = num
              } else {
                bad = arr(i)
              }
            }
            i += 1
          }
          if (bad != -1) {
            out.println(s"Conflict with $bad")
          } else {
            on.add(num)
            out.println("Success")
          }
        }
      } else {
        if (!on.contains(num)) {
          out.println("Already off")
        } else {
          var i = 0
          while (i < arr.length && s.primes(i) <= num) {
            if (num % s.primes(i) == 0) {
              arr(i) = -1
            }
            i += 1
          }
          on.remove(num)
          out.println("Success")
        }
      }
    }
    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object B154 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)

    val primes = scala.collection.mutable.ArrayBuffer.empty[Int]
    val isComposite = Array.fill(n + 1)(false)
    var i = 2
    while (i <= n) {
      if (!isComposite(i)) primes.append(i)
      var j = 0
      var break = false
      while (j < primes.size && i * primes(j) <= n && !break) {
        isComposite(i * primes(j)) = true
        if (i % primes(j) == 0)
          break = true
        j += 1
      }
      i += 1
    }
    val factors = Array.fill(n + 1)(Array.empty[Int])
    i = 0
    while (i <= n) {
      var x = i
      val idxs = ArrayBuffer.empty[Int]
      var j = 0
      while (j < primes.length && primes(j) * primes(j) <= x) {
        if (x % primes(j) == 0) {
          idxs.append(j)
          while (x % primes(j) == 0) x /= primes(j)
        }
        j += 1
      }
      if (x > 1)
        idxs.append(x)
      factors(i) = idxs.toArray.clone()
      i += 1
    }

    val arr = Array.fill(n + 1)(-1) // stores number with factor i
    val on = Array.fill(n + 1)(false)
    for (_ <- 0 until m) {
      val str = read.split(' ')
      val num = str(1).toInt
      if (str(0) == "+") {
        if (on(num)) {
          out.println("Already on")
        } else {
          var i = 0
          var break = factors(num).find(i => arr(i) != -1)
          if (break.isDefined) {
            out.println(s"Conflict with ${arr(break.get)}")
          } else {
            var i = 0
            factors(num).foreach(arr(_) = num)
            on(num) = true
            out.println("Success")
          }
        }
      } else {
        if (!on(num)) {
          out.println("Already off")
        } else {
          factors(num).foreach(arr(_) = -1)
          on(num) = false
          out.println("Success")
        }
      }
    }
    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))
    }
  }

}

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer

object D {
  object Int {
    def unapply(s: String) : Some[Int] = Some(s.toInt)
  }
  val N = 100000

  val factors = new Array[ListBuffer[Int]](N)
  val active = new Array[Boolean](N)

  factors.indices.foreach(factors(_) = ListBuffer[Int]())

  (1 until N/2).foreach (fc => (fc until N by fc).foreach (factors(_) += fc))

  val usedBy = new Array[Int](10000)

  def main(args: Array[String]): Unit = {
    scala.io.Source.stdin.getLines().toList.tail.foreach( cmd => {
      System.out.println (cmd.split(" ").toList match {
        case "+"::Int(n)::_ =>
          if (active(n)) "Already on"
          else factors(n).find(usedBy(_) > 0) match { case Some(uf) => "Conflict with " + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; "Success" }
        case "-"::Int(n)::_ =>
          if (!active(n)) "Already off"
          else { factors(n).foreach(usedBy(_) = 0); active(n) = false; "Success" }
     })
    })
  }
}

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer

object D {
  object Int {
    def unapply(s: String) : Some[Int] = Some(s.toInt)
  }
  val N = 100000

  val factors = new Array[ListBuffer[Int]](N)
  val active = new Array[Boolean](N)

  factors.indices.foreach(factors(_) = ListBuffer[Int]())

  (2 until N/2).foreach (fc => (fc*2 until N by fc).foreach (factors(_) += fc))

  val usedBy = new Array[Int](10000)

  def main(args: Array[String]): Unit = {
    scala.io.Source.stdin.getLines().toList.tail.foreach( cmd => {
      System.out.println (cmd.split(" ").toList match {
        case "+"::Int(n)::_ =>
          if (active(n)) "Already on"
          else factors(n).find(usedBy(_) > 0) match { case Some(uf) => "Conflict with " + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; "Success" }
        case "-"::Int(n)::_ =>
          if (!active(n)) "Already off"
          else { factors(n).foreach(usedBy(_) = 0); active(n) = false; "Success" }
     })
    })
  }
}

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import java.io.File
import java.io.BufferedOutputStream
import java.io.PrintWriter

object D {
  object Int {
    def unapply(s: String) : Some[Int] = Some(s.toInt)
  }
  val N = 100001

  val factors = new Array[ListBuffer[Int]](N)
  val active = new Array[Boolean](N)

  factors.indices.foreach(factors(_) = ListBuffer[Int]())

  (2 until N/2).foreach (fc => (fc until N by fc).foreach (factors(_) += fc))

  val usedBy = new Array[Int](N)

  def main(args: Array[String]): Unit = {
    val output = new PrintWriter(new BufferedOutputStream(System.out, 100000))

    val lines = scala.io.Source.stdin.getLines()
    lines.next()
    lines.foreach( cmd => {
      val s = cmd.split(" ")
      val n = s(1).toInt
      output.println( if (s(0).equals("+")) {
          if (active(n)) "Already on"
          else factors(n).find(usedBy(_) > 0) match { case Some(uf) => "Conflict with " + usedBy(uf); case None => factors(n).foreach(usedBy(_) = n); active(n) = true; "Success" }
      } else {
          if (!active(n)) "Already off"
          else { factors(n).foreach(usedBy(_) = 0); active(n) = false; "Success" }
     })
    })
}
}