Problem:
Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

The input is given from Standard Input in the following format:

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999

Solution in Scala (2.11.7) (judge verdict: Accepted)

object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val N, K = sc.nextInt()
    val D = Array.fill(K)(sc.nextInt())

    // N < 10^4 以下なので, 10^5 より小さい数 を使えば必ず買える金額が存在
    // 10^5 より小さい数の空間計算量は用意可能なので
    // [1,10^5)の範囲で {D_1, D_2, ..., D_k}の数が含まれないものだけを列挙する
    // そして N >= となる 最小の金額が達成する金額.

    def solve(N: Int, K: Int, D: Array[Int]): Int = {
      val MAX_DIGIT = 5
      val UPPER = 100000
      val LIKES = (0 to 9) filter (!D.contains(_))
      def dfs(stack: List[(Int, Int)], min: Int): Int =
        if (stack.nonEmpty) {
          val (digit, num) = stack.head
          if (digit <= MAX_DIGIT)
            dfs(LIKES.foldLeft(stack.tail)((stack, d) =>
              (digit + 1, num * 10 + d) :: stack), if (num >= N) min min num else min)
          else dfs(stack.tail, min)
        } else min
      dfs(LIKES.filter(_ != 0).map((1, _)).toList, UPPER)
    }

    println(solve(N, K, D))
  }

}