object C3 {

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

  def wins(b: Array[Array[Char]], char: Char): Boolean = {
    b.exists(_.forall(_==char)) || {
      (0 until 3).exists(j => Array(b(0)(j), b(1)(j), b(2)(j)).forall(_==char))
    } || {
      Array(b(0)(0), b(1)(1), b(2)(2)).forall(_==char)
    } || {
      Array(b(0)(2), b(1)(1), b(2)(0)).forall(_==char)
    }
  }

  def main(args: Array[String]): Unit = {
    val b = Array.fill(3)(read.toCharArray)
    val x = b.flatten.count(_ == 'X')
    val zero = b.flatten.count(_ == '0')
    if(x != zero && x != zero+1) {
      println("illegal") //also both can't win
    } else {
      if (wins(b, 'X') && wins(b, '0')) {
        println("illegal")
      } else if (wins(b, 'X')){
        if(x == zero+1)
          println("the first player won")
        else
          println("illegal")
      } else if (wins(b, '0')){
        if(x == zero)
          println("the second player won")
        else
          println("illegal")
      } else {
        if(b.flatten.contains('.')) {
          if(x == zero) {
            println("first")
          } else {
            println("second")
          }
        } else {
          println("draw")
        }
      }
    }

  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @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 cf3C extends App {
  val s = readLine + readLine + readLine
  val numX = s count {_ == 'X'}
  val num0 = s count {_ == '0'}
  val toX = numX== num0
  val to0 = numX== num0+1
  val filled = s forall {_!='.'}
  val lines = Array(
    Array(0, 1, 2), Array(3, 4, 5), Array(6, 7, 8),
    Array(0, 3, 6), Array(1, 4, 7), Array(2, 5, 8),
    Array(0, 4, 8), Array(2, 4, 6))
  val winX = lines exists {_ forall {s(_) == 'X'}}
  val win0 = lines exists {_ forall {s(_) == '0'}}
  val answer = () match {
    case _ if !toX && !to0 || toX && winX || to0 && win0 => "illegal"
    case _ if winX => "the first player won"
    case _ if win0 => "the second player won"
    case _ if filled => "draw"
    case _ if toX => "first"
    case _ if to0 => "second"
  }
  println(answer)
}

object P3C {
    def main(args : Array[String]) {
        val s = readLine + readLine + readLine
        val numX = s count {_ == 'X'}
        val num0 = s count {_ == '0'}
        val toX = numX == num0
        val to0 = numX == num0 + 1
        val filled = s forall {_ != '.'}
        val lines = Array(
            Array(0, 1, 2), Array(3, 4, 5), Array(6, 7, 8),
            Array(0, 3, 6), Array(1, 4, 7), Array(2, 5, 8),
            Array(0, 4, 8), Array(2, 4, 6))
        val winX = lines exists {_ forall {s(_) == 'X'}}
        val win0 = lines exists {_ forall {s(_) == '0'}}
        val answer = () match {
            case _ if !toX && !to0 || toX && winX || to0 && win0 => "illegal"
            case _ if winX => "the first player won"
            case _ if win0 => "the second player won"
            case _ if filled => "draw"
            case _ if toX => "first"
            case _ if to0 => "second"
        }
        println(answer)
    }
}

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach {
    i =>
      b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char): Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.zeroWon && board.count(2) > board.count(1)) {
    println("illegal")
  } else if (board.xWon && board.count(2) == board.count(1)) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int): Int = arr.flatten.count(_ == item)

    def draw: Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                      st = arr(x)(x)
                      rev = arr(x)(2 - x)} yield (st, rev)
      val res = diag.foldLeft(("", ""))((acc, t) => (acc._1 + t._1, acc._2 + t._2))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach {
    i =>
      b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char): Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.zeroWon && board.count(2) > board.count(1)) {
    println("illegal")
  } else if (board.xWon && board.count(2) == board.count(1)) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int): Int = arr.flatten.count(_ == item)

    def draw: Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                      st = arr(x)(x)
                      rev = arr(2 - x)(2 - x)} yield (st, rev)
      val res = diag.foldLeft(("", ""))((acc, t) => (acc._1 + t._1, acc._2 + t._1))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach {
    i =>
      b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char): Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.zeroWon && board.count(2) > board.count(1)) {
    println("illegal")
  } else if (board.xWon && board.count(2) == board.count(1)) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int): Int = arr.flatten.count(_ == item)

    def draw: Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                      st = arr(x)(2 - x)
                      rev = arr(2 - x)(2)} yield (st, rev)
      val res = diag.foldLeft(("", ""))((acc, t) => (acc._1 + t._1, acc._2 + t._1))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach {
    i =>
      b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char): Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.zeroWon && board.count(2) > board.count(1)) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int): Int = arr.flatten.count(_ == item)

    def draw: Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                      st = arr(x)(x)
                      rev = arr(2 - x)(2 - x)} yield (st, rev)
      val res = diag.foldLeft(("", ""))((acc, t) => (acc._1 + t._1, acc._2 + t._1))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

import java.util.Scanner

object ZeroCross extends App {

  /*val a = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString)
  println(a.mkString(" "))
*/

  val b = Array.ofDim[Int](3, 3)

  val scanner = new Scanner(System.in)
  (0 until 3).foreach { i =>
    b(i) = scanner.next.toCharArray.map(convert)
  }

  def convert(ch: Char):Int = {
    if (ch == '.') 0
    else if (ch == '0') 1
    else 2
  }

  val board = Board(b)

  if (board.xWon && board.zeroWon) {
    println("illegal")
  } else if (board.count(2) < board.count(1)) {
    println("illegal")
  } else if (board.count(2) - board.count(1) > 1) {
    println("illegal")
  } else if (board.xWon) {
    println("the first player won")
  } else if (board.zeroWon) {
    println("the second player won")
  } else if (board.draw) {
    println("draw")
  } else if (board.count(1) == board.count(2)) {
    println("first")
  } else if (board.count(2) - board.count(1) == 1) {
    println("second")
  } else {
    println("illegal")
  }

  case class Board(arr: Array[Array[Int]]) {

    def xWon: Boolean = won(2)

    def zeroWon: Boolean = won(1)

    def won(item: Int): Boolean = {
      wonHorizontal(item) || wonVertical(item) || wonDiagonal(item)
    }

    def count(item: Int):Int = arr.flatten.count(_ == item)

    def draw:Boolean = count(1) == 4 && count(2) == 5

    def wonDiagonal(item: Int) = {
      val diag = for {x <- 0 until 3
                        st = arr(x)(x)
                        rev = arr(2 - x)(2 - x)} yield (st, rev)
      val res = diag.foldLeft(("",""))((acc, t) => (acc._1 + t._1, acc._2 + t._1))
      List(res._1, res._2).contains(item.toString * 3)
    }

    def wonHorizontal(item: Int): Boolean = arr.map(a => a.mkString).contains(item.toString * 3)

    def wonVertical(item: Int): Boolean = b.map(a => a.zipWithIndex).flatten.groupBy(_._2).values.map(_.map(_._1)).map(_.mkString).toList.contains(item.toString * 3)

  }

}

