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)
  }

}


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(" "))

}

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(" "))
}


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()
    }
}


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(" "))
}


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
  }
}


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
  }
}


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)
  }
}


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
    }
    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 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(" "))
}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()
  if (n % 2 == 0)
    println(line.grouped(2).mkString("-"))
  else
    println((line.take(3) :: line.drop(3).grouped(2).toList).mkString("-"))
}

object P025B {
  def main(argv: Array[String]) = {
    val n = readInt
    var s = readLine
    val firstWidth = n % 2 + 2
    print(s.slice(0, firstWidth))
    s = s.drop(firstWidth)
    while (s.length() > 0) {
      print('-' + s.slice(0, 2))
      s = s.drop(2)
    }
    println()
  }
}

object PhoneNo {
  def main(args: Array[String]) {
    val n = io.StdIn.readLine.toInt
    val p = io.StdIn.readLine
    if (n < 4) {
      println(p)
      return
    }
    for (i<-0 until n-3 by 2) {
      print(p.substring(i,i+2) + '-')
    }
    if (n%2 == 0) println(p.substring(n-2))
    else println(p.substring(n-3))
  }
}

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

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var number = readLine;
    if (n == 2 || n == 3) {
      println(number);
      return;
    }
    var beginInd = 0;
    if (n % 2 != 0) {
      print(number(0).toString + number(1).toString + number(2).toString);
      beginInd = 3;
      if (n > 3) {
        print("-");
      }
    }
    for (i <- beginInd until n) {
      print(number(i));
      if (beginInd == 3) {
        if (i % 2 == 0 && i < n - 1) {
	      print("-");
	    }
      } else {
        if (i % 2 > 0 && i < n - 1) {
	      print("-");
	    }
      }

    }
  }

}

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

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var number = readLine.toCharArray();
    if (n == 2 || n == 3) {
      println(number);
      return;
    }
    var beginInd = 0;
    if (n % 2 != 0) {
      print(number(0).toString + number(1).toString + number(2).toString);
      beginInd = 3;
      if (n > 3) {
        print("-");
      }
    }
    for (i <- beginInd until n) {
      print(number(i));
      if (beginInd == 3) {
        if (i % 2 == 0 && i < n - 1) {
	      print("-");
	    }
      } else {
        if (i % 2 > 0 && i < n - 1) {
	      print("-");
	    }
      }

    }
  }

}


/**
  * Created by octavian on 30/01/2016.
  */
object GuessPerm {

  def main(args: Array[String]) = {

    //System.setIn(new FileInputStream("./src/guessPerm.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/guessPerm.out")))

    val n = readInt()
    var mtx = Array.ofDim[Int](n, 0)

    //println("n is " + n)
    for(i <- 0 until n) {
      mtx(i) = readLine().split(" ").map(_.toInt)
      //println("mtx of " + i + " is " + mtx(i).mkString(" "))
    }

    var result = Array.ofDim[Int](n)
    var madeMax: Boolean = false
    for(i <- 0 until n) {
      result(i) = mtx(i).max
      //println("result of " + i + " is " + result(i))
      if(result(i) == n - 1 && madeMax == false) {
        result(i) = n
        madeMax = true
      }
    }

    println(result.mkString(" "))
  }
}

import scala.collection.mutable

object B341 {
  def main(args: Array[String]) {
    val n = scala.io.StdIn.readInt
    val a = (1 to n).map(q => scala.io.StdIn.readLine.split(" ").map(_.toInt).max).to[mutable.MutableList]
    a(a.indexOf(n-1)) = n
    println(a.mkString(" "))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  var found = false
  val data = (1 to n).map{_ =>
    val res = in.next().split(' ').map(_.toInt).max
    if (res == n - 1 && !found) {
      found = true
      n
    } else res
  }
  println(data.mkString(" "))
}

import scala.collection._

object B extends App {

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

  val Array(n) = readInts(1)
  val as = Array.fill(n) { readInts(n) }

  val res = Array.fill(n) { 0 }
  for (i <- 1 to n) {
    var maxCnt = -1
    var maxPos = -1
    for (j <- 0 until n) {
      val cnt = as(j).count(_ == i)
      if (cnt > maxCnt && res(j) == 0) {
        maxCnt = cnt
        maxPos = j
      }
    }
    //println(i, maxPos, maxCnt)
    res(maxPos) = i
  }

  println(res.mkString(" "))
}

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

object _618B extends CodeForcesApp {
  override type Result = Seq[Int]

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    var c = n-2
    (1 to n) map {i =>
      val nums = Seq.fill(n)(nextInt()).groupBy(identity).mapValues(_.size)
      nums.maxBy(_._2) match {
        case (_, 1) =>
          c = c + 1
          c
        case (x, _) => x
      }
    }
  }

  override def format(result: Seq[Int]) = result mkString " "
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

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

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()

