A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".

The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.

Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var k = in.next().toInt
  val str = in.next().map(_.asDigit)

  if (k == 0) {
    val (sum, soFar) = str.foldLeft(0l, 0l) {
      case ((sum, soFar), 0) => (sum, soFar + 1)
      case (acc@(sum, 0), 1) => acc
      case ((sum, soFar), 1) => (sum + soFar * (soFar + 1) / 2, 0)
    }
    if (soFar == 0)
      println(sum)
    else
      println(sum + soFar * (soFar + 1) / 2)
  }
  else {
    val answer = Array.ofDim[Int](str.sum + 1)

    str.scanLeft(0) {
      _ + _
    }.tail.foreach {
      i => answer(i) += 1
    }

    answer(0) += 1
    println(answer.indices.foldLeft(0l) {
      case(acc, i) => acc + (if ((i + k) > answer.length - 1) 0 else answer(i).toLong * answer(i + k))
    })
  }

}

object C165 {

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

  def main(args: Array[String]): Unit = {
    val Array(k) = readInts(1)
    val str = read
    val sum = Array.fill(str.length+1)(0)
    val cntSum = Array.fill(str.length+10)(0L)
    sum(0) = 0
    cntSum(0) += 1
    for(i <- 0 until str.length) {
      sum(i+1) = sum(i) + str(i)-'0'
      cntSum(sum(i+1)) += 1
    }

    var res = 0L
    for(i <- cntSum.indices if i+k < cntSum.length)
      if(k == 0)
        res += cntSum(i)*(cntSum(i)-1)/2
      else
        res += cntSum(i)*cntSum(i+k)
    out.println(res)

    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(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 Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val k = in.next().toInt
  val str = in.next().map(_.asDigit)
  val answer = Array.ofDim[Int](str.sum + 1)

  str.scanLeft(0){_+_}.tail.foreach {
    i => answer(i) += 1
  }
  answer(0) += 1
  println(answer.indices.map{
    i => if ((i + k) > answer.length - 1) 0 else answer(i) * answer(i + k)
  }.sum)

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var k = in.next().toInt
  val str = in.next().map(_.asDigit)

  if (k == 0) {
    val (sum, soFar) = str.foldLeft(0l, 0l) {
      case ((sum, soFar), 0) => (sum, soFar + 1)
      case (acc@(sum, 0), 1) => acc
      case ((sum, soFar), 1) => (sum + soFar * (soFar + 1) / 2, 0)
    }
    if (soFar == 0)
      println(sum)
    else
      println(sum + soFar * (soFar + 1) / 2)
  }
  else {
    val answer = Array.ofDim[Int](str.sum + 1)

    str.scanLeft(0) {
      _ + _
    }.tail.foreach {
      i => answer(i) += 1
    }

    answer(0) += 1
    println(answer.indices.map {
      i => if ((i + k) > answer.length - 1) 0 else answer(i) * answer(i + k)
    }.sum)
  }

}

object C165 {

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

  def main(args: Array[String]): Unit = {
    val Array(k) = readInts(1)
    val str = read
    val sum = Array.fill(str.length+1)(0)
    val cntSum = cu.Map.empty[Int, Int].withDefaultValue(0)
    sum(0) = 0
    cntSum(0) += 1
    for(i <- 0 until str.length) {
      sum(i+1) = sum(i) + str(i)-'0'
      cntSum(sum(i+1)) += 1
    }
    var res = 0L
    for(i <- 0 until 1000000)
      if(k == 0)
        res += cntSum(i)*(cntSum(i)-1)/2
      else
        res += cntSum(i)*cntSum(i+k)
    println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(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 C165 {

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

  def main(args: Array[String]): Unit = {
    val Array(k) = readInts(1)
    val str = read
    val sum = Array.fill(str.length+1)(0)
    val cntSum = cu.Map.empty[Int, Int].withDefaultValue(0)
    sum(0) = 0
    cntSum(0) += 1
    for(i <- 0 until str.length) {
      sum(i+1) = sum(i) + str(i)-'0'
      cntSum(sum(i+1)) += 1
    }
    var res = 0L
    for(i <- 0 until 1000000)
      res += cntSum(i)*cntSum(i+k)
    println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(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 Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var k = in.next().toInt
  val str = in.next().map(_.asDigit)

  def factorial(i: Int): Long = {
    (2 to i).foldLeft(1l) {
      case(acc, i) => acc * i
    }
  }

  if (k == 0) {
    val (sum, soFar) = str.foldLeft(0l, 0) {
      case ((sum, soFar), 0) => (sum, soFar + 1)
      case (acc@(sum, 0), 1) => acc
      case ((sum, soFar), 1) => (sum + factorial(soFar), 0)
    }
    if (soFar == 0)
      println(sum)
    else
      println(sum + factorial(soFar))
  }
  else {
    val answer = Array.ofDim[Int](str.sum + 1)

    str.scanLeft(0) {
      _ + _
    }.tail.foreach {
      i => answer(i) += 1
    }

    answer(0) += 1
    println(answer.indices.map {
      i => if ((i + k) > answer.length - 1) 0 else answer(i) * answer(i + k)
    }.sum)
  }

}


The GCD table G of size n × n for an array of positive integers a of length n is defined by formula   Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows:  Given all the numbers of the GCD table G, restore array a.

The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a.  All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.

In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.

import scala.collection.immutable.TreeMap
import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  var queue = TreeMap.empty[Int, Int]
  val data = in.next().split(' ').map(_.toInt).foreach{
    i => queue += (i -> (queue.getOrElse(i, 0) + 1))
  }

  def remove(map: TreeMap[Int, Int], number: Int) = {
    val quantity = map(number)
    if (quantity == 1)
      map - number
    else
      map + (number -> (quantity - 1))
  }

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

  var result = List.empty[Int]
  while (queue.nonEmpty) {
    val (value, _) = queue.last
    queue = remove(queue, value)
    result.foreach{
      i =>
        val gc = gcd(value, i)
        queue = remove(queue, gc)
        queue = remove(queue, gc)
    }
    result ::= value
  }
  println(result.mkString(" "))
}

import scala.collection._

object A extends App {

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

  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)

  val Array(n) = readInts(1)
  val gs = readInts(n * n).sorted.reverse
  val as = Array.ofDim[Int](n)

  val cnts = mutable.Map.empty[Int, Int]
  for (g <- gs) {
    if (cnts.contains(g)) cnts(g) = cnts(g) + 1
    else cnts(g) = 1
  }

  var i = 0
  for (g <- gs) {
    if (cnts(g) > 0) {
      as(i) = g
      for (j <- 0 to i) {
        val a = as(j)
        val gg = gcd(a, g)
        assert(cnts(gg) > 0)
        cnts(gg) = cnts(gg) - (if (j == i) 1 else 2)
      }
      i += 1
    }
  }

  println(as.mkString(" "))
}

import scala.io.StdIn._

object C extends App {

  def gcd(a: Int, b: Int): Int = if (b == 0) a.abs else gcd(b, a % b)

  val n = readInt()
  val A = readLine().split(" ").map(_.toInt).sortWith(_ < _)

  val S = new collection.mutable.Stack[Int]

  for (x <- A) {
    S.push(x)
  }

  val Counter = collection.mutable.Map(A.groupBy(identity).map(t => (t._1, t._2.length)).toSeq: _*)
  val GCD = Array.ofDim[Int](n, n)

  val answer = new scala.collection.mutable.ArrayBuffer[Int]
  var size = 0
  while (!S.isEmpty) {
    val curr = S.pop()
    if (Counter(curr) > 0) {
      GCD(answer.length)(answer.length) = curr
      Counter(curr) -= 1
      val j = size
      for {
        i <- 0 until size
        if i != j
      } {
        val a = GCD(i)(i)
        val b = GCD(j)(j)
        GCD(i)(j) = gcd(a, b)
        Counter(GCD(i)(j)) -= 2
        GCD(j)(i) = GCD(i)(j)
      }

      answer += curr
      size += 1
    }
  }

  println(answer.mkString(" "))

}


You are given an array $$$a$$$ of $$$n$$$ positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that $$$a_1 < a_2 < \dots < a_n$$$ holds.

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

For each test case, output "YES" (without quotes) if the array satisfies the condition, and "NO" (without quotes) otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case any rearrangement will keep the array $$$[1,1,1,1]$$$, which is not strictly increasing.In the second test case, you can make the array $$$[1,3,4,7,8]$$$.

object HelloWorld {

  def main(args: Array[String]): Unit = {
    val tests = scala.io.StdIn.readInt()
    for (t <- 1 to tests) {
      scala.io.StdIn.readLine()
      val array = scala.io.StdIn.readLine().split(" ").map(_.toInt)

      if (array.distinct.size == array.size) println("YES") else println("NO")
    }
  }
}

object Increasing {

    def solve_test() = {
        val _ = scala.io.StdIn.readInt()
        val a = scala.io.StdIn.readLine().split(' ').map(_.toInt).sorted.toList
        def exists_same_elements(xs: List[Int]): Boolean = {
            xs match {
                case Nil => return false
                case x :: Nil => return false
                case x :: y :: lst =>
                    if (x == y)
                        return true
                    else
                        exists_same_elements(y :: lst)
            }
        }
        if (exists_same_elements(a))
            println("NO")
        else
            println("YES")
    }

    def main (args: Array[String]): Unit = {
        val test = scala.io.StdIn.readInt()
        for (i <- 0 until test) solve_test()
    }
}


One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple.Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column.Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps).A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step.Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.

The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).

Print the single number — the number of steps Vasya had made. 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.

NoteIn the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0,  - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps.In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.

import java.io.BufferedReader
import java.util.StringTokenizer

/**
 *
 * @author Vladislav Isenbaev (vladislav.isenbaev@odnoklassniki.ru)
 */

object CF152B extends App {

  def main() {
    val n = nextInt()
    val m = nextInt()
    var x: Long = nextInt() - 1
    var y: Long = nextInt() - 1
    var ans = 0L
    for (it <- 0 until nextInt()) {
      val dx = nextInt()
      val dy = nextInt()
      val stepsX = if (dx == 0) Long.MaxValue else if (dx > 0) (n - x - 1) / dx else x / (-dx)
      val stepsY = if (dy == 0) Long.MaxValue else if (dy > 0) (m - y - 1) / dy else y / (-dy)
      val steps = stepsX min stepsY
      ans += steps
      x += dx * steps
      y += dy * steps
    }
    println(ans)
  }

  class Tokenizer(in: BufferedReader, pattern: String = " \t\n\r\f") {
    private def tokenizer = new StringTokenizer(_: String, pattern)
    var st: StringTokenizer = tokenizer("")
    def nextLine() = in.readLine()
    def nextToken(): String = {
      while (!st.hasMoreTokens) {
        val line = nextLine()
        if (line == null) return null
        st = tokenizer(line)
      }
      st.nextToken()
    }
    def next[A](f: String => A): A = f(nextToken())
  }

  implicit val tokenizer = new Tokenizer(Console.in)

  implicit def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
  implicit def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
  implicit def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
  implicit def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
  implicit def nextString()(implicit t: Tokenizer) = t.next(identity[String])

  def nextSeq[A](len: Int = nextInt())(implicit c: () => A): Seq[A] = for (i <- 0 until len) yield c()

  main()
}


A class of students wrote a multiple-choice test.There are $$$n$$$ students in the class. The test had $$$m$$$ questions, each of them had $$$5$$$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $$$i$$$ worth $$$a_i$$$ points. Incorrect answers are graded with zero points.The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of students in the class and the number of questions in the test. Each of the next $$$n$$$ lines contains string $$$s_i$$$ ($$$|s_i| = m$$$), describing an answer of the $$$i$$$-th student. The $$$j$$$-th character represents the student answer (A, B, C, D or E) on the $$$j$$$-th question. The last line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \le a_i \le 1000$$$) — the number of points for the correct answer for every question.

Print a single integer — the maximum possible total score of the class.

NoteIn the first example, one of the most optimal test answers is "ABCD", this way the total number of points will be $$$16$$$.In the second example, one of the most optimal test answers is "CCC", this way each question will be answered by exactly one student and the total number of points is $$$5 + 4 + 12 = 21$$$.

import scala.io.StdIn._

object A_1201 extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val C           = Array.ofDim[Int](m, 5)

  0 until n foreach { _ =>
    readLine().toCharArray.zipWithIndex.foreach {
      case (ch, j) =>
        C(j)(ch - 'A') += 1
    }
  }

  val W = readLine().split(" ").map(_.toInt) ++ Array(0, 0, 0, 0, 0)

  var counter = 0
  0 until m foreach { j =>
    counter += C(j).max * W(j)
  }

  println(counter)
}


In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:  overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.

The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.

Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val result = Array.ofDim[Int](n)
  val data = (1 to m).foreach { _ =>
    val Array(a, b, c) = in.next().split(' ').map(_.toInt - 1)
    if (result(a) != 0) {
      result(b) = result(a) % 3 + 1
      result(c) = (result(a) + 1) % 3 + 1
    } else if (result(b) != 0) {
      result(a) = result(b) % 3 + 1
      result(c) = (result(b) + 1) % 3 + 1
    } else if (result(c) != 0) {
      result(a) = result(c) % 3 + 1
      result(b) = (result(c) + 1) % 3 + 1
    } else {
      result(a) = 1
      result(b) = 2
      result(c) = 3
    }
  }
  println(result.mkString(" "))
}

