Let $$$f_{x} = c^{2x-6} \cdot f_{x-1} \cdot f_{x-2} \cdot f_{x-3}$$$ for $$$x \ge 4$$$.You have given integers $$$n$$$, $$$f_{1}$$$, $$$f_{2}$$$, $$$f_{3}$$$, and $$$c$$$. Find $$$f_{n} \bmod (10^{9}+7)$$$.

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, f1, f2, f3, C = nl()

    val A = Array(
      Array[Long](1, 1, 1),
      Array[Long](1, 0, 0),
      Array[Long](0, 1, 0)
    )
    val B = power(A, N - 3, MOD - 1)(0)

    val A2 = Array(
      Array[Long](1, 1, 1, 1, 0),
      Array[Long](1, 0, 0, 0, 0),
      Array[Long](0, 1, 0, 0, 0),
      Array[Long](0, 0, 0, 1, 1),
      Array[Long](0, 0, 0, 0, 1)
    )

    val B2 = power(A2, N - 3, MOD - 1)(0)
    debug(B2)

    val v3 = B(0)
    val v2 = B(1)
    val v1 = B(2)
    val cc = B2(3) + B2(4)

    debug(s"v1:$v1 v2:$v2 v3:$v3 cc:$cc")

    val ans = powMod(f1, v1, MOD) *
      powMod(f2, v2, MOD) % MOD *
      powMod(f3, v3, MOD) % MOD *
      powMod(C * C % MOD, cc, MOD) % MOD

    out.println(ans)
  }

  def powMod(x: Long, n: Long, m: Long): Long = {
    def step(x: Long, n: Long, stack: Long): Long = {
      n match {
        case 0 => stack
        case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
      }
    }
    step(x, n, 1)
  }

  def power(a: Array[Array[Long]], n: Long, mod: Int): Array[Array[Long]] = {
    if (n == 1) a
    else {
      val q = n / 2
      val r = n % 2
      val b = power(mul(a, a, mod), q, mod)
      if (r == 1) mul(a, b, mod) else b
    }
  }

  def mul(a1: Array[Array[Long]], a2: Array[Array[Long]], mod: Int): Array[Array[Long]] = {
    assert(a1(0).length == a2.length)
    val r = a1.length
    val c = a2(0).length
    val len = a1(0).length
    val res = Array.ofDim[Long](r, c)
    REP(r) { i =>
      REP(c) { j =>
        var v = 0L
        REP(len) { k =>
          v += + a1(i)(k) * a2(k)(j)
          if (v > 7e18.toLong) v %= mod
        }
        res(i)(j) = if (v >= mod) v % mod else v
      }
    }
    res
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, f1, f2, f3, C = nl()

    val A = Array(
      Array[Long](1, 1, 1),
      Array[Long](1, 0, 0),
      Array[Long](0, 1, 0)
    )
    val B = power(A, N - 3, MOD)(0)

    val A2 = Array(
      Array[Long](1, 1, 1, 1, 0),
      Array[Long](1, 0, 0, 0, 0),
      Array[Long](0, 1, 0, 0, 0),
      Array[Long](0, 0, 0, 1, 1),
      Array[Long](0, 0, 0, 0, 1)
    )

    val B2 = power(A2, N - 3, MOD)(0)
    debug(B2)

    val v3 = B(0)
    val v2 = B(1)
    val v1 = B(2)
    val cc = B2(3) + B2(4)

    debug(s"v1:$v1 v2:$v2 v3:$v3 cc:$cc")

    val ans = powMod(f1, v1, MOD) *
      powMod(f2, v2, MOD) % MOD *
      powMod(f3, v3, MOD) % MOD *
      powMod(C * C % MOD, cc, MOD) % MOD

    out.println(ans)
  }

  def powMod(x: Long, n: Long, m: Long): Long = {
    def step(x: Long, n: Long, stack: Long): Long = {
      n match {
        case 0 => stack
        case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
      }
    }
    step(x, n, 1)
  }

  def power(a: Array[Array[Long]], n: Long, mod: Int): Array[Array[Long]] = {
    if (n == 1) a
    else {
      val q = n / 2
      val r = n % 2
      val b = power(mul(a, a, mod), q, mod)
      if (r == 1) mul(a, b, mod) else b
    }
  }

  def mul(a1: Array[Array[Long]], a2: Array[Array[Long]], mod: Int): Array[Array[Long]] = {
    assert(a1(0).length == a2.length)
    val r = a1.length
    val c = a2(0).length
    val len = a1(0).length
    val res = Array.ofDim[Long](r, c)
    REP(r) { i =>
      REP(c) { j =>
        var v = 0L
        REP(len) { k =>
          v += + a1(i)(k) * a2(k)(j)
          if (v > 7e18.toLong) v %= mod
        }
        res(i)(j) = if (v >= mod) v % mod else v
      }
    }
    res
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, f1, f2, f3, C = nl()

    val A = Array(
      Array[Long](1, 1, 1),
      Array[Long](1, 0, 0),
      Array[Long](0, 1, 0)
    )
    val B = power(A, N - 3, MOD)(0)

    val A2 = Array(
      Array[Long](1, 1, 1, 1, 0),
      Array[Long](1, 0, 0, 0, 0),
      Array[Long](0, 1, 0, 0, 0),
      Array[Long](0, 0, 0, 1, 1),
      Array[Long](0, 0, 0, 0, 1)
    )

    val B2 = power(A2, N - 3, MOD)(0)
    debug(B2)

    val v3 = B(0)
    val v2 = B(1)
    val v1 = B(2)
    val cc = B2(3) + B2(4)

    debug(s"v1:$v1 v2:$v2 v3:$v3 cc:$cc")

    val ans = powMod(f1, v1, MOD) *
      powMod(f2, v2, MOD) % MOD *
      powMod(f3, v3, MOD) % MOD *
      powMod(C * C % MOD, cc, MOD) % MOD

    out.println(ans)
  }

  def powMod(x: Long, n: Long, m: Long): Long = {
    def step(x: Long, n: Long, stack: Long): Long = {
      n match {
        case 0 => stack
        case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
      }
    }
    step(x, n, 1)
  }

  def power(a: Array[Array[Long]], n: Long, mod: Int): Array[Array[Long]] = {
    if (n == 1) a
    else {
      val q = n / 2
      val r = n % 2
      val b = power(mul(a, a, mod), q, mod)
      if (r == 1) mul(a, b, mod) else b
    }
  }

  def mul(a1: Array[Array[Long]], a2: Array[Array[Long]], mod: Int): Array[Array[Long]] = {
    assert(a1(0).length == a2.length)
    val r = a1.length
    val c = a2(0).length
    val len = a1(0).length
    val res = Array.ofDim[Long](r, c)
    REP(r) { i =>
      REP(c) { j =>
        var v = 0L
        REP(len) { k =>
          v += + a1(i)(k) * a2(k)(j)
          if (v > 7e18.toInt) v %= mod
        }
        res(i)(j) = if (v >= mod) v % mod else v
      }
    }
    res
  }
}


Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of lengths of the other two forms. Help him to do this.

