main = getLine >>= main' . read . head . words
    where
        main' n = getLine
                >>= print . solve n . map read . words

solve :: Int -> [Int] -> Int
solve 0 _ = 0
solve n ds
    | y < 10 = solve r ds * 10 + y
    | otherwise = solve (n + 10 - x) ds
    where
        (r, x) = n `divMod` 10
        y = minval x ds

minval :: Int -> [Int] -> Int
minval x (d : ds)
    | d < x = minval x ds
    | d == x = minval (x + 1) ds
    | otherwise = x
minval x _ = x