import scala.collection._

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  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, m) = readInts(2)

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

  for (i <- 0 until m) {
    val dancers = readInts(3).map(_ - 1)
    val danced = dancers.indexWhere(color(_) > 0)
    if (danced < 0) {
      for (d <- 0 to 2) color(dancers(d)) = d + 1
    } else {
      var c = color(dancers(danced))
      for (d <- 0 to 2) {
        if (d != danced) {
          c = if (c == 3) 1 else c + 1
          color(dancers(d)) = c
        }
      }
    }
  }

  println(color.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){
    case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)
      map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +
            (b -> ((a, c) :: map.getOrElse(b, Nil))) +
            (c -> ((a, b) :: map.getOrElse(c, Nil)))
  }
  val result = Array.ofDim[Int](n)
  data.foreach {
    case (k, list) if result(k - 1) == 0 =>
      result(k - 1) = 1
      list.foreach{
        case(first, second) =>
          result(first - 1) = 2
          result(second - 1) = 3
      }
    case (k, list) =>
  }
  println(result.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){
    case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)
      map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +
            (b -> ((a, c) :: map.getOrElse(b, Nil))) +
            (c -> ((a, b) :: map.getOrElse(c, Nil)))
  }
  val result = Array.ofDim[Int](n)
//  data.foreach(println)
  data.foreach {
    case (k, list) if result(k - 1) == 0 =>
//      println(result.mkString(" "))
      result(k - 1) = 1
      list.foreach {
        case(first, second) if result(first - 1) == 3 || result(second - 1) == 2 =>
          result(second - 1) = 2
          result(first - 1) = 3
        case(first, second) =>
          result(first - 1) = 2
          result(second - 1) = 3
      }
    case (k, list) =>
  }
  println(result.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){
    case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)
      map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +
            (b -> ((a, c) :: map.getOrElse(b, Nil))) +
            (c -> ((a, b) :: map.getOrElse(c, Nil)))
  }
  val result = Array.ofDim[Int](n)