The first line contains integer n (3 ≤ n ≤ 100) — amount of worm's forms. The second line contains n space-separated integers ai (1 ≤ ai ≤ 1000) — lengths of worms of each form.

Output 3 distinct integers i j k (1 ≤ i, j, k ≤ n) — such indexes of worm's forms that ai = aj + ak. If there is no such triple, output -1. If there are several solutions, output any of them. It possible that aj = ak.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val set = data.toSet
  var ir = -1
  var jr = -1
  var kr = -1
  val result = (0 until n - 1).foreach { i =>
    val f = (i + 1 until n).find(j => set.contains(data(i) + data(j)))
    if (f.nonEmpty) {
      ir = i + 1
      jr = f.get + 1
      kr = data.indices.find(x => data(x) == data(i) + data(f.get)).get + 1
    }

  }
  if (ir != -1)
    println(s"$kr $jr $ir")
  else
    println(-1)
}

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

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var arr = readLine.split(" ").map(_.toInt);
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        for (k <- 0 until n) {
          if (i != j && i != k && j != k) {
            if (arr(i) == arr(j) + arr(k)) {
              println((i + 1) + " " + (j + 1) + " " + (k + 1));
              return;
            }
          }
        }
      }
    }
    println("-1");
  }

}


There are $$$n$$$ friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.For each friend the value $$$f_i$$$ is known: it is either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$.You want to fill in the unknown values ($$$f_i = 0$$$) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.If there are several answers, you can print any.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of friends. The second line of the input contains $$$n$$$ integers $$$f_1, f_2, \dots, f_n$$$ ($$$0 \le f_i \le n$$$, $$$f_i \ne i$$$, all $$$f_i \ne 0$$$ are distinct), where $$$f_i$$$ is the either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$. It is also guaranteed that there is at least two values $$$f_i = 0$$$.