object C3 {

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

  def wins(b: Array[Array[Char]], char: Char): Boolean = {
    b.exists(_.forall(_==char)) || {
      (0 until 3).exists(j => Array(b(0)(j), b(1)(j), b(2)(j)).forall(_==char))
    } || {
      Array(b(0)(0), b(1)(1), b(2)(2)).forall(_==char)
    } || {
      Array(b(0)(2), b(1)(1), b(2)(0)).forall(_==char)
    }
  }

  def main(args: Array[String]): Unit = {
    val b = Array.fill(3)(read.toCharArray)
    val x = b.flatten.count(_ == 'X')
    val zero = b.flatten.count(_ == '0')
    if(x != zero || x != zero+1) {
      println("illegal") //also both can't win
    } else {
      if (wins(b, 'X') && wins(b, '0')) {
        println("illegal")
      } else if (wins(b, 'X')){
        if(x == zero+1)
          println("the first player won")
        else
          println("illegal")
      } else if (wins(b, '0')){
        if(x == zero)
          println("the second player won")
        else
          println("illegal")
      } else {
        if(b.flatten.contains('.')) {
          if(x == zero) {
            println("first")
          } else {
            println("second")
          }
        } else {
          println("draw")
        }
      }
    }

  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @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 C3 {

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

  def wins(b: Array[Array[Char]], char: Char): Boolean = {
    b.exists(_.forall(_==char)) || {
      (0 until 3).exists(j => Array(b(0)(j), b(1)(j), b(2)(j)).forall(_==char))
    } || {
      Array(b(0)(0), b(1)(1), b(2)(2)).forall(_==char)
    } || {
      Array(b(0)(2), b(1)(1), b(2)(0)).forall(_==char)
    }
  }

  def main(args: Array[String]): Unit = {
    val b = Array.fill(3)(read.toCharArray)
    val x = b.flatten.count(_ == 'X')
    val zero = b.flatten.count(_ == '0')
    if(x < zero) {
      println("illegal") //also both can't win
    } else {
      if (wins(b, 'X') && wins(b, '0')) {
        println("illegal")
      } else if (wins(b, 'X')){
        if(x == zero+1)
          println("the first player won")
        else
          println("illegal")
      } else if (wins(b, '0')){
        if(x == zero)
          println("the second player won")
        else
          println("illegal")
      } else {
        if(b.flatten.contains('.')) {
          if(x == zero) {
            println("first")
          } else {
            println("second")
          }
        } else {
          println("draw")
        }
      }
    }

  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @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 C3 {

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

  def wins(b: Array[Array[Char]], char: Char): Boolean = {
    b.exists(_.forall(_==char)) || {
      (0 until 3).exists(j => Array(b(0)(j), b(1)(j), b(2)(j)).forall(_==char))
    } || {
      Array(b(0)(0), b(1)(1), b(2)(2)).forall(_==char)
    } || {
      Array(b(0)(2), b(1)(1), b(2)(0)).forall(_==char)
    }
  }

  def main(args: Array[String]): Unit = {
    val b = Array.fill(3)(read.toCharArray)
    if(b.flatten.count(_ == 'X') < b.flatten.count(_ == '0') || (wins(b, 'X') && wins(b, '0')) ) {
      println("illegal") //also both can't win
    } else if (wins(b, 'X')){
      println("the first player won")
    } else if (wins(b, 'X')){
      println("the second player won")
    } else {
      if(b.flatten.contains('.')) {
        if(b.flatten.count(_ == 'X') == b.flatten.count(_ == '0')) {
          println("first")
        } else {
          println("second")
        }
      } else {
        println("draw")
      }
    }
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @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 P3C {
    def main(args : Array[String]) {
        val s = readLine + readLine + readLine
        val numX = s count {_ == 'X'}
        val num0 = s count {_ == '0'}
        val filled = s forall {_ != '.'}
        val lines = Array(
            Array(0, 1, 2), Array(3, 4, 5), Array(6, 7, 8),
            Array(0, 3, 6), Array(1, 4, 7), Array(2, 5, 8),
            Array(0, 4, 8), Array(2, 4, 6))
        val winX = lines exists {_ forall {s(_) == 'X'}}
        val win0 = lines exists {_ forall {s(_) == '0'}}
        val answer = () match {
            case _ if numX < num0 || num0 + 1 < numX => "Illegal"
            case _ if winX && win0 => "Illegal"
            case _ if winX => "the first player won"
            case _ if win0 => "the second player won"
            case _ if filled => "draw"
            case _ if numX == num0 => "first"
            case _ => "second"
        }
        println(answer)
    }
}

object P3C {
    def main(args : Array[String]) {
        val s = readLine + readLine + readLine
        val numX = s count {_ == 'X'}
        val num0 = s count {_ == '0'}
        val filled = s forall {_ != '.'}
        val lines = Array(
            Array(0, 1, 2), Array(3, 4, 5), Array(6, 7, 8),
            Array(0, 3, 6), Array(1, 4, 7), Array(2, 5, 8),
            Array(0, 4, 8), Array(2, 4, 6))
        val winX = lines exists {_ forall {s(_) == 'X'}}
        val win0 = lines exists {_ forall {s(_) == '0'}}
        val answer = () match {
            case _ if numX < num0 || num0 + 1 < numX => "illegal"
            case _ if winX && win0 => "illegal"
            case _ if winX => "the first player won"
            case _ if win0 => "the second player won"
            case _ if filled => "draw"
            case _ if numX == num0 => "first"
            case _ => "second"
        }
        println(answer)
    }
}


import java.util._
import java.io._
import java.util

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    var k = nextInt
    out.println("+------------------------+")
    val ans = new Array[util.ArrayList[Char]](4)
    for (i <- 0 until 4) {
      ans(i) = new util.ArrayList[Char]()
      ans(i).add('|')
    }
    for (j <- 0 until 11) {
      for (i <- 0 until 4) {
        if (k > 0) {
          if (i == 2) {
            if (j == 0) {
              ans(i).add('O')
              ans(i).add('.')
              k -= 1
            } else {
              ans(i).add('.')
              ans(i).add('.')
            }
          }
          else {
            ans(i).add('O')
            ans(i).add('.')
            k -= 1
          }
        }
        else {
          if (i == 2 && j > 0) {
            ans(i).add('.')
            ans(i).add('.')
          } else {
            ans(i).add('#')
            ans(i).add('.')
          }
        }
      }
    }
    ans(0).add('|')
    ans(0).add('D')
    ans(0).add('|')
    ans(0).add(')')
    ans(1).add('|')
    ans(1).add('.')
    ans(1).add('|')
    ans(2).add('.')
    ans(2).add('.')
    ans(2).add('|')
    ans(3).add('|')
    ans(3).add('.')
    ans(3).add('|')
    ans(3).add(')')
    for (i <- 0 until 4) {
      for (j <- 0 until ans(i).size()) {
        out.print(ans(i).get(j))
      }
      out.println
    }
    out.println("+------------------------+")
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

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

  val Array(n) = readInts(1)

  val seats = Array.fill(4, 11)(false)
  var used = 0

  for (r <- 0 until 11) {
    for (c <- 0 until 4 if r == 0 || c != 2) {
      if (used < n) {
        seats(c)(r) = true
        used += 1
      }
    }
  }

  println("+------------------------+")

  print("|")
  for (s <- seats(0)) print(if (s) "O." else "#.")
  println("|D|)")

  print("|")
  for (s <- seats(1)) print(if (s) "O." else "#.")
  println("|.|")

  print("|")
  if (seats(2)(0)) print("O") else print("#")
  println(".......................|")

  print("|")
  for (s <- seats(3)) print(if (s) "O." else "#.")
  println("|.|)")

  println("+------------------------+")

//|O.O.O.#.#.#.#.#.#.#.#.|D|)
//|O.O.O.#.#.#.#.#.#.#.#.|.|
//|O.......................|
//|O.O.#.#.#.#.#.#.#.#.#.|.|)
//+------------------------+
}

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

/**
 * Created by arseny on 05.10.14.
 */
object A extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val k = nextInt
    var r1 = "+------------------------+"
    var r2 = "|#.#.#.#.#.#.#.#.#.#.#.|D|)"
    var r3 = "|#.#.#.#.#.#.#.#.#.#.#.|.|"
    var r4 = "|#.......................|"
    var r5 = "|#.#.#.#.#.#.#.#.#.#.#.|.|)"
    var r6 = "+------------------------+"

    if (k >= 1) {
      r2 = r2.updated(1, 'O')
    }
    if (k >= 2) {
      r3 = r3.updated(1, 'O')
    }
    if (k >= 3) {
      r4 = r4.updated(1, 'O')
    }
    if (k >= 4) {
      r5 = r5.updated(1, 'O')
    }
    if (k >= 5) {
      val m = (k - 4) / 3
      for (i <- 0 until m) {
        r2 = r2.updated((i + 1) * 2 + 1, 'O')
        r3 = r3.updated((i + 1) * 2 + 1, 'O')
        r5 = r5.updated((i + 1) * 2 + 1, 'O')
      }
      val t = (k - 4) % 3
      if (t >= 1) {
       r2 = r2.updated(2 * m + 3, 'O')
      }
      if (t >= 2) {
        r3 = r3.updated(2 * m + 3, 'O')
      }
    }

    out.println(r1)
    out.println(r2)
    out.println(r3)
    out.println(r4)
    out.println(r5)
    out.println(r6)

  }

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


import scala.io.StdIn

object DW extends App {

  val required = StdIn.readLine().toCharArray.map {
    case '+' => 1
    case '-' => -1
  }.sum
  val (actual, uncertain) = StdIn.readLine().toCharArray.map {
    case '+' => (1, 0)
    case '-' => (-1, 0)
    case '?' => (0, 1)
  }.fold(0,0) {
    case ((a1, b1), (a2, b2)) => (a1 + a2, b1 + b2)
  }
  val miss = math.abs(required - actual)
  if (
    required > (actual + uncertain) ||
    required < (actual - uncertain) ||
    miss == 0 && uncertain % 2 != 0
  ) println(0.0d)
  else {

    val pluses = miss + (uncertain - miss) / 2
    println(
      math.pow(0.5f, uncertain) * factorial(uncertain) / (factorial(pluses) * factorial(math.abs(uncertain - pluses)))
    )
  }

  def factorial(n: Int): Int = {
    var res = 1
    for (i  <- 1 to n) {
      res *= i
    }
    res
  }
}

import scala.io.StdIn._

object Wifi
{
	var original, total, correct: Int = 0

	def main(args: Array[String])
	{
		val a, b = readLine

		for (c <- a) c match
		{
			case '+' => original += 1
			case '-' => original -= 1
		}

		parse(b, 0)
		printf("%1$.12f", correct.toDouble / total)
	}

	def parse(str: String, _pos: Int)
	{
		if (str isEmpty)
		{
			if (_pos == original) correct += 1
			total += 1
			return
		}
		var pos = _pos

		for (i <- 0 until str.size) str(i) match
		{
			case '+' => pos += 1
			case '-' => pos -= 1
			case '?' => {
							parse(str.substring(i + 1), pos + 1)
							parse(str.substring(i + 1), pos - 1)
							return
						}
		}

		if (pos == original) correct += 1
		total += 1
	}
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val s1 = scala.io.StdIn.readLine
    val s2 = scala.io.StdIn.readLine
    val total = math.pow(2.0, s2.count(_ == '?'))
    val count = gen(0, s2.toCharArray, calc(s1.toCharArray))
    println(count.toDouble/total)
  }

  def calc(str: Array[Char]): Int = {
    val ret = str.foldLeft(0) { case (sum, ch) =>
      if(ch == '+') {
        sum + 1
      } else {
        sum - 1
      }
    }
    ret
  }

  def gen(ind: Int, str: Array[Char], finalPos: Int): Int = {
    if(ind == str.length) {
      if(calc(str) == finalPos) 1 else 0
    } else if (str(ind) != '?'){
      gen(ind + 1, str, finalPos)
    } else {
      var score = 0

      str(ind) = '+'
      score = gen(ind + 1, str, finalPos)

      str(ind) = '-'
      score += gen(ind + 1, str, finalPos)

      str(ind) = '?'

      score
    }
  }
}

object Main extends App {
  def step(acc: Array[Int], op: Char): Array[Int] =
    if (op == '+') acc.map(_ + 1)
    else if (op == '-') acc.map(_ - 1)
    else acc.flatMap(x => Array(x - 1, x + 1))

  val orig = readLine
  val endPos = orig.foldLeft(Array(0))(step)(0)

  val recieved = readLine
  val sampleSpace = recieved.foldLeft(Array(0))(step)

  println(sampleSpace.count(_ == endPos) / sampleSpace.size.toDouble)
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val s1 = scala.io.StdIn.readLine
    val s2 = scala.io.StdIn.readLine
    val total = s2.count(_ == '?').toDouble
    if(total == 0) {
      println(1.0d)
    } else {
      val count = gen(0, s2.toCharArray, calc(s1.toCharArray))
      println(count.toDouble/total)
    }
  }

  def calc(str: Array[Char]): Int = {
    str.foldLeft(0) { case (sum, ch) =>
      if(ch == '+') {
        sum + 1
      } else {
        sum - 1
      }
    }
  }

  def gen(ind: Int, str: Array[Char], finalPos: Int): Int = {
    if(ind == str.length) {
      if(calc(str) == finalPos) 1 else 0
    } else if (str(ind) != '?'){
      gen(ind + 1, str, finalPos)
    } else {
      var score = 0

      str(ind) = '+'
      score = gen(ind + 1, str, finalPos)

      str(ind) = '-'
      score += gen(ind + 1, str, finalPos)

      score
    }
  }
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val s1 = scala.io.StdIn.readLine
    val s2 = scala.io.StdIn.readLine
    val total = math.pow(2.0, s2.count(_ == '?'))
    val count = gen(0, s2.toCharArray, calc(s1.toCharArray))
    println(count.toDouble/total)
  }

  def calc(str: Array[Char]): Int = {
    str.foldLeft(0) { case (sum, ch) =>
      if(ch == '+') {
        sum + 1
      } else {
        sum - 1
      }
    }
  }

  def gen(ind: Int, str: Array[Char], finalPos: Int): Int = {
    if(ind == str.length) {
      if(calc(str) == finalPos) 1 else 0
    } else if (str(ind) != '?'){
      gen(ind + 1, str, finalPos)
    } else {
      var score = 0

      str(ind) = '+'
      score = gen(ind + 1, str, finalPos)

      str(ind) = '-'
      score += gen(ind + 1, str, finalPos)

      score
    }
  }
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(day, of, period) = in.next().split(' ')
  val d = day.toInt
  if (period == "week") {
    d match {
      case 6 => println(53)
      case 5 => println(53)
      case _ => println(52)
    }
  } else {
    d match {
      case 31 => println(7)
      case 30 => println(11)
      case _ => println(12)
    }
  }
}

import scala.math._
import scala.collection.immutable.Range
import scala.io.Source

object a8 {
  def main(args: Array[String]): Unit = {
    val a = Array.iterate(4,366)(a=>(a + 1)%7).map(_+1)
    val b = Array(31,29,31,30,31,30,31,31,30,31,30,31).map(a=>(1 to a ).toArray)
    val line = Source.stdin.getLines().toArray.head.split(' ')
    val x = line(0).toInt
    println(line(2) match {
      case  "week" => a.count(_ == x)
      case "month" => b.map(_.count(_ == x)).sum
    })
    //a.foreach(println)
  }

}

object A611 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