//  data.foreach(println)
  data.foreach {
    case (k, list) if result(k - 1) == 0 =>
      result(k - 1) = 1
      list.foreach {
        case(first, second) if result(first - 1) == 2 =>
          result(second - 1) = 3
        case(first, second) =>
          result(first - 1) = 3
          result(second - 1) = 2
      }
    case (k, list) =>
  }
  println(result.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){
    case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)
      map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +
            (b -> ((a, c) :: map.getOrElse(b, Nil))) +
            (c -> ((a, b) :: map.getOrElse(c, Nil)))
  }
  val result = Array.ofDim[Int](n)
//  data.foreach(println)
  data.foreach {
    case (k, list) if result(k - 1) == 0 =>
      println(result.mkString(" "))
      result(k - 1) = 1
      list.foreach {
        case(first, second) if result(first - 1) == 3 || result(second - 1) == 2 =>
          result(second - 1) = 2
          result(first - 1) = 3
        case(first, second) =>
          result(first - 1) = 2
          result(second - 1) = 3
      }
    case (k, list) =>
  }
  println(result.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = (1 to m).foldLeft(Map.empty[Int, List[(Int, Int)]]){
    case (map, _) => val Array(a, b, c) = in.next().split(' ').map(_.toInt)
      map + (a -> ((b, c) :: map.getOrElse(a, Nil))) +
            (b -> ((a, c) :: map.getOrElse(b, Nil))) +
            (c -> ((a, b) :: map.getOrElse(c, Nil)))
  }
  val result = Array.ofDim[Int](n)
  data.foreach {
    case (k, list) if result(k - 1) == 0 =>
      result(k - 1) = 1
      list.foreach {
        case(first, second) if result(first - 1) == 2 =>
          result(first - 1) = 3
          result(second - 1) = 2
        case(first, second) =>
          result(first - 1) = 2
          result(second - 1) = 3
      }
    case (k, list) =>
  }
  println(result.mkString(" "))
}


Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: red – brown – yellow – red – brown – yellow and so on. There are many chandeliers that differs in color set or order of colors. And the person responsible for the light made a critical mistake — they bought two different chandeliers.Since chandeliers are different, some days they will have the same color, but some days — different. Of course, it looks poor and only annoys Vasya. As a result, at the $$$k$$$-th time when chandeliers will light with different colors, Vasya will become very angry and, most probably, will fire the person who bought chandeliers.Your task is to calculate the day, when it happens (counting from the day chandeliers were installed). You can think that Vasya works every day without weekends and days off.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 500\,000$$$; $$$1 \le k \le 10^{12}$$$) — the number of colors in the first and the second chandeliers and how many times colors should differ to anger Vasya. The second line contains $$$n$$$ different integers $$$a_i$$$ ($$$1 \le a_i \le 2 \cdot \max(n, m)$$$) that describe the first chandelier's sequence of colors. The third line contains $$$m$$$ different integers $$$b_j$$$ ($$$1 \le b_i \le 2 \cdot \max(n, m)$$$) that describe the second chandelier's sequence of colors. At the $$$i$$$-th day, the first chandelier has a color $$$a_x$$$, where $$$x = ((i - 1) \mod n) + 1)$$$ and the second one has a color $$$b_y$$$, where $$$y = ((i - 1) \mod m) + 1)$$$. It's guaranteed that sequence $$$a$$$ differs from sequence $$$b$$$, so there are will be days when colors of chandeliers differs.