Print $$$n$$$ integers $$$nf_1, nf_2, \dots, nf_n$$$, where $$$nf_i$$$ should be equal to $$$f_i$$$ if $$$f_i \ne 0$$$ or the number of friend whom the $$$i$$$-th friend wants to give the gift to. All values $$$nf_i$$$ should be distinct, $$$nf_i$$$ cannot be equal to $$$i$$$. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. If there are several answers, you can print any.

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()

  val t = stdin.next().toInt
  val to: Array[Int] = stdin.next().split(" ").map(_.toInt)
  val from = new Array[Int](t)
  Range(0, t).filter(i => to(i) != 0).foreach(i => from(to(i) - 1) = i + 1)
  var startIndex = from.indexOf(0)
  var freeIndexes = Range(0, t).filter(i => from(i) == 0 && i != startIndex)
  var currentIndex = startIndex
  var i = 0
  while (i == 0 || (currentIndex != startIndex)) {
    if (to(currentIndex) == 0 && freeIndexes.nonEmpty) {
      to(currentIndex) = freeIndexes.head + 1
      freeIndexes = freeIndexes.tail
    }
    else if (to(currentIndex) == 0) {
      to(currentIndex) = startIndex + 1
    }
    currentIndex = to(currentIndex) - 1
    i += 1
  }
  println(to.mkString(" "))
}

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()

  val t = stdin.next().toInt
  val arr = stdin.next().split(" ").map(_.toInt)
  var res = arr.toSet
  val str = {
    var i = 1
    def loop(cand: Int): Stream[Int] =
      if (cand == 0) loop(t)
      else if (res.contains(cand)) loop(cand - 1)
      else if (cand == i) loop(cand - 1)
      else {
        res = res + cand
        i += 1
        cand #:: loop(cand - 1)
      }
    loop(t)
  }.iterator

  println(arr.map(x => if (x == 0) str.next() else x).mkString(" "))
}

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()

  val t = stdin.next().toInt
  val arr = stdin.next().split(" ").map(_.toInt)
  var set = arr.toSet

  val iter = {
    def loop(cand: Int): Stream[Int] = if (set.contains(cand)) loop(cand - 1) else cand #:: loop(cand - 1)
    loop(t).iterator
  }

  var res = arr.zipWithIndex.foldLeft((None: Option[Int], List.empty[Int])) {
    case ((x, list), (el, _)) if el != 0 => (x, el :: list)
    case ((None, list), (el, i)) => {
      val cand = iter.next()
      if (cand == i + 1)
        (Some(cand), iter.next() :: list)
      else
        (None, cand :: list)
    }
    case ((Some(x), list), (el, i)) => (None, x :: list)
  }

  val list = (res._1 ++ res._2).toList.reverse

  println(list.mkString(" "))
}

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()

  val t = stdin.next().toInt
  val arr = stdin.next().split(" ").map(_.toInt)
  val res = arr.toSet
  val str = {
    def loop(cand: Int): Stream[Int] = if (res.contains(cand)) loop(cand - 1) else cand #:: loop(cand - 1)
    loop(t)
  }.iterator

  println(arr.map(x => if (x == 0) str.next() else x).mkString(" "))
}

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()

  val t = stdin.next().toInt
  val to: Array[Int] = stdin.next().split(" ").map(_.toInt)
  val from = new Array[Int](t)
  Range(0, t).filter(i => to(i) != 0).foreach(i => from(to(i) - 1) = i + 1)
  var startIndex = from.find(_ == 0).get
  var freeIndexes = Range(0, t).filter(i => from(i) == 0 && i != startIndex)
  var currentIndex = to(startIndex) - 1
  var i = 0
  while (currentIndex != startIndex && i < t) {
    if (to(currentIndex) == 0 && freeIndexes.nonEmpty) {
      to(currentIndex) = freeIndexes.head + 1
      freeIndexes = freeIndexes.tail
    }
    else if (to(currentIndex) == 0) {
      to(currentIndex) = startIndex + 1
    }
    currentIndex = to(currentIndex) - 1
    i += 1
  }
  println(to.mkString(" "))
}


zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this task!

The only line contains the string s (1 ≤ |s| ≤ 2·105) — the string given to zscoder. The string s consists of only lowercase English letters.

Print the simple string s' — the string s after the minimal number of changes. If there are multiple solutions, you may output any of them. Note that the string s' should also consist of only lowercase English letters.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next().toCharArray
  (1 until str.length).foreach { i =>
      if (str(i) == str(i - 1))
        str(i) = List(str(i), 'a', 'b', 'c')
          .find(nch => nch != str(i - 1) && (i == str.length - 1 || nch != str(i + 1))).get
  }
  println(str.mkString(""))
}


Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that:   the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN",  or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of clubs in the league. Each of the next n lines contains two words — the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.

It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them.

3
PLAYFOOTBALL MOSCOW
PLAYVOLLEYBALL SPB
GOGO TECHNOCUP

NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different.

import scala.io.StdIn._

import scala.collection.mutable

import scala.collection.mutable._

object Solution {

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

  var m: Int = _

  val adj = Array.fill(3000)(ArrayBuffer[Int]())
  val matches = Array.fill(3000)(-1)
  val used = Array.fill(3000)(false)

  def dfs(v: Int): Boolean = {
    used(v) = true
    adj(v).exists { u =>
      val w = matches(u)
      if (w < 0 || (!used(w) && dfs(w))) {
        matches(u) = v
        matches(v) = u
        true
      } else {
        false
      }
    }
  }

