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 Rust (1.15.1) (judge verdict: Accepted)

#[derive(Copy, Clone, Eq, PartialEq)]
struct State {
    v: usize,
    d: usize,
}

use std::cmp::Ordering;
impl Ord for State {
    fn cmp(&self, other: &State) -> Ordering {
        other.d.cmp(&self.d)
    }
}

impl PartialOrd for State {
    fn partial_cmp(&self, other: &State) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

fn run() {
    let n: usize = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        s.trim().parse().unwrap()
    };
    let mut g = vec![vec![]; n + 1];
    for i in 0..n {
        for d in 0..10 {
            let k = (10 * i + d) % n;
            g[i].push((k, d));
        }
    }
    for d in 1..10 {
        let k = d % n;
        g[n].push((k, d));
    }
    let mut dp = vec![9 * (n + 1); n + 1];
    dp[n] = 0;
    let mut h = std::collections::BinaryHeap::new();
    h.push(State{v: n, d: 0});
    while let Some(State{v, d}) = h.pop() {
        if d > dp[v] {
            continue;
        }
        for &(u, c) in g[v].iter() {
            let d = d + c;
            if d < dp[u] {
                dp[u] = d;
                h.push(State{v: u, d: d});
            }
        }
    }
    println!("{}", dp[0]);
}

fn main() {
    run();
}