  def main(args: Array[String]): Unit = {
    val t1 = tokenizeLine
    val input = Array.fill(3)(t1.nextToken)
    if(input.contains("week")) {
      val day = input(0).toInt
      if(Array(1,2,3,4,7).contains(day))
        println("52")
      else
        println("53")
    } else {
      val day = input(0).toInt
      if(day <= 29) {
        println("12")
      } else if (day == 30) {
        println("11")
      } else {
        println("7")
      }
    }
  }
}

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

  val ss = readLine.split(" ")

  val n = ss(0).toInt
  if (ss(2) == "week") {
    val w = Seq(0, 52, 52, 52, 52, 53, 53, 52)
    println(w(n))
  } else {
    val x = if (n <= 29) 12
    else if (n <= 30) 11
    else 7
    println(x)
  }
}

/**
 * @author pvasilyev
 * @since 05 May 2016
 */
object A611 extends App {

  val Array(x, y, z) = scala.io.StdIn.readLine().split(" ")
  val n = x.toInt
  var answer = 0
  if ("month".equals(z)) {
    if (n < 30) {
      answer = 12
    } else if (n == 30) {
      answer = 11
    } else {
      answer = 7
    }
  } else {
    if (n == 5 || n == 6) {
      answer = 53
    } else {
      answer = 52
    }
  }