  def main(args: Array[String]) {

    val n = readLine.toInt
    val opt = Array.fill(n) {
      val Array(first, second) = readLine.split(" ")
      (first.take(3), first.take(2) + second.take(1))
    }

    val key = mutable.HashMap[String, ArrayBuffer[Int]]().withDefaultValue(ArrayBuffer[Int]())

    val n2i = mutable.HashMap[String, Int]()
    val i2n = Array.fill(3000)("")

    m = n

    opt.zipWithIndex.foreach {
      case ((first, second), i) =>
        key.getOrElseUpdate(first, ArrayBuffer[Int]()).append(i)
        if (!n2i.contains(first)) {
          n2i.put(first, m)
          i2n(m) = first
          m += 1
        }
        if (!n2i.contains(second)) {
          n2i.put(second, m)
          i2n(m) = second
          m += 1
        }
    }

    key.foreach { case (_, array) =>
      if (array.size > 1) {
        array.foreach { i =>
          adj(i).append(n2i(opt(i)._2))
          adj(n2i(opt(i)._2)).append(i)
        }
      } else {
        val i = array.head
        adj(i).append(n2i(opt(i)._1))
        adj(i).append(n2i(opt(i)._2))
        adj(n2i(opt(i)._1)).append(i)
        adj(n2i(opt(i)._2)).append(i)
      }
    }

    var res = 0

    for (i <- 0 to n - 1) {
      if (matches(i) < 0) {
        for (j <- 0 to m - 1) used(j) = false
        if (dfs(i)) res += 1
      }
    }

    if (res == n) {
      println("YES")
      matches.take(n).map(i2n(_)).foreach(println)
    } else {
      println("NO")
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}

import scala.collection.mutable

import scala.collection.mutable._

object Solution {

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

  def main(args: Array[String]) {

    val n = readLine.toInt
    val opt = Array.fill(n) {
      val Array(first, second) = readLine.split(" ")
      (first.take(3), first.take(2) + second.take(1))
    }
    val res = Array.fill[String](n)("")

    val key = mutable.HashMap[String, ArrayBuffer[Int]]().withDefaultValue(ArrayBuffer[Int]())
    val name = mutable.HashSet[String]()

    opt.zipWithIndex.foreach { case ((first, _), i) =>
      key.getOrElseUpdate(first, ArrayBuffer[Int]()).append(i)
    }

    var valid = true
    key.filter(_._2.size > 1).foreach { case (_, array) =>
      if (valid) {
        array.foreach { i =>
          if (name.contains(opt(i)._2)) valid = false
          else {
            name.add(opt(i)._2)
            res(i) = opt(i)._2
          }
        }
      }
    }

    val single = key.filter(valid && _._2.size == 1).map(_._2.head).toList

    var dep = true
    while (single.filter(res(_)=="").nonEmpty && dep && valid) {
      single.filter(res(_)=="").foreach { i =>
        if (name.contains(opt(i)._1) && !name.contains(opt(i)._2)) {
          name.add(opt(i)._2)
          res(i) = opt(i)._2
        } else if (!name.contains(opt(i)._1) && name.contains(opt(i)._2)) {
          name.add(opt(i)._1)
          res(i) = opt(i)._1
        } else if (name.contains(opt(i)._1) && name.contains(opt(i)._2)) {
          valid = false
        } else {
          dep = false
        }
      }
    }

    for (i <- res.indices) {
      if (res(i) == "") res(i) = opt(i)._1
    }

    if (valid) {
      println("YES")
      res.foreach(println)
    } else {
      println("NO")
    }

    //    Console.withOut(new java.io.BufferedOutputStream(Console.out))
    //    println(res.mkString("\n"))
    //    Console.flush
  }
}


Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student’s laziness level is equal to their task’s difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the task’s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.

The first line of input contains integer n (1 ≤ n ≤ 100 000) — the number of tasks. The next n lines contain exactly one integer number ai (1 ≤ ai ≤ 100 000) — both the difficulty of the initial task and the laziness of the i-th students.

Print the minimum total time to finish all tasks modulo 10 007.

NoteIn the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toLong).toArray.sorted
  println(sor.zip(sor.reverse).map(i => i._1 * i._2 % 10007).sum[Long] % 10007)
}

  import scala.io.StdIn
  import scala.util.Sorting

  object Solution extends App {
    val n = StdIn.readInt
    val a = (1 to n).map(_ => StdIn.readInt).toArray

    Sorting.quickSort(a)
    val middle = if (n % 2 == 0) n / 2 - 1 else n / 2

    var r: Long = 0
    for (i <- 0 to middle) {
      var v = a(i).toLong * a(n - i - 1)
      if (i != n - i - 1) {
        v *= 2
      }
      r += v
    }

    println(r % 10007)
  }

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toInt % 10007).toArray.sorted
  println((0 until n).foldLeft(0) {
    case (acc, i) => (acc + sor(i) * sor(n - i - 1)) % 10007
  })
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toInt).toArray.sorted
  println((0 until n / 2).foldLeft(if (n % 2 == 0) 0 else sor(n / 2)) {
    case (acc, i) => (i + 2 * sor(i) * sor(n - i - 1)) % 10007
  })
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toLong).toArray.sorted
  println((0 until n / 2).foldLeft(if (n % 2 == 0) 0l else sor(n / 2) * sor(n / 2) % 10007) {
    case (acc, i) => (i + 2 * sor(i) * sor(n - i - 1)) % 10007
  })
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toLong % 10007).toArray.sorted
  println(sor.zip(sor.reverse).map(i => i._1 * i._2 % 10007).sum[Long] % 10007)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toInt).toArray.sorted
  println((0 until n / 2).foldLeft(if (n % 2 == 0) 0 else sor(n / 2) * sor(n / 2)) {
    case (acc, i) => (i + 2 * sor(i) * sor(n - i - 1)) % 10007
  }  % 10007)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toInt % 10007).toArray.sorted
  println((0 until n / 2).foldLeft(if (n % 2 == 0) 0 else sor(n / 2) * sor(n / 2) % 10007) {
    case (acc, i) => (acc + 2 * sor(i) * sor(n - i - 1)) % 10007
  })
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val sor = in.take(n).map(_.toLong % 10007).toArray.sorted
  println((0 until n).foldLeft(0l) {
    case (acc, i) => (acc + sor(i) * sor(n - i - 1)) % 10007
  })
}

  import scala.io.StdIn
  import scala.util.Sorting

  object Solution extends App {
    val n = StdIn.readInt
    val a = (1 to n).map(_ => StdIn.readInt).toArray

    Sorting.quickSort(a)
    val middle = if (n % 2 == 0) n / 2 - 1 else n / 2

    var r: Long = 0
    for (i <- 0 to middle) {
      var v = a(i) * a(n - i - 1)
      if (i != n - i - 1) {
        v *= 2
      }
      r += v
    }

    println(r % 10007)
  }

  import scala.io.StdIn
  import scala.util.Sorting

  object Solution extends App {
    val n = StdIn.readInt
    val a = (1 to n).map(_ => StdIn.readInt).toArray

    Sorting.quickSort(a)
    val middle = if (n % 2 == 0) n / 2 - 1 else n / 2

    var r: Long = 0
    for (i <- 0 to middle) {
      var v: Long = a(i) * a(n - i - 1)
      if (i != n - i - 1) {
        v *= 2
      }
      r += v
    }

    println(r % 10007)
  }

  import scala.io.StdIn
  import scala.util.Sorting

  object Solution extends App {
    val n = StdIn.readInt
    val a = (1 to n).map(_ => StdIn.readInt).toArray

    Sorting.quickSort(a)
    val middle = if (n % 2 == 0) n / 2 - 1 else n / 2

    var r: Long = 0
    for (i <- 0 to middle) {
      var v = a(i) * a(n - i - 1)
      if (i != n - i - 1) {
        v *= 2
      }
      r += v
    }

    println(r)
  }


