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: Time Limit Exceeded)

#include <cstdio>
#include <iostream>
#include <array>
#include <vector>
#include <deque>
#include <string>
#include <algorithm>
#include <functional>
#include <tuple>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <utility>
#include <memory>
#include <valarray>
#include <climits>

using namespace std;

using ll = long long int;

#define REP(i, N) for (int i = 0; i < (N); ++i)
#define scanInt(x) int x; scanf("%d", &(x)); getchar();
#define scanLLInt(x) ll x; scanf("%lld", &(x)); getchar();
#define scanVecInt(A, N) vector<int> A(N); REP(i, N){scanf("%d", &(A[i])); getchar();}
#define scanVecLLInt(A, N) vector<ll> A(N); REP(i, N){scanf("%lld", &(A[i])); getchar();}

int getSum(int K)
{
    int sum = 0;
    while (10 <= K){
        sum += (K % 10);
        K /= 10;
    }
    return sum + K;
}

int main()
{
    scanLLInt(K);
    while (K % 2 == 0) K /= 2;
    while (K % 5 == 0) K /= 5;
    if (K == 1){
        cout << 1 << endl;
        return 0;
    }
    unordered_set<ll> rests;
    rests.emplace(1);
    ll old = 1;
    while (true){
        const ll next_old = (old * 10) % K;
        if (rests.count(next_old)) break;
        rests.emplace(next_old);
        old = next_old;
    }
    unordered_set<ll> now;
    unordered_set<ll> already;
    now.emplace(0);
    for (int n = 0; ; ++n){
        decltype(now) next;
        for (auto& e : now){
            for (auto& s : rests){
                const auto ans = e + s;
                if (ans % K == 0){
                    cout << n + 1 << endl;
                    return 0;
                }
                if (!already.count(ans)) next.emplace(ans);
                already.emplace(ans);
            }
        }
        now.swap(next);
    }
}