  println(answer)

}

import java.util.Scanner

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

    if(span == "week"){
      if(n == 7)
        println(52)
      else if(n >= 5)
        println(53)
      else
        println(52)
    }
    else if(span == "month"){
      if(n <= 29)
        println(12)
      else if(n == 30)
        println(11)
      else  // n == 31
        println(7)
    }
  }
}

import scala.math._
import scala.collection.immutable.Range
import scala.io.Source

object a8 {
  def main(args: Array[String]): Unit = {
    val a = Array.iterate(4,365)(a=>(a + 1)%7).map(_+1)
    val b = Array(31,28,31,30,31,30,31,31,30,31,30,31).map(a=>(1 to a ).toArray)
    val line = Source.stdin.getLines().toArray.head.split(' ')
    val x = line(0).toInt
    println(line(2) match {
      case  "week" => a.count(_ == x)
      case "month" => b.map(_.count(_ == x)).sum
    })
    //b.foreach(println)
  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(day, of, period) = in.next().split(' ')
  val d = day.toInt
  if (period == "week") {
    d match {
      case 6 => println(53)
      case 5 => println(53)
      case _ => println(52)
    }
  } else {
    d match {
      case 31 => println(7)
      case 30 => println(11)
      case 29 => println(11)
      case _ => println(12)
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(day, of, period) = in.next().split(' ')
  val d = day.toInt
  if (period == "week") {
    d match {
      case 7 => println(53)
      case 6 => println(53)
      case _ => println(52)
    }
  } else {
    d match {
      case 31 => println(7)
      case 30 => println(11)
      case 29 => println(11)
      case _ => println(12)
    }
  }
}

import java.util.Scanner

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

    if(span == "week"){
      if(n >= 5)
        println(53)
      else
        println(52)
    }
    else if(span == "month"){
      if(n <= 29)
        println(12)
      else if(n == 30)
        println(11)
      else  // n == 31
        println(7)
    }
  }
}


import scala.io.StdIn._
object B extends App{
  val Array(n,m) = readLine().split(" ").map(_.toLong)
  if (2*m-1 >= n){
    println(Math.max(m-1,1))
  }else{
    println(Math.min(n,m+1))
  }
}

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

object SimpleGame {

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

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