Print the single integer — the index of day when Vasya will become angry.

NoteIn the first example, the chandeliers will have different colors at days $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. That's why the answer is $$$5$$$.

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(mg, ng)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    var i = 0
    while (i < bs.length) {
      dayByD(bs(i)) = i
      i += 1
    }

    val xs = Array.ofDim[Long](n.toInt)

    var aDay = 0
    while (aDay < as.length) {
      val a = as(aDay)
      val bDay = dayByD(a)

      if (aDay % g == bDay % g) {
        val x0 = (bDay / g + mg * ((aDay / g - bDay / g + l) * mInv % ng)) % l
        xs(aDay) = (x0 * g + aDay % g) % l
      } else dayByD(a) = -1

      aDay += 1
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      val timeDivL = time / l
      val timeModL = time % l
      var aDay = 0

      while (aDay < n) {

        if (dayByD(as(aDay)) != -1) {
          same += timeDivL
          if (xs(aDay) < timeModL) same += 1
        }

        aDay += 1
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, k * (n + m) + 1)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(mg, ng)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    var i = 0
    while (i < bs.length) {
      dayByD(bs(i)) = i
      i += 1
    }

    val xs = Array.ofDim[Long](n.toInt)

    var aDay = 0
    while (aDay < as.length) {
      val a = as(aDay)
      val bDay = dayByD(a)

      if (aDay % g == bDay % g) {
        val x0 = (bDay / g + mg * ((aDay / g - bDay / g + l) * mInv % ng)) % l
        xs(aDay) = (x0 * g + aDay % g) % l
      } else dayByD(a) = -1

      aDay += 1
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      val timeDivL = time / l
      val timeModL = time % l
      var aDay = 0

      while (aDay < n) {

        val bDay = dayByD(as(aDay))

        if (bDay != -1) {
//          if (g > 1) {
//            if (aDay % g == bDay % g) {
              same += timeDivL
//              val x0 = (bDay + mg * ((aDay / g - bDay + l) * mInv % ng)) % l
//              val x = (x0 * g + aDay % g) % l
              if (xs(aDay) < timeModL) same += 1
//            }
//          } else {
//            same += timeDivL
//            val x = (bDay + mg * ((aDay - bDay + l) * mInv % ng)) % l
//            if (x < timeModL) same += 1
//          }
        }

        aDay += 1
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, k * (n + m) + 1)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(mg, ng)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    var i = 0
    while (i < bs.length) {
      dayByD(bs(i)) = i
      i += 1
    }

    val xs = Array.ofDim[Long](n.toInt)

    var aDay = 0
    while (aDay < as.length) {
      val a = as(aDay)
      val bDay = dayByD(a)
//      if (aDay % g == bDay % g) {
//        dayByD(a) /= g
//      } else dayByD(a) = -1

      val x0 = (bDay / g + mg * ((aDay / g - bDay / g + l) * mInv % ng)) % l
      xs(aDay) = (x0 * g + aDay % g) % l

      aDay += 1
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      val timeDivL = time / l
      val timeModL = time % l
      var aDay = 0

      while (aDay < n) {

        val bDay = dayByD(as(aDay))

        if (bDay != -1) {
//          if (g > 1) {
//            if (aDay % g == bDay % g) {
              same += timeDivL
//              val x0 = (bDay + mg * ((aDay / g - bDay + l) * mInv % ng)) % l
//              val x = (x0 * g + aDay % g) % l
              if (xs(aDay) < timeModL) same += 1
//            }
//          } else {
//            same += timeDivL
//            val x = (bDay + mg * ((aDay - bDay + l) * mInv % ng)) % l
//            if (x < timeModL) same += 1
//          }
        }

        aDay += 1
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, k * (n + m) + 1)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(mg, ng)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          if (m == n && aDay == bDay) {
            same += time / l
            val x = aDay
            if (x < time % l) same += 1
          } else if (aDay % g == bDay % g) {
            same += time / l
//            val x = bDay * ng + aDay * mg
            val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)
            val x = (x0 * g + aDay % g) % (l)
//            println(g, x0, x)
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)
//          println(g, aDay, bDay, mInv, x)
          if (x % l < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(mg, ng)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          if (aDay == bDay) {
            same += time / l
            val x = aDay
            if (x < time % l) same += 1
          } else if (aDay % g == bDay % g) {
            same += time / l
//            val x = bDay * ng + aDay * mg
            val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)
            val x = (x0 * g + aDay % g) % (l)
//            println(g, x0, x)
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)
//          println(g, aDay, bDay, mInv, x)
          if (x % l < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(mg, ng)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          /*if (aDay == bDay) {
            same += time / l
            val x = aDay
            if (x < time % l) same += 1
          } else */if (aDay % g == bDay % g) {
            same += time / l
//            val x = bDay * ng + aDay * mg
            val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)
            val x = (x0 * g + aDay % g) % (l)
//            println(g, x0, x)
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)
//          println(g, aDay, bDay, mInv, x)
          if (x % l < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(mg, ng)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          /*if (aDay == bDay) {
            same += time / l
            val x = aDay
            if (x < time % l) same += 1
          } else */if (aDay % g == bDay % g) {
            same += time / l
//            val x = bDay * ng + aDay * mg
            val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)
            val x = (x0 * g + aDay % g) % (l)
//            println(g, x0, x)
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)
//          println(g, aDay, bDay, mInv, x)
          if (x < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(mg, ng)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          /*if (aDay == bDay) {
            same += time / l
            val x = aDay
            if (x < time % l) same += 1
          } else */if (aDay % g == bDay % g) {
            same += time / l
//            val x = bDay * ng + aDay * mg
            val x0 = (bDay / g + mg * ((aDay / g - bDay / g) * mInv % ng)) % (mg * ng)
            val x = x0 * g + aDay % g
//            println(g, x0, x)
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * ((aDay - bDay) * mInv % ng)) % (mg * ng)
//          println(g, aDay, bDay, mInv, x)
          if (x < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(mg, ng)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          /*if (aDay == bDay) {
            same += time / l
            val x = aDay
            if (x < time % l) same += 1
          } else */if (aDay % g == bDay % g) {
            same += time / l
//            val x = bDay * ng + aDay * mg
            val x0 = (bDay / g + mg * (aDay / g - bDay / g) * mInv % ng) % (mg * ng)
            val x = x0 * g + aDay % g
//            println(x)
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)
          if (x < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(m, n)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          /*if (aDay == bDay) {
            same += time / l
            val x = aDay
            if (x < time % l) same += 1
          } else */if (aDay % g == bDay % g) {
            same += time / l
//            val x = bDay * ng + aDay * mg
            val x0 = (bDay / g + mg * (aDay / g - bDay / g) * mInv % ng) % (mg * ng)
            val x = x0 * g + aDay % g
//            println(x)
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)
          if (x < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(m, n)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          if (aDay == bDay) {
            same += time / l
            val x = aDay
            if (x < time % l) same += 1
          } else if (aDay % g == bDay % g) {
            same += time / l
            val x = bDay * ng + aDay * mg
//            val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)
//            println(x)
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)
          if (x < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(m, n)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1L)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          if (aDay % g == bDay % g) {
            same += time / l
            val x = (bDay * n + aDay * m) / g
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)
          if (x < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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

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

    def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
    def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    def modInverse(a: Long, m: Long): Long = {

      def modInv(a: Long, m: Long, x: Long, y: Long): Long =
        if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

      val inv = modInv(a, m, 1, 0)
      if (inv < 0) inv + m else inv
    }

    val _n, _m, k = nextLong
    val _as = nextInts(_n.toInt)
    val _bs = nextInts(_m.toInt)

    val n = _n max _m
    val m = _n min _m
    val as = if (_n < _m) _bs else _as
    val bs = if (_n < _m) _as else _bs
    val g = gcd(n, m)
    val l = lcm(n, m)
    val ng = n / g
    val mg = m / g

    val mInv = modInverse(m, n)

    val dayByD = Array.fill(Math.max(as.max, bs.max) + 1)(-1)
    for (i <- bs.indices) {
      dayByD(bs(i)) = i
    }

    def countDiff(time: Long): Long = {
      var same = 0L
      for (aDay <- as.indices) {
        val a = as(aDay)
        val bDay = dayByD(a)
        if (bDay == -1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
        } else if (g > 1) {
//          diff += time / n
//          if (aDay < time % n) diff += 1
          if (aDay % g == bDay % g) {
            same += time / l
            val x = (bDay * n + aDay * m) / g
            if (x < time % l) same += 1
          }
        } else {
          same += time / l
          val x = (bDay + mg * (aDay - bDay) * mInv % ng) % (mg * ng)
          if (x < time % l) same += 1
        }
      }
      time - same
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (countDiff(mid) >= k) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, Long.MaxValue/2)

    out.println(res)

    out.flush()
  }

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


Let's denote correct match equation (we will denote it as CME) an equation $$$a + b = c$$$ there all integers $$$a$$$, $$$b$$$ and $$$c$$$ are greater than zero.For example, equations $$$2 + 2 = 4$$$ (||+||=||||) and $$$1 + 2 = 3$$$ (|+||=|||) are CME but equations $$$1 + 2 = 4$$$ (|+||=||||), $$$2 + 2 = 3$$$ (||+||=|||), and $$$0 + 1 = 1$$$ (+|=|) are not.Now, you have $$$n$$$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if $$$n = 2$$$, you can buy two matches and assemble |+|=||, and if $$$n = 5$$$ you can buy one match and assemble ||+|=|||.   Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. The only line of each query contains one integer $$$n$$$ ($$$2 \le n \le 10^9$$$) — the number of matches.

For each test case print one integer in single line — the minimum number of matches which you have to buy for assembling CME.

NoteThe first and second queries are explained in the statement.In the third query, you can assemble $$$1 + 3 = 4$$$ (|+|||=||||) without buying matches.In the fourth query, buy one match and assemble $$$2 + 4 = 6$$$ (||+||||=||||||).

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

  override def apply(io: IO): io.type = {
    val matches = io.read[Seq[Int]]
    val ans = matches map {m => if (m <= 4) 4-m else m%2}
    io.writeAll(ans, separator = "\n")
  }
}
/****************************[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 = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn

object Codeforces1223A extends App {
  var q = StdIn.readLine().toInt
  while (q > 0) {
    val n = StdIn.readLine().toInt
    if (n < 4) {
      println((4 - n))
    } else {
      println(n % 2)
    }
    q -= 1
  }
}


You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.You must paint a fence which consists of $$$10^{100}$$$ planks in two colors in the following way (suppose planks are numbered from left to right from $$$0$$$):   if the index of the plank is divisible by $$$r$$$ (such planks have indices $$$0$$$, $$$r$$$, $$$2r$$$ and so on) then you must paint it red;  if the index of the plank is divisible by $$$b$$$ (such planks have indices $$$0$$$, $$$b$$$, $$$2b$$$ and so on) then you must paint it blue;  if the index is divisible both by $$$r$$$ and $$$b$$$ you can choose the color to paint the plank;  otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it). Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are $$$k$$$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. The next $$$T$$$ lines contain descriptions of test cases — one per line. Each test case contains three integers $$$r$$$, $$$b$$$, $$$k$$$ ($$$1 \le r, b \le 10^9$$$, $$$2 \le k \le 10^9$$$) — the corresponding coefficients.

Print $$$T$$$ words — one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.

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

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

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()) { _ =>
      var a, b, k = ni()
      // a <= b
      if (a > b) {
        val t = a
        a = b
        b = t
      }
      val g = gcd(a, b)
      a /= g
      b /= g
      val c = (b - 1 + a - 1) / a // b-1に切り上げでaが何個入るか
      debug(s"a:$a b:$b c:$c")
      if (c >= k) out.println("REBEL")
      else out.println("OBEY")
    }
  }
}


There are $$$n$$$ boxes with different quantities of candies in each of them. The $$$i$$$-th box has $$$a_i$$$ candies inside.You also have $$$n$$$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none) candies from each box so that all boxes have the same quantity of candies in them. Note that you may eat a different number of candies from different boxes and you cannot add candies to any of the boxes.What's the minimum total number of candies you have to eat to satisfy the requirements?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the number of boxes you have. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the quantity of candies in each box.

For each test case, print a single integer denoting the minimum number of candies you have to eat to satisfy the requirements.

NoteFor the first test case, you can eat $$$1$$$ candy from the second box, $$$2$$$ candies from the third box, $$$3$$$ candies from the fourth box and $$$4$$$ candies from the fifth box. Now the boxes have $$$[1, 1, 1, 1, 1]$$$ candies in them and you ate $$$0 + 1 + 2 + 3 + 4 = 10$$$ candies in total so the answer is $$$10$$$.For the second test case, the best answer is obtained by making all boxes contain $$$5$$$ candies in them, thus eating $$$995 + 995 + 0 + 995 + 995 + 995 = 4975$$$ candies in total.

object EqualCandies {
  def main (args: Array[String]) = {
    val tests = io.StdIn.readInt
    for (_ <- 1 to tests) {
      val n = io.StdIn.readInt
      val a = io.StdIn.readLine.split(" ").map(Integer.parseInt(_))
      val minimum = a.min
      val out = a.fold(0)(_ + _ - minimum)
      println(out)
    }
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Indices of the array start from zero (i. e. the first element is $$$a_0$$$, the second one is $$$a_1$$$, and so on).You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of $$$a$$$ with borders $$$l$$$ and $$$r$$$ is $$$a[l; r] = a_l, a_{l + 1}, \dots, a_{r}$$$.Your task is to reverse such a subarray that the sum of elements on even positions of the resulting array is maximized (i. e. the sum of elements $$$a_0, a_2, \dots, a_{2k}$$$ for integer $$$k = \lfloor\frac{n-1}{2}\rfloor$$$ should be maximum possible).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_0, a_1, \dots, a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer on the separate line — the maximum possible sum of elements on even positions after reversing at most one subarray (continuous subsegment) of $$$a$$$.

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

  def kadane(an: Seq[Int]): Long = an match {
    case a +: _ =>
      an.foldLeft((a.toLong, 0L)) {
          case ((subSum, partSum), a) =>
            (subSum max (partSum + a), 0L max (partSum + a))
        }
        ._1
    case _ => 0L
  }

  val t = readInt()

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

    val ans = n match {
      case 1 => an.head
      case _ =>
        val evens = an.zipWithIndex.collect { case (a, i) if i % 2 == 0 => a }
        val base  = evens.foldLeft(0L)(_ + _)
        val odds  = an.zipWithIndex.collect { case (a, i) if i % 2 == 1 => a }

        val d1 = evens.zip(odds).map { case (e, o)      => o - e }
        val d2 = odds.zip(evens.tail).map { case (o, e) => o - e }

        val profit = 0L max kadane(d1) max kadane(d2)

        base + profit
    }

    println(ans)
  }
}

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

  def kadane(an: Seq[Int]): Long = an match {
    case a +: _ =>
      an.foldLeft((a.toLong, 0L)) {
          case ((subSum, partSum), a) =>
            (subSum max (partSum + a), 0L max (partSum + a))
        }
        ._1
    case _ => 0L
  }

  val t = readInt()

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

    val ans = n match {
      case 1 => an.head
      case _ =>
        val evens = an.zipWithIndex.collect { case (a, i) if i % 2 == 0 => a }
        val odds  = an.zipWithIndex.collect { case (a, i) if i % 2 == 1 => a }

        val d1 = evens.zip(odds).map { case (e, o)      => o - e }
        val d2 = odds.zip(evens.tail).map { case (o, e) => o - e }

        val profit = kadane(d1) max kadane(d2)

        evens.foldLeft(0L)(_ + _) + (0L max profit)
    }

    println(ans)
  }
}

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

  def kadane(an: Seq[Int]): Int = an match {
    case a +: _ =>
      an.foldLeft((a, 0)) {
          case ((subSum, partSum), a) =>
            (subSum max (partSum + a), 0 max (partSum + a))
        }
        ._1
    case _ => 0
  }

  val t = readInt()

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

    val ans = n match {
      case 1 => an.head
      case _ =>
        val evens = an.zipWithIndex.collect { case (a, i) if i % 2 == 0 => a }
        val odds  = an.zipWithIndex.collect { case (a, i) if i % 2 == 1 => a }

        val d1 = evens.zip(odds).map { case (e, o)      => o - e }
        val d2 = odds.zip(evens.tail).map { case (o, e) => o - e }

        val profit = kadane(d1) max kadane(d2)

        evens.sum + (0 max profit)
    }

    println(ans)
  }
}


Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.At each step he selects one of his guests A, who pairwise introduces all of his friends to each other. After this action any two friends of A become friends. This process is run until all pairs of guests are friends.Arseny doesn't want to spend much time doing it, so he wants to finish this process using the minimum number of steps. Help Arseny to do it.

The first line contains two integers n and m (1 ≤ n ≤ 22; ) — the number of guests at the party (including Arseny) and the number of pairs of people which are friends. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n; u ≠ v), which means that people with numbers u and v are friends initially. It's guaranteed that each pair of friends is described not more than once and the graph of friendship is connected.

In the first line print the minimum number of steps required to make all pairs of guests friends. In the second line print the ids of guests, who are selected at each step. If there are multiple solutions, you can output any of them.

NoteIn the first test case there is no guest who is friend of all other guests, so at least two steps are required to perform the task. After second guest pairwise introduces all his friends, only pairs of guests (4, 1) and (4, 2) are not friends. Guest 3 or 5 can introduce them.In the second test case guest number 1 is a friend of all guests, so he can pairwise introduce all guests in one step.

import java.util

import scala.collection.mutable
import scala.io.StdIn

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  def doCase() : Unit = {
    val Array(n, m) = readIntLine()

    val adj = Array.fill(n){0}
    for (_ <- 0 until m) {
      var Array(u, v) = readIntLine()
      u -= 1
      v -= 1
      adj(u) |= 1 << v
      adj(v) |= 1 << u
    }
    val complete = (1 << n) - 1
    val isClique = adj.indices.forall {
      i =>
        (adj(i) | (1 << i)) == complete
    }

    if (isClique) {
      println(0)
      println("")
      return
    }

    val dp = Array.fill(1 << n){null : (Int, List[Int])}

    var (cost, path) = adj.indices.map {
      i =>
        val set = 1 << i
        dyn(set, 0, adj, dp, complete, adj.length)
    }.minBy(_._1)

    println(cost)
    println(path.map(_ + 1).toArray.mkString(" "))
  }

  def dyn(set : Int, cost : Int, adj : Array[Int], dp : Array[(Int, List[Int])], complete : Int, l : Int) : (Int, List[Int]) = {
    if (set == complete) {
      return (0, List())
    }
    if (dp(set) == null) {
      var best = (Int.MaxValue, List() : List[Int])
      var i = 0
      while (i < l) {
        val newSet = adj(i) | set
        if (((1 << i) & set) > 0 &&  newSet != set) {
          val recur = dyn(newSet, cost + 1, adj, dp, complete, l)
          if (recur._1 < best._1) {
            best = (recur._1 + 1, i :: recur._2)
          }
        }
        i += 1
      }
      dp(set) = best
    }
    dp(set)
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
    }
  }

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

}

import scala.collection.mutable

object E extends App {

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

  val Array(n, m) = readInts(2)

  val friendsBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }

  for (_ <- 1 to m) {
    val Array(u, v) = readInts(2)
    friendsBuilders(u - 1) += v - 1
    friendsBuilders(v - 1) += u - 1
  }

  val friends = friendsBuilders.map(_.result)

  val orderBuilder = new mutable.ArrayBuilder.ofInt
  val queue = mutable.Queue(0)
  val visited = mutable.BitSet(0)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    orderBuilder += u
    for (v <- friends(u)) if (!visited(v)) {
      visited += v
      queue += v
    }
  }

  val order = orderBuilder.result()

  val goal = (1 << n) - 1
  var bestSteps = n + 1
  var bestPath = Array.empty[Int]

  val path = Array.ofDim[Int](n)

  def bit(i: Int): Int = 1 << i

  def dfs(step: Int, mask: Int, prev: Int): Unit = {
    if (step < bestSteps) {
      if (mask == goal) {
        bestSteps = step
        bestPath = path.take(step)
      } else {
        for (nextI <- prev + 1 until n) {
          val next = order(nextI)
          if ((mask & bit(next)) > 0 || step == 0) {
            var nextMask = mask | bit(next)
            for (friend <- friends(next)) nextMask |= bit(friend)
            path(step) = next
            dfs(step + 1, nextMask, nextI)
          }
        }
      }
    }
  }

  if (m < n * (n - 1) / 2) dfs(0, 0, -1)
  else bestSteps = 0

  println(bestSteps)
  println(bestPath.map(_ + 1).mkString(" "))
}

import java.util

import scala.collection.mutable
import scala.io.StdIn

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  def doCase() : Unit = {
    val Array(n, m) = readIntLine()

    val adj = Array.fill(n){0}
    for (_ <- 0 until m) {
      var Array(u, v) = readIntLine()
      u -= 1
      v -= 1
      adj(u) |= 1 << v
      adj(v) |= 1 << u
    }

    var (cost, path) = adj.indices.map {
      i => greedilyNode(i, adj)
    }.minBy(_._1)
    println(cost)
    println(path.reverse.map(_ + 1).toArray.mkString(" "))

  }

  def greedilyNode(n : Int, adj : Array[Int]) : (Int, List[Int]) = {
    val l = adj.length
    var count = 0
    var set = 0
    set |= 1 << n
    var complete = (1 << l) - 1
    var path : List[Int] = List()
    while (set != complete) {
      var i = 0
      while (i < l) {
        if (((1 << i) & set) > 0 && (~set & adj(i)) > 0) {
          set |= adj(i)
          path ::= i
          count += 1
        }
        i += 1
      }
    }
    (count, path)
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
    }
  }

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

}

import scala.collection.mutable

object E extends App {

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

  val Array(n, m) = readInts(2)

  val friendsBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }

  for (_ <- 1 to m) {
    val Array(u, v) = readInts(2)
    friendsBuilders(u - 1) += v - 1
    friendsBuilders(v - 1) += u - 1
  }

  val friends = friendsBuilders.map(_.result)

  val orderBuilder = new mutable.ArrayBuilder.ofInt
  val queue = mutable.Queue(0)
  val visited = mutable.BitSet(0)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    orderBuilder += u
    for (v <- friends(u)) if (!visited(v)) {
      visited += v
      queue += v
    }
  }

  val order = orderBuilder.result()

  val goal = (1 << n) - 1
  var bestSteps = n + 1
  var bestPath = Array.empty[Int]

  val path = Array.ofDim[Int](n)

  def bit(i: Int): Int = 1 << i

  def dfs(step: Int, mask: Int, prev: Int): Unit = {
    if (step < bestSteps) {
      if (mask == goal) {
        bestSteps = step
        bestPath = path.take(step)
      } else {
        for (nextI <- prev + 1 until n) {
          val next = order(nextI)
          if ((mask & bit(next)) > 0 || step == 0) {
            var nextMask = mask | bit(next)
            for (friend <- friends(next)) nextMask |= bit(friend)
            path(step) = next
            dfs(step + 1, nextMask, nextI)
          }
        }
      }
    }
  }

  if (n > 1) dfs(0, 0, -1)
  else bestSteps = 0

  println(bestSteps)
  println(bestPath.map(_ + 1).mkString(" "))
}

import scala.collection.mutable

object E extends App {

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

  val Array(n, m) = readInts(2)

  val friendsBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }

  for (_ <- 1 to m) {
    val Array(u, v) = readInts(2)
    friendsBuilders(u - 1) += v - 1
    friendsBuilders(v - 1) += u - 1
  }

  val friends = friendsBuilders.map(_.result)

  val orderBuilder = new mutable.ArrayBuilder.ofInt
  val queue = mutable.Queue(0)
  val visited = mutable.BitSet(0)

  while (queue.nonEmpty) {
    val u = queue.dequeue()
    orderBuilder += u
    for (v <- friends(u)) if (!visited(v)) {
      visited += v
      queue += v
    }
  }

  val order = orderBuilder.result()

  val goal = (1 << n) - 1
  var bestSteps = n + 1
  var bestPath: Array[Int] = _

  val path = Array.ofDim[Int](n)

  def bit(i: Int): Int = 1 << i

  def dfs(step: Int, mask: Int, prev: Int): Unit = {
    if (step < bestSteps) {
      if (mask == goal) {
        bestSteps = step
        bestPath = path.take(step)
      } else {
        for (nextI <- prev + 1 until n) {
          val next = order(nextI)
          if ((mask & bit(next)) > 0 || step == 0) {
            var nextMask = mask | bit(next)
            for (friend <- friends(next)) nextMask |= bit(friend)
            path(step) = next
            dfs(step + 1, nextMask, nextI)
          }
        }
      }
    }
  }

  dfs(0, 0, -1)

  println(bestSteps)
  println(bestPath.map(_ + 1).mkString(" "))
}