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 C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

const int INF = 1e9;

struct Node {
    int dist;
    vector<int> to, cost;

    bool operator <(Node that) const {return dist > that.dist;} // 小さい方から出てくるようにする
};

int main() {
    int K; cin >> K;
    vector<Node> node(K);
    for (int i = 0; i < K; i++) {
        node[i].dist = INF;

        node[i].to.push_back((i + 1) %K);
        node[i].cost.push_back(1);

        node[i].to.push_back((i*10) %K);
        node[i].cost.push_back(0);
    }

    // ダイクストラ法
    priority_queue<Node> que;
    node[1].dist = 0; que.push(node[1]);

    while (que.size() > 0) {
        Node n = que.top(); que.pop();

        for (int i = 0; i < n.to.size(); i++) {
            if (n.dist + n.cost[i] < node[n.to[i]].dist) {
                node[n.to[i]].dist = n.dist + n.cost[i];
                que.push(node[n.to[i]]);
            }
        }
    }

    cout << node[0].dist + 1 << endl;
    return 0;
}