   def main(args: Array[String]) {
     val (n,m) = readTuple()
     if (m <= n/2) println(Math.min(m+1,n)) else println(Math.max(m-1,1))
   }

}

object B570 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    var maxAndrew = 0
    var res = n-m+1
    Array(m+1, m-1).foreach{
      case a if a > 0 && a <= n =>
        var andrew = 0
        if(a == m+1) {
          andrew = n - m - 1
        } else {
          andrew = m-1
        }
        if(andrew > maxAndrew) {
          maxAndrew = andrew
          res = a
        }
      case _ =>
    }
    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

import java.io._
import java.util._

import scala.collection.mutable

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    if (n == 1) {
      out.println(1)
      return 0
    }
    val abs = n - m
    if (abs > m) {
      out.println(m + 1)
    } else if (abs < m){
      out.println(m - 1)
    } else {
      out.println(m + 1)
    }
    return 0
  }
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)

    println (if (m <= n/2) Math.min(n,m+1) else Math.max(1,m-1))
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _570B extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  (n, m) match {
    case (1, _) => 1
    case (_, 1) => 2
    case (_, `n`) => n-1
    case _  => m + (if (m <= n / 2) 1 else -1)
  }
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object SomeTest extends App {
  val Array(n, m) = readLine().split(" ").map(_.toLong)

  if (n == 1) println(1)
  else if (n - m > m - 1) {
    println(m + 1)
  } else {
    println(m - 1)
  }
}

import scala.io.StdIn._
object B extends App{
  val Array(n,m) = readLine().split(" ").map(_.toInt)
  if (2*m-1 >= n){
    println(m-1)
  }else{
    println(m+1)
  }
}

import scala.io.StdIn._
object B extends App{
  val Array(n,m) = readLine().split(" ").map(_.toLong)
  if (2*m-1 >= n){
    println(m-1)
  }else{
    println(m+1)
  }
}

import scala.io.StdIn._
object B extends App{
  val Array(n,m) = readLine().split(" ").map(_.toLong)
  if (2*m-1 >= n){
    println(Math.max(m-1,0))
  }else{
    println(Math.min(n,m+1))
  }
}

import scala.io.StdIn._
object B extends App{
  val Array(n,m) = readLine().split(" ").map(_.toInt)
  if (2*m-1 <= n){
    println(m+1)
  }else{
    println(m-1)
  }
}

object B570 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    var maxAndrew = 0
    var res = 0
    Array(m+1, m-1).foreach{
      case a if a > 1 && a <= n =>
        var andrew = 0
        if(a == m+1) {
          andrew = n - (m+1)
        } else {
          andrew = m-1
        }
        if(andrew > maxAndrew) {
          maxAndrew = andrew
          res = a
        }
      case _ =>
    }
    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

    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 B570 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    var maxAndrew = 0
    var res = 1
    Array(m+1, m-1).foreach{
      case a if a > 0 && a <= n =>
        var andrew = 0
        if(a == m+1) {
          andrew = n - m
        } else {
          andrew = a
        }
        if(andrew > maxAndrew) {
          maxAndrew = andrew
          res = a
        }
      case _ =>
    }
    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

    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 B570 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    var maxAndrew = 0
    var res = 1
    Array(m+1, m-1).foreach{
      case a if a > 1 && a <= n =>
        var andrew = 0
        if(a == m+1) {
          andrew = n - (m+1)
        } else {
          andrew = m-1
        }
        if(andrew > maxAndrew) {
          maxAndrew = andrew
          res = a
        }
      case _ =>
    }
    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

import java.io._
import java.util._

import scala.collection.mutable

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    if (n == 1) {
      out.println(1)
      return 0
    }
    val abs: Int = Math.abs(n - m)
    if (abs > m) {
      out.println(m + 1)
    } else if (abs < m){
      out.println(m - 1)
    } else {
      out.println(m - 1)
    }
    return 0
  }
}

import java.io._
import java.util._

import scala.collection.mutable

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    if (n == 1) {
      out.println(1)
      return 0
    }
    val mid = n / 2 + n % 2
    if (m > mid) {
      out.println(mid)
    } else if (m < mid) {
      out.println(m + 1)
    } else {
      out.println(m - 1)
    }
    return 0
  }
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)

    println (if (m < (n+1)/2) m+1 else m-1)
  }
}

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

object Solution {

  def main(args: Array[String]) {
    val Array(n, m) = readLine().split(" ").map(_.toInt)

    println (if (m <= n/2) m+1 else m-1)
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _570B extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  if (m < n/2) {
    m+1
  } else if (m > n/2) {
    m-1
  } else {
    if (n%2 == 1) m+1 else m-1
  }
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _570B extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, m) = (nextInt, nextInt)
  (n, m) match {
    case (1, _) => 1
    case (2, 1) => 2
    case (2, 2) => 1
    case (3, 1) => 2
    case (3, 2) => 1
    case (3, 3) => 1
    case _ if m <= n/2 => m+1
    case _ if m > n/2 => m-1
  }
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toLong)
  val Half = Math.ceil(n / 2.0).toLong

  if (m >= Half) {
    println(m - 1)
  } else {
    println(m + 1)
  }
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toLong)
  val Half = Math.ceil(n / 2.0)

  if (m >= Half) {
    println(m - 1)
  } else if (m < Half) {
    println(m + 1)
  }
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toLong)
  val Half = Math.ceil(n / 2.0)

  if (n == 1) println(1)
  else if (m >= Half) {
    println(m - 1)
  } else if (m < Half) {
    println(m + 1)
  }
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toLong)
  val Half = Math.ceil(n / 2.0).toInt

  if (m >= Half) {
    println(m - 1)
  } else {
    println(m + 1)
  }
}

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

object SimpleGame {

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

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

   def main(args: Array[String]) {
     val (n,m) = readTuple()
     if (m <= n/2) println(m+1) else println(m-1)
   }

}


import java.util._
import java.io._
import java.util
import scala.annotation.tailrec

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null
  var ans = 0

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val a = nextInt
    val b = nextInt
    var min = Int.MaxValue
    for (i <- 0 to n / m + 1) {
      var temp = i * b
      val x: Int = n - (i * m)
      if ( x > 0) {
        temp += x * a
      }
      min = Math.min(min, temp)
    }
    out.println(min)
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