    val perm = Array.ofDim[Int](n, n)

    for(i <- 0 until n)
      for(j <- 0 until n)
        perm(i)(j) = sc.nextInt()

    //
    var flag = false

    val z = perm(0).max
    if(z == n-1){
      flag = true
      print(z)
    }
    else
      print(z)

    for(i <- 1 until n){
      val a = perm(i).max
      print(' ')

      if(a == n-1){
        if(flag)
          print(n)
        else{
          flag = true
          print(n-1)
        }
      }
      else
        print(a)
    }

    println()
  }
}

object Runner {

  def main(args: Array[String]) = {
    val n = readLine.toInt
    var res = List[Int]()
    for (i <- 0 until n) {
      val numbers = readLine().split(" ").map(_.toInt)
      var max: Option[Int] = Option.empty
      for (j <- 0 until numbers.size) {
        if (!j.equals(i)) {
          if (max.isEmpty || max.get < numbers(j)) {
            max = Option(numbers(j))
          }
        }
      }
      res = res :+ max.get
    }
    var flag = false
    var str = new StringBuilder()
    for (i <- 0 until res.size) {
      var a = res(i)
      if (!flag && a == n - 1) {
        flag = true
        a = a + 1
      }
      str.append(a)
      if (i != res.size - 1) {
        str.append(" ")
      }
    }
    println(str)
  }
}

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

object CF2016_B {

  def main(args: Array[String]): Unit = {

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

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val arr = Array.ofDim[Int](n, n)

    for (i <- 0 until n) {
      val line = readLine
      for(j <- 0 until n) {
        arr(i)(j) = line.int
      }
    }

    val res = new Array[Int](n+1)
    for (d <- 1 to n) {
      var maxLine = -1
      var maxCount = 0
      for (i <- 0 until n) {
        var count = 0
        for (j <- 0 until n) {
          if (arr(i)(j) == d) {
        	  count += 1
          }
        }
        if (maxCount < count) {
          maxLine = i
          maxCount = count
        }
      }
      if (maxLine != -1) {
       res(d) = maxLine + 1
      }
    }

    val res2 = new Array[Int](n+1)
    for(i <- 1 to n) {
      val place = res(i)
      res2(place) = i
    }
    for(i <- 1 to n) {
      if (res2(i) == 0) {
        res2(i) = n
      }
    }

    for(i <- 1 to n) {
    	print(res2(i) + " ")
    }

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

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
5
0 2 2 1 2
2 0 4 1 3
2 4 0 1 3
1 1 1 0 1
2 3 3 1 0
"""

}

}

object Runner {

  def main(args: Array[String]) = {
    val n = readLine.toInt
    var res = List[Int]()
    for (i <- 0 until n) {
      val numbers = readLine().split(" ").map(_.toInt)
      var max: Option[Int] = Option.empty
      for (j <- 0 until numbers.size) {
        if (!j.equals(i)) {
          if (max.isEmpty || max.get < numbers(j)) {
            max = Option(numbers(j))
          }
        }
      }
      res = res :+ max.get
    }
    var str = new StringBuilder()
    for (i <- 0 until res.size) {
      str.append(res(i))
      if (i != res.size - 1) {
        str.append(" ")
      }
    }
    println(str)
  }
}


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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m, i, j) = readLine().split(" ").map(_.toInt)

    val (x1, y1) = (if (i - 1 < n - i) n else 1, if (j - 1 < m - j) m else 1)
    val (x2, y2) = (if (x1 == n) 1 else n, if (y1 == m) 1 else m)

    println(s"$x1 $y1 $x2 $y2")
  }
}

import java.io.PrintWriter
import java.util.Scanner

object Solution {
  def solve(n: Int, m: Int, i: Int, j: Int): (Int, Int, Int, Int) = {
    // he goes to one, then to second, and then come back
    // |x1-x2| + |y1-y2| <- anyway between yoyos
    // either
    //   |x1-i| + |y1-j| + |x2-i| + |y2-j|
    // or
    //   |x2-i| + |y2-j| + |x1-i| + |y1-j|
    // so no difference. i.e. it's always
    // |x1-x2| + |y1-y2| + |x1-i| + |y1-j| + |x2-i| + |y2-j|
    // i.e.
    // |x1-x2| + |x1-i| + |x2-i| +
    // |y1-y2| + |y1-j| + |y2-j| - so it's independent on coordinates
    // so seems like it's always 1 and max
    (1, 1, n, m)
  }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    val (x1, y1, x2, y2) = solve(input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt())
    output.println(s"$x1 $y1 $x2 $y2")
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m, i, j) = readLine().split(" ").map(_.toInt)

    println(s"1 1 $n $m")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m, i, j) = readLine().split(" ").map(_.toInt)

    println("1 1 n m")
  }
}