Problem:
Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36

Solution in Haskell (GHC 7.10.3) (judge verdict: Wrong Answer)

{-# LANGUAGE  ViewPatterns #-}
import Data.List
import qualified Data.Set as S
import Control.Monad

main :: IO ()
main = readLn >>= print . solve 

solve :: Int -> Int 
solve k = walk S.empty $ cons (1, 1) empty
    where
        walk s (pop -> Just ((v, d), xs))
            | v == 0 = d
            | S.member i s && S.member j s = walk s xs
            | S.member i s = walk s1 $ snoc (j, d + 1) xs
            | S.member j s = walk s2 $ cons (i, d) xs
            | otherwise = walk s3 . cons (i, d) $ snoc (j, d + 1) xs
            where
                i = (v * 10) `mod` k 
                j = (v + 1) `mod` k
                s1 = S.insert j s
                s2 = S.insert i s
                s3 = S.insert i s1

data DQ a = DQ [a] [a]
    deriving (Show, Eq)

empty :: DQ a
empty = DQ [] []

cons :: a -> DQ a -> DQ a
cons v (DQ xs ys) = DQ (v : xs) ys

snoc :: a -> DQ a -> DQ a
snoc v (DQ xs ys) = DQ xs $ v : ys

pop :: DQ a -> Maybe (a, DQ a)
pop (DQ (x : xs) ys) = return (x, DQ xs ys)
pop (DQ _ []) = Nothing
pop (DQ _ ys) = pop $ DQ (reverse ys) []