object CheapTravel {
	def main (args: Array[String]) {
		//Parsing the input
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt();
		val m = scanner.nextInt();
		val a = scanner.nextInt();
		val b = scanner.nextInt();
		// Check whether it is cheaper to buy m-rides tickets
		if (a*m >= b) {
		  val lastTicket = if ((n%m * a) < b) n%m*a else b
			println(n / m * b + lastTicket)
		}
		else
			println(n * a)
	}
}

object Main {
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val m = cin.nextInt()
    val a = cin.nextInt()
    val b = cin.nextInt()
    println(Math.min(Math.min(n * a, (n / m) * b + (n % m) * a), ((n + m - 1) / m) * b))
  }
}

//package xubiker.archive

import java.util.Scanner

object Task_466A extends App {

  val sc = new Scanner(System.in)

  val n = sc.nextInt()
  val m = sc.nextInt()
  val a = sc.nextInt()
  val b = sc.nextInt()

  sc.close()

  val price1 = (Math.ceil(n.toDouble / m) * b).toInt
  val price2 = a * n
  val price3 = (n / m) * b + (n % m) * a

  val price = price1.min(price2.min(price3))
  println(price)

}

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

object CheapTravel {

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

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

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

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

   def main(args: Array[String]) {
     val (n,m,a,b) = readQuad()
     val pricePerRide = b.toDouble/m
     if (pricePerRide >= a) println(a*n) // always by single tickets
     else {
       val priceRem = if ( (n%m)*a <= b) (n%m)*a else b
       println( (n/m)*b + priceRem)
     }
   }

}

object Main extends App {
  val in = readLine
  val Array(n, m, a, b) = in.split(" ").map(_.toInt)
  if (m * a <= b)
    println(a * n)
  else
    println((n / m) * b + (if (n % m > 0) Math.min(b, n % m * a) else 0))
}

import scala.io.StdIn._

object Main2 extends App {
  val Array(ridesNumber, subscriptionRidesNumber, ridePrice, subscriptionPrice) = readLine().split(" ").map(_.toInt)
  val ans = if (subscriptionRidesNumber * ridePrice > subscriptionPrice) {
    val priceWithGreedySubscriptions = (ridesNumber/subscriptionRidesNumber) * subscriptionPrice
    val remainingRides = ridesNumber%subscriptionRidesNumber
    if (remainingRides * ridePrice < subscriptionPrice) {
      priceWithGreedySubscriptions + remainingRides * ridePrice
    } else {
      priceWithGreedySubscriptions + subscriptionPrice
    }
  } else {
    ridesNumber * ridePrice
  }
  println(ans)
}

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

object App {

  def main(args: Array[String]) {

    val Array(n,m,a,b) = StdIn.readLine().split(" ").map(_.toInt)

    var ans = 10000000;
    for(i <- 0 to 1000) {
      ans = math.min(ans, b * i + math.max(n - m * i,0) * a)
    }

    println(ans)

  }

}

object Main {
   def main(args: Array[String]): Unit = {
val Array(n,m,a,b) = scala.io.StdIn.readLine().split(' ').map(_.toInt)
println(scala.math.min(n/m*b+scala.math.min(n%m*a, b), n*a))
      }
    }

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, a, b) = in.next().split(" ").map(_.toInt)
  if (m * a <= b)
    println(a * n)
  else {
    println((n / m) * b + (if (n % m > 0) Math.min(b, n % m * a) else 0))
  }

}

import scala.collection.JavaConversions._

object Codeforces466A {
    def main(args: Array[String]) {
        val Array(n, m, a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        if (b.toFloat/m > a) {
            println(n*a)
        }
        else {
            val x = n / m
            val y = n % m
            if (y > 0) {
                if (y*a < b)
                    println(x*b + y*a)
                else
                    println(x*b + b)
            }
            else
                println(x*b)
        }
    }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    val Array(n, m, a, b) = readLine.split(" ").map(_.toInt)

    var ans = Int.MaxValue
    for(i <- 0 to n){
      var by_one = i
      var by_one_price = by_one * a

      var remained_tickets = n - i
      if(remained_tickets >= 0){
        var by_m = (remained_tickets + (m - 1)) / m
        var by_m_price = by_m * b

        ans = Array(ans, by_one_price + by_m_price).min
      }
    }

    println(ans)
  }
}

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

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

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

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

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

    var res = n * a
    res = math.min(res, b*(if(n%m == 0) n/m else n/m + 1) )
    res = math.min(res, if(n%m == 0) b*(n/m) else b*(n/m) + a*(n%m))
    println(res)
  }
}

object Main {
   def main(args: Array[String]): Unit = {
val Array(n,m,a,b) = scala.io.StdIn.readLine().split(' ').map(_.toInt)
println(n/m*b+n%m*a)
      }
    }

import scala.io.StdIn

object Task466A {
	def main(args: Array[String]) {
		val nmab = StdIn.readLine().split(" ").map(_.toInt)
		if (nmab(3).toDouble / nmab(1) < nmab(2))
			println(nmab(0) / nmab(1) * nmab(3) + Math.min(nmab(2), nmab(3)))
		else println(nmab(0) * nmab(2))
	}
}

import scala.io.StdIn

object Task466A {
	def main(args: Array[String]) {
		val nmab = StdIn.readLine().split(" ").map(_.toInt)
		if (nmab(3).toDouble / nmab(1) < nmab(2))
			println(nmab(0) / nmab(1) * nmab(3) + nmab(0) % nmab(1) * Math.min(nmab(2), nmab(3)))
		else println(nmab(0) * nmab(2))
	}
}

import scala.io.StdIn

object Task466A {
	def main(args: Array[String]) {
		val nmab = StdIn.readLine().split(" ").map(_.toInt)
		println(if (nmab(3).toDouble / nmab(1) < nmab(2))
			if (nmab(0).toDouble / nmab(1) < 1) nmab(3)
			else nmab(0) / nmab(1) * nmab(3) + nmab(0) % nmab(1) * Math.min(nmab(2), nmab(3))
		else nmab(0) * nmab(2))
	}
}

import scala.collection.JavaConversions._