City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.Road repairs are planned for n2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.According to the schedule of road works tell in which days at least one road will be asphalted.

The first line contains integer n (1 ≤ n ≤ 50) — the number of vertical and horizontal roads in the city.  Next n2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers hi, vi (1 ≤ hi, vi ≤ n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the hi-th horizontal and vi-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.

In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.

NoteIn the sample the brigade acts like that:  On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road;  On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road.

object Program{
	def main(ins:Array[String]){
		var ins = new Array[Int](2);
		var n = readInt();
		var x = new Array[Int](n); var y = new Array[Int](n)
		var a = 0; var b = 0
		for (i <-1 to n*n){
			ins = readLine.split(" ").map(_.toInt)
			a = ins(0); b = ins(1)
			if (x(a - 1) == 0 && y(b - 1) == 0){
				x(a - 1) = 1; y(b - 1) = 1
				print(i+" ")
			}
		}
	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var visited = Set.empty[Int]
  var visited2 = Set.empty[Int]
  val n = in.next().toInt
  val res = (1 to n * n).filter { i =>
    val Array(x, y) = in.next().split(" ").map(_.toInt)
    if (visited.contains(x) || visited2.contains(y))
      false
    else {
      visited += x
      visited2 += y
      true
    }
  }
  println(res.mkString(" "))
}

object A583 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val row = Array.fill[Boolean](n)(false)
    val col = Array.fill[Boolean](n)(false)
    var res = Array.empty[Int]
    for(i <- 0 until n*n) {
      val arr = readInts(2)
      if(!row(arr(0)-1) && !col(arr(1)-1)) {
        row(arr(0)-1) = true
        col(arr(1)-1) = true
        res = res ++ Array(i+1)
      }
    }
    println(res.mkString(" "))
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _583A extends CodeForcesApp[Seq[Int]]({scanner => import scanner._
  val n = nextInt
  val vs = bag[Int]
  val hs = bag[Int]

  val ans = for {
    d <- 1 to n*n
    (i, j) = (nextInt, nextInt)
    if !(vs contains i) && !(hs contains j)
  } yield {
      vs.add(i)
      hs.add(j)
      d
   }

  ans
}) {
  override def format(result: Result) = result mkString " "
}
/********************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._

object A extends App {

  val H = Array.ofDim[Boolean](51)
  val V = Array.ofDim[Boolean](51)

  def needWork(h: Int, v: Int) = {
    if (H(h) || V(v)) {
      false
    } else {
      H(h) = true
      V(v) = true
      true
    }
  }

  val n = readInt()
  val answer = new ArrayBuffer[Int]
  for (i <- 1 to n*n) {
    val Array(h, v) = readLine().split(" ").map(_.toInt)
    if (needWork(h, v)) answer += i
  }

  println(answer.mkString(" "))

}

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

object A_Asphalt {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    val hor = Array.fill(number+1)(false)
    val ver = Array.fill(number+1)(false)

    var res = new StringBuffer();
    for (i <- 0 until number*number) {
      val line = br.readLine().split(" ")
      val h = line(0).toInt
      val v = line(1).toInt
      if (!hor(h) && !ver(v)) {
        res.append(i+1).append(" ")
        hor(h) = true
        ver(v) = true
      }
    }

    println(res)

    //---------------------------- parameters reading end --------------------------------

  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var visited = Set.empty[Int]
  val n = in.next().toInt
  val res = (1 to n * n).filter { i =>
    val Array(x, y) = in.next().split(" ").map(_.toInt)
    if (visited.contains(x) || visited.contains(y))
      false
    else {
      visited += x
      visited += y
      true
    }
  }
  println(res.mkString(" "))
}

object A583 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val row = Array.fill[Boolean](n)(false)
    val col = Array.fill[Boolean](n)(false)
    var res = Array.empty[Int]
    for(i <- 0 until n*n) {
      val arr = readInts(2)
      if(!row(arr(0)-1) && !row(arr(1)-1)) {
        row(arr(0)-1) = true
        row(arr(1)-1) = true
        res = res ++ Array(i+1)
      }
    }
    println(res.mkString(" "))
  }
}


It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?

First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).  Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).

Output a single integer — the minimum day at which Borya can visit the last doctor.

NoteIn the first sample case, Borya can visit all doctors on days 2, 3 and 4.In the second sample case, Borya can visit all doctors on days 10 and 11.

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

  override def apply(io: IO): io.type = {
    val doctors = io.read[Seq[(Int, Int)]]
    val ans = doctors.foldLeft(0) {
      case (day, (s, d)) =>
        Iterator.from(start = (day - s)/d max 0)
          .map(i => s + i*d)
          .find(_ > day).get
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def getBit(i: Int): Int = (x >> i) & 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def getBit(i: Int): Long = (x >> i) & 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative.getOrElse(f)   //e.g. students.indexOf("Greg").whenNegative(Int.MaxValue)
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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

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

  override def apply(io: IO): io.type = {
    val doctors = io.read[Seq[(Int, Int)]]
    val ans = doctors.foldLeft(0) {
      case (day, (s, d)) =>
        val i = (1 + (day - s)/d) max 0
        s + i*d
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def getBit(i: Int): Int = (x >> i) & 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def getBit(i: Int): Long = (x >> i) & 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative.getOrElse(f)   //e.g. students.indexOf("Greg").whenNegative(Int.MaxValue)
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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