object Codeforces468A {
    def main(args: Array[String]) {
        val Array(n, m, a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        if (m.toFloat/b > a) {
            println(n*a)
        }
        else {
            println((n/m)*b + (n%m)*a)
        }
    }
}

import scala.collection.JavaConversions._

object Codeforces466A {
    def main(args: Array[String]) {
        val Array(n, m, a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        if (m.toFloat/b > a) {
            println(n*a)
        }
        else {
            val x = n / m
            val y = n % m
            if (y*a < b)
                println((n/m)*b + (n%m)*a)
            else
                println((n/m)*b + b)
        }
    }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    val Array(n, m, a, b) = readLine.split(" ").map(_.toInt)

    var ans = Int.MaxValue
    for(i <- 0 to n){
      var by_one = i
      var by_one_price = by_one * a

      var remained_tickets = n - i
      if(remained_tickets > 0){
        var by_m = (remained_tickets + (m - 1)) / m
        var by_m_price = by_m * b

        ans = Array(ans, by_one_price + by_m_price).min
      }
    }

    println(ans)
  }
}

import java.util._
import java.io._
import java.util
import scala.annotation.tailrec

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null
  var ans = 0

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val a = nextInt
    val b = nextInt
    var min = Int.MaxValue
    for (i <- 0 to n / m) {
      min = Math.min(min, i * b + (n - (i * m)) * a)
    }
    out.println(min)
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import java.util._
import java.io._
import java.util
import scala.annotation.tailrec

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null
  var ans = 0

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val a = nextInt
    val b = nextInt
    out.println(Math.min(n * a, (n / m) * b + (n % m) * a))
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

object CheapTravel {
	def main (args: Array[String]) {
		//Parsing the input
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt();
		val m = scanner.nextInt();
		val a = scanner.nextInt();
		val b = scanner.nextInt();
		// Check whether it is cheaper to buy m-rides tickets
		if (a*m >= b)
			println(n / m * b + n%m * a)
			else
				println(n * a)
	}
}

import scala.io.StdIn._

object Main2 extends App {
  val Array(ridesNumber, subscriptionRidesNumber, ridePrice, subscriptionPrice) = readLine().split(" ").map(_.toInt)
  val ans = if (subscriptionRidesNumber * ridePrice > subscriptionPrice) {
    val subscriptionsPrice = (ridesNumber/subscriptionRidesNumber) * subscriptionPrice
    val remainingRides = (ridesNumber%subscriptionRidesNumber)
    if (remainingRides * ridePrice < subscriptionsPrice) {
      subscriptionsPrice + remainingRides * ridePrice
    } else {
      subscriptionsPrice + subscriptionPrice
    }
  } else {
    ridesNumber * ridePrice
  }
  println(ans)
}

import scala.io.StdIn._

object Main2 extends App {
  val Array(ridesNumber, subscriptionRidesNumber, ridePrice, subscriptionPrice) = readLine().split(" ").map(_.toInt)
  val ans = if (subscriptionRidesNumber * ridePrice > subscriptionPrice) {
    (ridesNumber/subscriptionRidesNumber) * subscriptionPrice + (ridesNumber%subscriptionRidesNumber) * ridePrice
  } else {
    ridesNumber * ridePrice
  }
  println(ans)
}

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

object App {

  def main(args: Array[String]) {

    val Array(n,m,a,b) = StdIn.readLine().split(" ").map(_.toInt)

    var ans = 10000;
    for(i <- 0 to 1000) {
      ans = math.min(ans, b * i + math.max(n - m * i,0) * a)
    }

    println(ans)

  }

}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val data = in.next().split(' ').map(_.toLong)
  var (a, b) = if (data.head % data.last == 0) (data.head /data.last, 1l) else (data.head, data.last)
  var r = 0l
  while (b > 0) {
    r += a / b
    val newB = a % b
    a = b
    b = newB
  }
  println(r)
}

object C extends App {

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

  def cnt(a: Long, b: Long): Long = {
    if (a == 1L) b
    else if (a > b) a / b + cnt(a % b, b)
    else cnt(b, a)
  }

  val Array(a, b) = readLongs(2)

  println(cnt(a, b))
}

import scala.collection._

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

  def cnt(a: Long, b: Long): Long = {
    //println(a, b)
    if (a == 0L || b == 0L) 0L
    else if (a == 1L) b
    else if (b == a) 1L
    else if (b == 1L) a
    else if (a > b) a / b + cnt(a % b, b)
    else b / a + cnt(b % a, a)
  }

  val Array(a, b) = readLongs(2)

  println(cnt(a, b))
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(a, b) = readLongs(2)
    println(rec(a, b))
  }
  def rec(a: Long, b: Long): Long = {
    if(a == 1 || b == 1) {
      a+b-1
    } else {
      if (a > b) {
        (a / b) + rec(b, a%b)
      } else {
        rec(b, a)
      }
    }
  }
}

import scala.collection._

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

  def cnt(a: Long, b: Long): Long = {
    //println(a, b)
    if (a == 0L || b == 0L) 0L
    //else if (a == 1L) b
    else if (b == a) 1L
    else if (b == 1L) a
    else if (a > b) (a - b) + cnt(a % b, b)
    else (b - a) + cnt(b % a, a)
  }

  val Array(a, b) = readLongs(2)

  println(cnt(a, b))
}

import scala.collection._

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

  def cnt(a: Long, b: Long): Long = {
    //println(a, b)
    if (a == 0L || b == 0L) 0L
    else if (a == 1L) b
    else if (b == a) 1L
    else if (b == 1L) a
    else if (a > b) (a - b) + cnt(a % b, b)
    else (b - a) + cnt(b % a, a)
  }

  val Array(a, b) = readLongs(2)

  println(cnt(a, b))
}

import scala.collection._

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

  def cnt(a: Long, b: Long): Long = {
    //println(a, b)
    if (a == 0L || b == 0L) 0L
    else if (a == 1L) b
    else if (b == a) 1L
    else if (a > b) (a - b) + cnt(a % b, b)
    else (b - a) + cnt(b % a, a)
  }

  val Array(a, b) = readLongs(2)

  println(cnt(a, b))
}

import scala.collection._

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

  def cnt(a: Long, b: Long): Long = {
    //println(a, b)
    /*if (a == 1L) b
    else*/ if (b == 1L) 1L
    else if (a > b) (a - b) + cnt(a % b, b)
    else (b - a) + cnt(b % a, a)
  }

  val Array(a, b) = readLongs(2)

  println(cnt(a, b))
}

import scala.collection._

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

  def cnt(a: Long, b: Long): Long = {
    //println(a, b)
    if (a == 1L) b
    else if (b == 1L) 1L
    else if (a > b) (a - b) + cnt(a % b, b)
    else cnt(b, a)
  }

  val Array(a, b) = readLongs(2)

  println(cnt(a, b))
}


import java.util.Scanner

object A extends App {
    val sc = new java.util.Scanner(System.in)
    val n, x, y = sc.nextInt()
    println(math.max(0, (n*y+99)/100-x))
}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val Array(n, x, y) = readInts
  def ceil(a: Int, b: Int) = a / b + (if(a % b == 0) 0 else 1)
//  def ans = ceil(n * y - 100 * x, 100) max 0
  def ans = (0.01 * n * y - 0.000001 - x).ceil.toInt max 0

  def main(args: Array[String]) {
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) {
    val nxy = readLine().split(" ").map(_.toInt)
    val n = nxy(0)
    val x = nxy(1)
    val y = nxy(2)
    println((((n * y + 99) / 100) - x).max(0))
  }
}

object Solver {
  def main(args: Array[String]) {
    var input = Console.readLine.split(" ").map(x => x.toInt)
    var n = input(0); var x = input(1); var y = input(2);

    var required = Math.ceil(n * y / 100.0).toInt
    var clones = if (required > x) required - x else 0
    println(clones)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, x, y) = in.next().split(" ").map(_.toInt)
  println(Range(0, 1000 * 1000 + 1).find(i => (i + x) * 100 / n >= y).get)
}

import scala.math
object Main
{
	def up(a:Double):Int =
	{
		if(a.floor == a)
			return a.floor.toInt
		return (a.floor.toInt + 1)
	}

	def main(args:Array[String])
	{
		val rd = readLine.split(" ").map(i => i.toInt);
		val n = rd(0)
		val x = rd(1)
		val y = rd(2)

		val cl = up((n / 100.0) * y - x)
		if (cl < 0)
			println(0)
		else
			println(cl)
	}
}

import java.util.Scanner

object A {
    def main(args: Array[String]) {
        val sc = new java.util.Scanner(System.in)
        val n, x, y = sc.nextInt()
        println(math.max(0, (n*y+99)/100-x))
    }
}

import java.util.Scanner
object A {
    def main(args: Array[String]) {
        val sc = new java.util.Scanner(System.in)
        val n, x, y = sc.nextInt()
        val s = n * y - x * 100
        if (s <= 0) println(0)
        else if(s % 100 == 0) println(s / 100)
        else println((s + 100) / 100)
    }
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P168A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N, X, Y = sc.nextInt

  val p = math.ceil(N * Y / 100.0).toInt - X

  out.println(if (p < 0) 0 else p)
  out.close
}

import java.util.Scanner
object A {
    def main(args: Array[String]) {
        val sc = new java.util.Scanner(System.in)
        val n, x, y = sc.nextInt()
        if ((n * y - x * 100) <= 0) println(0)
        else println(((n * y - x * 100) / 100).ceil)
    }
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P168A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N, X, Y = sc.nextInt

  val answer = math.ceil(N * Y / 100.0).toInt - X

  out.println(answer)
  out.close
}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val Array(n, x, y) = readInts
  def ceil(a: Int, b: Int) = a / b + (if(a % b == 0) 0 else 1)
//  def ans = ceil(n * y - 100 * x, 100) max 0
  def ans = (0.01 * n * y - 0.1 - x).ceil.toInt max 0

  def main(args: Array[String]) {
    println(ans)
  }
}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val Array(n, x, y) = readInts
  def ceil(a: Int, b: Int) = a / b + (if(a % b == 0) 0 else 1)
//  def ans = ceil(n * y - 100 * x, 100) max 0
  def ans = (0.01 * n * y - x).ceil.toInt max 0

  def main(args: Array[String]) {
    println(ans)
  }
}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val Array(n, x, y) = readInts
  def ceil(a: Int, b: Int) = a / b + (if(a % b == 0) 0 else 1)
//  def ans = ceil(n * y - 100 * x, 100) max 0
  def ans = (1.0 * n * y - x).ceil.toInt max 0

  def main(args: Array[String]) {
    println(ans)
  }
}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val Array(n, x, y) = readInts
  def ceil(a: Int, b: Int) = a / b + (if(a % b == 0) 0 else 1)
  def ans = ceil(n * y - 100 * x, 100) max 0

  def main(args: Array[String]) {
    println(ans)
  }
}


/**
  * Created by moiseev on 21.04.2017.
  */
object Task2 extends App {

  import java.util.{Scanner}

  val in = new Scanner(System.in)

  val X = in.next
  val Y = in.next

  def middleChar( charLeft: Char, charRes: Char ): (Boolean,Char) = {
    if ( charLeft < charRes ) (false,' ')
    else  {
      // a - 92 z - 122
      // charLeft - between 92 and 122
      // result should be between charLeft and 122 inclusive
      (
        true,if ( charLeft == charRes ) {
        val randRandge: Int = 122 - charLeft
        (charLeft.toInt + (if (randRandge > 0)scala.util.Random.nextInt(randRandge) else 0) ).toChar
      }
      else charRes
      )
    }
  }

  def findSecondString( strLeft:String, strRes: String ): (Boolean, String) = {
    if ( strLeft.size == 0 ) (true,"") // Finishing the recursion
    else if (strLeft.size != strRes.size )
      (false,"") // Strings are of different size - false definetly
    else {
      val (res, ch) = middleChar(strLeft.head, strRes.head)

      if (!res)
        (false, "") // Some i chars says they are not from our F()
      else {
        val (recRes, strRec) = findSecondString(strLeft.tail, strRes.tail)

        if (!recRes)
          (false, "") // Just to recursevly inform about failure
        else (true, ch + strRec)
      }
    }
  }

  val (resBool,resStr) = findSecondString(X,Y)
  if (resBool) {
    println(resStr)
  } else {
    println(-1)
  }
}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val x, z = read[String]

    val ans = Try{x.zip(z).map({case (a, b) => b.ensuring(b <= a)})}

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

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

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

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

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

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

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

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

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

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


import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val a = StdIn.readLine().split(" ")
    val b = StdIn.readLine().split(" ")
    val c = a.filter(item => b.contains(item))
    c.foreach(item => print(item + " "))
  }
}

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

object Main {
    def main(arg: Array[String]) {
        var z = readLine().split(" ")
        var n = z(0).toInt
        var m = z(1).toInt

        var x = readLine.split(" ").map(_.toInt).toArray
        var y = readLine.split(" ").map(_.toInt).toArray

        for(ele <- x){
            if(y contains ele) {
                print(ele + " ")
            }
        }
    }
}

/**
  * @author ShankarShastri
  *         Algorithm: ProblemA (http://codeforces.com/contest/994/problem/A)
  */

import scala.io.StdIn._
import scala.annotation.tailrec

object ProblemA {
  def main(args: Array[String]): Unit = {
    readLine
    val list = readLine.split(" ").map(_.toInt).toList
    val keys = readLine.split(" ").map(_.toInt).toList
    val res = keys.map(x => (x, list.indexOf(x))).filter(_._2 != -1).sortBy(_._2).map(_._1)
    println(res.mkString(" "))
  }
}